| File: | 3rdparty/sqlite3/sqlite3.c |
| Warning: | line 26628, column 10 Access to field 'xWrite' results in a dereference of a null pointer (loaded from field 'pMethods') |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 1 | /****************************************************************************** | ||||
| 2 | ** This file is an amalgamation of many separate C source files from SQLite | ||||
| 3 | ** version 3.50.3. By combining all the individual C code files into this | ||||
| 4 | ** single large file, the entire code can be compiled as a single translation | ||||
| 5 | ** unit. This allows many compilers to do optimizations that would not be | ||||
| 6 | ** possible if the files were compiled separately. Performance improvements | ||||
| 7 | ** of 5% or more are commonly seen when SQLite is compiled as a single | ||||
| 8 | ** translation unit. | ||||
| 9 | ** | ||||
| 10 | ** This file is all you need to compile SQLite. To use SQLite in other | ||||
| 11 | ** programs, you need this file and the "sqlite3.h" header file that defines | ||||
| 12 | ** the programming interface to the SQLite library. (If you do not have | ||||
| 13 | ** the "sqlite3.h" header file at hand, you will find a copy embedded within | ||||
| 14 | ** the text of this file. Search for "Begin file sqlite3.h" to find the start | ||||
| 15 | ** of the embedded sqlite3.h header file.) Additional code files may be needed | ||||
| 16 | ** if you want a wrapper to interface SQLite with your choice of programming | ||||
| 17 | ** language. The code for the "sqlite3" command-line shell is also in a | ||||
| 18 | ** separate file. This file contains only code for the core SQLite library. | ||||
| 19 | ** | ||||
| 20 | ** The content in this amalgamation comes from Fossil check-in | ||||
| 21 | ** 3ce993b8657d6d9deda380a93cdd6404a8c8 with changes in files: | ||||
| 22 | ** | ||||
| 23 | ** | ||||
| 24 | */ | ||||
| 25 | #ifndef SQLITE_AMALGAMATION1 | ||||
| 26 | #define SQLITE_CORE1 1 | ||||
| 27 | #define SQLITE_AMALGAMATION1 1 | ||||
| 28 | #ifndef SQLITE_PRIVATEstatic | ||||
| 29 | # define SQLITE_PRIVATEstatic static | ||||
| 30 | #endif | ||||
| 31 | /************** Begin file sqliteInt.h ***************************************/ | ||||
| 32 | /* | ||||
| 33 | ** 2001 September 15 | ||||
| 34 | ** | ||||
| 35 | ** The author disclaims copyright to this source code. In place of | ||||
| 36 | ** a legal notice, here is a blessing: | ||||
| 37 | ** | ||||
| 38 | ** May you do good and not evil. | ||||
| 39 | ** May you find forgiveness for yourself and forgive others. | ||||
| 40 | ** May you share freely, never taking more than you give. | ||||
| 41 | ** | ||||
| 42 | ************************************************************************* | ||||
| 43 | ** Internal interface definitions for SQLite. | ||||
| 44 | ** | ||||
| 45 | */ | ||||
| 46 | #ifndef SQLITEINT_H | ||||
| 47 | #define SQLITEINT_H | ||||
| 48 | |||||
| 49 | /* Special Comments: | ||||
| 50 | ** | ||||
| 51 | ** Some comments have special meaning to the tools that measure test | ||||
| 52 | ** coverage: | ||||
| 53 | ** | ||||
| 54 | ** NO_TEST - The branches on this line are not | ||||
| 55 | ** measured by branch coverage. This is | ||||
| 56 | ** used on lines of code that actually | ||||
| 57 | ** implement parts of coverage testing. | ||||
| 58 | ** | ||||
| 59 | ** OPTIMIZATION-IF-TRUE - This branch is allowed to always be false | ||||
| 60 | ** and the correct answer is still obtained, | ||||
| 61 | ** though perhaps more slowly. | ||||
| 62 | ** | ||||
| 63 | ** OPTIMIZATION-IF-FALSE - This branch is allowed to always be true | ||||
| 64 | ** and the correct answer is still obtained, | ||||
| 65 | ** though perhaps more slowly. | ||||
| 66 | ** | ||||
| 67 | ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread | ||||
| 68 | ** that would be harmless and undetectable | ||||
| 69 | ** if it did occur. | ||||
| 70 | ** | ||||
| 71 | ** In all cases, the special comment must be enclosed in the usual | ||||
| 72 | ** slash-asterisk...asterisk-slash comment marks, with no spaces between the | ||||
| 73 | ** asterisks and the comment text. | ||||
| 74 | */ | ||||
| 75 | |||||
| 76 | /* | ||||
| 77 | ** Make sure the Tcl calling convention macro is defined. This macro is | ||||
| 78 | ** only used by test code and Tcl integration code. | ||||
| 79 | */ | ||||
| 80 | #ifndef SQLITE_TCLAPI | ||||
| 81 | # define SQLITE_TCLAPI | ||||
| 82 | #endif | ||||
| 83 | |||||
| 84 | /* | ||||
| 85 | ** Include the header file used to customize the compiler options for MSVC. | ||||
| 86 | ** This should be done first so that it can successfully prevent spurious | ||||
| 87 | ** compiler warnings due to subsequent content in this file and other files | ||||
| 88 | ** that are included by this file. | ||||
| 89 | */ | ||||
| 90 | /************** Include msvc.h in the middle of sqliteInt.h ******************/ | ||||
| 91 | /************** Begin file msvc.h ********************************************/ | ||||
| 92 | /* | ||||
| 93 | ** 2015 January 12 | ||||
| 94 | ** | ||||
| 95 | ** The author disclaims copyright to this source code. In place of | ||||
| 96 | ** a legal notice, here is a blessing: | ||||
| 97 | ** | ||||
| 98 | ** May you do good and not evil. | ||||
| 99 | ** May you find forgiveness for yourself and forgive others. | ||||
| 100 | ** May you share freely, never taking more than you give. | ||||
| 101 | ** | ||||
| 102 | ****************************************************************************** | ||||
| 103 | ** | ||||
| 104 | ** This file contains code that is specific to MSVC. | ||||
| 105 | */ | ||||
| 106 | #ifndef SQLITE_MSVC_H | ||||
| 107 | #define SQLITE_MSVC_H | ||||
| 108 | |||||
| 109 | #if defined(_MSC_VER) | ||||
| 110 | #pragma warning(disable : 4054) | ||||
| 111 | #pragma warning(disable : 4055) | ||||
| 112 | #pragma warning(disable : 4100) | ||||
| 113 | #pragma warning(disable : 4127) | ||||
| 114 | #pragma warning(disable : 4130) | ||||
| 115 | #pragma warning(disable : 4152) | ||||
| 116 | #pragma warning(disable : 4189) | ||||
| 117 | #pragma warning(disable : 4206) | ||||
| 118 | #pragma warning(disable : 4210) | ||||
| 119 | #pragma warning(disable : 4232) | ||||
| 120 | #pragma warning(disable : 4244) | ||||
| 121 | #pragma warning(disable : 4305) | ||||
| 122 | #pragma warning(disable : 4306) | ||||
| 123 | #pragma warning(disable : 4702) | ||||
| 124 | #pragma warning(disable : 4706) | ||||
| 125 | #endif /* defined(_MSC_VER) */ | ||||
| 126 | |||||
| 127 | #if defined(_MSC_VER) && !defined(_WIN64) | ||||
| 128 | #undef SQLITE_4_BYTE_ALIGNED_MALLOC | ||||
| 129 | #define SQLITE_4_BYTE_ALIGNED_MALLOC | ||||
| 130 | #endif /* defined(_MSC_VER) && !defined(_WIN64) */ | ||||
| 131 | |||||
| 132 | #if !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 | ||||
| 133 | #define HAVE_LOG2 0 | ||||
| 134 | #endif /* !defined(HAVE_LOG2) && defined(_MSC_VER) && _MSC_VER<1800 */ | ||||
| 135 | |||||
| 136 | #endif /* SQLITE_MSVC_H */ | ||||
| 137 | |||||
| 138 | /************** End of msvc.h ************************************************/ | ||||
| 139 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 140 | |||||
| 141 | /* | ||||
| 142 | ** Special setup for VxWorks | ||||
| 143 | */ | ||||
| 144 | /************** Include vxworks.h in the middle of sqliteInt.h ***************/ | ||||
| 145 | /************** Begin file vxworks.h *****************************************/ | ||||
| 146 | /* | ||||
| 147 | ** 2015-03-02 | ||||
| 148 | ** | ||||
| 149 | ** The author disclaims copyright to this source code. In place of | ||||
| 150 | ** a legal notice, here is a blessing: | ||||
| 151 | ** | ||||
| 152 | ** May you do good and not evil. | ||||
| 153 | ** May you find forgiveness for yourself and forgive others. | ||||
| 154 | ** May you share freely, never taking more than you give. | ||||
| 155 | ** | ||||
| 156 | ****************************************************************************** | ||||
| 157 | ** | ||||
| 158 | ** This file contains code that is specific to Wind River's VxWorks | ||||
| 159 | */ | ||||
| 160 | #if defined(__RTP__) || defined(_WRS_KERNEL) | ||||
| 161 | /* This is VxWorks. Set up things specially for that OS | ||||
| 162 | */ | ||||
| 163 | #include <vxWorks.h> | ||||
| 164 | #include <pthread.h> /* amalgamator: dontcache */ | ||||
| 165 | #define OS_VXWORKS0 1 | ||||
| 166 | #define SQLITE_OS_OTHER0 0 | ||||
| 167 | #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1 | ||||
| 168 | #define SQLITE_OMIT_LOAD_EXTENSION1 1 | ||||
| 169 | #define SQLITE_ENABLE_LOCKING_STYLE0 0 | ||||
| 170 | #define HAVE_UTIME 1 | ||||
| 171 | #else | ||||
| 172 | /* This is not VxWorks. */ | ||||
| 173 | #define OS_VXWORKS0 0 | ||||
| 174 | #define HAVE_FCHOWN1 1 | ||||
| 175 | #define HAVE_READLINK1 1 | ||||
| 176 | #define HAVE_LSTAT1 1 | ||||
| 177 | #endif /* defined(_WRS_KERNEL) */ | ||||
| 178 | |||||
| 179 | /************** End of vxworks.h *********************************************/ | ||||
| 180 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 181 | |||||
| 182 | /* | ||||
| 183 | ** These #defines should enable >2GB file support on POSIX if the | ||||
| 184 | ** underlying operating system supports it. If the OS lacks | ||||
| 185 | ** large file support, or if the OS is windows, these should be no-ops. | ||||
| 186 | ** | ||||
| 187 | ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any | ||||
| 188 | ** system #includes. Hence, this block of code must be the very first | ||||
| 189 | ** code in all source files. | ||||
| 190 | ** | ||||
| 191 | ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch | ||||
| 192 | ** on the compiler command line. This is necessary if you are compiling | ||||
| 193 | ** on a recent machine (ex: Red Hat 7.2) but you want your code to work | ||||
| 194 | ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 | ||||
| 195 | ** without this option, LFS is enable. But LFS does not exist in the kernel | ||||
| 196 | ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary | ||||
| 197 | ** portability you should omit LFS. | ||||
| 198 | ** | ||||
| 199 | ** The previous paragraph was written in 2005. (This paragraph is written | ||||
| 200 | ** on 2008-11-28.) These days, all Linux kernels support large files, so | ||||
| 201 | ** you should probably leave LFS enabled. But some embedded platforms might | ||||
| 202 | ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful. | ||||
| 203 | ** | ||||
| 204 | ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. | ||||
| 205 | */ | ||||
| 206 | #ifndef SQLITE_DISABLE_LFS | ||||
| 207 | # define _LARGE_FILE1 1 | ||||
| 208 | # ifndef _FILE_OFFSET_BITS64 | ||||
| 209 | # define _FILE_OFFSET_BITS64 64 | ||||
| 210 | # endif | ||||
| 211 | # define _LARGEFILE_SOURCE1 1 | ||||
| 212 | #endif | ||||
| 213 | |||||
| 214 | /* The GCC_VERSION and MSVC_VERSION macros are used to | ||||
| 215 | ** conditionally include optimizations for each of these compilers. A | ||||
| 216 | ** value of 0 means that compiler is not being used. The | ||||
| 217 | ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific | ||||
| 218 | ** optimizations, and hence set all compiler macros to 0 | ||||
| 219 | ** | ||||
| 220 | ** There was once also a CLANG_VERSION macro. However, we learn that the | ||||
| 221 | ** version numbers in clang are for "marketing" only and are inconsistent | ||||
| 222 | ** and unreliable. Fortunately, all versions of clang also recognize the | ||||
| 223 | ** gcc version numbers and have reasonable settings for gcc version numbers, | ||||
| 224 | ** so the GCC_VERSION macro will be set to a correct non-zero value even | ||||
| 225 | ** when compiling with clang. | ||||
| 226 | */ | ||||
| 227 | #if defined(__GNUC__4) && !defined(SQLITE_DISABLE_INTRINSIC) | ||||
| 228 | # define GCC_VERSION(4*1000000+2*1000+1) (__GNUC__4*1000000+__GNUC_MINOR__2*1000+__GNUC_PATCHLEVEL__1) | ||||
| 229 | #else | ||||
| 230 | # define GCC_VERSION(4*1000000+2*1000+1) 0 | ||||
| 231 | #endif | ||||
| 232 | #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) | ||||
| 233 | # define MSVC_VERSION0 _MSC_VER | ||||
| 234 | #else | ||||
| 235 | # define MSVC_VERSION0 0 | ||||
| 236 | #endif | ||||
| 237 | |||||
| 238 | /* | ||||
| 239 | ** Some C99 functions in "math.h" are only present for MSVC when its version | ||||
| 240 | ** is associated with Visual Studio 2013 or higher. | ||||
| 241 | */ | ||||
| 242 | #ifndef SQLITE_HAVE_C99_MATH_FUNCS(1) | ||||
| 243 | # if MSVC_VERSION0==0 || MSVC_VERSION0>=1800 | ||||
| 244 | # define SQLITE_HAVE_C99_MATH_FUNCS(1) (1) | ||||
| 245 | # else | ||||
| 246 | # define SQLITE_HAVE_C99_MATH_FUNCS(1) (0) | ||||
| 247 | # endif | ||||
| 248 | #endif | ||||
| 249 | |||||
| 250 | /* Needed for various definitions... */ | ||||
| 251 | #if defined(__GNUC__4) && !defined(_GNU_SOURCE) | ||||
| 252 | # define _GNU_SOURCE | ||||
| 253 | #endif | ||||
| 254 | |||||
| 255 | #if defined(__OpenBSD__) && !defined(_BSD_SOURCE) | ||||
| 256 | # define _BSD_SOURCE | ||||
| 257 | #endif | ||||
| 258 | |||||
| 259 | /* | ||||
| 260 | ** Macro to disable warnings about missing "break" at the end of a "case". | ||||
| 261 | */ | ||||
| 262 | #if defined(__has_attribute)0 | ||||
| 263 | # if __has_attribute(fallthrough)1 | ||||
| 264 | # define deliberate_fall_through__attribute__((fallthrough)); __attribute__((fallthrough)); | ||||
| 265 | # endif | ||||
| 266 | #endif | ||||
| 267 | #if !defined(deliberate_fall_through__attribute__((fallthrough));) | ||||
| 268 | # define deliberate_fall_through__attribute__((fallthrough)); | ||||
| 269 | #endif | ||||
| 270 | |||||
| 271 | /* | ||||
| 272 | ** For MinGW, check to see if we can include the header file containing its | ||||
| 273 | ** version information, among other things. Normally, this internal MinGW | ||||
| 274 | ** header file would [only] be included automatically by other MinGW header | ||||
| 275 | ** files; however, the contained version information is now required by this | ||||
| 276 | ** header file to work around binary compatibility issues (see below) and | ||||
| 277 | ** this is the only known way to reliably obtain it. This entire #if block | ||||
| 278 | ** would be completely unnecessary if there was any other way of detecting | ||||
| 279 | ** MinGW via their preprocessor (e.g. if they customized their GCC to define | ||||
| 280 | ** some MinGW-specific macros). When compiling for MinGW, either the | ||||
| 281 | ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be | ||||
| 282 | ** defined; otherwise, detection of conditions specific to MinGW will be | ||||
| 283 | ** disabled. | ||||
| 284 | */ | ||||
| 285 | #if defined(_HAVE_MINGW_H) | ||||
| 286 | # include "mingw.h" | ||||
| 287 | #elif defined(_HAVE__MINGW_H) | ||||
| 288 | # include "_mingw.h" | ||||
| 289 | #endif | ||||
| 290 | |||||
| 291 | /* | ||||
| 292 | ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T | ||||
| 293 | ** define is required to maintain binary compatibility with the MSVC runtime | ||||
| 294 | ** library in use (e.g. for Windows XP). | ||||
| 295 | */ | ||||
| 296 | #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \ | ||||
| 297 | defined(_WIN32) && !defined(_WIN64) && \ | ||||
| 298 | defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \ | ||||
| 299 | defined(__MSVCRT__) | ||||
| 300 | # define _USE_32BIT_TIME_T | ||||
| 301 | #endif | ||||
| 302 | |||||
| 303 | /* Optionally #include a user-defined header, whereby compilation options | ||||
| 304 | ** may be set prior to where they take effect, but after platform setup. | ||||
| 305 | ** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include | ||||
| 306 | ** file. | ||||
| 307 | */ | ||||
| 308 | #ifdef SQLITE_CUSTOM_INCLUDE | ||||
| 309 | # define INC_STRINGIFY_(f) #f | ||||
| 310 | # define INC_STRINGIFY(f) INC_STRINGIFY_(f) | ||||
| 311 | # include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE) | ||||
| 312 | #endif | ||||
| 313 | |||||
| 314 | /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear | ||||
| 315 | ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for | ||||
| 316 | ** MinGW. | ||||
| 317 | */ | ||||
| 318 | /************** Include sqlite3.h in the middle of sqliteInt.h ***************/ | ||||
| 319 | /************** Begin file sqlite3.h *****************************************/ | ||||
| 320 | /* | ||||
| 321 | ** 2001-09-15 | ||||
| 322 | ** | ||||
| 323 | ** The author disclaims copyright to this source code. In place of | ||||
| 324 | ** a legal notice, here is a blessing: | ||||
| 325 | ** | ||||
| 326 | ** May you do good and not evil. | ||||
| 327 | ** May you find forgiveness for yourself and forgive others. | ||||
| 328 | ** May you share freely, never taking more than you give. | ||||
| 329 | ** | ||||
| 330 | ************************************************************************* | ||||
| 331 | ** This header file defines the interface that the SQLite library | ||||
| 332 | ** presents to client programs. If a C-function, structure, datatype, | ||||
| 333 | ** or constant definition does not appear in this file, then it is | ||||
| 334 | ** not a published API of SQLite, is subject to change without | ||||
| 335 | ** notice, and should not be referenced by programs that use SQLite. | ||||
| 336 | ** | ||||
| 337 | ** Some of the definitions that are in this file are marked as | ||||
| 338 | ** "experimental". Experimental interfaces are normally new | ||||
| 339 | ** features recently added to SQLite. We do not anticipate changes | ||||
| 340 | ** to experimental interfaces but reserve the right to make minor changes | ||||
| 341 | ** if experience from use "in the wild" suggest such changes are prudent. | ||||
| 342 | ** | ||||
| 343 | ** The official C-language API documentation for SQLite is derived | ||||
| 344 | ** from comments in this file. This file is the authoritative source | ||||
| 345 | ** on how SQLite interfaces are supposed to operate. | ||||
| 346 | ** | ||||
| 347 | ** The name of this file under configuration management is "sqlite.h.in". | ||||
| 348 | ** The makefile makes some minor changes to this file (such as inserting | ||||
| 349 | ** the version number) and changes its name to "sqlite3.h" as | ||||
| 350 | ** part of the build process. | ||||
| 351 | */ | ||||
| 352 | #ifndef SQLITE3_H | ||||
| 353 | #define SQLITE3_H | ||||
| 354 | #include <stdarg.h> /* Needed for the definition of va_list */ | ||||
| 355 | |||||
| 356 | /* | ||||
| 357 | ** Make sure we can call this stuff from C++. | ||||
| 358 | */ | ||||
| 359 | #if 0 | ||||
| 360 | extern "C" { | ||||
| 361 | #endif | ||||
| 362 | |||||
| 363 | |||||
| 364 | /* | ||||
| 365 | ** Facilitate override of interface linkage and calling conventions. | ||||
| 366 | ** Be aware that these macros may not be used within this particular | ||||
| 367 | ** translation of the amalgamation and its associated header file. | ||||
| 368 | ** | ||||
| 369 | ** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the | ||||
| 370 | ** compiler that the target identifier should have external linkage. | ||||
| 371 | ** | ||||
| 372 | ** The SQLITE_CDECL macro is used to set the calling convention for | ||||
| 373 | ** public functions that accept a variable number of arguments. | ||||
| 374 | ** | ||||
| 375 | ** The SQLITE_APICALL macro is used to set the calling convention for | ||||
| 376 | ** public functions that accept a fixed number of arguments. | ||||
| 377 | ** | ||||
| 378 | ** The SQLITE_STDCALL macro is no longer used and is now deprecated. | ||||
| 379 | ** | ||||
| 380 | ** The SQLITE_CALLBACK macro is used to set the calling convention for | ||||
| 381 | ** function pointers. | ||||
| 382 | ** | ||||
| 383 | ** The SQLITE_SYSAPI macro is used to set the calling convention for | ||||
| 384 | ** functions provided by the operating system. | ||||
| 385 | ** | ||||
| 386 | ** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and | ||||
| 387 | ** SQLITE_SYSAPI macros are used only when building for environments | ||||
| 388 | ** that require non-default calling conventions. | ||||
| 389 | */ | ||||
| 390 | #ifndef SQLITE_EXTERNextern | ||||
| 391 | # define SQLITE_EXTERNextern extern | ||||
| 392 | #endif | ||||
| 393 | #ifndef SQLITE_API | ||||
| 394 | # define SQLITE_API | ||||
| 395 | #endif | ||||
| 396 | #ifndef SQLITE_CDECL | ||||
| 397 | # define SQLITE_CDECL | ||||
| 398 | #endif | ||||
| 399 | #ifndef SQLITE_APICALL | ||||
| 400 | # define SQLITE_APICALL | ||||
| 401 | #endif | ||||
| 402 | #ifndef SQLITE_STDCALL | ||||
| 403 | # define SQLITE_STDCALL SQLITE_APICALL | ||||
| 404 | #endif | ||||
| 405 | #ifndef SQLITE_CALLBACK | ||||
| 406 | # define SQLITE_CALLBACK | ||||
| 407 | #endif | ||||
| 408 | #ifndef SQLITE_SYSAPI | ||||
| 409 | # define SQLITE_SYSAPI | ||||
| 410 | #endif | ||||
| 411 | |||||
| 412 | /* | ||||
| 413 | ** These no-op macros are used in front of interfaces to mark those | ||||
| 414 | ** interfaces as either deprecated or experimental. New applications | ||||
| 415 | ** should not use deprecated interfaces - they are supported for backwards | ||||
| 416 | ** compatibility only. Application writers should be aware that | ||||
| 417 | ** experimental interfaces are subject to change in point releases. | ||||
| 418 | ** | ||||
| 419 | ** These macros used to resolve to various kinds of compiler magic that | ||||
| 420 | ** would generate warning messages when they were used. But that | ||||
| 421 | ** compiler magic ended up generating such a flurry of bug reports | ||||
| 422 | ** that we have taken it all out and gone back to using simple | ||||
| 423 | ** noop macros. | ||||
| 424 | */ | ||||
| 425 | #define SQLITE_DEPRECATED | ||||
| 426 | #define SQLITE_EXPERIMENTAL | ||||
| 427 | |||||
| 428 | /* | ||||
| 429 | ** Ensure these symbols were not defined by some previous header file. | ||||
| 430 | */ | ||||
| 431 | #ifdef SQLITE_VERSION"3.50.3" | ||||
| 432 | # undef SQLITE_VERSION"3.50.3" | ||||
| 433 | #endif | ||||
| 434 | #ifdef SQLITE_VERSION_NUMBER3050003 | ||||
| 435 | # undef SQLITE_VERSION_NUMBER3050003 | ||||
| 436 | #endif | ||||
| 437 | |||||
| 438 | /* | ||||
| 439 | ** CAPI3REF: Compile-Time Library Version Numbers | ||||
| 440 | ** | ||||
| 441 | ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header | ||||
| 442 | ** evaluates to a string literal that is the SQLite version in the | ||||
| 443 | ** format "X.Y.Z" where X is the major version number (always 3 for | ||||
| 444 | ** SQLite3) and Y is the minor version number and Z is the release number.)^ | ||||
| 445 | ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer | ||||
| 446 | ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same | ||||
| 447 | ** numbers used in [SQLITE_VERSION].)^ | ||||
| 448 | ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also | ||||
| 449 | ** be larger than the release from which it is derived. Either Y will | ||||
| 450 | ** be held constant and Z will be incremented or else Y will be incremented | ||||
| 451 | ** and Z will be reset to zero. | ||||
| 452 | ** | ||||
| 453 | ** Since [version 3.6.18] ([dateof:3.6.18]), | ||||
| 454 | ** SQLite source code has been stored in the | ||||
| 455 | ** <a href="http://fossil-scm.org/">Fossil configuration management | ||||
| 456 | ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to | ||||
| 457 | ** a string which identifies a particular check-in of SQLite | ||||
| 458 | ** within its configuration management system. ^The SQLITE_SOURCE_ID | ||||
| 459 | ** string contains the date and time of the check-in (UTC) and a SHA1 | ||||
| 460 | ** or SHA3-256 hash of the entire source tree. If the source code has | ||||
| 461 | ** been edited in any way since it was last checked in, then the last | ||||
| 462 | ** four hexadecimal digits of the hash may be modified. | ||||
| 463 | ** | ||||
| 464 | ** See also: [sqlite3_libversion()], | ||||
| 465 | ** [sqlite3_libversion_number()], [sqlite3_sourceid()], | ||||
| 466 | ** [sqlite_version()] and [sqlite_source_id()]. | ||||
| 467 | */ | ||||
| 468 | #define SQLITE_VERSION"3.50.3" "3.50.3" | ||||
| 469 | #define SQLITE_VERSION_NUMBER3050003 3050003 | ||||
| 470 | #define SQLITE_SOURCE_ID"2025-07-17 13:25:10 3ce993b8657d6d9deda380a93cdd6404a8c8ba1b185b2bc423703e41ae5f2543" "2025-07-17 13:25:10 3ce993b8657d6d9deda380a93cdd6404a8c8ba1b185b2bc423703e41ae5f2543" | ||||
| 471 | |||||
| 472 | /* | ||||
| 473 | ** CAPI3REF: Run-Time Library Version Numbers | ||||
| 474 | ** KEYWORDS: sqlite3_version sqlite3_sourceid | ||||
| 475 | ** | ||||
| 476 | ** These interfaces provide the same information as the [SQLITE_VERSION], | ||||
| 477 | ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros | ||||
| 478 | ** but are associated with the library instead of the header file. ^(Cautious | ||||
| 479 | ** programmers might include assert() statements in their application to | ||||
| 480 | ** verify that values returned by these interfaces match the macros in | ||||
| 481 | ** the header, and thus ensure that the application is | ||||
| 482 | ** compiled with matching library and header files. | ||||
| 483 | ** | ||||
| 484 | ** <blockquote><pre> | ||||
| 485 | ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); | ||||
| 486 | ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 ); | ||||
| 487 | ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); | ||||
| 488 | ** </pre></blockquote>)^ | ||||
| 489 | ** | ||||
| 490 | ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] | ||||
| 491 | ** macro. ^The sqlite3_libversion() function returns a pointer to the | ||||
| 492 | ** to the sqlite3_version[] string constant. The sqlite3_libversion() | ||||
| 493 | ** function is provided for use in DLLs since DLL users usually do not have | ||||
| 494 | ** direct access to string constants within the DLL. ^The | ||||
| 495 | ** sqlite3_libversion_number() function returns an integer equal to | ||||
| 496 | ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns | ||||
| 497 | ** a pointer to a string constant whose value is the same as the | ||||
| 498 | ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built | ||||
| 499 | ** using an edited copy of [the amalgamation], then the last four characters | ||||
| 500 | ** of the hash might be different from [SQLITE_SOURCE_ID].)^ | ||||
| 501 | ** | ||||
| 502 | ** See also: [sqlite_version()] and [sqlite_source_id()]. | ||||
| 503 | */ | ||||
| 504 | SQLITE_API const char sqlite3_version[] = SQLITE_VERSION"3.50.3"; | ||||
| 505 | SQLITE_API const char *sqlite3_libversion(void); | ||||
| 506 | SQLITE_API const char *sqlite3_sourceid(void); | ||||
| 507 | SQLITE_API int sqlite3_libversion_number(void); | ||||
| 508 | |||||
| 509 | /* | ||||
| 510 | ** CAPI3REF: Run-Time Library Compilation Options Diagnostics | ||||
| 511 | ** | ||||
| 512 | ** ^The sqlite3_compileoption_used() function returns 0 or 1 | ||||
| 513 | ** indicating whether the specified option was defined at | ||||
| 514 | ** compile time. ^The SQLITE_ prefix may be omitted from the | ||||
| 515 | ** option name passed to sqlite3_compileoption_used(). | ||||
| 516 | ** | ||||
| 517 | ** ^The sqlite3_compileoption_get() function allows iterating | ||||
| 518 | ** over the list of options that were defined at compile time by | ||||
| 519 | ** returning the N-th compile time option string. ^If N is out of range, | ||||
| 520 | ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ | ||||
| 521 | ** prefix is omitted from any strings returned by | ||||
| 522 | ** sqlite3_compileoption_get(). | ||||
| 523 | ** | ||||
| 524 | ** ^Support for the diagnostic functions sqlite3_compileoption_used() | ||||
| 525 | ** and sqlite3_compileoption_get() may be omitted by specifying the | ||||
| 526 | ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. | ||||
| 527 | ** | ||||
| 528 | ** See also: SQL functions [sqlite_compileoption_used()] and | ||||
| 529 | ** [sqlite_compileoption_get()] and the [compile_options pragma]. | ||||
| 530 | */ | ||||
| 531 | #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS | ||||
| 532 | SQLITE_API int sqlite3_compileoption_used(const char *zOptName); | ||||
| 533 | SQLITE_API const char *sqlite3_compileoption_get(int N); | ||||
| 534 | #else | ||||
| 535 | # define sqlite3_compileoption_used(X) 0 | ||||
| 536 | # define sqlite3_compileoption_get(X) ((void*)0) | ||||
| 537 | #endif | ||||
| 538 | |||||
| 539 | /* | ||||
| 540 | ** CAPI3REF: Test To See If The Library Is Threadsafe | ||||
| 541 | ** | ||||
| 542 | ** ^The sqlite3_threadsafe() function returns zero if and only if | ||||
| 543 | ** SQLite was compiled with mutexing code omitted due to the | ||||
| 544 | ** [SQLITE_THREADSAFE] compile-time option being set to 0. | ||||
| 545 | ** | ||||
| 546 | ** SQLite can be compiled with or without mutexes. When | ||||
| 547 | ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes | ||||
| 548 | ** are enabled and SQLite is threadsafe. When the | ||||
| 549 | ** [SQLITE_THREADSAFE] macro is 0, | ||||
| 550 | ** the mutexes are omitted. Without the mutexes, it is not safe | ||||
| 551 | ** to use SQLite concurrently from more than one thread. | ||||
| 552 | ** | ||||
| 553 | ** Enabling mutexes incurs a measurable performance penalty. | ||||
| 554 | ** So if speed is of utmost importance, it makes sense to disable | ||||
| 555 | ** the mutexes. But for maximum safety, mutexes should be enabled. | ||||
| 556 | ** ^The default behavior is for mutexes to be enabled. | ||||
| 557 | ** | ||||
| 558 | ** This interface can be used by an application to make sure that the | ||||
| 559 | ** version of SQLite that it is linking against was compiled with | ||||
| 560 | ** the desired setting of the [SQLITE_THREADSAFE] macro. | ||||
| 561 | ** | ||||
| 562 | ** This interface only reports on the compile-time mutex setting | ||||
| 563 | ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with | ||||
| 564 | ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but | ||||
| 565 | ** can be fully or partially disabled using a call to [sqlite3_config()] | ||||
| 566 | ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], | ||||
| 567 | ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the | ||||
| 568 | ** sqlite3_threadsafe() function shows only the compile-time setting of | ||||
| 569 | ** thread safety, not any run-time changes to that setting made by | ||||
| 570 | ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() | ||||
| 571 | ** is unchanged by calls to sqlite3_config().)^ | ||||
| 572 | ** | ||||
| 573 | ** See the [threading mode] documentation for additional information. | ||||
| 574 | */ | ||||
| 575 | SQLITE_API int sqlite3_threadsafe(void); | ||||
| 576 | |||||
| 577 | /* | ||||
| 578 | ** CAPI3REF: Database Connection Handle | ||||
| 579 | ** KEYWORDS: {database connection} {database connections} | ||||
| 580 | ** | ||||
| 581 | ** Each open SQLite database is represented by a pointer to an instance of | ||||
| 582 | ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 | ||||
| 583 | ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and | ||||
| 584 | ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] | ||||
| 585 | ** and [sqlite3_close_v2()] are its destructors. There are many other | ||||
| 586 | ** interfaces (such as | ||||
| 587 | ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and | ||||
| 588 | ** [sqlite3_busy_timeout()] to name but three) that are methods on an | ||||
| 589 | ** sqlite3 object. | ||||
| 590 | */ | ||||
| 591 | typedef struct sqlite3 sqlite3; | ||||
| 592 | |||||
| 593 | /* | ||||
| 594 | ** CAPI3REF: 64-Bit Integer Types | ||||
| 595 | ** KEYWORDS: sqlite_int64 sqlite_uint64 | ||||
| 596 | ** | ||||
| 597 | ** Because there is no cross-platform way to specify 64-bit integer types | ||||
| 598 | ** SQLite includes typedefs for 64-bit signed and unsigned integers. | ||||
| 599 | ** | ||||
| 600 | ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. | ||||
| 601 | ** The sqlite_int64 and sqlite_uint64 types are supported for backwards | ||||
| 602 | ** compatibility only. | ||||
| 603 | ** | ||||
| 604 | ** ^The sqlite3_int64 and sqlite_int64 types can store integer values | ||||
| 605 | ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The | ||||
| 606 | ** sqlite3_uint64 and sqlite_uint64 types can store integer values | ||||
| 607 | ** between 0 and +18446744073709551615 inclusive. | ||||
| 608 | */ | ||||
| 609 | #ifdef SQLITE_INT64_TYPE | ||||
| 610 | typedef SQLITE_INT64_TYPE sqlite_int64; | ||||
| 611 | # ifdef SQLITE_UINT64_TYPE | ||||
| 612 | typedef SQLITE_UINT64_TYPE sqlite_uint64; | ||||
| 613 | # else | ||||
| 614 | typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; | ||||
| 615 | # endif | ||||
| 616 | #elif defined(_MSC_VER) || defined(__BORLANDC__) | ||||
| 617 | typedef __int64 sqlite_int64; | ||||
| 618 | typedef unsigned __int64 sqlite_uint64; | ||||
| 619 | #else | ||||
| 620 | typedef long long int sqlite_int64; | ||||
| 621 | typedef unsigned long long int sqlite_uint64; | ||||
| 622 | #endif | ||||
| 623 | typedef sqlite_int64 sqlite3_int64; | ||||
| 624 | typedef sqlite_uint64 sqlite3_uint64; | ||||
| 625 | |||||
| 626 | /* | ||||
| 627 | ** If compiling for a processor that lacks floating point support, | ||||
| 628 | ** substitute integer for floating-point. | ||||
| 629 | */ | ||||
| 630 | #ifdef SQLITE_OMIT_FLOATING_POINT | ||||
| 631 | # define double sqlite3_int64 | ||||
| 632 | #endif | ||||
| 633 | |||||
| 634 | /* | ||||
| 635 | ** CAPI3REF: Closing A Database Connection | ||||
| 636 | ** DESTRUCTOR: sqlite3 | ||||
| 637 | ** | ||||
| 638 | ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors | ||||
| 639 | ** for the [sqlite3] object. | ||||
| 640 | ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if | ||||
| 641 | ** the [sqlite3] object is successfully destroyed and all associated | ||||
| 642 | ** resources are deallocated. | ||||
| 643 | ** | ||||
| 644 | ** Ideally, applications should [sqlite3_finalize | finalize] all | ||||
| 645 | ** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and | ||||
| 646 | ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated | ||||
| 647 | ** with the [sqlite3] object prior to attempting to close the object. | ||||
| 648 | ** ^If the database connection is associated with unfinalized prepared | ||||
| 649 | ** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then | ||||
| 650 | ** sqlite3_close() will leave the database connection open and return | ||||
| 651 | ** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared | ||||
| 652 | ** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups, | ||||
| 653 | ** it returns [SQLITE_OK] regardless, but instead of deallocating the database | ||||
| 654 | ** connection immediately, it marks the database connection as an unusable | ||||
| 655 | ** "zombie" and makes arrangements to automatically deallocate the database | ||||
| 656 | ** connection after all prepared statements are finalized, all BLOB handles | ||||
| 657 | ** are closed, and all backups have finished. The sqlite3_close_v2() interface | ||||
| 658 | ** is intended for use with host languages that are garbage collected, and | ||||
| 659 | ** where the order in which destructors are called is arbitrary. | ||||
| 660 | ** | ||||
| 661 | ** ^If an [sqlite3] object is destroyed while a transaction is open, | ||||
| 662 | ** the transaction is automatically rolled back. | ||||
| 663 | ** | ||||
| 664 | ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] | ||||
| 665 | ** must be either a NULL | ||||
| 666 | ** pointer or an [sqlite3] object pointer obtained | ||||
| 667 | ** from [sqlite3_open()], [sqlite3_open16()], or | ||||
| 668 | ** [sqlite3_open_v2()], and not previously closed. | ||||
| 669 | ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer | ||||
| 670 | ** argument is a harmless no-op. | ||||
| 671 | */ | ||||
| 672 | SQLITE_API int sqlite3_close(sqlite3*); | ||||
| 673 | SQLITE_API int sqlite3_close_v2(sqlite3*); | ||||
| 674 | |||||
| 675 | /* | ||||
| 676 | ** The type for a callback function. | ||||
| 677 | ** This is legacy and deprecated. It is included for historical | ||||
| 678 | ** compatibility and is not documented. | ||||
| 679 | */ | ||||
| 680 | typedef int (*sqlite3_callback)(void*,int,char**, char**); | ||||
| 681 | |||||
| 682 | /* | ||||
| 683 | ** CAPI3REF: One-Step Query Execution Interface | ||||
| 684 | ** METHOD: sqlite3 | ||||
| 685 | ** | ||||
| 686 | ** The sqlite3_exec() interface is a convenience wrapper around | ||||
| 687 | ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], | ||||
| 688 | ** that allows an application to run multiple statements of SQL | ||||
| 689 | ** without having to use a lot of C code. | ||||
| 690 | ** | ||||
| 691 | ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, | ||||
| 692 | ** semicolon-separate SQL statements passed into its 2nd argument, | ||||
| 693 | ** in the context of the [database connection] passed in as its 1st | ||||
| 694 | ** argument. ^If the callback function of the 3rd argument to | ||||
| 695 | ** sqlite3_exec() is not NULL, then it is invoked for each result row | ||||
| 696 | ** coming out of the evaluated SQL statements. ^The 4th argument to | ||||
| 697 | ** sqlite3_exec() is relayed through to the 1st argument of each | ||||
| 698 | ** callback invocation. ^If the callback pointer to sqlite3_exec() | ||||
| 699 | ** is NULL, then no callback is ever invoked and result rows are | ||||
| 700 | ** ignored. | ||||
| 701 | ** | ||||
| 702 | ** ^If an error occurs while evaluating the SQL statements passed into | ||||
| 703 | ** sqlite3_exec(), then execution of the current statement stops and | ||||
| 704 | ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() | ||||
| 705 | ** is not NULL then any error message is written into memory obtained | ||||
| 706 | ** from [sqlite3_malloc()] and passed back through the 5th parameter. | ||||
| 707 | ** To avoid memory leaks, the application should invoke [sqlite3_free()] | ||||
| 708 | ** on error message strings returned through the 5th parameter of | ||||
| 709 | ** sqlite3_exec() after the error message string is no longer needed. | ||||
| 710 | ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors | ||||
| 711 | ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to | ||||
| 712 | ** NULL before returning. | ||||
| 713 | ** | ||||
| 714 | ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() | ||||
| 715 | ** routine returns SQLITE_ABORT without invoking the callback again and | ||||
| 716 | ** without running any subsequent SQL statements. | ||||
| 717 | ** | ||||
| 718 | ** ^The 2nd argument to the sqlite3_exec() callback function is the | ||||
| 719 | ** number of columns in the result. ^The 3rd argument to the sqlite3_exec() | ||||
| 720 | ** callback is an array of pointers to strings obtained as if from | ||||
| 721 | ** [sqlite3_column_text()], one for each column. ^If an element of a | ||||
| 722 | ** result row is NULL then the corresponding string pointer for the | ||||
| 723 | ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the | ||||
| 724 | ** sqlite3_exec() callback is an array of pointers to strings where each | ||||
| 725 | ** entry represents the name of corresponding result column as obtained | ||||
| 726 | ** from [sqlite3_column_name()]. | ||||
| 727 | ** | ||||
| 728 | ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer | ||||
| 729 | ** to an empty string, or a pointer that contains only whitespace and/or | ||||
| 730 | ** SQL comments, then no SQL statements are evaluated and the database | ||||
| 731 | ** is not changed. | ||||
| 732 | ** | ||||
| 733 | ** Restrictions: | ||||
| 734 | ** | ||||
| 735 | ** <ul> | ||||
| 736 | ** <li> The application must ensure that the 1st parameter to sqlite3_exec() | ||||
| 737 | ** is a valid and open [database connection]. | ||||
| 738 | ** <li> The application must not close the [database connection] specified by | ||||
| 739 | ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. | ||||
| 740 | ** <li> The application must not modify the SQL statement text passed into | ||||
| 741 | ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. | ||||
| 742 | ** <li> The application must not dereference the arrays or string pointers | ||||
| 743 | ** passed as the 3rd and 4th callback parameters after it returns. | ||||
| 744 | ** </ul> | ||||
| 745 | */ | ||||
| 746 | SQLITE_API int sqlite3_exec( | ||||
| 747 | sqlite3*, /* An open database */ | ||||
| 748 | const char *sql, /* SQL to be evaluated */ | ||||
| 749 | int (*callback)(void*,int,char**,char**), /* Callback function */ | ||||
| 750 | void *, /* 1st argument to callback */ | ||||
| 751 | char **errmsg /* Error msg written here */ | ||||
| 752 | ); | ||||
| 753 | |||||
| 754 | /* | ||||
| 755 | ** CAPI3REF: Result Codes | ||||
| 756 | ** KEYWORDS: {result code definitions} | ||||
| 757 | ** | ||||
| 758 | ** Many SQLite functions return an integer result code from the set shown | ||||
| 759 | ** here in order to indicate success or failure. | ||||
| 760 | ** | ||||
| 761 | ** New error codes may be added in future versions of SQLite. | ||||
| 762 | ** | ||||
| 763 | ** See also: [extended result code definitions] | ||||
| 764 | */ | ||||
| 765 | #define SQLITE_OK0 0 /* Successful result */ | ||||
| 766 | /* beginning-of-error-codes */ | ||||
| 767 | #define SQLITE_ERROR1 1 /* Generic error */ | ||||
| 768 | #define SQLITE_INTERNAL2 2 /* Internal logic error in SQLite */ | ||||
| 769 | #define SQLITE_PERM3 3 /* Access permission denied */ | ||||
| 770 | #define SQLITE_ABORT4 4 /* Callback routine requested an abort */ | ||||
| 771 | #define SQLITE_BUSY5 5 /* The database file is locked */ | ||||
| 772 | #define SQLITE_LOCKED6 6 /* A table in the database is locked */ | ||||
| 773 | #define SQLITE_NOMEM7 7 /* A malloc() failed */ | ||||
| 774 | #define SQLITE_READONLY8 8 /* Attempt to write a readonly database */ | ||||
| 775 | #define SQLITE_INTERRUPT9 9 /* Operation terminated by sqlite3_interrupt()*/ | ||||
| 776 | #define SQLITE_IOERR10 10 /* Some kind of disk I/O error occurred */ | ||||
| 777 | #define SQLITE_CORRUPT11 11 /* The database disk image is malformed */ | ||||
| 778 | #define SQLITE_NOTFOUND12 12 /* Unknown opcode in sqlite3_file_control() */ | ||||
| 779 | #define SQLITE_FULL13 13 /* Insertion failed because database is full */ | ||||
| 780 | #define SQLITE_CANTOPEN14 14 /* Unable to open the database file */ | ||||
| 781 | #define SQLITE_PROTOCOL15 15 /* Database lock protocol error */ | ||||
| 782 | #define SQLITE_EMPTY16 16 /* Internal use only */ | ||||
| 783 | #define SQLITE_SCHEMA17 17 /* The database schema changed */ | ||||
| 784 | #define SQLITE_TOOBIG18 18 /* String or BLOB exceeds size limit */ | ||||
| 785 | #define SQLITE_CONSTRAINT19 19 /* Abort due to constraint violation */ | ||||
| 786 | #define SQLITE_MISMATCH20 20 /* Data type mismatch */ | ||||
| 787 | #define SQLITE_MISUSE21 21 /* Library used incorrectly */ | ||||
| 788 | #define SQLITE_NOLFS22 22 /* Uses OS features not supported on host */ | ||||
| 789 | #define SQLITE_AUTH23 23 /* Authorization denied */ | ||||
| 790 | #define SQLITE_FORMAT24 24 /* Not used */ | ||||
| 791 | #define SQLITE_RANGE25 25 /* 2nd parameter to sqlite3_bind out of range */ | ||||
| 792 | #define SQLITE_NOTADB26 26 /* File opened that is not a database file */ | ||||
| 793 | #define SQLITE_NOTICE27 27 /* Notifications from sqlite3_log() */ | ||||
| 794 | #define SQLITE_WARNING28 28 /* Warnings from sqlite3_log() */ | ||||
| 795 | #define SQLITE_ROW100 100 /* sqlite3_step() has another row ready */ | ||||
| 796 | #define SQLITE_DONE101 101 /* sqlite3_step() has finished executing */ | ||||
| 797 | /* end-of-error-codes */ | ||||
| 798 | |||||
| 799 | /* | ||||
| 800 | ** CAPI3REF: Extended Result Codes | ||||
| 801 | ** KEYWORDS: {extended result code definitions} | ||||
| 802 | ** | ||||
| 803 | ** In its default configuration, SQLite API routines return one of 30 integer | ||||
| 804 | ** [result codes]. However, experience has shown that many of | ||||
| 805 | ** these result codes are too coarse-grained. They do not provide as | ||||
| 806 | ** much information about problems as programmers might like. In an effort to | ||||
| 807 | ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8] | ||||
| 808 | ** and later) include | ||||
| 809 | ** support for additional result codes that provide more detailed information | ||||
| 810 | ** about errors. These [extended result codes] are enabled or disabled | ||||
| 811 | ** on a per database connection basis using the | ||||
| 812 | ** [sqlite3_extended_result_codes()] API. Or, the extended code for | ||||
| 813 | ** the most recent error can be obtained using | ||||
| 814 | ** [sqlite3_extended_errcode()]. | ||||
| 815 | */ | ||||
| 816 | #define SQLITE_ERROR_MISSING_COLLSEQ(1 | (1<<8)) (SQLITE_ERROR1 | (1<<8)) | ||||
| 817 | #define SQLITE_ERROR_RETRY(1 | (2<<8)) (SQLITE_ERROR1 | (2<<8)) | ||||
| 818 | #define SQLITE_ERROR_SNAPSHOT(1 | (3<<8)) (SQLITE_ERROR1 | (3<<8)) | ||||
| 819 | #define SQLITE_IOERR_READ(10 | (1<<8)) (SQLITE_IOERR10 | (1<<8)) | ||||
| 820 | #define SQLITE_IOERR_SHORT_READ(10 | (2<<8)) (SQLITE_IOERR10 | (2<<8)) | ||||
| 821 | #define SQLITE_IOERR_WRITE(10 | (3<<8)) (SQLITE_IOERR10 | (3<<8)) | ||||
| 822 | #define SQLITE_IOERR_FSYNC(10 | (4<<8)) (SQLITE_IOERR10 | (4<<8)) | ||||
| 823 | #define SQLITE_IOERR_DIR_FSYNC(10 | (5<<8)) (SQLITE_IOERR10 | (5<<8)) | ||||
| 824 | #define SQLITE_IOERR_TRUNCATE(10 | (6<<8)) (SQLITE_IOERR10 | (6<<8)) | ||||
| 825 | #define SQLITE_IOERR_FSTAT(10 | (7<<8)) (SQLITE_IOERR10 | (7<<8)) | ||||
| 826 | #define SQLITE_IOERR_UNLOCK(10 | (8<<8)) (SQLITE_IOERR10 | (8<<8)) | ||||
| 827 | #define SQLITE_IOERR_RDLOCK(10 | (9<<8)) (SQLITE_IOERR10 | (9<<8)) | ||||
| 828 | #define SQLITE_IOERR_DELETE(10 | (10<<8)) (SQLITE_IOERR10 | (10<<8)) | ||||
| 829 | #define SQLITE_IOERR_BLOCKED(10 | (11<<8)) (SQLITE_IOERR10 | (11<<8)) | ||||
| 830 | #define SQLITE_IOERR_NOMEM(10 | (12<<8)) (SQLITE_IOERR10 | (12<<8)) | ||||
| 831 | #define SQLITE_IOERR_ACCESS(10 | (13<<8)) (SQLITE_IOERR10 | (13<<8)) | ||||
| 832 | #define SQLITE_IOERR_CHECKRESERVEDLOCK(10 | (14<<8)) (SQLITE_IOERR10 | (14<<8)) | ||||
| 833 | #define SQLITE_IOERR_LOCK(10 | (15<<8)) (SQLITE_IOERR10 | (15<<8)) | ||||
| 834 | #define SQLITE_IOERR_CLOSE(10 | (16<<8)) (SQLITE_IOERR10 | (16<<8)) | ||||
| 835 | #define SQLITE_IOERR_DIR_CLOSE(10 | (17<<8)) (SQLITE_IOERR10 | (17<<8)) | ||||
| 836 | #define SQLITE_IOERR_SHMOPEN(10 | (18<<8)) (SQLITE_IOERR10 | (18<<8)) | ||||
| 837 | #define SQLITE_IOERR_SHMSIZE(10 | (19<<8)) (SQLITE_IOERR10 | (19<<8)) | ||||
| 838 | #define SQLITE_IOERR_SHMLOCK(10 | (20<<8)) (SQLITE_IOERR10 | (20<<8)) | ||||
| 839 | #define SQLITE_IOERR_SHMMAP(10 | (21<<8)) (SQLITE_IOERR10 | (21<<8)) | ||||
| 840 | #define SQLITE_IOERR_SEEK(10 | (22<<8)) (SQLITE_IOERR10 | (22<<8)) | ||||
| 841 | #define SQLITE_IOERR_DELETE_NOENT(10 | (23<<8)) (SQLITE_IOERR10 | (23<<8)) | ||||
| 842 | #define SQLITE_IOERR_MMAP(10 | (24<<8)) (SQLITE_IOERR10 | (24<<8)) | ||||
| 843 | #define SQLITE_IOERR_GETTEMPPATH(10 | (25<<8)) (SQLITE_IOERR10 | (25<<8)) | ||||
| 844 | #define SQLITE_IOERR_CONVPATH(10 | (26<<8)) (SQLITE_IOERR10 | (26<<8)) | ||||
| 845 | #define SQLITE_IOERR_VNODE(10 | (27<<8)) (SQLITE_IOERR10 | (27<<8)) | ||||
| 846 | #define SQLITE_IOERR_AUTH(10 | (28<<8)) (SQLITE_IOERR10 | (28<<8)) | ||||
| 847 | #define SQLITE_IOERR_BEGIN_ATOMIC(10 | (29<<8)) (SQLITE_IOERR10 | (29<<8)) | ||||
| 848 | #define SQLITE_IOERR_COMMIT_ATOMIC(10 | (30<<8)) (SQLITE_IOERR10 | (30<<8)) | ||||
| 849 | #define SQLITE_IOERR_ROLLBACK_ATOMIC(10 | (31<<8)) (SQLITE_IOERR10 | (31<<8)) | ||||
| 850 | #define SQLITE_IOERR_DATA(10 | (32<<8)) (SQLITE_IOERR10 | (32<<8)) | ||||
| 851 | #define SQLITE_IOERR_CORRUPTFS(10 | (33<<8)) (SQLITE_IOERR10 | (33<<8)) | ||||
| 852 | #define SQLITE_IOERR_IN_PAGE(10 | (34<<8)) (SQLITE_IOERR10 | (34<<8)) | ||||
| 853 | #define SQLITE_LOCKED_SHAREDCACHE(6 | (1<<8)) (SQLITE_LOCKED6 | (1<<8)) | ||||
| 854 | #define SQLITE_LOCKED_VTAB(6 | (2<<8)) (SQLITE_LOCKED6 | (2<<8)) | ||||
| 855 | #define SQLITE_BUSY_RECOVERY(5 | (1<<8)) (SQLITE_BUSY5 | (1<<8)) | ||||
| 856 | #define SQLITE_BUSY_SNAPSHOT(5 | (2<<8)) (SQLITE_BUSY5 | (2<<8)) | ||||
| 857 | #define SQLITE_BUSY_TIMEOUT(5 | (3<<8)) (SQLITE_BUSY5 | (3<<8)) | ||||
| 858 | #define SQLITE_CANTOPEN_NOTEMPDIR(14 | (1<<8)) (SQLITE_CANTOPEN14 | (1<<8)) | ||||
| 859 | #define SQLITE_CANTOPEN_ISDIR(14 | (2<<8)) (SQLITE_CANTOPEN14 | (2<<8)) | ||||
| 860 | #define SQLITE_CANTOPEN_FULLPATH(14 | (3<<8)) (SQLITE_CANTOPEN14 | (3<<8)) | ||||
| 861 | #define SQLITE_CANTOPEN_CONVPATH(14 | (4<<8)) (SQLITE_CANTOPEN14 | (4<<8)) | ||||
| 862 | #define SQLITE_CANTOPEN_DIRTYWAL(14 | (5<<8)) (SQLITE_CANTOPEN14 | (5<<8)) /* Not Used */ | ||||
| 863 | #define SQLITE_CANTOPEN_SYMLINK(14 | (6<<8)) (SQLITE_CANTOPEN14 | (6<<8)) | ||||
| 864 | #define SQLITE_CORRUPT_VTAB(11 | (1<<8)) (SQLITE_CORRUPT11 | (1<<8)) | ||||
| 865 | #define SQLITE_CORRUPT_SEQUENCE(11 | (2<<8)) (SQLITE_CORRUPT11 | (2<<8)) | ||||
| 866 | #define SQLITE_CORRUPT_INDEX(11 | (3<<8)) (SQLITE_CORRUPT11 | (3<<8)) | ||||
| 867 | #define SQLITE_READONLY_RECOVERY(8 | (1<<8)) (SQLITE_READONLY8 | (1<<8)) | ||||
| 868 | #define SQLITE_READONLY_CANTLOCK(8 | (2<<8)) (SQLITE_READONLY8 | (2<<8)) | ||||
| 869 | #define SQLITE_READONLY_ROLLBACK(8 | (3<<8)) (SQLITE_READONLY8 | (3<<8)) | ||||
| 870 | #define SQLITE_READONLY_DBMOVED(8 | (4<<8)) (SQLITE_READONLY8 | (4<<8)) | ||||
| 871 | #define SQLITE_READONLY_CANTINIT(8 | (5<<8)) (SQLITE_READONLY8 | (5<<8)) | ||||
| 872 | #define SQLITE_READONLY_DIRECTORY(8 | (6<<8)) (SQLITE_READONLY8 | (6<<8)) | ||||
| 873 | #define SQLITE_ABORT_ROLLBACK(4 | (2<<8)) (SQLITE_ABORT4 | (2<<8)) | ||||
| 874 | #define SQLITE_CONSTRAINT_CHECK(19 | (1<<8)) (SQLITE_CONSTRAINT19 | (1<<8)) | ||||
| 875 | #define SQLITE_CONSTRAINT_COMMITHOOK(19 | (2<<8)) (SQLITE_CONSTRAINT19 | (2<<8)) | ||||
| 876 | #define SQLITE_CONSTRAINT_FOREIGNKEY(19 | (3<<8)) (SQLITE_CONSTRAINT19 | (3<<8)) | ||||
| 877 | #define SQLITE_CONSTRAINT_FUNCTION(19 | (4<<8)) (SQLITE_CONSTRAINT19 | (4<<8)) | ||||
| 878 | #define SQLITE_CONSTRAINT_NOTNULL(19 | (5<<8)) (SQLITE_CONSTRAINT19 | (5<<8)) | ||||
| 879 | #define SQLITE_CONSTRAINT_PRIMARYKEY(19 | (6<<8)) (SQLITE_CONSTRAINT19 | (6<<8)) | ||||
| 880 | #define SQLITE_CONSTRAINT_TRIGGER(19 | (7<<8)) (SQLITE_CONSTRAINT19 | (7<<8)) | ||||
| 881 | #define SQLITE_CONSTRAINT_UNIQUE(19 | (8<<8)) (SQLITE_CONSTRAINT19 | (8<<8)) | ||||
| 882 | #define SQLITE_CONSTRAINT_VTAB(19 | (9<<8)) (SQLITE_CONSTRAINT19 | (9<<8)) | ||||
| 883 | #define SQLITE_CONSTRAINT_ROWID(19 |(10<<8)) (SQLITE_CONSTRAINT19 |(10<<8)) | ||||
| 884 | #define SQLITE_CONSTRAINT_PINNED(19 |(11<<8)) (SQLITE_CONSTRAINT19 |(11<<8)) | ||||
| 885 | #define SQLITE_CONSTRAINT_DATATYPE(19 |(12<<8)) (SQLITE_CONSTRAINT19 |(12<<8)) | ||||
| 886 | #define SQLITE_NOTICE_RECOVER_WAL(27 | (1<<8)) (SQLITE_NOTICE27 | (1<<8)) | ||||
| 887 | #define SQLITE_NOTICE_RECOVER_ROLLBACK(27 | (2<<8)) (SQLITE_NOTICE27 | (2<<8)) | ||||
| 888 | #define SQLITE_NOTICE_RBU(27 | (3<<8)) (SQLITE_NOTICE27 | (3<<8)) | ||||
| 889 | #define SQLITE_WARNING_AUTOINDEX(28 | (1<<8)) (SQLITE_WARNING28 | (1<<8)) | ||||
| 890 | #define SQLITE_AUTH_USER(23 | (1<<8)) (SQLITE_AUTH23 | (1<<8)) | ||||
| 891 | #define SQLITE_OK_LOAD_PERMANENTLY(0 | (1<<8)) (SQLITE_OK0 | (1<<8)) | ||||
| 892 | #define SQLITE_OK_SYMLINK(0 | (2<<8)) (SQLITE_OK0 | (2<<8)) /* internal use only */ | ||||
| 893 | |||||
| 894 | /* | ||||
| 895 | ** CAPI3REF: Flags For File Open Operations | ||||
| 896 | ** | ||||
| 897 | ** These bit values are intended for use in the | ||||
| 898 | ** 3rd parameter to the [sqlite3_open_v2()] interface and | ||||
| 899 | ** in the 4th parameter to the [sqlite3_vfs.xOpen] method. | ||||
| 900 | ** | ||||
| 901 | ** Only those flags marked as "Ok for sqlite3_open_v2()" may be | ||||
| 902 | ** used as the third argument to the [sqlite3_open_v2()] interface. | ||||
| 903 | ** The other flags have historically been ignored by sqlite3_open_v2(), | ||||
| 904 | ** though future versions of SQLite might change so that an error is | ||||
| 905 | ** raised if any of the disallowed bits are passed into sqlite3_open_v2(). | ||||
| 906 | ** Applications should not depend on the historical behavior. | ||||
| 907 | ** | ||||
| 908 | ** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into | ||||
| 909 | ** [sqlite3_open_v2()] does *not* cause the underlying database file | ||||
| 910 | ** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into | ||||
| 911 | ** [sqlite3_open_v2()] has historically be a no-op and might become an | ||||
| 912 | ** error in future versions of SQLite. | ||||
| 913 | */ | ||||
| 914 | #define SQLITE_OPEN_READONLY0x00000001 0x00000001 /* Ok for sqlite3_open_v2() */ | ||||
| 915 | #define SQLITE_OPEN_READWRITE0x00000002 0x00000002 /* Ok for sqlite3_open_v2() */ | ||||
| 916 | #define SQLITE_OPEN_CREATE0x00000004 0x00000004 /* Ok for sqlite3_open_v2() */ | ||||
| 917 | #define SQLITE_OPEN_DELETEONCLOSE0x00000008 0x00000008 /* VFS only */ | ||||
| 918 | #define SQLITE_OPEN_EXCLUSIVE0x00000010 0x00000010 /* VFS only */ | ||||
| 919 | #define SQLITE_OPEN_AUTOPROXY0x00000020 0x00000020 /* VFS only */ | ||||
| 920 | #define SQLITE_OPEN_URI0x00000040 0x00000040 /* Ok for sqlite3_open_v2() */ | ||||
| 921 | #define SQLITE_OPEN_MEMORY0x00000080 0x00000080 /* Ok for sqlite3_open_v2() */ | ||||
| 922 | #define SQLITE_OPEN_MAIN_DB0x00000100 0x00000100 /* VFS only */ | ||||
| 923 | #define SQLITE_OPEN_TEMP_DB0x00000200 0x00000200 /* VFS only */ | ||||
| 924 | #define SQLITE_OPEN_TRANSIENT_DB0x00000400 0x00000400 /* VFS only */ | ||||
| 925 | #define SQLITE_OPEN_MAIN_JOURNAL0x00000800 0x00000800 /* VFS only */ | ||||
| 926 | #define SQLITE_OPEN_TEMP_JOURNAL0x00001000 0x00001000 /* VFS only */ | ||||
| 927 | #define SQLITE_OPEN_SUBJOURNAL0x00002000 0x00002000 /* VFS only */ | ||||
| 928 | #define SQLITE_OPEN_SUPER_JOURNAL0x00004000 0x00004000 /* VFS only */ | ||||
| 929 | #define SQLITE_OPEN_NOMUTEX0x00008000 0x00008000 /* Ok for sqlite3_open_v2() */ | ||||
| 930 | #define SQLITE_OPEN_FULLMUTEX0x00010000 0x00010000 /* Ok for sqlite3_open_v2() */ | ||||
| 931 | #define SQLITE_OPEN_SHAREDCACHE0x00020000 0x00020000 /* Ok for sqlite3_open_v2() */ | ||||
| 932 | #define SQLITE_OPEN_PRIVATECACHE0x00040000 0x00040000 /* Ok for sqlite3_open_v2() */ | ||||
| 933 | #define SQLITE_OPEN_WAL0x00080000 0x00080000 /* VFS only */ | ||||
| 934 | #define SQLITE_OPEN_NOFOLLOW0x01000000 0x01000000 /* Ok for sqlite3_open_v2() */ | ||||
| 935 | #define SQLITE_OPEN_EXRESCODE0x02000000 0x02000000 /* Extended result codes */ | ||||
| 936 | |||||
| 937 | /* Reserved: 0x00F00000 */ | ||||
| 938 | /* Legacy compatibility: */ | ||||
| 939 | #define SQLITE_OPEN_MASTER_JOURNAL0x00004000 0x00004000 /* VFS only */ | ||||
| 940 | |||||
| 941 | |||||
| 942 | /* | ||||
| 943 | ** CAPI3REF: Device Characteristics | ||||
| 944 | ** | ||||
| 945 | ** The xDeviceCharacteristics method of the [sqlite3_io_methods] | ||||
| 946 | ** object returns an integer which is a vector of these | ||||
| 947 | ** bit values expressing I/O characteristics of the mass storage | ||||
| 948 | ** device that holds the file that the [sqlite3_io_methods] | ||||
| 949 | ** refers to. | ||||
| 950 | ** | ||||
| 951 | ** The SQLITE_IOCAP_ATOMIC property means that all writes of | ||||
| 952 | ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values | ||||
| 953 | ** mean that writes of blocks that are nnn bytes in size and | ||||
| 954 | ** are aligned to an address which is an integer multiple of | ||||
| 955 | ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means | ||||
| 956 | ** that when data is appended to a file, the data is appended | ||||
| 957 | ** first then the size of the file is extended, never the other | ||||
| 958 | ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that | ||||
| 959 | ** information is written to disk in the same order as calls | ||||
| 960 | ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that | ||||
| 961 | ** after reboot following a crash or power loss, the only bytes in a | ||||
| 962 | ** file that were written at the application level might have changed | ||||
| 963 | ** and that adjacent bytes, even bytes within the same sector are | ||||
| 964 | ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | ||||
| 965 | ** flag indicates that a file cannot be deleted when open. The | ||||
| 966 | ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on | ||||
| 967 | ** read-only media and cannot be changed even by processes with | ||||
| 968 | ** elevated privileges. | ||||
| 969 | ** | ||||
| 970 | ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying | ||||
| 971 | ** filesystem supports doing multiple write operations atomically when those | ||||
| 972 | ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and | ||||
| 973 | ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. | ||||
| 974 | ** | ||||
| 975 | ** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read | ||||
| 976 | ** from the database file in amounts that are not a multiple of the | ||||
| 977 | ** page size and that do not begin at a page boundary. Without this | ||||
| 978 | ** property, SQLite is careful to only do full-page reads and write | ||||
| 979 | ** on aligned pages, with the one exception that it will do a sub-page | ||||
| 980 | ** read of the first page to access the database header. | ||||
| 981 | */ | ||||
| 982 | #define SQLITE_IOCAP_ATOMIC0x00000001 0x00000001 | ||||
| 983 | #define SQLITE_IOCAP_ATOMIC5120x00000002 0x00000002 | ||||
| 984 | #define SQLITE_IOCAP_ATOMIC1K0x00000004 0x00000004 | ||||
| 985 | #define SQLITE_IOCAP_ATOMIC2K0x00000008 0x00000008 | ||||
| 986 | #define SQLITE_IOCAP_ATOMIC4K0x00000010 0x00000010 | ||||
| 987 | #define SQLITE_IOCAP_ATOMIC8K0x00000020 0x00000020 | ||||
| 988 | #define SQLITE_IOCAP_ATOMIC16K0x00000040 0x00000040 | ||||
| 989 | #define SQLITE_IOCAP_ATOMIC32K0x00000080 0x00000080 | ||||
| 990 | #define SQLITE_IOCAP_ATOMIC64K0x00000100 0x00000100 | ||||
| 991 | #define SQLITE_IOCAP_SAFE_APPEND0x00000200 0x00000200 | ||||
| 992 | #define SQLITE_IOCAP_SEQUENTIAL0x00000400 0x00000400 | ||||
| 993 | #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN0x00000800 0x00000800 | ||||
| 994 | #define SQLITE_IOCAP_POWERSAFE_OVERWRITE0x00001000 0x00001000 | ||||
| 995 | #define SQLITE_IOCAP_IMMUTABLE0x00002000 0x00002000 | ||||
| 996 | #define SQLITE_IOCAP_BATCH_ATOMIC0x00004000 0x00004000 | ||||
| 997 | #define SQLITE_IOCAP_SUBPAGE_READ0x00008000 0x00008000 | ||||
| 998 | |||||
| 999 | /* | ||||
| 1000 | ** CAPI3REF: File Locking Levels | ||||
| 1001 | ** | ||||
| 1002 | ** SQLite uses one of these integer values as the second | ||||
| 1003 | ** argument to calls it makes to the xLock() and xUnlock() methods | ||||
| 1004 | ** of an [sqlite3_io_methods] object. These values are ordered from | ||||
| 1005 | ** lest restrictive to most restrictive. | ||||
| 1006 | ** | ||||
| 1007 | ** The argument to xLock() is always SHARED or higher. The argument to | ||||
| 1008 | ** xUnlock is either SHARED or NONE. | ||||
| 1009 | */ | ||||
| 1010 | #define SQLITE_LOCK_NONE0 0 /* xUnlock() only */ | ||||
| 1011 | #define SQLITE_LOCK_SHARED1 1 /* xLock() or xUnlock() */ | ||||
| 1012 | #define SQLITE_LOCK_RESERVED2 2 /* xLock() only */ | ||||
| 1013 | #define SQLITE_LOCK_PENDING3 3 /* xLock() only */ | ||||
| 1014 | #define SQLITE_LOCK_EXCLUSIVE4 4 /* xLock() only */ | ||||
| 1015 | |||||
| 1016 | /* | ||||
| 1017 | ** CAPI3REF: Synchronization Type Flags | ||||
| 1018 | ** | ||||
| 1019 | ** When SQLite invokes the xSync() method of an | ||||
| 1020 | ** [sqlite3_io_methods] object it uses a combination of | ||||
| 1021 | ** these integer values as the second argument. | ||||
| 1022 | ** | ||||
| 1023 | ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the | ||||
| 1024 | ** sync operation only needs to flush data to mass storage. Inode | ||||
| 1025 | ** information need not be flushed. If the lower four bits of the flag | ||||
| 1026 | ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. | ||||
| 1027 | ** If the lower four bits equal SQLITE_SYNC_FULL, that means | ||||
| 1028 | ** to use Mac OS X style fullsync instead of fsync(). | ||||
| 1029 | ** | ||||
| 1030 | ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags | ||||
| 1031 | ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL | ||||
| 1032 | ** settings. The [synchronous pragma] determines when calls to the | ||||
| 1033 | ** xSync VFS method occur and applies uniformly across all platforms. | ||||
| 1034 | ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how | ||||
| 1035 | ** energetic or rigorous or forceful the sync operations are and | ||||
| 1036 | ** only make a difference on Mac OSX for the default SQLite code. | ||||
| 1037 | ** (Third-party VFS implementations might also make the distinction | ||||
| 1038 | ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the | ||||
| 1039 | ** operating systems natively supported by SQLite, only Mac OSX | ||||
| 1040 | ** cares about the difference.) | ||||
| 1041 | */ | ||||
| 1042 | #define SQLITE_SYNC_NORMAL0x00002 0x00002 | ||||
| 1043 | #define SQLITE_SYNC_FULL0x00003 0x00003 | ||||
| 1044 | #define SQLITE_SYNC_DATAONLY0x00010 0x00010 | ||||
| 1045 | |||||
| 1046 | /* | ||||
| 1047 | ** CAPI3REF: OS Interface Open File Handle | ||||
| 1048 | ** | ||||
| 1049 | ** An [sqlite3_file] object represents an open file in the | ||||
| 1050 | ** [sqlite3_vfs | OS interface layer]. Individual OS interface | ||||
| 1051 | ** implementations will | ||||
| 1052 | ** want to subclass this object by appending additional fields | ||||
| 1053 | ** for their own use. The pMethods entry is a pointer to an | ||||
| 1054 | ** [sqlite3_io_methods] object that defines methods for performing | ||||
| 1055 | ** I/O operations on the open file. | ||||
| 1056 | */ | ||||
| 1057 | typedef struct sqlite3_file sqlite3_file; | ||||
| 1058 | struct sqlite3_file { | ||||
| 1059 | const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ | ||||
| 1060 | }; | ||||
| 1061 | |||||
| 1062 | /* | ||||
| 1063 | ** CAPI3REF: OS Interface File Virtual Methods Object | ||||
| 1064 | ** | ||||
| 1065 | ** Every file opened by the [sqlite3_vfs.xOpen] method populates an | ||||
| 1066 | ** [sqlite3_file] object (or, more commonly, a subclass of the | ||||
| 1067 | ** [sqlite3_file] object) with a pointer to an instance of this object. | ||||
| 1068 | ** This object defines the methods used to perform various operations | ||||
| 1069 | ** against the open file represented by the [sqlite3_file] object. | ||||
| 1070 | ** | ||||
| 1071 | ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element | ||||
| 1072 | ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method | ||||
| 1073 | ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The | ||||
| 1074 | ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] | ||||
| 1075 | ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element | ||||
| 1076 | ** to NULL. | ||||
| 1077 | ** | ||||
| 1078 | ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or | ||||
| 1079 | ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). | ||||
| 1080 | ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] | ||||
| 1081 | ** flag may be ORed in to indicate that only the data of the file | ||||
| 1082 | ** and not its inode needs to be synced. | ||||
| 1083 | ** | ||||
| 1084 | ** The integer values to xLock() and xUnlock() are one of | ||||
| 1085 | ** <ul> | ||||
| 1086 | ** <li> [SQLITE_LOCK_NONE], | ||||
| 1087 | ** <li> [SQLITE_LOCK_SHARED], | ||||
| 1088 | ** <li> [SQLITE_LOCK_RESERVED], | ||||
| 1089 | ** <li> [SQLITE_LOCK_PENDING], or | ||||
| 1090 | ** <li> [SQLITE_LOCK_EXCLUSIVE]. | ||||
| 1091 | ** </ul> | ||||
| 1092 | ** xLock() upgrades the database file lock. In other words, xLock() moves the | ||||
| 1093 | ** database file lock in the direction NONE toward EXCLUSIVE. The argument to | ||||
| 1094 | ** xLock() is always one of SHARED, RESERVED, PENDING, or EXCLUSIVE, never | ||||
| 1095 | ** SQLITE_LOCK_NONE. If the database file lock is already at or above the | ||||
| 1096 | ** requested lock, then the call to xLock() is a no-op. | ||||
| 1097 | ** xUnlock() downgrades the database file lock to either SHARED or NONE. | ||||
| 1098 | ** If the lock is already at or below the requested lock state, then the call | ||||
| 1099 | ** to xUnlock() is a no-op. | ||||
| 1100 | ** The xCheckReservedLock() method checks whether any database connection, | ||||
| 1101 | ** either in this process or in some other process, is holding a RESERVED, | ||||
| 1102 | ** PENDING, or EXCLUSIVE lock on the file. It returns, via its output | ||||
| 1103 | ** pointer parameter, true if such a lock exists and false otherwise. | ||||
| 1104 | ** | ||||
| 1105 | ** The xFileControl() method is a generic interface that allows custom | ||||
| 1106 | ** VFS implementations to directly control an open file using the | ||||
| 1107 | ** [sqlite3_file_control()] interface. The second "op" argument is an | ||||
| 1108 | ** integer opcode. The third argument is a generic pointer intended to | ||||
| 1109 | ** point to a structure that may contain arguments or space in which to | ||||
| 1110 | ** write return values. Potential uses for xFileControl() might be | ||||
| 1111 | ** functions to enable blocking locks with timeouts, to change the | ||||
| 1112 | ** locking strategy (for example to use dot-file locks), to inquire | ||||
| 1113 | ** about the status of a lock, or to break stale locks. The SQLite | ||||
| 1114 | ** core reserves all opcodes less than 100 for its own use. | ||||
| 1115 | ** A [file control opcodes | list of opcodes] less than 100 is available. | ||||
| 1116 | ** Applications that define a custom xFileControl method should use opcodes | ||||
| 1117 | ** greater than 100 to avoid conflicts. VFS implementations should | ||||
| 1118 | ** return [SQLITE_NOTFOUND] for file control opcodes that they do not | ||||
| 1119 | ** recognize. | ||||
| 1120 | ** | ||||
| 1121 | ** The xSectorSize() method returns the sector size of the | ||||
| 1122 | ** device that underlies the file. The sector size is the | ||||
| 1123 | ** minimum write that can be performed without disturbing | ||||
| 1124 | ** other bytes in the file. The xDeviceCharacteristics() | ||||
| 1125 | ** method returns a bit vector describing behaviors of the | ||||
| 1126 | ** underlying device: | ||||
| 1127 | ** | ||||
| 1128 | ** <ul> | ||||
| 1129 | ** <li> [SQLITE_IOCAP_ATOMIC] | ||||
| 1130 | ** <li> [SQLITE_IOCAP_ATOMIC512] | ||||
| 1131 | ** <li> [SQLITE_IOCAP_ATOMIC1K] | ||||
| 1132 | ** <li> [SQLITE_IOCAP_ATOMIC2K] | ||||
| 1133 | ** <li> [SQLITE_IOCAP_ATOMIC4K] | ||||
| 1134 | ** <li> [SQLITE_IOCAP_ATOMIC8K] | ||||
| 1135 | ** <li> [SQLITE_IOCAP_ATOMIC16K] | ||||
| 1136 | ** <li> [SQLITE_IOCAP_ATOMIC32K] | ||||
| 1137 | ** <li> [SQLITE_IOCAP_ATOMIC64K] | ||||
| 1138 | ** <li> [SQLITE_IOCAP_SAFE_APPEND] | ||||
| 1139 | ** <li> [SQLITE_IOCAP_SEQUENTIAL] | ||||
| 1140 | ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] | ||||
| 1141 | ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] | ||||
| 1142 | ** <li> [SQLITE_IOCAP_IMMUTABLE] | ||||
| 1143 | ** <li> [SQLITE_IOCAP_BATCH_ATOMIC] | ||||
| 1144 | ** <li> [SQLITE_IOCAP_SUBPAGE_READ] | ||||
| 1145 | ** </ul> | ||||
| 1146 | ** | ||||
| 1147 | ** The SQLITE_IOCAP_ATOMIC property means that all writes of | ||||
| 1148 | ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values | ||||
| 1149 | ** mean that writes of blocks that are nnn bytes in size and | ||||
| 1150 | ** are aligned to an address which is an integer multiple of | ||||
| 1151 | ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means | ||||
| 1152 | ** that when data is appended to a file, the data is appended | ||||
| 1153 | ** first then the size of the file is extended, never the other | ||||
| 1154 | ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that | ||||
| 1155 | ** information is written to disk in the same order as calls | ||||
| 1156 | ** to xWrite(). | ||||
| 1157 | ** | ||||
| 1158 | ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill | ||||
| 1159 | ** in the unread portions of the buffer with zeros. A VFS that | ||||
| 1160 | ** fails to zero-fill short reads might seem to work. However, | ||||
| 1161 | ** failure to zero-fill short reads will eventually lead to | ||||
| 1162 | ** database corruption. | ||||
| 1163 | */ | ||||
| 1164 | typedef struct sqlite3_io_methods sqlite3_io_methods; | ||||
| 1165 | struct sqlite3_io_methods { | ||||
| 1166 | int iVersion; | ||||
| 1167 | int (*xClose)(sqlite3_file*); | ||||
| 1168 | int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); | ||||
| 1169 | int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); | ||||
| 1170 | int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); | ||||
| 1171 | int (*xSync)(sqlite3_file*, int flags); | ||||
| 1172 | int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); | ||||
| 1173 | int (*xLock)(sqlite3_file*, int); | ||||
| 1174 | int (*xUnlock)(sqlite3_file*, int); | ||||
| 1175 | int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); | ||||
| 1176 | int (*xFileControl)(sqlite3_file*, int op, void *pArg); | ||||
| 1177 | int (*xSectorSize)(sqlite3_file*); | ||||
| 1178 | int (*xDeviceCharacteristics)(sqlite3_file*); | ||||
| 1179 | /* Methods above are valid for version 1 */ | ||||
| 1180 | int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); | ||||
| 1181 | int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); | ||||
| 1182 | void (*xShmBarrier)(sqlite3_file*); | ||||
| 1183 | int (*xShmUnmap)(sqlite3_file*, int deleteFlag); | ||||
| 1184 | /* Methods above are valid for version 2 */ | ||||
| 1185 | int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); | ||||
| 1186 | int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); | ||||
| 1187 | /* Methods above are valid for version 3 */ | ||||
| 1188 | /* Additional methods may be added in future releases */ | ||||
| 1189 | }; | ||||
| 1190 | |||||
| 1191 | /* | ||||
| 1192 | ** CAPI3REF: Standard File Control Opcodes | ||||
| 1193 | ** KEYWORDS: {file control opcodes} {file control opcode} | ||||
| 1194 | ** | ||||
| 1195 | ** These integer constants are opcodes for the xFileControl method | ||||
| 1196 | ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] | ||||
| 1197 | ** interface. | ||||
| 1198 | ** | ||||
| 1199 | ** <ul> | ||||
| 1200 | ** <li>[[SQLITE_FCNTL_LOCKSTATE]] | ||||
| 1201 | ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This | ||||
| 1202 | ** opcode causes the xFileControl method to write the current state of | ||||
| 1203 | ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], | ||||
| 1204 | ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) | ||||
| 1205 | ** into an integer that the pArg argument points to. | ||||
| 1206 | ** This capability is only available if SQLite is compiled with [SQLITE_DEBUG]. | ||||
| 1207 | ** | ||||
| 1208 | ** <li>[[SQLITE_FCNTL_SIZE_HINT]] | ||||
| 1209 | ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS | ||||
| 1210 | ** layer a hint of how large the database file will grow to be during the | ||||
| 1211 | ** current transaction. This hint is not guaranteed to be accurate but it | ||||
| 1212 | ** is often close. The underlying VFS might choose to preallocate database | ||||
| 1213 | ** file space based on this hint in order to help writes to the database | ||||
| 1214 | ** file run faster. | ||||
| 1215 | ** | ||||
| 1216 | ** <li>[[SQLITE_FCNTL_SIZE_LIMIT]] | ||||
| 1217 | ** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that | ||||
| 1218 | ** implements [sqlite3_deserialize()] to set an upper bound on the size | ||||
| 1219 | ** of the in-memory database. The argument is a pointer to a [sqlite3_int64]. | ||||
| 1220 | ** If the integer pointed to is negative, then it is filled in with the | ||||
| 1221 | ** current limit. Otherwise the limit is set to the larger of the value | ||||
| 1222 | ** of the integer pointed to and the current database size. The integer | ||||
| 1223 | ** pointed to is set to the new limit. | ||||
| 1224 | ** | ||||
| 1225 | ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]] | ||||
| 1226 | ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS | ||||
| 1227 | ** extends and truncates the database file in chunks of a size specified | ||||
| 1228 | ** by the user. The fourth argument to [sqlite3_file_control()] should | ||||
| 1229 | ** point to an integer (type int) containing the new chunk-size to use | ||||
| 1230 | ** for the nominated database. Allocating database file space in large | ||||
| 1231 | ** chunks (say 1MB at a time), may reduce file-system fragmentation and | ||||
| 1232 | ** improve performance on some systems. | ||||
| 1233 | ** | ||||
| 1234 | ** <li>[[SQLITE_FCNTL_FILE_POINTER]] | ||||
| 1235 | ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer | ||||
| 1236 | ** to the [sqlite3_file] object associated with a particular database | ||||
| 1237 | ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. | ||||
| 1238 | ** | ||||
| 1239 | ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]] | ||||
| 1240 | ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer | ||||
| 1241 | ** to the [sqlite3_file] object associated with the journal file (either | ||||
| 1242 | ** the [rollback journal] or the [write-ahead log]) for a particular database | ||||
| 1243 | ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. | ||||
| 1244 | ** | ||||
| 1245 | ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]] | ||||
| 1246 | ** No longer in use. | ||||
| 1247 | ** | ||||
| 1248 | ** <li>[[SQLITE_FCNTL_SYNC]] | ||||
| 1249 | ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and | ||||
| 1250 | ** sent to the VFS immediately before the xSync method is invoked on a | ||||
| 1251 | ** database file descriptor. Or, if the xSync method is not invoked | ||||
| 1252 | ** because the user has configured SQLite with | ||||
| 1253 | ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place | ||||
| 1254 | ** of the xSync method. In most cases, the pointer argument passed with | ||||
| 1255 | ** this file-control is NULL. However, if the database file is being synced | ||||
| 1256 | ** as part of a multi-database commit, the argument points to a nul-terminated | ||||
| 1257 | ** string containing the transactions super-journal file name. VFSes that | ||||
| 1258 | ** do not need this signal should silently ignore this opcode. Applications | ||||
| 1259 | ** should not call [sqlite3_file_control()] with this opcode as doing so may | ||||
| 1260 | ** disrupt the operation of the specialized VFSes that do require it. | ||||
| 1261 | ** | ||||
| 1262 | ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]] | ||||
| 1263 | ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite | ||||
| 1264 | ** and sent to the VFS after a transaction has been committed immediately | ||||
| 1265 | ** but before the database is unlocked. VFSes that do not need this signal | ||||
| 1266 | ** should silently ignore this opcode. Applications should not call | ||||
| 1267 | ** [sqlite3_file_control()] with this opcode as doing so may disrupt the | ||||
| 1268 | ** operation of the specialized VFSes that do require it. | ||||
| 1269 | ** | ||||
| 1270 | ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]] | ||||
| 1271 | ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic | ||||
| 1272 | ** retry counts and intervals for certain disk I/O operations for the | ||||
| 1273 | ** windows [VFS] in order to provide robustness in the presence of | ||||
| 1274 | ** anti-virus programs. By default, the windows VFS will retry file read, | ||||
| 1275 | ** file write, and file delete operations up to 10 times, with a delay | ||||
| 1276 | ** of 25 milliseconds before the first retry and with the delay increasing | ||||
| 1277 | ** by an additional 25 milliseconds with each subsequent retry. This | ||||
| 1278 | ** opcode allows these two values (10 retries and 25 milliseconds of delay) | ||||
| 1279 | ** to be adjusted. The values are changed for all database connections | ||||
| 1280 | ** within the same process. The argument is a pointer to an array of two | ||||
| 1281 | ** integers where the first integer is the new retry count and the second | ||||
| 1282 | ** integer is the delay. If either integer is negative, then the setting | ||||
| 1283 | ** is not changed but instead the prior value of that setting is written | ||||
| 1284 | ** into the array entry, allowing the current retry settings to be | ||||
| 1285 | ** interrogated. The zDbName parameter is ignored. | ||||
| 1286 | ** | ||||
| 1287 | ** <li>[[SQLITE_FCNTL_PERSIST_WAL]] | ||||
| 1288 | ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the | ||||
| 1289 | ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary | ||||
| 1290 | ** write ahead log ([WAL file]) and shared memory | ||||
| 1291 | ** files used for transaction control | ||||
| 1292 | ** are automatically deleted when the latest connection to the database | ||||
| 1293 | ** closes. Setting persistent WAL mode causes those files to persist after | ||||
| 1294 | ** close. Persisting the files is useful when other processes that do not | ||||
| 1295 | ** have write permission on the directory containing the database file want | ||||
| 1296 | ** to read the database file, as the WAL and shared memory files must exist | ||||
| 1297 | ** in order for the database to be readable. The fourth parameter to | ||||
| 1298 | ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. | ||||
| 1299 | ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent | ||||
| 1300 | ** WAL mode. If the integer is -1, then it is overwritten with the current | ||||
| 1301 | ** WAL persistence setting. | ||||
| 1302 | ** | ||||
| 1303 | ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] | ||||
| 1304 | ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the | ||||
| 1305 | ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting | ||||
| 1306 | ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the | ||||
| 1307 | ** xDeviceCharacteristics methods. The fourth parameter to | ||||
| 1308 | ** [sqlite3_file_control()] for this opcode should be a pointer to an integer. | ||||
| 1309 | ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage | ||||
| 1310 | ** mode. If the integer is -1, then it is overwritten with the current | ||||
| 1311 | ** zero-damage mode setting. | ||||
| 1312 | ** | ||||
| 1313 | ** <li>[[SQLITE_FCNTL_OVERWRITE]] | ||||
| 1314 | ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening | ||||
| 1315 | ** a write transaction to indicate that, unless it is rolled back for some | ||||
| 1316 | ** reason, the entire database file will be overwritten by the current | ||||
| 1317 | ** transaction. This is used by VACUUM operations. | ||||
| 1318 | ** | ||||
| 1319 | ** <li>[[SQLITE_FCNTL_VFSNAME]] | ||||
| 1320 | ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of | ||||
| 1321 | ** all [VFSes] in the VFS stack. The names are of all VFS shims and the | ||||
| 1322 | ** final bottom-level VFS are written into memory obtained from | ||||
| 1323 | ** [sqlite3_malloc()] and the result is stored in the char* variable | ||||
| 1324 | ** that the fourth parameter of [sqlite3_file_control()] points to. | ||||
| 1325 | ** The caller is responsible for freeing the memory when done. As with | ||||
| 1326 | ** all file-control actions, there is no guarantee that this will actually | ||||
| 1327 | ** do anything. Callers should initialize the char* variable to a NULL | ||||
| 1328 | ** pointer in case this file-control is not implemented. This file-control | ||||
| 1329 | ** is intended for diagnostic use only. | ||||
| 1330 | ** | ||||
| 1331 | ** <li>[[SQLITE_FCNTL_VFS_POINTER]] | ||||
| 1332 | ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level | ||||
| 1333 | ** [VFSes] currently in use. ^(The argument X in | ||||
| 1334 | ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be | ||||
| 1335 | ** of type "[sqlite3_vfs] **". This opcodes will set *X | ||||
| 1336 | ** to a pointer to the top-level VFS.)^ | ||||
| 1337 | ** ^When there are multiple VFS shims in the stack, this opcode finds the | ||||
| 1338 | ** upper-most shim only. | ||||
| 1339 | ** | ||||
| 1340 | ** <li>[[SQLITE_FCNTL_PRAGMA]] | ||||
| 1341 | ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] | ||||
| 1342 | ** file control is sent to the open [sqlite3_file] object corresponding | ||||
| 1343 | ** to the database file to which the pragma statement refers. ^The argument | ||||
| 1344 | ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of | ||||
| 1345 | ** pointers to strings (char**) in which the second element of the array | ||||
| 1346 | ** is the name of the pragma and the third element is the argument to the | ||||
| 1347 | ** pragma or NULL if the pragma has no argument. ^The handler for an | ||||
| 1348 | ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element | ||||
| 1349 | ** of the char** argument point to a string obtained from [sqlite3_mprintf()] | ||||
| 1350 | ** or the equivalent and that string will become the result of the pragma or | ||||
| 1351 | ** the error message if the pragma fails. ^If the | ||||
| 1352 | ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal | ||||
| 1353 | ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] | ||||
| 1354 | ** file control returns [SQLITE_OK], then the parser assumes that the | ||||
| 1355 | ** VFS has handled the PRAGMA itself and the parser generates a no-op | ||||
| 1356 | ** prepared statement if result string is NULL, or that returns a copy | ||||
| 1357 | ** of the result string if the string is non-NULL. | ||||
| 1358 | ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns | ||||
| 1359 | ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means | ||||
| 1360 | ** that the VFS encountered an error while handling the [PRAGMA] and the | ||||
| 1361 | ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] | ||||
| 1362 | ** file control occurs at the beginning of pragma statement analysis and so | ||||
| 1363 | ** it is able to override built-in [PRAGMA] statements. | ||||
| 1364 | ** | ||||
| 1365 | ** <li>[[SQLITE_FCNTL_BUSYHANDLER]] | ||||
| 1366 | ** ^The [SQLITE_FCNTL_BUSYHANDLER] | ||||
| 1367 | ** file-control may be invoked by SQLite on the database file handle | ||||
| 1368 | ** shortly after it is opened in order to provide a custom VFS with access | ||||
| 1369 | ** to the connection's busy-handler callback. The argument is of type (void**) | ||||
| 1370 | ** - an array of two (void *) values. The first (void *) actually points | ||||
| 1371 | ** to a function of type (int (*)(void *)). In order to invoke the connection's | ||||
| 1372 | ** busy-handler, this function should be invoked with the second (void *) in | ||||
| 1373 | ** the array as the only argument. If it returns non-zero, then the operation | ||||
| 1374 | ** should be retried. If it returns zero, the custom VFS should abandon the | ||||
| 1375 | ** current operation. | ||||
| 1376 | ** | ||||
| 1377 | ** <li>[[SQLITE_FCNTL_TEMPFILENAME]] | ||||
| 1378 | ** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control | ||||
| 1379 | ** to have SQLite generate a | ||||
| 1380 | ** temporary filename using the same algorithm that is followed to generate | ||||
| 1381 | ** temporary filenames for TEMP tables and other internal uses. The | ||||
| 1382 | ** argument should be a char** which will be filled with the filename | ||||
| 1383 | ** written into memory obtained from [sqlite3_malloc()]. The caller should | ||||
| 1384 | ** invoke [sqlite3_free()] on the result to avoid a memory leak. | ||||
| 1385 | ** | ||||
| 1386 | ** <li>[[SQLITE_FCNTL_MMAP_SIZE]] | ||||
| 1387 | ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the | ||||
| 1388 | ** maximum number of bytes that will be used for memory-mapped I/O. | ||||
| 1389 | ** The argument is a pointer to a value of type sqlite3_int64 that | ||||
| 1390 | ** is an advisory maximum number of bytes in the file to memory map. The | ||||
| 1391 | ** pointer is overwritten with the old value. The limit is not changed if | ||||
| 1392 | ** the value originally pointed to is negative, and so the current limit | ||||
| 1393 | ** can be queried by passing in a pointer to a negative number. This | ||||
| 1394 | ** file-control is used internally to implement [PRAGMA mmap_size]. | ||||
| 1395 | ** | ||||
| 1396 | ** <li>[[SQLITE_FCNTL_TRACE]] | ||||
| 1397 | ** The [SQLITE_FCNTL_TRACE] file control provides advisory information | ||||
| 1398 | ** to the VFS about what the higher layers of the SQLite stack are doing. | ||||
| 1399 | ** This file control is used by some VFS activity tracing [shims]. | ||||
| 1400 | ** The argument is a zero-terminated string. Higher layers in the | ||||
| 1401 | ** SQLite stack may generate instances of this file control if | ||||
| 1402 | ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled. | ||||
| 1403 | ** | ||||
| 1404 | ** <li>[[SQLITE_FCNTL_HAS_MOVED]] | ||||
| 1405 | ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a | ||||
| 1406 | ** pointer to an integer and it writes a boolean into that integer depending | ||||
| 1407 | ** on whether or not the file has been renamed, moved, or deleted since it | ||||
| 1408 | ** was first opened. | ||||
| 1409 | ** | ||||
| 1410 | ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]] | ||||
| 1411 | ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the | ||||
| 1412 | ** underlying native file handle associated with a file handle. This file | ||||
| 1413 | ** control interprets its argument as a pointer to a native file handle and | ||||
| 1414 | ** writes the resulting value there. | ||||
| 1415 | ** | ||||
| 1416 | ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]] | ||||
| 1417 | ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This | ||||
| 1418 | ** opcode causes the xFileControl method to swap the file handle with the one | ||||
| 1419 | ** pointed to by the pArg argument. This capability is used during testing | ||||
| 1420 | ** and only needs to be supported when SQLITE_TEST is defined. | ||||
| 1421 | ** | ||||
| 1422 | ** <li>[[SQLITE_FCNTL_NULL_IO]] | ||||
| 1423 | ** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor | ||||
| 1424 | ** or file handle for the [sqlite3_file] object such that it will no longer | ||||
| 1425 | ** read or write to the database file. | ||||
| 1426 | ** | ||||
| 1427 | ** <li>[[SQLITE_FCNTL_WAL_BLOCK]] | ||||
| 1428 | ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might | ||||
| 1429 | ** be advantageous to block on the next WAL lock if the lock is not immediately | ||||
| 1430 | ** available. The WAL subsystem issues this signal during rare | ||||
| 1431 | ** circumstances in order to fix a problem with priority inversion. | ||||
| 1432 | ** Applications should <em>not</em> use this file-control. | ||||
| 1433 | ** | ||||
| 1434 | ** <li>[[SQLITE_FCNTL_ZIPVFS]] | ||||
| 1435 | ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other | ||||
| 1436 | ** VFS should return SQLITE_NOTFOUND for this opcode. | ||||
| 1437 | ** | ||||
| 1438 | ** <li>[[SQLITE_FCNTL_RBU]] | ||||
| 1439 | ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by | ||||
| 1440 | ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for | ||||
| 1441 | ** this opcode. | ||||
| 1442 | ** | ||||
| 1443 | ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]] | ||||
| 1444 | ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then | ||||
| 1445 | ** the file descriptor is placed in "batch write mode", which | ||||
| 1446 | ** means all subsequent write operations will be deferred and done | ||||
| 1447 | ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems | ||||
| 1448 | ** that do not support batch atomic writes will return SQLITE_NOTFOUND. | ||||
| 1449 | ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to | ||||
| 1450 | ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or | ||||
| 1451 | ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make | ||||
| 1452 | ** no VFS interface calls on the same [sqlite3_file] file descriptor | ||||
| 1453 | ** except for calls to the xWrite method and the xFileControl method | ||||
| 1454 | ** with [SQLITE_FCNTL_SIZE_HINT]. | ||||
| 1455 | ** | ||||
| 1456 | ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]] | ||||
| 1457 | ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write | ||||
| 1458 | ** operations since the previous successful call to | ||||
| 1459 | ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically. | ||||
| 1460 | ** This file control returns [SQLITE_OK] if and only if the writes were | ||||
| 1461 | ** all performed successfully and have been committed to persistent storage. | ||||
| 1462 | ** ^Regardless of whether or not it is successful, this file control takes | ||||
| 1463 | ** the file descriptor out of batch write mode so that all subsequent | ||||
| 1464 | ** write operations are independent. | ||||
| 1465 | ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without | ||||
| 1466 | ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. | ||||
| 1467 | ** | ||||
| 1468 | ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]] | ||||
| 1469 | ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write | ||||
| 1470 | ** operations since the previous successful call to | ||||
| 1471 | ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back. | ||||
| 1472 | ** ^This file control takes the file descriptor out of batch write mode | ||||
| 1473 | ** so that all subsequent write operations are independent. | ||||
| 1474 | ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without | ||||
| 1475 | ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. | ||||
| 1476 | ** | ||||
| 1477 | ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]] | ||||
| 1478 | ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS | ||||
| 1479 | ** to block for up to M milliseconds before failing when attempting to | ||||
| 1480 | ** obtain a file lock using the xLock or xShmLock methods of the VFS. | ||||
| 1481 | ** The parameter is a pointer to a 32-bit signed integer that contains | ||||
| 1482 | ** the value that M is to be set to. Before returning, the 32-bit signed | ||||
| 1483 | ** integer is overwritten with the previous value of M. | ||||
| 1484 | ** | ||||
| 1485 | ** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]] | ||||
| 1486 | ** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the | ||||
| 1487 | ** VFS to block when taking a SHARED lock to connect to a wal mode database. | ||||
| 1488 | ** This is used to implement the functionality associated with | ||||
| 1489 | ** SQLITE_SETLK_BLOCK_ON_CONNECT. | ||||
| 1490 | ** | ||||
| 1491 | ** <li>[[SQLITE_FCNTL_DATA_VERSION]] | ||||
| 1492 | ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to | ||||
| 1493 | ** a database file. The argument is a pointer to a 32-bit unsigned integer. | ||||
| 1494 | ** The "data version" for the pager is written into the pointer. The | ||||
| 1495 | ** "data version" changes whenever any change occurs to the corresponding | ||||
| 1496 | ** database file, either through SQL statements on the same database | ||||
| 1497 | ** connection or through transactions committed by separate database | ||||
| 1498 | ** connections possibly in other processes. The [sqlite3_total_changes()] | ||||
| 1499 | ** interface can be used to find if any database on the connection has changed, | ||||
| 1500 | ** but that interface responds to changes on TEMP as well as MAIN and does | ||||
| 1501 | ** not provide a mechanism to detect changes to MAIN only. Also, the | ||||
| 1502 | ** [sqlite3_total_changes()] interface responds to internal changes only and | ||||
| 1503 | ** omits changes made by other database connections. The | ||||
| 1504 | ** [PRAGMA data_version] command provides a mechanism to detect changes to | ||||
| 1505 | ** a single attached database that occur due to other database connections, | ||||
| 1506 | ** but omits changes implemented by the database connection on which it is | ||||
| 1507 | ** called. This file control is the only mechanism to detect changes that | ||||
| 1508 | ** happen either internally or externally and that are associated with | ||||
| 1509 | ** a particular attached database. | ||||
| 1510 | ** | ||||
| 1511 | ** <li>[[SQLITE_FCNTL_CKPT_START]] | ||||
| 1512 | ** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint | ||||
| 1513 | ** in wal mode before the client starts to copy pages from the wal | ||||
| 1514 | ** file to the database file. | ||||
| 1515 | ** | ||||
| 1516 | ** <li>[[SQLITE_FCNTL_CKPT_DONE]] | ||||
| 1517 | ** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint | ||||
| 1518 | ** in wal mode after the client has finished copying pages from the wal | ||||
| 1519 | ** file to the database file, but before the *-shm file is updated to | ||||
| 1520 | ** record the fact that the pages have been checkpointed. | ||||
| 1521 | ** | ||||
| 1522 | ** <li>[[SQLITE_FCNTL_EXTERNAL_READER]] | ||||
| 1523 | ** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect | ||||
| 1524 | ** whether or not there is a database client in another process with a wal-mode | ||||
| 1525 | ** transaction open on the database or not. It is only available on unix.The | ||||
| 1526 | ** (void*) argument passed with this file-control should be a pointer to a | ||||
| 1527 | ** value of type (int). The integer value is set to 1 if the database is a wal | ||||
| 1528 | ** mode database and there exists at least one client in another process that | ||||
| 1529 | ** currently has an SQL transaction open on the database. It is set to 0 if | ||||
| 1530 | ** the database is not a wal-mode db, or if there is no such connection in any | ||||
| 1531 | ** other process. This opcode cannot be used to detect transactions opened | ||||
| 1532 | ** by clients within the current process, only within other processes. | ||||
| 1533 | ** | ||||
| 1534 | ** <li>[[SQLITE_FCNTL_CKSM_FILE]] | ||||
| 1535 | ** The [SQLITE_FCNTL_CKSM_FILE] opcode is for use internally by the | ||||
| 1536 | ** [checksum VFS shim] only. | ||||
| 1537 | ** | ||||
| 1538 | ** <li>[[SQLITE_FCNTL_RESET_CACHE]] | ||||
| 1539 | ** If there is currently no transaction open on the database, and the | ||||
| 1540 | ** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control | ||||
| 1541 | ** purges the contents of the in-memory page cache. If there is an open | ||||
| 1542 | ** transaction, or if the db is a temp-db, this opcode is a no-op, not an error. | ||||
| 1543 | ** </ul> | ||||
| 1544 | */ | ||||
| 1545 | #define SQLITE_FCNTL_LOCKSTATE1 1 | ||||
| 1546 | #define SQLITE_FCNTL_GET_LOCKPROXYFILE2 2 | ||||
| 1547 | #define SQLITE_FCNTL_SET_LOCKPROXYFILE3 3 | ||||
| 1548 | #define SQLITE_FCNTL_LAST_ERRNO4 4 | ||||
| 1549 | #define SQLITE_FCNTL_SIZE_HINT5 5 | ||||
| 1550 | #define SQLITE_FCNTL_CHUNK_SIZE6 6 | ||||
| 1551 | #define SQLITE_FCNTL_FILE_POINTER7 7 | ||||
| 1552 | #define SQLITE_FCNTL_SYNC_OMITTED8 8 | ||||
| 1553 | #define SQLITE_FCNTL_WIN32_AV_RETRY9 9 | ||||
| 1554 | #define SQLITE_FCNTL_PERSIST_WAL10 10 | ||||
| 1555 | #define SQLITE_FCNTL_OVERWRITE11 11 | ||||
| 1556 | #define SQLITE_FCNTL_VFSNAME12 12 | ||||
| 1557 | #define SQLITE_FCNTL_POWERSAFE_OVERWRITE13 13 | ||||
| 1558 | #define SQLITE_FCNTL_PRAGMA14 14 | ||||
| 1559 | #define SQLITE_FCNTL_BUSYHANDLER15 15 | ||||
| 1560 | #define SQLITE_FCNTL_TEMPFILENAME16 16 | ||||
| 1561 | #define SQLITE_FCNTL_MMAP_SIZE18 18 | ||||
| 1562 | #define SQLITE_FCNTL_TRACE19 19 | ||||
| 1563 | #define SQLITE_FCNTL_HAS_MOVED20 20 | ||||
| 1564 | #define SQLITE_FCNTL_SYNC21 21 | ||||
| 1565 | #define SQLITE_FCNTL_COMMIT_PHASETWO22 22 | ||||
| 1566 | #define SQLITE_FCNTL_WIN32_SET_HANDLE23 23 | ||||
| 1567 | #define SQLITE_FCNTL_WAL_BLOCK24 24 | ||||
| 1568 | #define SQLITE_FCNTL_ZIPVFS25 25 | ||||
| 1569 | #define SQLITE_FCNTL_RBU26 26 | ||||
| 1570 | #define SQLITE_FCNTL_VFS_POINTER27 27 | ||||
| 1571 | #define SQLITE_FCNTL_JOURNAL_POINTER28 28 | ||||
| 1572 | #define SQLITE_FCNTL_WIN32_GET_HANDLE29 29 | ||||
| 1573 | #define SQLITE_FCNTL_PDB30 30 | ||||
| 1574 | #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE31 31 | ||||
| 1575 | #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE32 32 | ||||
| 1576 | #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE33 33 | ||||
| 1577 | #define SQLITE_FCNTL_LOCK_TIMEOUT34 34 | ||||
| 1578 | #define SQLITE_FCNTL_DATA_VERSION35 35 | ||||
| 1579 | #define SQLITE_FCNTL_SIZE_LIMIT36 36 | ||||
| 1580 | #define SQLITE_FCNTL_CKPT_DONE37 37 | ||||
| 1581 | #define SQLITE_FCNTL_RESERVE_BYTES38 38 | ||||
| 1582 | #define SQLITE_FCNTL_CKPT_START39 39 | ||||
| 1583 | #define SQLITE_FCNTL_EXTERNAL_READER40 40 | ||||
| 1584 | #define SQLITE_FCNTL_CKSM_FILE41 41 | ||||
| 1585 | #define SQLITE_FCNTL_RESET_CACHE42 42 | ||||
| 1586 | #define SQLITE_FCNTL_NULL_IO43 43 | ||||
| 1587 | #define SQLITE_FCNTL_BLOCK_ON_CONNECT44 44 | ||||
| 1588 | |||||
| 1589 | /* deprecated names */ | ||||
| 1590 | #define SQLITE_GET_LOCKPROXYFILE2 SQLITE_FCNTL_GET_LOCKPROXYFILE2 | ||||
| 1591 | #define SQLITE_SET_LOCKPROXYFILE3 SQLITE_FCNTL_SET_LOCKPROXYFILE3 | ||||
| 1592 | #define SQLITE_LAST_ERRNO4 SQLITE_FCNTL_LAST_ERRNO4 | ||||
| 1593 | |||||
| 1594 | |||||
| 1595 | /* | ||||
| 1596 | ** CAPI3REF: Mutex Handle | ||||
| 1597 | ** | ||||
| 1598 | ** The mutex module within SQLite defines [sqlite3_mutex] to be an | ||||
| 1599 | ** abstract type for a mutex object. The SQLite core never looks | ||||
| 1600 | ** at the internal representation of an [sqlite3_mutex]. It only | ||||
| 1601 | ** deals with pointers to the [sqlite3_mutex] object. | ||||
| 1602 | ** | ||||
| 1603 | ** Mutexes are created using [sqlite3_mutex_alloc()]. | ||||
| 1604 | */ | ||||
| 1605 | typedef struct sqlite3_mutex sqlite3_mutex; | ||||
| 1606 | |||||
| 1607 | /* | ||||
| 1608 | ** CAPI3REF: Loadable Extension Thunk | ||||
| 1609 | ** | ||||
| 1610 | ** A pointer to the opaque sqlite3_api_routines structure is passed as | ||||
| 1611 | ** the third parameter to entry points of [loadable extensions]. This | ||||
| 1612 | ** structure must be typedefed in order to work around compiler warnings | ||||
| 1613 | ** on some platforms. | ||||
| 1614 | */ | ||||
| 1615 | typedef struct sqlite3_api_routines sqlite3_api_routines; | ||||
| 1616 | |||||
| 1617 | /* | ||||
| 1618 | ** CAPI3REF: File Name | ||||
| 1619 | ** | ||||
| 1620 | ** Type [sqlite3_filename] is used by SQLite to pass filenames to the | ||||
| 1621 | ** xOpen method of a [VFS]. It may be cast to (const char*) and treated | ||||
| 1622 | ** as a normal, nul-terminated, UTF-8 buffer containing the filename, but | ||||
| 1623 | ** may also be passed to special APIs such as: | ||||
| 1624 | ** | ||||
| 1625 | ** <ul> | ||||
| 1626 | ** <li> sqlite3_filename_database() | ||||
| 1627 | ** <li> sqlite3_filename_journal() | ||||
| 1628 | ** <li> sqlite3_filename_wal() | ||||
| 1629 | ** <li> sqlite3_uri_parameter() | ||||
| 1630 | ** <li> sqlite3_uri_boolean() | ||||
| 1631 | ** <li> sqlite3_uri_int64() | ||||
| 1632 | ** <li> sqlite3_uri_key() | ||||
| 1633 | ** </ul> | ||||
| 1634 | */ | ||||
| 1635 | typedef const char *sqlite3_filename; | ||||
| 1636 | |||||
| 1637 | /* | ||||
| 1638 | ** CAPI3REF: OS Interface Object | ||||
| 1639 | ** | ||||
| 1640 | ** An instance of the sqlite3_vfs object defines the interface between | ||||
| 1641 | ** the SQLite core and the underlying operating system. The "vfs" | ||||
| 1642 | ** in the name of the object stands for "virtual file system". See | ||||
| 1643 | ** the [VFS | VFS documentation] for further information. | ||||
| 1644 | ** | ||||
| 1645 | ** The VFS interface is sometimes extended by adding new methods onto | ||||
| 1646 | ** the end. Each time such an extension occurs, the iVersion field | ||||
| 1647 | ** is incremented. The iVersion value started out as 1 in | ||||
| 1648 | ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2 | ||||
| 1649 | ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased | ||||
| 1650 | ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields | ||||
| 1651 | ** may be appended to the sqlite3_vfs object and the iVersion value | ||||
| 1652 | ** may increase again in future versions of SQLite. | ||||
| 1653 | ** Note that due to an oversight, the structure | ||||
| 1654 | ** of the sqlite3_vfs object changed in the transition from | ||||
| 1655 | ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0] | ||||
| 1656 | ** and yet the iVersion field was not increased. | ||||
| 1657 | ** | ||||
| 1658 | ** The szOsFile field is the size of the subclassed [sqlite3_file] | ||||
| 1659 | ** structure used by this VFS. mxPathname is the maximum length of | ||||
| 1660 | ** a pathname in this VFS. | ||||
| 1661 | ** | ||||
| 1662 | ** Registered sqlite3_vfs objects are kept on a linked list formed by | ||||
| 1663 | ** the pNext pointer. The [sqlite3_vfs_register()] | ||||
| 1664 | ** and [sqlite3_vfs_unregister()] interfaces manage this list | ||||
| 1665 | ** in a thread-safe way. The [sqlite3_vfs_find()] interface | ||||
| 1666 | ** searches the list. Neither the application code nor the VFS | ||||
| 1667 | ** implementation should use the pNext pointer. | ||||
| 1668 | ** | ||||
| 1669 | ** The pNext field is the only field in the sqlite3_vfs | ||||
| 1670 | ** structure that SQLite will ever modify. SQLite will only access | ||||
| 1671 | ** or modify this field while holding a particular static mutex. | ||||
| 1672 | ** The application should never modify anything within the sqlite3_vfs | ||||
| 1673 | ** object once the object has been registered. | ||||
| 1674 | ** | ||||
| 1675 | ** The zName field holds the name of the VFS module. The name must | ||||
| 1676 | ** be unique across all VFS modules. | ||||
| 1677 | ** | ||||
| 1678 | ** [[sqlite3_vfs.xOpen]] | ||||
| 1679 | ** ^SQLite guarantees that the zFilename parameter to xOpen | ||||
| 1680 | ** is either a NULL pointer or string obtained | ||||
| 1681 | ** from xFullPathname() with an optional suffix added. | ||||
| 1682 | ** ^If a suffix is added to the zFilename parameter, it will | ||||
| 1683 | ** consist of a single "-" character followed by no more than | ||||
| 1684 | ** 11 alphanumeric and/or "-" characters. | ||||
| 1685 | ** ^SQLite further guarantees that | ||||
| 1686 | ** the string will be valid and unchanged until xClose() is | ||||
| 1687 | ** called. Because of the previous sentence, | ||||
| 1688 | ** the [sqlite3_file] can safely store a pointer to the | ||||
| 1689 | ** filename if it needs to remember the filename for some reason. | ||||
| 1690 | ** If the zFilename parameter to xOpen is a NULL pointer then xOpen | ||||
| 1691 | ** must invent its own temporary name for the file. ^Whenever the | ||||
| 1692 | ** xFilename parameter is NULL it will also be the case that the | ||||
| 1693 | ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. | ||||
| 1694 | ** | ||||
| 1695 | ** The flags argument to xOpen() includes all bits set in | ||||
| 1696 | ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] | ||||
| 1697 | ** or [sqlite3_open16()] is used, then flags includes at least | ||||
| 1698 | ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. | ||||
| 1699 | ** If xOpen() opens a file read-only then it sets *pOutFlags to | ||||
| 1700 | ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. | ||||
| 1701 | ** | ||||
| 1702 | ** ^(SQLite will also add one of the following flags to the xOpen() | ||||
| 1703 | ** call, depending on the object being opened: | ||||
| 1704 | ** | ||||
| 1705 | ** <ul> | ||||
| 1706 | ** <li> [SQLITE_OPEN_MAIN_DB] | ||||
| 1707 | ** <li> [SQLITE_OPEN_MAIN_JOURNAL] | ||||
| 1708 | ** <li> [SQLITE_OPEN_TEMP_DB] | ||||
| 1709 | ** <li> [SQLITE_OPEN_TEMP_JOURNAL] | ||||
| 1710 | ** <li> [SQLITE_OPEN_TRANSIENT_DB] | ||||
| 1711 | ** <li> [SQLITE_OPEN_SUBJOURNAL] | ||||
| 1712 | ** <li> [SQLITE_OPEN_SUPER_JOURNAL] | ||||
| 1713 | ** <li> [SQLITE_OPEN_WAL] | ||||
| 1714 | ** </ul>)^ | ||||
| 1715 | ** | ||||
| 1716 | ** The file I/O implementation can use the object type flags to | ||||
| 1717 | ** change the way it deals with files. For example, an application | ||||
| 1718 | ** that does not care about crash recovery or rollback might make | ||||
| 1719 | ** the open of a journal file a no-op. Writes to this journal would | ||||
| 1720 | ** also be no-ops, and any attempt to read the journal would return | ||||
| 1721 | ** SQLITE_IOERR. Or the implementation might recognize that a database | ||||
| 1722 | ** file will be doing page-aligned sector reads and writes in a random | ||||
| 1723 | ** order and set up its I/O subsystem accordingly. | ||||
| 1724 | ** | ||||
| 1725 | ** SQLite might also add one of the following flags to the xOpen method: | ||||
| 1726 | ** | ||||
| 1727 | ** <ul> | ||||
| 1728 | ** <li> [SQLITE_OPEN_DELETEONCLOSE] | ||||
| 1729 | ** <li> [SQLITE_OPEN_EXCLUSIVE] | ||||
| 1730 | ** </ul> | ||||
| 1731 | ** | ||||
| 1732 | ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be | ||||
| 1733 | ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] | ||||
| 1734 | ** will be set for TEMP databases and their journals, transient | ||||
| 1735 | ** databases, and subjournals. | ||||
| 1736 | ** | ||||
| 1737 | ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction | ||||
| 1738 | ** with the [SQLITE_OPEN_CREATE] flag, which are both directly | ||||
| 1739 | ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() | ||||
| 1740 | ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the | ||||
| 1741 | ** SQLITE_OPEN_CREATE, is used to indicate that file should always | ||||
| 1742 | ** be created, and that it is an error if it already exists. | ||||
| 1743 | ** It is <i>not</i> used to indicate the file should be opened | ||||
| 1744 | ** for exclusive access. | ||||
| 1745 | ** | ||||
| 1746 | ** ^At least szOsFile bytes of memory are allocated by SQLite | ||||
| 1747 | ** to hold the [sqlite3_file] structure passed as the third | ||||
| 1748 | ** argument to xOpen. The xOpen method does not have to | ||||
| 1749 | ** allocate the structure; it should just fill it in. Note that | ||||
| 1750 | ** the xOpen method must set the sqlite3_file.pMethods to either | ||||
| 1751 | ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do | ||||
| 1752 | ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods | ||||
| 1753 | ** element will be valid after xOpen returns regardless of the success | ||||
| 1754 | ** or failure of the xOpen call. | ||||
| 1755 | ** | ||||
| 1756 | ** [[sqlite3_vfs.xAccess]] | ||||
| 1757 | ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] | ||||
| 1758 | ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to | ||||
| 1759 | ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] | ||||
| 1760 | ** to test whether a file is at least readable. The SQLITE_ACCESS_READ | ||||
| 1761 | ** flag is never actually used and is not implemented in the built-in | ||||
| 1762 | ** VFSes of SQLite. The file is named by the second argument and can be a | ||||
| 1763 | ** directory. The xAccess method returns [SQLITE_OK] on success or some | ||||
| 1764 | ** non-zero error code if there is an I/O error or if the name of | ||||
| 1765 | ** the file given in the second argument is illegal. If SQLITE_OK | ||||
| 1766 | ** is returned, then non-zero or zero is written into *pResOut to indicate | ||||
| 1767 | ** whether or not the file is accessible. | ||||
| 1768 | ** | ||||
| 1769 | ** ^SQLite will always allocate at least mxPathname+1 bytes for the | ||||
| 1770 | ** output buffer xFullPathname. The exact size of the output buffer | ||||
| 1771 | ** is also passed as a parameter to both methods. If the output buffer | ||||
| 1772 | ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is | ||||
| 1773 | ** handled as a fatal error by SQLite, vfs implementations should endeavor | ||||
| 1774 | ** to prevent this by setting mxPathname to a sufficiently large value. | ||||
| 1775 | ** | ||||
| 1776 | ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() | ||||
| 1777 | ** interfaces are not strictly a part of the filesystem, but they are | ||||
| 1778 | ** included in the VFS structure for completeness. | ||||
| 1779 | ** The xRandomness() function attempts to return nBytes bytes | ||||
| 1780 | ** of good-quality randomness into zOut. The return value is | ||||
| 1781 | ** the actual number of bytes of randomness obtained. | ||||
| 1782 | ** The xSleep() method causes the calling thread to sleep for at | ||||
| 1783 | ** least the number of microseconds given. ^The xCurrentTime() | ||||
| 1784 | ** method returns a Julian Day Number for the current date and time as | ||||
| 1785 | ** a floating point value. | ||||
| 1786 | ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian | ||||
| 1787 | ** Day Number multiplied by 86400000 (the number of milliseconds in | ||||
| 1788 | ** a 24-hour day). | ||||
| 1789 | ** ^SQLite will use the xCurrentTimeInt64() method to get the current | ||||
| 1790 | ** date and time if that method is available (if iVersion is 2 or | ||||
| 1791 | ** greater and the function pointer is not NULL) and will fall back | ||||
| 1792 | ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. | ||||
| 1793 | ** | ||||
| 1794 | ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces | ||||
| 1795 | ** are not used by the SQLite core. These optional interfaces are provided | ||||
| 1796 | ** by some VFSes to facilitate testing of the VFS code. By overriding | ||||
| 1797 | ** system calls with functions under its control, a test program can | ||||
| 1798 | ** simulate faults and error conditions that would otherwise be difficult | ||||
| 1799 | ** or impossible to induce. The set of system calls that can be overridden | ||||
| 1800 | ** varies from one VFS to another, and from one version of the same VFS to the | ||||
| 1801 | ** next. Applications that use these interfaces must be prepared for any | ||||
| 1802 | ** or all of these interfaces to be NULL or for their behavior to change | ||||
| 1803 | ** from one release to the next. Applications must not attempt to access | ||||
| 1804 | ** any of these methods if the iVersion of the VFS is less than 3. | ||||
| 1805 | */ | ||||
| 1806 | typedef struct sqlite3_vfs sqlite3_vfs; | ||||
| 1807 | typedef void (*sqlite3_syscall_ptr)(void); | ||||
| 1808 | struct sqlite3_vfs { | ||||
| 1809 | int iVersion; /* Structure version number (currently 3) */ | ||||
| 1810 | int szOsFile; /* Size of subclassed sqlite3_file */ | ||||
| 1811 | int mxPathname; /* Maximum file pathname length */ | ||||
| 1812 | sqlite3_vfs *pNext; /* Next registered VFS */ | ||||
| 1813 | const char *zName; /* Name of this virtual file system */ | ||||
| 1814 | void *pAppData; /* Pointer to application-specific data */ | ||||
| 1815 | int (*xOpen)(sqlite3_vfs*, sqlite3_filename zName, sqlite3_file*, | ||||
| 1816 | int flags, int *pOutFlags); | ||||
| 1817 | int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); | ||||
| 1818 | int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); | ||||
| 1819 | int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); | ||||
| 1820 | void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); | ||||
| 1821 | void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); | ||||
| 1822 | void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); | ||||
| 1823 | void (*xDlClose)(sqlite3_vfs*, void*); | ||||
| 1824 | int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); | ||||
| 1825 | int (*xSleep)(sqlite3_vfs*, int microseconds); | ||||
| 1826 | int (*xCurrentTime)(sqlite3_vfs*, double*); | ||||
| 1827 | int (*xGetLastError)(sqlite3_vfs*, int, char *); | ||||
| 1828 | /* | ||||
| 1829 | ** The methods above are in version 1 of the sqlite_vfs object | ||||
| 1830 | ** definition. Those that follow are added in version 2 or later | ||||
| 1831 | */ | ||||
| 1832 | int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); | ||||
| 1833 | /* | ||||
| 1834 | ** The methods above are in versions 1 and 2 of the sqlite_vfs object. | ||||
| 1835 | ** Those below are for version 3 and greater. | ||||
| 1836 | */ | ||||
| 1837 | int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); | ||||
| 1838 | sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); | ||||
| 1839 | const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); | ||||
| 1840 | /* | ||||
| 1841 | ** The methods above are in versions 1 through 3 of the sqlite_vfs object. | ||||
| 1842 | ** New fields may be appended in future versions. The iVersion | ||||
| 1843 | ** value will increment whenever this happens. | ||||
| 1844 | */ | ||||
| 1845 | }; | ||||
| 1846 | |||||
| 1847 | /* | ||||
| 1848 | ** CAPI3REF: Flags for the xAccess VFS method | ||||
| 1849 | ** | ||||
| 1850 | ** These integer constants can be used as the third parameter to | ||||
| 1851 | ** the xAccess method of an [sqlite3_vfs] object. They determine | ||||
| 1852 | ** what kind of permissions the xAccess method is looking for. | ||||
| 1853 | ** With SQLITE_ACCESS_EXISTS, the xAccess method | ||||
| 1854 | ** simply checks whether the file exists. | ||||
| 1855 | ** With SQLITE_ACCESS_READWRITE, the xAccess method | ||||
| 1856 | ** checks whether the named directory is both readable and writable | ||||
| 1857 | ** (in other words, if files can be added, removed, and renamed within | ||||
| 1858 | ** the directory). | ||||
| 1859 | ** The SQLITE_ACCESS_READWRITE constant is currently used only by the | ||||
| 1860 | ** [temp_store_directory pragma], though this could change in a future | ||||
| 1861 | ** release of SQLite. | ||||
| 1862 | ** With SQLITE_ACCESS_READ, the xAccess method | ||||
| 1863 | ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is | ||||
| 1864 | ** currently unused, though it might be used in a future release of | ||||
| 1865 | ** SQLite. | ||||
| 1866 | */ | ||||
| 1867 | #define SQLITE_ACCESS_EXISTS0 0 | ||||
| 1868 | #define SQLITE_ACCESS_READWRITE1 1 /* Used by PRAGMA temp_store_directory */ | ||||
| 1869 | #define SQLITE_ACCESS_READ2 2 /* Unused */ | ||||
| 1870 | |||||
| 1871 | /* | ||||
| 1872 | ** CAPI3REF: Flags for the xShmLock VFS method | ||||
| 1873 | ** | ||||
| 1874 | ** These integer constants define the various locking operations | ||||
| 1875 | ** allowed by the xShmLock method of [sqlite3_io_methods]. The | ||||
| 1876 | ** following are the only legal combinations of flags to the | ||||
| 1877 | ** xShmLock method: | ||||
| 1878 | ** | ||||
| 1879 | ** <ul> | ||||
| 1880 | ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED | ||||
| 1881 | ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE | ||||
| 1882 | ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED | ||||
| 1883 | ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE | ||||
| 1884 | ** </ul> | ||||
| 1885 | ** | ||||
| 1886 | ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as | ||||
| 1887 | ** was given on the corresponding lock. | ||||
| 1888 | ** | ||||
| 1889 | ** The xShmLock method can transition between unlocked and SHARED or | ||||
| 1890 | ** between unlocked and EXCLUSIVE. It cannot transition between SHARED | ||||
| 1891 | ** and EXCLUSIVE. | ||||
| 1892 | */ | ||||
| 1893 | #define SQLITE_SHM_UNLOCK1 1 | ||||
| 1894 | #define SQLITE_SHM_LOCK2 2 | ||||
| 1895 | #define SQLITE_SHM_SHARED4 4 | ||||
| 1896 | #define SQLITE_SHM_EXCLUSIVE8 8 | ||||
| 1897 | |||||
| 1898 | /* | ||||
| 1899 | ** CAPI3REF: Maximum xShmLock index | ||||
| 1900 | ** | ||||
| 1901 | ** The xShmLock method on [sqlite3_io_methods] may use values | ||||
| 1902 | ** between 0 and this upper bound as its "offset" argument. | ||||
| 1903 | ** The SQLite core will never attempt to acquire or release a | ||||
| 1904 | ** lock outside of this range | ||||
| 1905 | */ | ||||
| 1906 | #define SQLITE_SHM_NLOCK8 8 | ||||
| 1907 | |||||
| 1908 | |||||
| 1909 | /* | ||||
| 1910 | ** CAPI3REF: Initialize The SQLite Library | ||||
| 1911 | ** | ||||
| 1912 | ** ^The sqlite3_initialize() routine initializes the | ||||
| 1913 | ** SQLite library. ^The sqlite3_shutdown() routine | ||||
| 1914 | ** deallocates any resources that were allocated by sqlite3_initialize(). | ||||
| 1915 | ** These routines are designed to aid in process initialization and | ||||
| 1916 | ** shutdown on embedded systems. Workstation applications using | ||||
| 1917 | ** SQLite normally do not need to invoke either of these routines. | ||||
| 1918 | ** | ||||
| 1919 | ** A call to sqlite3_initialize() is an "effective" call if it is | ||||
| 1920 | ** the first time sqlite3_initialize() is invoked during the lifetime of | ||||
| 1921 | ** the process, or if it is the first time sqlite3_initialize() is invoked | ||||
| 1922 | ** following a call to sqlite3_shutdown(). ^(Only an effective call | ||||
| 1923 | ** of sqlite3_initialize() does any initialization. All other calls | ||||
| 1924 | ** are harmless no-ops.)^ | ||||
| 1925 | ** | ||||
| 1926 | ** A call to sqlite3_shutdown() is an "effective" call if it is the first | ||||
| 1927 | ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only | ||||
| 1928 | ** an effective call to sqlite3_shutdown() does any deinitialization. | ||||
| 1929 | ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ | ||||
| 1930 | ** | ||||
| 1931 | ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() | ||||
| 1932 | ** is not. The sqlite3_shutdown() interface must only be called from a | ||||
| 1933 | ** single thread. All open [database connections] must be closed and all | ||||
| 1934 | ** other SQLite resources must be deallocated prior to invoking | ||||
| 1935 | ** sqlite3_shutdown(). | ||||
| 1936 | ** | ||||
| 1937 | ** Among other things, ^sqlite3_initialize() will invoke | ||||
| 1938 | ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() | ||||
| 1939 | ** will invoke sqlite3_os_end(). | ||||
| 1940 | ** | ||||
| 1941 | ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. | ||||
| 1942 | ** ^If for some reason, sqlite3_initialize() is unable to initialize | ||||
| 1943 | ** the library (perhaps it is unable to allocate a needed resource such | ||||
| 1944 | ** as a mutex) it returns an [error code] other than [SQLITE_OK]. | ||||
| 1945 | ** | ||||
| 1946 | ** ^The sqlite3_initialize() routine is called internally by many other | ||||
| 1947 | ** SQLite interfaces so that an application usually does not need to | ||||
| 1948 | ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] | ||||
| 1949 | ** calls sqlite3_initialize() so the SQLite library will be automatically | ||||
| 1950 | ** initialized when [sqlite3_open()] is called if it has not be initialized | ||||
| 1951 | ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] | ||||
| 1952 | ** compile-time option, then the automatic calls to sqlite3_initialize() | ||||
| 1953 | ** are omitted and the application must call sqlite3_initialize() directly | ||||
| 1954 | ** prior to using any other SQLite interface. For maximum portability, | ||||
| 1955 | ** it is recommended that applications always invoke sqlite3_initialize() | ||||
| 1956 | ** directly prior to using any other SQLite interface. Future releases | ||||
| 1957 | ** of SQLite may require this. In other words, the behavior exhibited | ||||
| 1958 | ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the | ||||
| 1959 | ** default behavior in some future release of SQLite. | ||||
| 1960 | ** | ||||
| 1961 | ** The sqlite3_os_init() routine does operating-system specific | ||||
| 1962 | ** initialization of the SQLite library. The sqlite3_os_end() | ||||
| 1963 | ** routine undoes the effect of sqlite3_os_init(). Typical tasks | ||||
| 1964 | ** performed by these routines include allocation or deallocation | ||||
| 1965 | ** of static resources, initialization of global variables, | ||||
| 1966 | ** setting up a default [sqlite3_vfs] module, or setting up | ||||
| 1967 | ** a default configuration using [sqlite3_config()]. | ||||
| 1968 | ** | ||||
| 1969 | ** The application should never invoke either sqlite3_os_init() | ||||
| 1970 | ** or sqlite3_os_end() directly. The application should only invoke | ||||
| 1971 | ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() | ||||
| 1972 | ** interface is called automatically by sqlite3_initialize() and | ||||
| 1973 | ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate | ||||
| 1974 | ** implementations for sqlite3_os_init() and sqlite3_os_end() | ||||
| 1975 | ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. | ||||
| 1976 | ** When [custom builds | built for other platforms] | ||||
| 1977 | ** (using the [SQLITE_OS_OTHER=1] compile-time | ||||
| 1978 | ** option) the application must supply a suitable implementation for | ||||
| 1979 | ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied | ||||
| 1980 | ** implementation of sqlite3_os_init() or sqlite3_os_end() | ||||
| 1981 | ** must return [SQLITE_OK] on success and some other [error code] upon | ||||
| 1982 | ** failure. | ||||
| 1983 | */ | ||||
| 1984 | SQLITE_API int sqlite3_initialize(void); | ||||
| 1985 | SQLITE_API int sqlite3_shutdown(void); | ||||
| 1986 | SQLITE_API int sqlite3_os_init(void); | ||||
| 1987 | SQLITE_API int sqlite3_os_end(void); | ||||
| 1988 | |||||
| 1989 | /* | ||||
| 1990 | ** CAPI3REF: Configuring The SQLite Library | ||||
| 1991 | ** | ||||
| 1992 | ** The sqlite3_config() interface is used to make global configuration | ||||
| 1993 | ** changes to SQLite in order to tune SQLite to the specific needs of | ||||
| 1994 | ** the application. The default configuration is recommended for most | ||||
| 1995 | ** applications and so this routine is usually not necessary. It is | ||||
| 1996 | ** provided to support rare applications with unusual needs. | ||||
| 1997 | ** | ||||
| 1998 | ** <b>The sqlite3_config() interface is not threadsafe. The application | ||||
| 1999 | ** must ensure that no other SQLite interfaces are invoked by other | ||||
| 2000 | ** threads while sqlite3_config() is running.</b> | ||||
| 2001 | ** | ||||
| 2002 | ** The first argument to sqlite3_config() is an integer | ||||
| 2003 | ** [configuration option] that determines | ||||
| 2004 | ** what property of SQLite is to be configured. Subsequent arguments | ||||
| 2005 | ** vary depending on the [configuration option] | ||||
| 2006 | ** in the first argument. | ||||
| 2007 | ** | ||||
| 2008 | ** For most configuration options, the sqlite3_config() interface | ||||
| 2009 | ** may only be invoked prior to library initialization using | ||||
| 2010 | ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. | ||||
| 2011 | ** The exceptional configuration options that may be invoked at any time | ||||
| 2012 | ** are called "anytime configuration options". | ||||
| 2013 | ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before | ||||
| 2014 | ** [sqlite3_shutdown()] with a first argument that is not an anytime | ||||
| 2015 | ** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE. | ||||
| 2016 | ** Note, however, that ^sqlite3_config() can be called as part of the | ||||
| 2017 | ** implementation of an application-defined [sqlite3_os_init()]. | ||||
| 2018 | ** | ||||
| 2019 | ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. | ||||
| 2020 | ** ^If the option is unknown or SQLite is unable to set the option | ||||
| 2021 | ** then this routine returns a non-zero [error code]. | ||||
| 2022 | */ | ||||
| 2023 | SQLITE_API int sqlite3_config(int, ...); | ||||
| 2024 | |||||
| 2025 | /* | ||||
| 2026 | ** CAPI3REF: Configure database connections | ||||
| 2027 | ** METHOD: sqlite3 | ||||
| 2028 | ** | ||||
| 2029 | ** The sqlite3_db_config() interface is used to make configuration | ||||
| 2030 | ** changes to a [database connection]. The interface is similar to | ||||
| 2031 | ** [sqlite3_config()] except that the changes apply to a single | ||||
| 2032 | ** [database connection] (specified in the first argument). | ||||
| 2033 | ** | ||||
| 2034 | ** The second argument to sqlite3_db_config(D,V,...) is the | ||||
| 2035 | ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code | ||||
| 2036 | ** that indicates what aspect of the [database connection] is being configured. | ||||
| 2037 | ** Subsequent arguments vary depending on the configuration verb. | ||||
| 2038 | ** | ||||
| 2039 | ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if | ||||
| 2040 | ** the call is considered successful. | ||||
| 2041 | */ | ||||
| 2042 | SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); | ||||
| 2043 | |||||
| 2044 | /* | ||||
| 2045 | ** CAPI3REF: Memory Allocation Routines | ||||
| 2046 | ** | ||||
| 2047 | ** An instance of this object defines the interface between SQLite | ||||
| 2048 | ** and low-level memory allocation routines. | ||||
| 2049 | ** | ||||
| 2050 | ** This object is used in only one place in the SQLite interface. | ||||
| 2051 | ** A pointer to an instance of this object is the argument to | ||||
| 2052 | ** [sqlite3_config()] when the configuration option is | ||||
| 2053 | ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. | ||||
| 2054 | ** By creating an instance of this object | ||||
| 2055 | ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) | ||||
| 2056 | ** during configuration, an application can specify an alternative | ||||
| 2057 | ** memory allocation subsystem for SQLite to use for all of its | ||||
| 2058 | ** dynamic memory needs. | ||||
| 2059 | ** | ||||
| 2060 | ** Note that SQLite comes with several [built-in memory allocators] | ||||
| 2061 | ** that are perfectly adequate for the overwhelming majority of applications | ||||
| 2062 | ** and that this object is only useful to a tiny minority of applications | ||||
| 2063 | ** with specialized memory allocation requirements. This object is | ||||
| 2064 | ** also used during testing of SQLite in order to specify an alternative | ||||
| 2065 | ** memory allocator that simulates memory out-of-memory conditions in | ||||
| 2066 | ** order to verify that SQLite recovers gracefully from such | ||||
| 2067 | ** conditions. | ||||
| 2068 | ** | ||||
| 2069 | ** The xMalloc, xRealloc, and xFree methods must work like the | ||||
| 2070 | ** malloc(), realloc() and free() functions from the standard C library. | ||||
| 2071 | ** ^SQLite guarantees that the second argument to | ||||
| 2072 | ** xRealloc is always a value returned by a prior call to xRoundup. | ||||
| 2073 | ** | ||||
| 2074 | ** xSize should return the allocated size of a memory allocation | ||||
| 2075 | ** previously obtained from xMalloc or xRealloc. The allocated size | ||||
| 2076 | ** is always at least as big as the requested size but may be larger. | ||||
| 2077 | ** | ||||
| 2078 | ** The xRoundup method returns what would be the allocated size of | ||||
| 2079 | ** a memory allocation given a particular requested size. Most memory | ||||
| 2080 | ** allocators round up memory allocations at least to the next multiple | ||||
| 2081 | ** of 8. Some allocators round up to a larger multiple or to a power of 2. | ||||
| 2082 | ** Every memory allocation request coming in through [sqlite3_malloc()] | ||||
| 2083 | ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, | ||||
| 2084 | ** that causes the corresponding memory allocation to fail. | ||||
| 2085 | ** | ||||
| 2086 | ** The xInit method initializes the memory allocator. For example, | ||||
| 2087 | ** it might allocate any required mutexes or initialize internal data | ||||
| 2088 | ** structures. The xShutdown method is invoked (indirectly) by | ||||
| 2089 | ** [sqlite3_shutdown()] and should deallocate any resources acquired | ||||
| 2090 | ** by xInit. The pAppData pointer is used as the only parameter to | ||||
| 2091 | ** xInit and xShutdown. | ||||
| 2092 | ** | ||||
| 2093 | ** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes | ||||
| 2094 | ** the xInit method, so the xInit method need not be threadsafe. The | ||||
| 2095 | ** xShutdown method is only called from [sqlite3_shutdown()] so it does | ||||
| 2096 | ** not need to be threadsafe either. For all other methods, SQLite | ||||
| 2097 | ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the | ||||
| 2098 | ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which | ||||
| 2099 | ** it is by default) and so the methods are automatically serialized. | ||||
| 2100 | ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other | ||||
| 2101 | ** methods must be threadsafe or else make their own arrangements for | ||||
| 2102 | ** serialization. | ||||
| 2103 | ** | ||||
| 2104 | ** SQLite will never invoke xInit() more than once without an intervening | ||||
| 2105 | ** call to xShutdown(). | ||||
| 2106 | */ | ||||
| 2107 | typedef struct sqlite3_mem_methods sqlite3_mem_methods; | ||||
| 2108 | struct sqlite3_mem_methods { | ||||
| 2109 | void *(*xMalloc)(int); /* Memory allocation function */ | ||||
| 2110 | void (*xFree)(void*); /* Free a prior allocation */ | ||||
| 2111 | void *(*xRealloc)(void*,int); /* Resize an allocation */ | ||||
| 2112 | int (*xSize)(void*); /* Return the size of an allocation */ | ||||
| 2113 | int (*xRoundup)(int); /* Round up request size to allocation size */ | ||||
| 2114 | int (*xInit)(void*); /* Initialize the memory allocator */ | ||||
| 2115 | void (*xShutdown)(void*); /* Deinitialize the memory allocator */ | ||||
| 2116 | void *pAppData; /* Argument to xInit() and xShutdown() */ | ||||
| 2117 | }; | ||||
| 2118 | |||||
| 2119 | /* | ||||
| 2120 | ** CAPI3REF: Configuration Options | ||||
| 2121 | ** KEYWORDS: {configuration option} | ||||
| 2122 | ** | ||||
| 2123 | ** These constants are the available integer configuration options that | ||||
| 2124 | ** can be passed as the first argument to the [sqlite3_config()] interface. | ||||
| 2125 | ** | ||||
| 2126 | ** Most of the configuration options for sqlite3_config() | ||||
| 2127 | ** will only work if invoked prior to [sqlite3_initialize()] or after | ||||
| 2128 | ** [sqlite3_shutdown()]. The few exceptions to this rule are called | ||||
| 2129 | ** "anytime configuration options". | ||||
| 2130 | ** ^Calling [sqlite3_config()] with a first argument that is not an | ||||
| 2131 | ** anytime configuration option in between calls to [sqlite3_initialize()] and | ||||
| 2132 | ** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE. | ||||
| 2133 | ** | ||||
| 2134 | ** The set of anytime configuration options can change (by insertions | ||||
| 2135 | ** and/or deletions) from one release of SQLite to the next. | ||||
| 2136 | ** As of SQLite version 3.42.0, the complete set of anytime configuration | ||||
| 2137 | ** options is: | ||||
| 2138 | ** <ul> | ||||
| 2139 | ** <li> SQLITE_CONFIG_LOG | ||||
| 2140 | ** <li> SQLITE_CONFIG_PCACHE_HDRSZ | ||||
| 2141 | ** </ul> | ||||
| 2142 | ** | ||||
| 2143 | ** New configuration options may be added in future releases of SQLite. | ||||
| 2144 | ** Existing configuration options might be discontinued. Applications | ||||
| 2145 | ** should check the return code from [sqlite3_config()] to make sure that | ||||
| 2146 | ** the call worked. The [sqlite3_config()] interface will return a | ||||
| 2147 | ** non-zero [error code] if a discontinued or unsupported configuration option | ||||
| 2148 | ** is invoked. | ||||
| 2149 | ** | ||||
| 2150 | ** <dl> | ||||
| 2151 | ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt> | ||||
| 2152 | ** <dd>There are no arguments to this option. ^This option sets the | ||||
| 2153 | ** [threading mode] to Single-thread. In other words, it disables | ||||
| 2154 | ** all mutexing and puts SQLite into a mode where it can only be used | ||||
| 2155 | ** by a single thread. ^If SQLite is compiled with | ||||
| 2156 | ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then | ||||
| 2157 | ** it is not possible to change the [threading mode] from its default | ||||
| 2158 | ** value of Single-thread and so [sqlite3_config()] will return | ||||
| 2159 | ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD | ||||
| 2160 | ** configuration option.</dd> | ||||
| 2161 | ** | ||||
| 2162 | ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt> | ||||
| 2163 | ** <dd>There are no arguments to this option. ^This option sets the | ||||
| 2164 | ** [threading mode] to Multi-thread. In other words, it disables | ||||
| 2165 | ** mutexing on [database connection] and [prepared statement] objects. | ||||
| 2166 | ** The application is responsible for serializing access to | ||||
| 2167 | ** [database connections] and [prepared statements]. But other mutexes | ||||
| 2168 | ** are enabled so that SQLite will be safe to use in a multi-threaded | ||||
| 2169 | ** environment as long as no two threads attempt to use the same | ||||
| 2170 | ** [database connection] at the same time. ^If SQLite is compiled with | ||||
| 2171 | ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then | ||||
| 2172 | ** it is not possible to set the Multi-thread [threading mode] and | ||||
| 2173 | ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the | ||||
| 2174 | ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd> | ||||
| 2175 | ** | ||||
| 2176 | ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt> | ||||
| 2177 | ** <dd>There are no arguments to this option. ^This option sets the | ||||
| 2178 | ** [threading mode] to Serialized. In other words, this option enables | ||||
| 2179 | ** all mutexes including the recursive | ||||
| 2180 | ** mutexes on [database connection] and [prepared statement] objects. | ||||
| 2181 | ** In this mode (which is the default when SQLite is compiled with | ||||
| 2182 | ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access | ||||
| 2183 | ** to [database connections] and [prepared statements] so that the | ||||
| 2184 | ** application is free to use the same [database connection] or the | ||||
| 2185 | ** same [prepared statement] in different threads at the same time. | ||||
| 2186 | ** ^If SQLite is compiled with | ||||
| 2187 | ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then | ||||
| 2188 | ** it is not possible to set the Serialized [threading mode] and | ||||
| 2189 | ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the | ||||
| 2190 | ** SQLITE_CONFIG_SERIALIZED configuration option.</dd> | ||||
| 2191 | ** | ||||
| 2192 | ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt> | ||||
| 2193 | ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is | ||||
| 2194 | ** a pointer to an instance of the [sqlite3_mem_methods] structure. | ||||
| 2195 | ** The argument specifies | ||||
| 2196 | ** alternative low-level memory allocation routines to be used in place of | ||||
| 2197 | ** the memory allocation routines built into SQLite.)^ ^SQLite makes | ||||
| 2198 | ** its own private copy of the content of the [sqlite3_mem_methods] structure | ||||
| 2199 | ** before the [sqlite3_config()] call returns.</dd> | ||||
| 2200 | ** | ||||
| 2201 | ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt> | ||||
| 2202 | ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which | ||||
| 2203 | ** is a pointer to an instance of the [sqlite3_mem_methods] structure. | ||||
| 2204 | ** The [sqlite3_mem_methods] | ||||
| 2205 | ** structure is filled with the currently defined memory allocation routines.)^ | ||||
| 2206 | ** This option can be used to overload the default memory allocation | ||||
| 2207 | ** routines with a wrapper that simulations memory allocation failure or | ||||
| 2208 | ** tracks memory usage, for example. </dd> | ||||
| 2209 | ** | ||||
| 2210 | ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt> | ||||
| 2211 | ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of | ||||
| 2212 | ** type int, interpreted as a boolean, which if true provides a hint to | ||||
| 2213 | ** SQLite that it should avoid large memory allocations if possible. | ||||
| 2214 | ** SQLite will run faster if it is free to make large memory allocations, | ||||
| 2215 | ** but some application might prefer to run slower in exchange for | ||||
| 2216 | ** guarantees about memory fragmentation that are possible if large | ||||
| 2217 | ** allocations are avoided. This hint is normally off. | ||||
| 2218 | ** </dd> | ||||
| 2219 | ** | ||||
| 2220 | ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> | ||||
| 2221 | ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, | ||||
| 2222 | ** interpreted as a boolean, which enables or disables the collection of | ||||
| 2223 | ** memory allocation statistics. ^(When memory allocation statistics are | ||||
| 2224 | ** disabled, the following SQLite interfaces become non-operational: | ||||
| 2225 | ** <ul> | ||||
| 2226 | ** <li> [sqlite3_hard_heap_limit64()] | ||||
| 2227 | ** <li> [sqlite3_memory_used()] | ||||
| 2228 | ** <li> [sqlite3_memory_highwater()] | ||||
| 2229 | ** <li> [sqlite3_soft_heap_limit64()] | ||||
| 2230 | ** <li> [sqlite3_status64()] | ||||
| 2231 | ** </ul>)^ | ||||
| 2232 | ** ^Memory allocation statistics are enabled by default unless SQLite is | ||||
| 2233 | ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory | ||||
| 2234 | ** allocation statistics are disabled by default. | ||||
| 2235 | ** </dd> | ||||
| 2236 | ** | ||||
| 2237 | ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt> | ||||
| 2238 | ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used. | ||||
| 2239 | ** </dd> | ||||
| 2240 | ** | ||||
| 2241 | ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt> | ||||
| 2242 | ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool | ||||
| 2243 | ** that SQLite can use for the database page cache with the default page | ||||
| 2244 | ** cache implementation. | ||||
| 2245 | ** This configuration option is a no-op if an application-defined page | ||||
| 2246 | ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. | ||||
| 2247 | ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to | ||||
| 2248 | ** 8-byte aligned memory (pMem), the size of each page cache line (sz), | ||||
| 2249 | ** and the number of cache lines (N). | ||||
| 2250 | ** The sz argument should be the size of the largest database page | ||||
| 2251 | ** (a power of two between 512 and 65536) plus some extra bytes for each | ||||
| 2252 | ** page header. ^The number of extra bytes needed by the page header | ||||
| 2253 | ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. | ||||
| 2254 | ** ^It is harmless, apart from the wasted memory, | ||||
| 2255 | ** for the sz parameter to be larger than necessary. The pMem | ||||
| 2256 | ** argument must be either a NULL pointer or a pointer to an 8-byte | ||||
| 2257 | ** aligned block of memory of at least sz*N bytes, otherwise | ||||
| 2258 | ** subsequent behavior is undefined. | ||||
| 2259 | ** ^When pMem is not NULL, SQLite will strive to use the memory provided | ||||
| 2260 | ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if | ||||
| 2261 | ** a page cache line is larger than sz bytes or if all of the pMem buffer | ||||
| 2262 | ** is exhausted. | ||||
| 2263 | ** ^If pMem is NULL and N is non-zero, then each database connection | ||||
| 2264 | ** does an initial bulk allocation for page cache memory | ||||
| 2265 | ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or | ||||
| 2266 | ** of -1024*N bytes if N is negative, . ^If additional | ||||
| 2267 | ** page cache memory is needed beyond what is provided by the initial | ||||
| 2268 | ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each | ||||
| 2269 | ** additional cache line. </dd> | ||||
| 2270 | ** | ||||
| 2271 | ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt> | ||||
| 2272 | ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer | ||||
| 2273 | ** that SQLite will use for all of its dynamic memory allocation needs | ||||
| 2274 | ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE]. | ||||
| 2275 | ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled | ||||
| 2276 | ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns | ||||
| 2277 | ** [SQLITE_ERROR] if invoked otherwise. | ||||
| 2278 | ** ^There are three arguments to SQLITE_CONFIG_HEAP: | ||||
| 2279 | ** An 8-byte aligned pointer to the memory, | ||||
| 2280 | ** the number of bytes in the memory buffer, and the minimum allocation size. | ||||
| 2281 | ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts | ||||
| 2282 | ** to using its default memory allocator (the system malloc() implementation), | ||||
| 2283 | ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the | ||||
| 2284 | ** memory pointer is not NULL then the alternative memory | ||||
| 2285 | ** allocator is engaged to handle all of SQLites memory allocation needs. | ||||
| 2286 | ** The first pointer (the memory pointer) must be aligned to an 8-byte | ||||
| 2287 | ** boundary or subsequent behavior of SQLite will be undefined. | ||||
| 2288 | ** The minimum allocation size is capped at 2**12. Reasonable values | ||||
| 2289 | ** for the minimum allocation size are 2**5 through 2**8.</dd> | ||||
| 2290 | ** | ||||
| 2291 | ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt> | ||||
| 2292 | ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a | ||||
| 2293 | ** pointer to an instance of the [sqlite3_mutex_methods] structure. | ||||
| 2294 | ** The argument specifies alternative low-level mutex routines to be used | ||||
| 2295 | ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of | ||||
| 2296 | ** the content of the [sqlite3_mutex_methods] structure before the call to | ||||
| 2297 | ** [sqlite3_config()] returns. ^If SQLite is compiled with | ||||
| 2298 | ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then | ||||
| 2299 | ** the entire mutexing subsystem is omitted from the build and hence calls to | ||||
| 2300 | ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will | ||||
| 2301 | ** return [SQLITE_ERROR].</dd> | ||||
| 2302 | ** | ||||
| 2303 | ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt> | ||||
| 2304 | ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which | ||||
| 2305 | ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The | ||||
| 2306 | ** [sqlite3_mutex_methods] | ||||
| 2307 | ** structure is filled with the currently defined mutex routines.)^ | ||||
| 2308 | ** This option can be used to overload the default mutex allocation | ||||
| 2309 | ** routines with a wrapper used to track mutex usage for performance | ||||
| 2310 | ** profiling or testing, for example. ^If SQLite is compiled with | ||||
| 2311 | ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then | ||||
| 2312 | ** the entire mutexing subsystem is omitted from the build and hence calls to | ||||
| 2313 | ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will | ||||
| 2314 | ** return [SQLITE_ERROR].</dd> | ||||
| 2315 | ** | ||||
| 2316 | ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt> | ||||
| 2317 | ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine | ||||
| 2318 | ** the default size of [lookaside memory] on each [database connection]. | ||||
| 2319 | ** The first argument is the | ||||
| 2320 | ** size of each lookaside buffer slot ("sz") and the second is the number of | ||||
| 2321 | ** slots allocated to each database connection ("cnt").)^ | ||||
| 2322 | ** ^(SQLITE_CONFIG_LOOKASIDE sets the <i>default</i> lookaside size. | ||||
| 2323 | ** The [SQLITE_DBCONFIG_LOOKASIDE] option to [sqlite3_db_config()] can | ||||
| 2324 | ** be used to change the lookaside configuration on individual connections.)^ | ||||
| 2325 | ** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the | ||||
| 2326 | ** default lookaside configuration at compile-time. | ||||
| 2327 | ** </dd> | ||||
| 2328 | ** | ||||
| 2329 | ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt> | ||||
| 2330 | ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is | ||||
| 2331 | ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies | ||||
| 2332 | ** the interface to a custom page cache implementation.)^ | ||||
| 2333 | ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd> | ||||
| 2334 | ** | ||||
| 2335 | ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt> | ||||
| 2336 | ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which | ||||
| 2337 | ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of | ||||
| 2338 | ** the current page cache implementation into that object.)^ </dd> | ||||
| 2339 | ** | ||||
| 2340 | ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt> | ||||
| 2341 | ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite | ||||
| 2342 | ** global [error log]. | ||||
| 2343 | ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a | ||||
| 2344 | ** function with a call signature of void(*)(void*,int,const char*), | ||||
| 2345 | ** and a pointer to void. ^If the function pointer is not NULL, it is | ||||
| 2346 | ** invoked by [sqlite3_log()] to process each logging event. ^If the | ||||
| 2347 | ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. | ||||
| 2348 | ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is | ||||
| 2349 | ** passed through as the first parameter to the application-defined logger | ||||
| 2350 | ** function whenever that function is invoked. ^The second parameter to | ||||
| 2351 | ** the logger function is a copy of the first parameter to the corresponding | ||||
| 2352 | ** [sqlite3_log()] call and is intended to be a [result code] or an | ||||
| 2353 | ** [extended result code]. ^The third parameter passed to the logger is | ||||
| 2354 | ** log message after formatting via [sqlite3_snprintf()]. | ||||
| 2355 | ** The SQLite logging interface is not reentrant; the logger function | ||||
| 2356 | ** supplied by the application must not invoke any SQLite interface. | ||||
| 2357 | ** In a multi-threaded application, the application-defined logger | ||||
| 2358 | ** function must be threadsafe. </dd> | ||||
| 2359 | ** | ||||
| 2360 | ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI | ||||
| 2361 | ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int. | ||||
| 2362 | ** If non-zero, then URI handling is globally enabled. If the parameter is zero, | ||||
| 2363 | ** then URI handling is globally disabled.)^ ^If URI handling is globally | ||||
| 2364 | ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], | ||||
| 2365 | ** [sqlite3_open16()] or | ||||
| 2366 | ** specified as part of [ATTACH] commands are interpreted as URIs, regardless | ||||
| 2367 | ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database | ||||
| 2368 | ** connection is opened. ^If it is globally disabled, filenames are | ||||
| 2369 | ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the | ||||
| 2370 | ** database connection is opened. ^(By default, URI handling is globally | ||||
| 2371 | ** disabled. The default value may be changed by compiling with the | ||||
| 2372 | ** [SQLITE_USE_URI] symbol defined.)^ | ||||
| 2373 | ** | ||||
| 2374 | ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN | ||||
| 2375 | ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer | ||||
| 2376 | ** argument which is interpreted as a boolean in order to enable or disable | ||||
| 2377 | ** the use of covering indices for full table scans in the query optimizer. | ||||
| 2378 | ** ^The default setting is determined | ||||
| 2379 | ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" | ||||
| 2380 | ** if that compile-time option is omitted. | ||||
| 2381 | ** The ability to disable the use of covering indices for full table scans | ||||
| 2382 | ** is because some incorrectly coded legacy applications might malfunction | ||||
| 2383 | ** when the optimization is enabled. Providing the ability to | ||||
| 2384 | ** disable the optimization allows the older, buggy application code to work | ||||
| 2385 | ** without change even with newer versions of SQLite. | ||||
| 2386 | ** | ||||
| 2387 | ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] | ||||
| 2388 | ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE | ||||
| 2389 | ** <dd> These options are obsolete and should not be used by new code. | ||||
| 2390 | ** They are retained for backwards compatibility but are now no-ops. | ||||
| 2391 | ** </dd> | ||||
| 2392 | ** | ||||
| 2393 | ** [[SQLITE_CONFIG_SQLLOG]] | ||||
| 2394 | ** <dt>SQLITE_CONFIG_SQLLOG | ||||
| 2395 | ** <dd>This option is only available if sqlite is compiled with the | ||||
| 2396 | ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should | ||||
| 2397 | ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). | ||||
| 2398 | ** The second should be of type (void*). The callback is invoked by the library | ||||
| 2399 | ** in three separate circumstances, identified by the value passed as the | ||||
| 2400 | ** fourth parameter. If the fourth parameter is 0, then the database connection | ||||
| 2401 | ** passed as the second argument has just been opened. The third argument | ||||
| 2402 | ** points to a buffer containing the name of the main database file. If the | ||||
| 2403 | ** fourth parameter is 1, then the SQL statement that the third parameter | ||||
| 2404 | ** points to has just been executed. Or, if the fourth parameter is 2, then | ||||
| 2405 | ** the connection being passed as the second parameter is being closed. The | ||||
| 2406 | ** third parameter is passed NULL In this case. An example of using this | ||||
| 2407 | ** configuration option can be seen in the "test_sqllog.c" source file in | ||||
| 2408 | ** the canonical SQLite source tree.</dd> | ||||
| 2409 | ** | ||||
| 2410 | ** [[SQLITE_CONFIG_MMAP_SIZE]] | ||||
| 2411 | ** <dt>SQLITE_CONFIG_MMAP_SIZE | ||||
| 2412 | ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values | ||||
| 2413 | ** that are the default mmap size limit (the default setting for | ||||
| 2414 | ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. | ||||
| 2415 | ** ^The default setting can be overridden by each database connection using | ||||
| 2416 | ** either the [PRAGMA mmap_size] command, or by using the | ||||
| 2417 | ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size | ||||
| 2418 | ** will be silently truncated if necessary so that it does not exceed the | ||||
| 2419 | ** compile-time maximum mmap size set by the | ||||
| 2420 | ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ | ||||
| 2421 | ** ^If either argument to this option is negative, then that argument is | ||||
| 2422 | ** changed to its compile-time default. | ||||
| 2423 | ** | ||||
| 2424 | ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] | ||||
| 2425 | ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE | ||||
| 2426 | ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is | ||||
| 2427 | ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro | ||||
| 2428 | ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value | ||||
| 2429 | ** that specifies the maximum size of the created heap. | ||||
| 2430 | ** | ||||
| 2431 | ** [[SQLITE_CONFIG_PCACHE_HDRSZ]] | ||||
| 2432 | ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ | ||||
| 2433 | ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which | ||||
| 2434 | ** is a pointer to an integer and writes into that integer the number of extra | ||||
| 2435 | ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. | ||||
| 2436 | ** The amount of extra space required can change depending on the compiler, | ||||
| 2437 | ** target platform, and SQLite version. | ||||
| 2438 | ** | ||||
| 2439 | ** [[SQLITE_CONFIG_PMASZ]] | ||||
| 2440 | ** <dt>SQLITE_CONFIG_PMASZ | ||||
| 2441 | ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which | ||||
| 2442 | ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded | ||||
| 2443 | ** sorter to that integer. The default minimum PMA Size is set by the | ||||
| 2444 | ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched | ||||
| 2445 | ** to help with sort operations when multithreaded sorting | ||||
| 2446 | ** is enabled (using the [PRAGMA threads] command) and the amount of content | ||||
| 2447 | ** to be sorted exceeds the page size times the minimum of the | ||||
| 2448 | ** [PRAGMA cache_size] setting and this value. | ||||
| 2449 | ** | ||||
| 2450 | ** [[SQLITE_CONFIG_STMTJRNL_SPILL]] | ||||
| 2451 | ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL | ||||
| 2452 | ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which | ||||
| 2453 | ** becomes the [statement journal] spill-to-disk threshold. | ||||
| 2454 | ** [Statement journals] are held in memory until their size (in bytes) | ||||
| 2455 | ** exceeds this threshold, at which point they are written to disk. | ||||
| 2456 | ** Or if the threshold is -1, statement journals are always held | ||||
| 2457 | ** exclusively in memory. | ||||
| 2458 | ** Since many statement journals never become large, setting the spill | ||||
| 2459 | ** threshold to a value such as 64KiB can greatly reduce the amount of | ||||
| 2460 | ** I/O required to support statement rollback. | ||||
| 2461 | ** The default value for this setting is controlled by the | ||||
| 2462 | ** [SQLITE_STMTJRNL_SPILL] compile-time option. | ||||
| 2463 | ** | ||||
| 2464 | ** [[SQLITE_CONFIG_SORTERREF_SIZE]] | ||||
| 2465 | ** <dt>SQLITE_CONFIG_SORTERREF_SIZE | ||||
| 2466 | ** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter | ||||
| 2467 | ** of type (int) - the new value of the sorter-reference size threshold. | ||||
| 2468 | ** Usually, when SQLite uses an external sort to order records according | ||||
| 2469 | ** to an ORDER BY clause, all fields required by the caller are present in the | ||||
| 2470 | ** sorted records. However, if SQLite determines based on the declared type | ||||
| 2471 | ** of a table column that its values are likely to be very large - larger | ||||
| 2472 | ** than the configured sorter-reference size threshold - then a reference | ||||
| 2473 | ** is stored in each sorted record and the required column values loaded | ||||
| 2474 | ** from the database as records are returned in sorted order. The default | ||||
| 2475 | ** value for this option is to never use this optimization. Specifying a | ||||
| 2476 | ** negative value for this option restores the default behavior. | ||||
| 2477 | ** This option is only available if SQLite is compiled with the | ||||
| 2478 | ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option. | ||||
| 2479 | ** | ||||
| 2480 | ** [[SQLITE_CONFIG_MEMDB_MAXSIZE]] | ||||
| 2481 | ** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE | ||||
| 2482 | ** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter | ||||
| 2483 | ** [sqlite3_int64] parameter which is the default maximum size for an in-memory | ||||
| 2484 | ** database created using [sqlite3_deserialize()]. This default maximum | ||||
| 2485 | ** size can be adjusted up or down for individual databases using the | ||||
| 2486 | ** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this | ||||
| 2487 | ** configuration setting is never used, then the default maximum is determined | ||||
| 2488 | ** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that | ||||
| 2489 | ** compile-time option is not set, then the default maximum is 1073741824. | ||||
| 2490 | ** | ||||
| 2491 | ** [[SQLITE_CONFIG_ROWID_IN_VIEW]] | ||||
| 2492 | ** <dt>SQLITE_CONFIG_ROWID_IN_VIEW | ||||
| 2493 | ** <dd>The SQLITE_CONFIG_ROWID_IN_VIEW option enables or disables the ability | ||||
| 2494 | ** for VIEWs to have a ROWID. The capability can only be enabled if SQLite is | ||||
| 2495 | ** compiled with -DSQLITE_ALLOW_ROWID_IN_VIEW, in which case the capability | ||||
| 2496 | ** defaults to on. This configuration option queries the current setting or | ||||
| 2497 | ** changes the setting to off or on. The argument is a pointer to an integer. | ||||
| 2498 | ** If that integer initially holds a value of 1, then the ability for VIEWs to | ||||
| 2499 | ** have ROWIDs is activated. If the integer initially holds zero, then the | ||||
| 2500 | ** ability is deactivated. Any other initial value for the integer leaves the | ||||
| 2501 | ** setting unchanged. After changes, if any, the integer is written with | ||||
| 2502 | ** a 1 or 0, if the ability for VIEWs to have ROWIDs is on or off. If SQLite | ||||
| 2503 | ** is compiled without -DSQLITE_ALLOW_ROWID_IN_VIEW (which is the usual and | ||||
| 2504 | ** recommended case) then the integer is always filled with zero, regardless | ||||
| 2505 | ** if its initial value. | ||||
| 2506 | ** </dl> | ||||
| 2507 | */ | ||||
| 2508 | #define SQLITE_CONFIG_SINGLETHREAD1 1 /* nil */ | ||||
| 2509 | #define SQLITE_CONFIG_MULTITHREAD2 2 /* nil */ | ||||
| 2510 | #define SQLITE_CONFIG_SERIALIZED3 3 /* nil */ | ||||
| 2511 | #define SQLITE_CONFIG_MALLOC4 4 /* sqlite3_mem_methods* */ | ||||
| 2512 | #define SQLITE_CONFIG_GETMALLOC5 5 /* sqlite3_mem_methods* */ | ||||
| 2513 | #define SQLITE_CONFIG_SCRATCH6 6 /* No longer used */ | ||||
| 2514 | #define SQLITE_CONFIG_PAGECACHE7 7 /* void*, int sz, int N */ | ||||
| 2515 | #define SQLITE_CONFIG_HEAP8 8 /* void*, int nByte, int min */ | ||||
| 2516 | #define SQLITE_CONFIG_MEMSTATUS9 9 /* boolean */ | ||||
| 2517 | #define SQLITE_CONFIG_MUTEX10 10 /* sqlite3_mutex_methods* */ | ||||
| 2518 | #define SQLITE_CONFIG_GETMUTEX11 11 /* sqlite3_mutex_methods* */ | ||||
| 2519 | /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ | ||||
| 2520 | #define SQLITE_CONFIG_LOOKASIDE13 13 /* int int */ | ||||
| 2521 | #define SQLITE_CONFIG_PCACHE14 14 /* no-op */ | ||||
| 2522 | #define SQLITE_CONFIG_GETPCACHE15 15 /* no-op */ | ||||
| 2523 | #define SQLITE_CONFIG_LOG16 16 /* xFunc, void* */ | ||||
| 2524 | #define SQLITE_CONFIG_URI17 17 /* int */ | ||||
| 2525 | #define SQLITE_CONFIG_PCACHE218 18 /* sqlite3_pcache_methods2* */ | ||||
| 2526 | #define SQLITE_CONFIG_GETPCACHE219 19 /* sqlite3_pcache_methods2* */ | ||||
| 2527 | #define SQLITE_CONFIG_COVERING_INDEX_SCAN20 20 /* int */ | ||||
| 2528 | #define SQLITE_CONFIG_SQLLOG21 21 /* xSqllog, void* */ | ||||
| 2529 | #define SQLITE_CONFIG_MMAP_SIZE22 22 /* sqlite3_int64, sqlite3_int64 */ | ||||
| 2530 | #define SQLITE_CONFIG_WIN32_HEAPSIZE23 23 /* int nByte */ | ||||
| 2531 | #define SQLITE_CONFIG_PCACHE_HDRSZ24 24 /* int *psz */ | ||||
| 2532 | #define SQLITE_CONFIG_PMASZ25 25 /* unsigned int szPma */ | ||||
| 2533 | #define SQLITE_CONFIG_STMTJRNL_SPILL26 26 /* int nByte */ | ||||
| 2534 | #define SQLITE_CONFIG_SMALL_MALLOC27 27 /* boolean */ | ||||
| 2535 | #define SQLITE_CONFIG_SORTERREF_SIZE28 28 /* int nByte */ | ||||
| 2536 | #define SQLITE_CONFIG_MEMDB_MAXSIZE29 29 /* sqlite3_int64 */ | ||||
| 2537 | #define SQLITE_CONFIG_ROWID_IN_VIEW30 30 /* int* */ | ||||
| 2538 | |||||
| 2539 | /* | ||||
| 2540 | ** CAPI3REF: Database Connection Configuration Options | ||||
| 2541 | ** | ||||
| 2542 | ** These constants are the available integer configuration options that | ||||
| 2543 | ** can be passed as the second parameter to the [sqlite3_db_config()] interface. | ||||
| 2544 | ** | ||||
| 2545 | ** The [sqlite3_db_config()] interface is a var-args functions. It takes a | ||||
| 2546 | ** variable number of parameters, though always at least two. The number of | ||||
| 2547 | ** parameters passed into sqlite3_db_config() depends on which of these | ||||
| 2548 | ** constants is given as the second parameter. This documentation page | ||||
| 2549 | ** refers to parameters beyond the second as "arguments". Thus, when this | ||||
| 2550 | ** page says "the N-th argument" it means "the N-th parameter past the | ||||
| 2551 | ** configuration option" or "the (N+2)-th parameter to sqlite3_db_config()". | ||||
| 2552 | ** | ||||
| 2553 | ** New configuration options may be added in future releases of SQLite. | ||||
| 2554 | ** Existing configuration options might be discontinued. Applications | ||||
| 2555 | ** should check the return code from [sqlite3_db_config()] to make sure that | ||||
| 2556 | ** the call worked. ^The [sqlite3_db_config()] interface will return a | ||||
| 2557 | ** non-zero [error code] if a discontinued or unsupported configuration option | ||||
| 2558 | ** is invoked. | ||||
| 2559 | ** | ||||
| 2560 | ** <dl> | ||||
| 2561 | ** [[SQLITE_DBCONFIG_LOOKASIDE]] | ||||
| 2562 | ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt> | ||||
| 2563 | ** <dd> The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the | ||||
| 2564 | ** configuration of the [lookaside memory allocator] within a database | ||||
| 2565 | ** connection. | ||||
| 2566 | ** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are <i>not</i> | ||||
| 2567 | ** in the [DBCONFIG arguments|usual format]. | ||||
| 2568 | ** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two, | ||||
| 2569 | ** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE | ||||
| 2570 | ** should have a total of five parameters. | ||||
| 2571 | ** <ol> | ||||
| 2572 | ** <li><p>The first argument ("buf") is a | ||||
| 2573 | ** pointer to a memory buffer to use for lookaside memory. | ||||
| 2574 | ** The first argument may be NULL in which case SQLite will allocate the | ||||
| 2575 | ** lookaside buffer itself using [sqlite3_malloc()]. | ||||
| 2576 | ** <li><P>The second argument ("sz") is the | ||||
| 2577 | ** size of each lookaside buffer slot. Lookaside is disabled if "sz" | ||||
| 2578 | ** is less than 8. The "sz" argument should be a multiple of 8 less than | ||||
| 2579 | ** 65536. If "sz" does not meet this constraint, it is reduced in size until | ||||
| 2580 | ** it does. | ||||
| 2581 | ** <li><p>The third argument ("cnt") is the number of slots. Lookaside is disabled | ||||
| 2582 | ** if "cnt"is less than 1. The "cnt" value will be reduced, if necessary, so | ||||
| 2583 | ** that the product of "sz" and "cnt" does not exceed 2,147,418,112. The "cnt" | ||||
| 2584 | ** parameter is usually chosen so that the product of "sz" and "cnt" is less | ||||
| 2585 | ** than 1,000,000. | ||||
| 2586 | ** </ol> | ||||
| 2587 | ** <p>If the "buf" argument is not NULL, then it must | ||||
| 2588 | ** point to a memory buffer with a size that is greater than | ||||
| 2589 | ** or equal to the product of "sz" and "cnt". | ||||
| 2590 | ** The buffer must be aligned to an 8-byte boundary. | ||||
| 2591 | ** The lookaside memory | ||||
| 2592 | ** configuration for a database connection can only be changed when that | ||||
| 2593 | ** connection is not currently using lookaside memory, or in other words | ||||
| 2594 | ** when the value returned by [SQLITE_DBSTATUS_LOOKASIDE_USED] is zero. | ||||
| 2595 | ** Any attempt to change the lookaside memory configuration when lookaside | ||||
| 2596 | ** memory is in use leaves the configuration unchanged and returns | ||||
| 2597 | ** [SQLITE_BUSY]. | ||||
| 2598 | ** If the "buf" argument is NULL and an attempt | ||||
| 2599 | ** to allocate memory based on "sz" and "cnt" fails, then | ||||
| 2600 | ** lookaside is silently disabled. | ||||
| 2601 | ** <p> | ||||
| 2602 | ** The [SQLITE_CONFIG_LOOKASIDE] configuration option can be used to set the | ||||
| 2603 | ** default lookaside configuration at initialization. The | ||||
| 2604 | ** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside | ||||
| 2605 | ** configuration at compile-time. Typical values for lookaside are 1200 for | ||||
| 2606 | ** "sz" and 40 to 100 for "cnt". | ||||
| 2607 | ** </dd> | ||||
| 2608 | ** | ||||
| 2609 | ** [[SQLITE_DBCONFIG_ENABLE_FKEY]] | ||||
| 2610 | ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt> | ||||
| 2611 | ** <dd> ^This option is used to enable or disable the enforcement of | ||||
| 2612 | ** [foreign key constraints]. This is the same setting that is | ||||
| 2613 | ** enabled or disabled by the [PRAGMA foreign_keys] statement. | ||||
| 2614 | ** The first argument is an integer which is 0 to disable FK enforcement, | ||||
| 2615 | ** positive to enable FK enforcement or negative to leave FK enforcement | ||||
| 2616 | ** unchanged. The second parameter is a pointer to an integer into which | ||||
| 2617 | ** is written 0 or 1 to indicate whether FK enforcement is off or on | ||||
| 2618 | ** following this call. The second parameter may be a NULL pointer, in | ||||
| 2619 | ** which case the FK enforcement setting is not reported back. </dd> | ||||
| 2620 | ** | ||||
| 2621 | ** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]] | ||||
| 2622 | ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt> | ||||
| 2623 | ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers]. | ||||
| 2624 | ** There should be two additional arguments. | ||||
| 2625 | ** The first argument is an integer which is 0 to disable triggers, | ||||
| 2626 | ** positive to enable triggers or negative to leave the setting unchanged. | ||||
| 2627 | ** The second parameter is a pointer to an integer into which | ||||
| 2628 | ** is written 0 or 1 to indicate whether triggers are disabled or enabled | ||||
| 2629 | ** following this call. The second parameter may be a NULL pointer, in | ||||
| 2630 | ** which case the trigger setting is not reported back. | ||||
| 2631 | ** | ||||
| 2632 | ** <p>Originally this option disabled all triggers. ^(However, since | ||||
| 2633 | ** SQLite version 3.35.0, TEMP triggers are still allowed even if | ||||
| 2634 | ** this option is off. So, in other words, this option now only disables | ||||
| 2635 | ** triggers in the main database schema or in the schemas of [ATTACH]-ed | ||||
| 2636 | ** databases.)^ </dd> | ||||
| 2637 | ** | ||||
| 2638 | ** [[SQLITE_DBCONFIG_ENABLE_VIEW]] | ||||
| 2639 | ** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt> | ||||
| 2640 | ** <dd> ^This option is used to enable or disable [CREATE VIEW | views]. | ||||
| 2641 | ** There must be two additional arguments. | ||||
| 2642 | ** The first argument is an integer which is 0 to disable views, | ||||
| 2643 | ** positive to enable views or negative to leave the setting unchanged. | ||||
| 2644 | ** The second parameter is a pointer to an integer into which | ||||
| 2645 | ** is written 0 or 1 to indicate whether views are disabled or enabled | ||||
| 2646 | ** following this call. The second parameter may be a NULL pointer, in | ||||
| 2647 | ** which case the view setting is not reported back. | ||||
| 2648 | ** | ||||
| 2649 | ** <p>Originally this option disabled all views. ^(However, since | ||||
| 2650 | ** SQLite version 3.35.0, TEMP views are still allowed even if | ||||
| 2651 | ** this option is off. So, in other words, this option now only disables | ||||
| 2652 | ** views in the main database schema or in the schemas of ATTACH-ed | ||||
| 2653 | ** databases.)^ </dd> | ||||
| 2654 | ** | ||||
| 2655 | ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]] | ||||
| 2656 | ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt> | ||||
| 2657 | ** <dd> ^This option is used to enable or disable the | ||||
| 2658 | ** [fts3_tokenizer()] function which is part of the | ||||
| 2659 | ** [FTS3] full-text search engine extension. | ||||
| 2660 | ** There must be two additional arguments. | ||||
| 2661 | ** The first argument is an integer which is 0 to disable fts3_tokenizer() or | ||||
| 2662 | ** positive to enable fts3_tokenizer() or negative to leave the setting | ||||
| 2663 | ** unchanged. | ||||
| 2664 | ** The second parameter is a pointer to an integer into which | ||||
| 2665 | ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled | ||||
| 2666 | ** following this call. The second parameter may be a NULL pointer, in | ||||
| 2667 | ** which case the new setting is not reported back. </dd> | ||||
| 2668 | ** | ||||
| 2669 | ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]] | ||||
| 2670 | ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt> | ||||
| 2671 | ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()] | ||||
| 2672 | ** interface independently of the [load_extension()] SQL function. | ||||
| 2673 | ** The [sqlite3_enable_load_extension()] API enables or disables both the | ||||
| 2674 | ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. | ||||
| 2675 | ** There must be two additional arguments. | ||||
| 2676 | ** When the first argument to this interface is 1, then only the C-API is | ||||
| 2677 | ** enabled and the SQL function remains disabled. If the first argument to | ||||
| 2678 | ** this interface is 0, then both the C-API and the SQL function are disabled. | ||||
| 2679 | ** If the first argument is -1, then no changes are made to state of either the | ||||
| 2680 | ** C-API or the SQL function. | ||||
| 2681 | ** The second parameter is a pointer to an integer into which | ||||
| 2682 | ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface | ||||
| 2683 | ** is disabled or enabled following this call. The second parameter may | ||||
| 2684 | ** be a NULL pointer, in which case the new setting is not reported back. | ||||
| 2685 | ** </dd> | ||||
| 2686 | ** | ||||
| 2687 | ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> | ||||
| 2688 | ** <dd> ^This option is used to change the name of the "main" database | ||||
| 2689 | ** schema. This option does not follow the | ||||
| 2690 | ** [DBCONFIG arguments|usual SQLITE_DBCONFIG argument format]. | ||||
| 2691 | ** This option takes exactly one additional argument so that the | ||||
| 2692 | ** [sqlite3_db_config()] call has a total of three parameters. The | ||||
| 2693 | ** extra argument must be a pointer to a constant UTF8 string which | ||||
| 2694 | ** will become the new schema name in place of "main". ^SQLite does | ||||
| 2695 | ** not make a copy of the new main schema name string, so the application | ||||
| 2696 | ** must ensure that the argument passed into SQLITE_DBCONFIG MAINDBNAME | ||||
| 2697 | ** is unchanged until after the database connection closes. | ||||
| 2698 | ** </dd> | ||||
| 2699 | ** | ||||
| 2700 | ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] | ||||
| 2701 | ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt> | ||||
| 2702 | ** <dd> Usually, when a database in [WAL mode] is closed or detached from a | ||||
| 2703 | ** database handle, SQLite checks if if there are other connections to the | ||||
| 2704 | ** same database, and if there are no other database connection (if the | ||||
| 2705 | ** connection being closed is the last open connection to the database), | ||||
| 2706 | ** then SQLite performs a [checkpoint] before closing the connection and | ||||
| 2707 | ** deletes the WAL file. The SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE option can | ||||
| 2708 | ** be used to override that behavior. The first argument passed to this | ||||
| 2709 | ** operation (the third parameter to [sqlite3_db_config()]) is an integer | ||||
| 2710 | ** which is positive to disable checkpoints-on-close, or zero (the default) | ||||
| 2711 | ** to enable them, and negative to leave the setting unchanged. | ||||
| 2712 | ** The second argument (the fourth parameter) is a pointer to an integer | ||||
| 2713 | ** into which is written 0 or 1 to indicate whether checkpoints-on-close | ||||
| 2714 | ** have been disabled - 0 if they are not disabled, 1 if they are. | ||||
| 2715 | ** </dd> | ||||
| 2716 | ** | ||||
| 2717 | ** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt> | ||||
| 2718 | ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates | ||||
| 2719 | ** the [query planner stability guarantee] (QPSG). When the QPSG is active, | ||||
| 2720 | ** a single SQL query statement will always use the same algorithm regardless | ||||
| 2721 | ** of values of [bound parameters].)^ The QPSG disables some query optimizations | ||||
| 2722 | ** that look at the values of bound parameters, which can make some queries | ||||
| 2723 | ** slower. But the QPSG has the advantage of more predictable behavior. With | ||||
| 2724 | ** the QPSG active, SQLite will always use the same query plan in the field as | ||||
| 2725 | ** was used during testing in the lab. | ||||
| 2726 | ** The first argument to this setting is an integer which is 0 to disable | ||||
| 2727 | ** the QPSG, positive to enable QPSG, or negative to leave the setting | ||||
| 2728 | ** unchanged. The second parameter is a pointer to an integer into which | ||||
| 2729 | ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled | ||||
| 2730 | ** following this call. | ||||
| 2731 | ** </dd> | ||||
| 2732 | ** | ||||
| 2733 | ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt> | ||||
| 2734 | ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not | ||||
| 2735 | ** include output for any operations performed by trigger programs. This | ||||
| 2736 | ** option is used to set or clear (the default) a flag that governs this | ||||
| 2737 | ** behavior. The first parameter passed to this operation is an integer - | ||||
| 2738 | ** positive to enable output for trigger programs, or zero to disable it, | ||||
| 2739 | ** or negative to leave the setting unchanged. | ||||
| 2740 | ** The second parameter is a pointer to an integer into which is written | ||||
| 2741 | ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if | ||||
| 2742 | ** it is not disabled, 1 if it is. | ||||
| 2743 | ** </dd> | ||||
| 2744 | ** | ||||
| 2745 | ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt> | ||||
| 2746 | ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run | ||||
| 2747 | ** [VACUUM] in order to reset a database back to an empty database | ||||
| 2748 | ** with no schema and no content. The following process works even for | ||||
| 2749 | ** a badly corrupted database file: | ||||
| 2750 | ** <ol> | ||||
| 2751 | ** <li> If the database connection is newly opened, make sure it has read the | ||||
| 2752 | ** database schema by preparing then discarding some query against the | ||||
| 2753 | ** database, or calling sqlite3_table_column_metadata(), ignoring any | ||||
| 2754 | ** errors. This step is only necessary if the application desires to keep | ||||
| 2755 | ** the database in WAL mode after the reset if it was in WAL mode before | ||||
| 2756 | ** the reset. | ||||
| 2757 | ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); | ||||
| 2758 | ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0); | ||||
| 2759 | ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0); | ||||
| 2760 | ** </ol> | ||||
| 2761 | ** Because resetting a database is destructive and irreversible, the | ||||
| 2762 | ** process requires the use of this obscure API and multiple steps to | ||||
| 2763 | ** help ensure that it does not happen by accident. Because this | ||||
| 2764 | ** feature must be capable of resetting corrupt databases, and | ||||
| 2765 | ** shutting down virtual tables may require access to that corrupt | ||||
| 2766 | ** storage, the library must abandon any installed virtual tables | ||||
| 2767 | ** without calling their xDestroy() methods. | ||||
| 2768 | ** | ||||
| 2769 | ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt> | ||||
| 2770 | ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the | ||||
| 2771 | ** "defensive" flag for a database connection. When the defensive | ||||
| 2772 | ** flag is enabled, language features that allow ordinary SQL to | ||||
| 2773 | ** deliberately corrupt the database file are disabled. The disabled | ||||
| 2774 | ** features include but are not limited to the following: | ||||
| 2775 | ** <ul> | ||||
| 2776 | ** <li> The [PRAGMA writable_schema=ON] statement. | ||||
| 2777 | ** <li> The [PRAGMA journal_mode=OFF] statement. | ||||
| 2778 | ** <li> The [PRAGMA schema_version=N] statement. | ||||
| 2779 | ** <li> Writes to the [sqlite_dbpage] virtual table. | ||||
| 2780 | ** <li> Direct writes to [shadow tables]. | ||||
| 2781 | ** </ul> | ||||
| 2782 | ** </dd> | ||||
| 2783 | ** | ||||
| 2784 | ** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt> | ||||
| 2785 | ** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the | ||||
| 2786 | ** "writable_schema" flag. This has the same effect and is logically equivalent | ||||
| 2787 | ** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF]. | ||||
| 2788 | ** The first argument to this setting is an integer which is 0 to disable | ||||
| 2789 | ** the writable_schema, positive to enable writable_schema, or negative to | ||||
| 2790 | ** leave the setting unchanged. The second parameter is a pointer to an | ||||
| 2791 | ** integer into which is written 0 or 1 to indicate whether the writable_schema | ||||
| 2792 | ** is enabled or disabled following this call. | ||||
| 2793 | ** </dd> | ||||
| 2794 | ** | ||||
| 2795 | ** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]] | ||||
| 2796 | ** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt> | ||||
| 2797 | ** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates | ||||
| 2798 | ** the legacy behavior of the [ALTER TABLE RENAME] command such it | ||||
| 2799 | ** behaves as it did prior to [version 3.24.0] (2018-06-04). See the | ||||
| 2800 | ** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for | ||||
| 2801 | ** additional information. This feature can also be turned on and off | ||||
| 2802 | ** using the [PRAGMA legacy_alter_table] statement. | ||||
| 2803 | ** </dd> | ||||
| 2804 | ** | ||||
| 2805 | ** [[SQLITE_DBCONFIG_DQS_DML]] | ||||
| 2806 | ** <dt>SQLITE_DBCONFIG_DQS_DML</dt> | ||||
| 2807 | ** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates | ||||
| 2808 | ** the legacy [double-quoted string literal] misfeature for DML statements | ||||
| 2809 | ** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The | ||||
| 2810 | ** default value of this setting is determined by the [-DSQLITE_DQS] | ||||
| 2811 | ** compile-time option. | ||||
| 2812 | ** </dd> | ||||
| 2813 | ** | ||||
| 2814 | ** [[SQLITE_DBCONFIG_DQS_DDL]] | ||||
| 2815 | ** <dt>SQLITE_DBCONFIG_DQS_DDL</dt> | ||||
| 2816 | ** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates | ||||
| 2817 | ** the legacy [double-quoted string literal] misfeature for DDL statements, | ||||
| 2818 | ** such as CREATE TABLE and CREATE INDEX. The | ||||
| 2819 | ** default value of this setting is determined by the [-DSQLITE_DQS] | ||||
| 2820 | ** compile-time option. | ||||
| 2821 | ** </dd> | ||||
| 2822 | ** | ||||
| 2823 | ** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]] | ||||
| 2824 | ** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</dt> | ||||
| 2825 | ** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to | ||||
| 2826 | ** assume that database schemas are untainted by malicious content. | ||||
| 2827 | ** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite | ||||
| 2828 | ** takes additional defensive steps to protect the application from harm | ||||
| 2829 | ** including: | ||||
| 2830 | ** <ul> | ||||
| 2831 | ** <li> Prohibit the use of SQL functions inside triggers, views, | ||||
| 2832 | ** CHECK constraints, DEFAULT clauses, expression indexes, | ||||
| 2833 | ** partial indexes, or generated columns | ||||
| 2834 | ** unless those functions are tagged with [SQLITE_INNOCUOUS]. | ||||
| 2835 | ** <li> Prohibit the use of virtual tables inside of triggers or views | ||||
| 2836 | ** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS]. | ||||
| 2837 | ** </ul> | ||||
| 2838 | ** This setting defaults to "on" for legacy compatibility, however | ||||
| 2839 | ** all applications are advised to turn it off if possible. This setting | ||||
| 2840 | ** can also be controlled using the [PRAGMA trusted_schema] statement. | ||||
| 2841 | ** </dd> | ||||
| 2842 | ** | ||||
| 2843 | ** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]] | ||||
| 2844 | ** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt> | ||||
| 2845 | ** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates | ||||
| 2846 | ** the legacy file format flag. When activated, this flag causes all newly | ||||
| 2847 | ** created database file to have a schema format version number (the 4-byte | ||||
| 2848 | ** integer found at offset 44 into the database header) of 1. This in turn | ||||
| 2849 | ** means that the resulting database file will be readable and writable by | ||||
| 2850 | ** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting, | ||||
| 2851 | ** newly created databases are generally not understandable by SQLite versions | ||||
| 2852 | ** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there | ||||
| 2853 | ** is now scarcely any need to generate database files that are compatible | ||||
| 2854 | ** all the way back to version 3.0.0, and so this setting is of little | ||||
| 2855 | ** practical use, but is provided so that SQLite can continue to claim the | ||||
| 2856 | ** ability to generate new database files that are compatible with version | ||||
| 2857 | ** 3.0.0. | ||||
| 2858 | ** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on, | ||||
| 2859 | ** the [VACUUM] command will fail with an obscure error when attempting to | ||||
| 2860 | ** process a table with generated columns and a descending index. This is | ||||
| 2861 | ** not considered a bug since SQLite versions 3.3.0 and earlier do not support | ||||
| 2862 | ** either generated columns or descending indexes. | ||||
| 2863 | ** </dd> | ||||
| 2864 | ** | ||||
| 2865 | ** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]] | ||||
| 2866 | ** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt> | ||||
| 2867 | ** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in | ||||
| 2868 | ** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears | ||||
| 2869 | ** a flag that enables collection of the sqlite3_stmt_scanstatus_v2() | ||||
| 2870 | ** statistics. For statistics to be collected, the flag must be set on | ||||
| 2871 | ** the database handle both when the SQL statement is prepared and when it | ||||
| 2872 | ** is stepped. The flag is set (collection of statistics is enabled) | ||||
| 2873 | ** by default. <p>This option takes two arguments: an integer and a pointer to | ||||
| 2874 | ** an integer.. The first argument is 1, 0, or -1 to enable, disable, or | ||||
| 2875 | ** leave unchanged the statement scanstatus option. If the second argument | ||||
| 2876 | ** is not NULL, then the value of the statement scanstatus setting after | ||||
| 2877 | ** processing the first argument is written into the integer that the second | ||||
| 2878 | ** argument points to. | ||||
| 2879 | ** </dd> | ||||
| 2880 | ** | ||||
| 2881 | ** [[SQLITE_DBCONFIG_REVERSE_SCANORDER]] | ||||
| 2882 | ** <dt>SQLITE_DBCONFIG_REVERSE_SCANORDER</dt> | ||||
| 2883 | ** <dd>The SQLITE_DBCONFIG_REVERSE_SCANORDER option changes the default order | ||||
| 2884 | ** in which tables and indexes are scanned so that the scans start at the end | ||||
| 2885 | ** and work toward the beginning rather than starting at the beginning and | ||||
| 2886 | ** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the | ||||
| 2887 | ** same as setting [PRAGMA reverse_unordered_selects]. <p>This option takes | ||||
| 2888 | ** two arguments which are an integer and a pointer to an integer. The first | ||||
| 2889 | ** argument is 1, 0, or -1 to enable, disable, or leave unchanged the | ||||
| 2890 | ** reverse scan order flag, respectively. If the second argument is not NULL, | ||||
| 2891 | ** then 0 or 1 is written into the integer that the second argument points to | ||||
| 2892 | ** depending on if the reverse scan order flag is set after processing the | ||||
| 2893 | ** first argument. | ||||
| 2894 | ** </dd> | ||||
| 2895 | ** | ||||
| 2896 | ** [[SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]] | ||||
| 2897 | ** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE</dt> | ||||
| 2898 | ** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE option enables or disables | ||||
| 2899 | ** the ability of the [ATTACH DATABASE] SQL command to create a new database | ||||
| 2900 | ** file if the database filed named in the ATTACH command does not already | ||||
| 2901 | ** exist. This ability of ATTACH to create a new database is enabled by | ||||
| 2902 | ** default. Applications can disable or reenable the ability for ATTACH to | ||||
| 2903 | ** create new database files using this DBCONFIG option.<p> | ||||
| 2904 | ** This option takes two arguments which are an integer and a pointer | ||||
| 2905 | ** to an integer. The first argument is 1, 0, or -1 to enable, disable, or | ||||
| 2906 | ** leave unchanged the attach-create flag, respectively. If the second | ||||
| 2907 | ** argument is not NULL, then 0 or 1 is written into the integer that the | ||||
| 2908 | ** second argument points to depending on if the attach-create flag is set | ||||
| 2909 | ** after processing the first argument. | ||||
| 2910 | ** </dd> | ||||
| 2911 | ** | ||||
| 2912 | ** [[SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE]] | ||||
| 2913 | ** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE</dt> | ||||
| 2914 | ** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the | ||||
| 2915 | ** ability of the [ATTACH DATABASE] SQL command to open a database for writing. | ||||
| 2916 | ** This capability is enabled by default. Applications can disable or | ||||
| 2917 | ** reenable this capability using the current DBCONFIG option. If the | ||||
| 2918 | ** the this capability is disabled, the [ATTACH] command will still work, | ||||
| 2919 | ** but the database will be opened read-only. If this option is disabled, | ||||
| 2920 | ** then the ability to create a new database using [ATTACH] is also disabled, | ||||
| 2921 | ** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE] | ||||
| 2922 | ** option.<p> | ||||
| 2923 | ** This option takes two arguments which are an integer and a pointer | ||||
| 2924 | ** to an integer. The first argument is 1, 0, or -1 to enable, disable, or | ||||
| 2925 | ** leave unchanged the ability to ATTACH another database for writing, | ||||
| 2926 | ** respectively. If the second argument is not NULL, then 0 or 1 is written | ||||
| 2927 | ** into the integer to which the second argument points, depending on whether | ||||
| 2928 | ** the ability to ATTACH a read/write database is enabled or disabled | ||||
| 2929 | ** after processing the first argument. | ||||
| 2930 | ** </dd> | ||||
| 2931 | ** | ||||
| 2932 | ** [[SQLITE_DBCONFIG_ENABLE_COMMENTS]] | ||||
| 2933 | ** <dt>SQLITE_DBCONFIG_ENABLE_COMMENTS</dt> | ||||
| 2934 | ** <dd>The SQLITE_DBCONFIG_ENABLE_COMMENTS option enables or disables the | ||||
| 2935 | ** ability to include comments in SQL text. Comments are enabled by default. | ||||
| 2936 | ** An application can disable or reenable comments in SQL text using this | ||||
| 2937 | ** DBCONFIG option.<p> | ||||
| 2938 | ** This option takes two arguments which are an integer and a pointer | ||||
| 2939 | ** to an integer. The first argument is 1, 0, or -1 to enable, disable, or | ||||
| 2940 | ** leave unchanged the ability to use comments in SQL text, | ||||
| 2941 | ** respectively. If the second argument is not NULL, then 0 or 1 is written | ||||
| 2942 | ** into the integer that the second argument points to depending on if | ||||
| 2943 | ** comments are allowed in SQL text after processing the first argument. | ||||
| 2944 | ** </dd> | ||||
| 2945 | ** | ||||
| 2946 | ** </dl> | ||||
| 2947 | ** | ||||
| 2948 | ** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3> | ||||
| 2949 | ** | ||||
| 2950 | ** <p>Most of the SQLITE_DBCONFIG options take two arguments, so that the | ||||
| 2951 | ** overall call to [sqlite3_db_config()] has a total of four parameters. | ||||
| 2952 | ** The first argument (the third parameter to sqlite3_db_config()) is a integer. | ||||
| 2953 | ** The second argument is a pointer to an integer. If the first argument is 1, | ||||
| 2954 | ** then the option becomes enabled. If the first integer argument is 0, then the | ||||
| 2955 | ** option is disabled. If the first argument is -1, then the option setting | ||||
| 2956 | ** is unchanged. The second argument, the pointer to an integer, may be NULL. | ||||
| 2957 | ** If the second argument is not NULL, then a value of 0 or 1 is written into | ||||
| 2958 | ** the integer to which the second argument points, depending on whether the | ||||
| 2959 | ** setting is disabled or enabled after applying any changes specified by | ||||
| 2960 | ** the first argument. | ||||
| 2961 | ** | ||||
| 2962 | ** <p>While most SQLITE_DBCONFIG options use the argument format | ||||
| 2963 | ** described in the previous paragraph, the [SQLITE_DBCONFIG_MAINDBNAME] | ||||
| 2964 | ** and [SQLITE_DBCONFIG_LOOKASIDE] options are different. See the | ||||
| 2965 | ** documentation of those exceptional options for details. | ||||
| 2966 | */ | ||||
| 2967 | #define SQLITE_DBCONFIG_MAINDBNAME1000 1000 /* const char* */ | ||||
| 2968 | #define SQLITE_DBCONFIG_LOOKASIDE1001 1001 /* void* int int */ | ||||
| 2969 | #define SQLITE_DBCONFIG_ENABLE_FKEY1002 1002 /* int int* */ | ||||
| 2970 | #define SQLITE_DBCONFIG_ENABLE_TRIGGER1003 1003 /* int int* */ | ||||
| 2971 | #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER1004 1004 /* int int* */ | ||||
| 2972 | #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION1005 1005 /* int int* */ | ||||
| 2973 | #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE1006 1006 /* int int* */ | ||||
| 2974 | #define SQLITE_DBCONFIG_ENABLE_QPSG1007 1007 /* int int* */ | ||||
| 2975 | #define SQLITE_DBCONFIG_TRIGGER_EQP1008 1008 /* int int* */ | ||||
| 2976 | #define SQLITE_DBCONFIG_RESET_DATABASE1009 1009 /* int int* */ | ||||
| 2977 | #define SQLITE_DBCONFIG_DEFENSIVE1010 1010 /* int int* */ | ||||
| 2978 | #define SQLITE_DBCONFIG_WRITABLE_SCHEMA1011 1011 /* int int* */ | ||||
| 2979 | #define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE1012 1012 /* int int* */ | ||||
| 2980 | #define SQLITE_DBCONFIG_DQS_DML1013 1013 /* int int* */ | ||||
| 2981 | #define SQLITE_DBCONFIG_DQS_DDL1014 1014 /* int int* */ | ||||
| 2982 | #define SQLITE_DBCONFIG_ENABLE_VIEW1015 1015 /* int int* */ | ||||
| 2983 | #define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT1016 1016 /* int int* */ | ||||
| 2984 | #define SQLITE_DBCONFIG_TRUSTED_SCHEMA1017 1017 /* int int* */ | ||||
| 2985 | #define SQLITE_DBCONFIG_STMT_SCANSTATUS1018 1018 /* int int* */ | ||||
| 2986 | #define SQLITE_DBCONFIG_REVERSE_SCANORDER1019 1019 /* int int* */ | ||||
| 2987 | #define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE1020 1020 /* int int* */ | ||||
| 2988 | #define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE1021 1021 /* int int* */ | ||||
| 2989 | #define SQLITE_DBCONFIG_ENABLE_COMMENTS1022 1022 /* int int* */ | ||||
| 2990 | #define SQLITE_DBCONFIG_MAX1022 1022 /* Largest DBCONFIG */ | ||||
| 2991 | |||||
| 2992 | /* | ||||
| 2993 | ** CAPI3REF: Enable Or Disable Extended Result Codes | ||||
| 2994 | ** METHOD: sqlite3 | ||||
| 2995 | ** | ||||
| 2996 | ** ^The sqlite3_extended_result_codes() routine enables or disables the | ||||
| 2997 | ** [extended result codes] feature of SQLite. ^The extended result | ||||
| 2998 | ** codes are disabled by default for historical compatibility. | ||||
| 2999 | */ | ||||
| 3000 | SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); | ||||
| 3001 | |||||
| 3002 | /* | ||||
| 3003 | ** CAPI3REF: Last Insert Rowid | ||||
| 3004 | ** METHOD: sqlite3 | ||||
| 3005 | ** | ||||
| 3006 | ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables) | ||||
| 3007 | ** has a unique 64-bit signed | ||||
| 3008 | ** integer key called the [ROWID | "rowid"]. ^The rowid is always available | ||||
| 3009 | ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those | ||||
| 3010 | ** names are not also used by explicitly declared columns. ^If | ||||
| 3011 | ** the table has a column of type [INTEGER PRIMARY KEY] then that column | ||||
| 3012 | ** is another alias for the rowid. | ||||
| 3013 | ** | ||||
| 3014 | ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of | ||||
| 3015 | ** the most recent successful [INSERT] into a rowid table or [virtual table] | ||||
| 3016 | ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not | ||||
| 3017 | ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred | ||||
| 3018 | ** on the database connection D, then sqlite3_last_insert_rowid(D) returns | ||||
| 3019 | ** zero. | ||||
| 3020 | ** | ||||
| 3021 | ** As well as being set automatically as rows are inserted into database | ||||
| 3022 | ** tables, the value returned by this function may be set explicitly by | ||||
| 3023 | ** [sqlite3_set_last_insert_rowid()] | ||||
| 3024 | ** | ||||
| 3025 | ** Some virtual table implementations may INSERT rows into rowid tables as | ||||
| 3026 | ** part of committing a transaction (e.g. to flush data accumulated in memory | ||||
| 3027 | ** to disk). In this case subsequent calls to this function return the rowid | ||||
| 3028 | ** associated with these internal INSERT operations, which leads to | ||||
| 3029 | ** unintuitive results. Virtual table implementations that do write to rowid | ||||
| 3030 | ** tables in this way can avoid this problem by restoring the original | ||||
| 3031 | ** rowid value using [sqlite3_set_last_insert_rowid()] before returning | ||||
| 3032 | ** control to the user. | ||||
| 3033 | ** | ||||
| 3034 | ** ^(If an [INSERT] occurs within a trigger then this routine will | ||||
| 3035 | ** return the [rowid] of the inserted row as long as the trigger is | ||||
| 3036 | ** running. Once the trigger program ends, the value returned | ||||
| 3037 | ** by this routine reverts to what it was before the trigger was fired.)^ | ||||
| 3038 | ** | ||||
| 3039 | ** ^An [INSERT] that fails due to a constraint violation is not a | ||||
| 3040 | ** successful [INSERT] and does not change the value returned by this | ||||
| 3041 | ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, | ||||
| 3042 | ** and INSERT OR ABORT make no changes to the return value of this | ||||
| 3043 | ** routine when their insertion fails. ^(When INSERT OR REPLACE | ||||
| 3044 | ** encounters a constraint violation, it does not fail. The | ||||
| 3045 | ** INSERT continues to completion after deleting rows that caused | ||||
| 3046 | ** the constraint problem so INSERT OR REPLACE will always change | ||||
| 3047 | ** the return value of this interface.)^ | ||||
| 3048 | ** | ||||
| 3049 | ** ^For the purposes of this routine, an [INSERT] is considered to | ||||
| 3050 | ** be successful even if it is subsequently rolled back. | ||||
| 3051 | ** | ||||
| 3052 | ** This function is accessible to SQL statements via the | ||||
| 3053 | ** [last_insert_rowid() SQL function]. | ||||
| 3054 | ** | ||||
| 3055 | ** If a separate thread performs a new [INSERT] on the same | ||||
| 3056 | ** database connection while the [sqlite3_last_insert_rowid()] | ||||
| 3057 | ** function is running and thus changes the last insert [rowid], | ||||
| 3058 | ** then the value returned by [sqlite3_last_insert_rowid()] is | ||||
| 3059 | ** unpredictable and might not equal either the old or the new | ||||
| 3060 | ** last insert [rowid]. | ||||
| 3061 | */ | ||||
| 3062 | SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); | ||||
| 3063 | |||||
| 3064 | /* | ||||
| 3065 | ** CAPI3REF: Set the Last Insert Rowid value. | ||||
| 3066 | ** METHOD: sqlite3 | ||||
| 3067 | ** | ||||
| 3068 | ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to | ||||
| 3069 | ** set the value returned by calling sqlite3_last_insert_rowid(D) to R | ||||
| 3070 | ** without inserting a row into the database. | ||||
| 3071 | */ | ||||
| 3072 | SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64); | ||||
| 3073 | |||||
| 3074 | /* | ||||
| 3075 | ** CAPI3REF: Count The Number Of Rows Modified | ||||
| 3076 | ** METHOD: sqlite3 | ||||
| 3077 | ** | ||||
| 3078 | ** ^These functions return the number of rows modified, inserted or | ||||
| 3079 | ** deleted by the most recently completed INSERT, UPDATE or DELETE | ||||
| 3080 | ** statement on the database connection specified by the only parameter. | ||||
| 3081 | ** The two functions are identical except for the type of the return value | ||||
| 3082 | ** and that if the number of rows modified by the most recent INSERT, UPDATE, | ||||
| 3083 | ** or DELETE is greater than the maximum value supported by type "int", then | ||||
| 3084 | ** the return value of sqlite3_changes() is undefined. ^Executing any other | ||||
| 3085 | ** type of SQL statement does not modify the value returned by these functions. | ||||
| 3086 | ** For the purposes of this interface, a CREATE TABLE AS SELECT statement | ||||
| 3087 | ** does not count as an INSERT, UPDATE or DELETE statement and hence the rows | ||||
| 3088 | ** added to the new table by the CREATE TABLE AS SELECT statement are not | ||||
| 3089 | ** counted. | ||||
| 3090 | ** | ||||
| 3091 | ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are | ||||
| 3092 | ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], | ||||
| 3093 | ** [foreign key actions] or [REPLACE] constraint resolution are not counted. | ||||
| 3094 | ** | ||||
| 3095 | ** Changes to a view that are intercepted by | ||||
| 3096 | ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value | ||||
| 3097 | ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or | ||||
| 3098 | ** DELETE statement run on a view is always zero. Only changes made to real | ||||
| 3099 | ** tables are counted. | ||||
| 3100 | ** | ||||
| 3101 | ** Things are more complicated if the sqlite3_changes() function is | ||||
| 3102 | ** executed while a trigger program is running. This may happen if the | ||||
| 3103 | ** program uses the [changes() SQL function], or if some other callback | ||||
| 3104 | ** function invokes sqlite3_changes() directly. Essentially: | ||||
| 3105 | ** | ||||
| 3106 | ** <ul> | ||||
| 3107 | ** <li> ^(Before entering a trigger program the value returned by | ||||
| 3108 | ** sqlite3_changes() function is saved. After the trigger program | ||||
| 3109 | ** has finished, the original value is restored.)^ | ||||
| 3110 | ** | ||||
| 3111 | ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE | ||||
| 3112 | ** statement sets the value returned by sqlite3_changes() | ||||
| 3113 | ** upon completion as normal. Of course, this value will not include | ||||
| 3114 | ** any changes performed by sub-triggers, as the sqlite3_changes() | ||||
| 3115 | ** value will be saved and restored after each sub-trigger has run.)^ | ||||
| 3116 | ** </ul> | ||||
| 3117 | ** | ||||
| 3118 | ** ^This means that if the changes() SQL function (or similar) is used | ||||
| 3119 | ** by the first INSERT, UPDATE or DELETE statement within a trigger, it | ||||
| 3120 | ** returns the value as set when the calling statement began executing. | ||||
| 3121 | ** ^If it is used by the second or subsequent such statement within a trigger | ||||
| 3122 | ** program, the value returned reflects the number of rows modified by the | ||||
| 3123 | ** previous INSERT, UPDATE or DELETE statement within the same trigger. | ||||
| 3124 | ** | ||||
| 3125 | ** If a separate thread makes changes on the same database connection | ||||
| 3126 | ** while [sqlite3_changes()] is running then the value returned | ||||
| 3127 | ** is unpredictable and not meaningful. | ||||
| 3128 | ** | ||||
| 3129 | ** See also: | ||||
| 3130 | ** <ul> | ||||
| 3131 | ** <li> the [sqlite3_total_changes()] interface | ||||
| 3132 | ** <li> the [count_changes pragma] | ||||
| 3133 | ** <li> the [changes() SQL function] | ||||
| 3134 | ** <li> the [data_version pragma] | ||||
| 3135 | ** </ul> | ||||
| 3136 | */ | ||||
| 3137 | SQLITE_API int sqlite3_changes(sqlite3*); | ||||
| 3138 | SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*); | ||||
| 3139 | |||||
| 3140 | /* | ||||
| 3141 | ** CAPI3REF: Total Number Of Rows Modified | ||||
| 3142 | ** METHOD: sqlite3 | ||||
| 3143 | ** | ||||
| 3144 | ** ^These functions return the total number of rows inserted, modified or | ||||
| 3145 | ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed | ||||
| 3146 | ** since the database connection was opened, including those executed as | ||||
| 3147 | ** part of trigger programs. The two functions are identical except for the | ||||
| 3148 | ** type of the return value and that if the number of rows modified by the | ||||
| 3149 | ** connection exceeds the maximum value supported by type "int", then | ||||
| 3150 | ** the return value of sqlite3_total_changes() is undefined. ^Executing | ||||
| 3151 | ** any other type of SQL statement does not affect the value returned by | ||||
| 3152 | ** sqlite3_total_changes(). | ||||
| 3153 | ** | ||||
| 3154 | ** ^Changes made as part of [foreign key actions] are included in the | ||||
| 3155 | ** count, but those made as part of REPLACE constraint resolution are | ||||
| 3156 | ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers | ||||
| 3157 | ** are not counted. | ||||
| 3158 | ** | ||||
| 3159 | ** The [sqlite3_total_changes(D)] interface only reports the number | ||||
| 3160 | ** of rows that changed due to SQL statement run against database | ||||
| 3161 | ** connection D. Any changes by other database connections are ignored. | ||||
| 3162 | ** To detect changes against a database file from other database | ||||
| 3163 | ** connections use the [PRAGMA data_version] command or the | ||||
| 3164 | ** [SQLITE_FCNTL_DATA_VERSION] [file control]. | ||||
| 3165 | ** | ||||
| 3166 | ** If a separate thread makes changes on the same database connection | ||||
| 3167 | ** while [sqlite3_total_changes()] is running then the value | ||||
| 3168 | ** returned is unpredictable and not meaningful. | ||||
| 3169 | ** | ||||
| 3170 | ** See also: | ||||
| 3171 | ** <ul> | ||||
| 3172 | ** <li> the [sqlite3_changes()] interface | ||||
| 3173 | ** <li> the [count_changes pragma] | ||||
| 3174 | ** <li> the [changes() SQL function] | ||||
| 3175 | ** <li> the [data_version pragma] | ||||
| 3176 | ** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control] | ||||
| 3177 | ** </ul> | ||||
| 3178 | */ | ||||
| 3179 | SQLITE_API int sqlite3_total_changes(sqlite3*); | ||||
| 3180 | SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*); | ||||
| 3181 | |||||
| 3182 | /* | ||||
| 3183 | ** CAPI3REF: Interrupt A Long-Running Query | ||||
| 3184 | ** METHOD: sqlite3 | ||||
| 3185 | ** | ||||
| 3186 | ** ^This function causes any pending database operation to abort and | ||||
| 3187 | ** return at its earliest opportunity. This routine is typically | ||||
| 3188 | ** called in response to a user action such as pressing "Cancel" | ||||
| 3189 | ** or Ctrl-C where the user wants a long query operation to halt | ||||
| 3190 | ** immediately. | ||||
| 3191 | ** | ||||
| 3192 | ** ^It is safe to call this routine from a thread different from the | ||||
| 3193 | ** thread that is currently running the database operation. But it | ||||
| 3194 | ** is not safe to call this routine with a [database connection] that | ||||
| 3195 | ** is closed or might close before sqlite3_interrupt() returns. | ||||
| 3196 | ** | ||||
| 3197 | ** ^If an SQL operation is very nearly finished at the time when | ||||
| 3198 | ** sqlite3_interrupt() is called, then it might not have an opportunity | ||||
| 3199 | ** to be interrupted and might continue to completion. | ||||
| 3200 | ** | ||||
| 3201 | ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. | ||||
| 3202 | ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE | ||||
| 3203 | ** that is inside an explicit transaction, then the entire transaction | ||||
| 3204 | ** will be rolled back automatically. | ||||
| 3205 | ** | ||||
| 3206 | ** ^The sqlite3_interrupt(D) call is in effect until all currently running | ||||
| 3207 | ** SQL statements on [database connection] D complete. ^Any new SQL statements | ||||
| 3208 | ** that are started after the sqlite3_interrupt() call and before the | ||||
| 3209 | ** running statement count reaches zero are interrupted as if they had been | ||||
| 3210 | ** running prior to the sqlite3_interrupt() call. ^New SQL statements | ||||
| 3211 | ** that are started after the running statement count reaches zero are | ||||
| 3212 | ** not effected by the sqlite3_interrupt(). | ||||
| 3213 | ** ^A call to sqlite3_interrupt(D) that occurs when there are no running | ||||
| 3214 | ** SQL statements is a no-op and has no effect on SQL statements | ||||
| 3215 | ** that are started after the sqlite3_interrupt() call returns. | ||||
| 3216 | ** | ||||
| 3217 | ** ^The [sqlite3_is_interrupted(D)] interface can be used to determine whether | ||||
| 3218 | ** or not an interrupt is currently in effect for [database connection] D. | ||||
| 3219 | ** It returns 1 if an interrupt is currently in effect, or 0 otherwise. | ||||
| 3220 | */ | ||||
| 3221 | SQLITE_API void sqlite3_interrupt(sqlite3*); | ||||
| 3222 | SQLITE_API int sqlite3_is_interrupted(sqlite3*); | ||||
| 3223 | |||||
| 3224 | /* | ||||
| 3225 | ** CAPI3REF: Determine If An SQL Statement Is Complete | ||||
| 3226 | ** | ||||
| 3227 | ** These routines are useful during command-line input to determine if the | ||||
| 3228 | ** currently entered text seems to form a complete SQL statement or | ||||
| 3229 | ** if additional input is needed before sending the text into | ||||
| 3230 | ** SQLite for parsing. ^These routines return 1 if the input string | ||||
| 3231 | ** appears to be a complete SQL statement. ^A statement is judged to be | ||||
| 3232 | ** complete if it ends with a semicolon token and is not a prefix of a | ||||
| 3233 | ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within | ||||
| 3234 | ** string literals or quoted identifier names or comments are not | ||||
| 3235 | ** independent tokens (they are part of the token in which they are | ||||
| 3236 | ** embedded) and thus do not count as a statement terminator. ^Whitespace | ||||
| 3237 | ** and comments that follow the final semicolon are ignored. | ||||
| 3238 | ** | ||||
| 3239 | ** ^These routines return 0 if the statement is incomplete. ^If a | ||||
| 3240 | ** memory allocation fails, then SQLITE_NOMEM is returned. | ||||
| 3241 | ** | ||||
| 3242 | ** ^These routines do not parse the SQL statements thus | ||||
| 3243 | ** will not detect syntactically incorrect SQL. | ||||
| 3244 | ** | ||||
| 3245 | ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior | ||||
| 3246 | ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked | ||||
| 3247 | ** automatically by sqlite3_complete16(). If that initialization fails, | ||||
| 3248 | ** then the return value from sqlite3_complete16() will be non-zero | ||||
| 3249 | ** regardless of whether or not the input SQL is complete.)^ | ||||
| 3250 | ** | ||||
| 3251 | ** The input to [sqlite3_complete()] must be a zero-terminated | ||||
| 3252 | ** UTF-8 string. | ||||
| 3253 | ** | ||||
| 3254 | ** The input to [sqlite3_complete16()] must be a zero-terminated | ||||
| 3255 | ** UTF-16 string in native byte order. | ||||
| 3256 | */ | ||||
| 3257 | SQLITE_API int sqlite3_complete(const char *sql); | ||||
| 3258 | SQLITE_API int sqlite3_complete16(const void *sql); | ||||
| 3259 | |||||
| 3260 | /* | ||||
| 3261 | ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors | ||||
| 3262 | ** KEYWORDS: {busy-handler callback} {busy handler} | ||||
| 3263 | ** METHOD: sqlite3 | ||||
| 3264 | ** | ||||
| 3265 | ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X | ||||
| 3266 | ** that might be invoked with argument P whenever | ||||
| 3267 | ** an attempt is made to access a database table associated with | ||||
| 3268 | ** [database connection] D when another thread | ||||
| 3269 | ** or process has the table locked. | ||||
| 3270 | ** The sqlite3_busy_handler() interface is used to implement | ||||
| 3271 | ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. | ||||
| 3272 | ** | ||||
| 3273 | ** ^If the busy callback is NULL, then [SQLITE_BUSY] | ||||
| 3274 | ** is returned immediately upon encountering the lock. ^If the busy callback | ||||
| 3275 | ** is not NULL, then the callback might be invoked with two arguments. | ||||
| 3276 | ** | ||||
| 3277 | ** ^The first argument to the busy handler is a copy of the void* pointer which | ||||
| 3278 | ** is the third argument to sqlite3_busy_handler(). ^The second argument to | ||||
| 3279 | ** the busy handler callback is the number of times that the busy handler has | ||||
| 3280 | ** been invoked previously for the same locking event. ^If the | ||||
| 3281 | ** busy callback returns 0, then no additional attempts are made to | ||||
| 3282 | ** access the database and [SQLITE_BUSY] is returned | ||||
| 3283 | ** to the application. | ||||
| 3284 | ** ^If the callback returns non-zero, then another attempt | ||||
| 3285 | ** is made to access the database and the cycle repeats. | ||||
| 3286 | ** | ||||
| 3287 | ** The presence of a busy handler does not guarantee that it will be invoked | ||||
| 3288 | ** when there is lock contention. ^If SQLite determines that invoking the busy | ||||
| 3289 | ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] | ||||
| 3290 | ** to the application instead of invoking the | ||||
| 3291 | ** busy handler. | ||||
| 3292 | ** Consider a scenario where one process is holding a read lock that | ||||
| 3293 | ** it is trying to promote to a reserved lock and | ||||
| 3294 | ** a second process is holding a reserved lock that it is trying | ||||
| 3295 | ** to promote to an exclusive lock. The first process cannot proceed | ||||
| 3296 | ** because it is blocked by the second and the second process cannot | ||||
| 3297 | ** proceed because it is blocked by the first. If both processes | ||||
| 3298 | ** invoke the busy handlers, neither will make any progress. Therefore, | ||||
| 3299 | ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this | ||||
| 3300 | ** will induce the first process to release its read lock and allow | ||||
| 3301 | ** the second process to proceed. | ||||
| 3302 | ** | ||||
| 3303 | ** ^The default busy callback is NULL. | ||||
| 3304 | ** | ||||
| 3305 | ** ^(There can only be a single busy handler defined for each | ||||
| 3306 | ** [database connection]. Setting a new busy handler clears any | ||||
| 3307 | ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] | ||||
| 3308 | ** or evaluating [PRAGMA busy_timeout=N] will change the | ||||
| 3309 | ** busy handler and thus clear any previously set busy handler. | ||||
| 3310 | ** | ||||
| 3311 | ** The busy callback should not take any actions which modify the | ||||
| 3312 | ** database connection that invoked the busy handler. In other words, | ||||
| 3313 | ** the busy handler is not reentrant. Any such actions | ||||
| 3314 | ** result in undefined behavior. | ||||
| 3315 | ** | ||||
| 3316 | ** A busy handler must not close the database connection | ||||
| 3317 | ** or [prepared statement] that invoked the busy handler. | ||||
| 3318 | */ | ||||
| 3319 | SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); | ||||
| 3320 | |||||
| 3321 | /* | ||||
| 3322 | ** CAPI3REF: Set A Busy Timeout | ||||
| 3323 | ** METHOD: sqlite3 | ||||
| 3324 | ** | ||||
| 3325 | ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps | ||||
| 3326 | ** for a specified amount of time when a table is locked. ^The handler | ||||
| 3327 | ** will sleep multiple times until at least "ms" milliseconds of sleeping | ||||
| 3328 | ** have accumulated. ^After at least "ms" milliseconds of sleeping, | ||||
| 3329 | ** the handler returns 0 which causes [sqlite3_step()] to return | ||||
| 3330 | ** [SQLITE_BUSY]. | ||||
| 3331 | ** | ||||
| 3332 | ** ^Calling this routine with an argument less than or equal to zero | ||||
| 3333 | ** turns off all busy handlers. | ||||
| 3334 | ** | ||||
| 3335 | ** ^(There can only be a single busy handler for a particular | ||||
| 3336 | ** [database connection] at any given moment. If another busy handler | ||||
| 3337 | ** was defined (using [sqlite3_busy_handler()]) prior to calling | ||||
| 3338 | ** this routine, that other busy handler is cleared.)^ | ||||
| 3339 | ** | ||||
| 3340 | ** See also: [PRAGMA busy_timeout] | ||||
| 3341 | */ | ||||
| 3342 | SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); | ||||
| 3343 | |||||
| 3344 | /* | ||||
| 3345 | ** CAPI3REF: Set the Setlk Timeout | ||||
| 3346 | ** METHOD: sqlite3 | ||||
| 3347 | ** | ||||
| 3348 | ** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If | ||||
| 3349 | ** the VFS supports blocking locks, it sets the timeout in ms used by | ||||
| 3350 | ** eligible locks taken on wal mode databases by the specified database | ||||
| 3351 | ** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does | ||||
| 3352 | ** not support blocking locks, this function is a no-op. | ||||
| 3353 | ** | ||||
| 3354 | ** Passing 0 to this function disables blocking locks altogether. Passing | ||||
| 3355 | ** -1 to this function requests that the VFS blocks for a long time - | ||||
| 3356 | ** indefinitely if possible. The results of passing any other negative value | ||||
| 3357 | ** are undefined. | ||||
| 3358 | ** | ||||
| 3359 | ** Internally, each SQLite database handle store two timeout values - the | ||||
| 3360 | ** busy-timeout (used for rollback mode databases, or if the VFS does not | ||||
| 3361 | ** support blocking locks) and the setlk-timeout (used for blocking locks | ||||
| 3362 | ** on wal-mode databases). The sqlite3_busy_timeout() method sets both | ||||
| 3363 | ** values, this function sets only the setlk-timeout value. Therefore, | ||||
| 3364 | ** to configure separate busy-timeout and setlk-timeout values for a single | ||||
| 3365 | ** database handle, call sqlite3_busy_timeout() followed by this function. | ||||
| 3366 | ** | ||||
| 3367 | ** Whenever the number of connections to a wal mode database falls from | ||||
| 3368 | ** 1 to 0, the last connection takes an exclusive lock on the database, | ||||
| 3369 | ** then checkpoints and deletes the wal file. While it is doing this, any | ||||
| 3370 | ** new connection that tries to read from the database fails with an | ||||
| 3371 | ** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is | ||||
| 3372 | ** passed to this API, the new connection blocks until the exclusive lock | ||||
| 3373 | ** has been released. | ||||
| 3374 | */ | ||||
| 3375 | SQLITE_API int sqlite3_setlk_timeout(sqlite3*, int ms, int flags); | ||||
| 3376 | |||||
| 3377 | /* | ||||
| 3378 | ** CAPI3REF: Flags for sqlite3_setlk_timeout() | ||||
| 3379 | */ | ||||
| 3380 | #define SQLITE_SETLK_BLOCK_ON_CONNECT0x01 0x01 | ||||
| 3381 | |||||
| 3382 | /* | ||||
| 3383 | ** CAPI3REF: Convenience Routines For Running Queries | ||||
| 3384 | ** METHOD: sqlite3 | ||||
| 3385 | ** | ||||
| 3386 | ** This is a legacy interface that is preserved for backwards compatibility. | ||||
| 3387 | ** Use of this interface is not recommended. | ||||
| 3388 | ** | ||||
| 3389 | ** Definition: A <b>result table</b> is memory data structure created by the | ||||
| 3390 | ** [sqlite3_get_table()] interface. A result table records the | ||||
| 3391 | ** complete query results from one or more queries. | ||||
| 3392 | ** | ||||
| 3393 | ** The table conceptually has a number of rows and columns. But | ||||
| 3394 | ** these numbers are not part of the result table itself. These | ||||
| 3395 | ** numbers are obtained separately. Let N be the number of rows | ||||
| 3396 | ** and M be the number of columns. | ||||
| 3397 | ** | ||||
| 3398 | ** A result table is an array of pointers to zero-terminated UTF-8 strings. | ||||
| 3399 | ** There are (N+1)*M elements in the array. The first M pointers point | ||||
| 3400 | ** to zero-terminated strings that contain the names of the columns. | ||||
| 3401 | ** The remaining entries all point to query results. NULL values result | ||||
| 3402 | ** in NULL pointers. All other values are in their UTF-8 zero-terminated | ||||
| 3403 | ** string representation as returned by [sqlite3_column_text()]. | ||||
| 3404 | ** | ||||
| 3405 | ** A result table might consist of one or more memory allocations. | ||||
| 3406 | ** It is not safe to pass a result table directly to [sqlite3_free()]. | ||||
| 3407 | ** A result table should be deallocated using [sqlite3_free_table()]. | ||||
| 3408 | ** | ||||
| 3409 | ** ^(As an example of the result table format, suppose a query result | ||||
| 3410 | ** is as follows: | ||||
| 3411 | ** | ||||
| 3412 | ** <blockquote><pre> | ||||
| 3413 | ** Name | Age | ||||
| 3414 | ** ----------------------- | ||||
| 3415 | ** Alice | 43 | ||||
| 3416 | ** Bob | 28 | ||||
| 3417 | ** Cindy | 21 | ||||
| 3418 | ** </pre></blockquote> | ||||
| 3419 | ** | ||||
| 3420 | ** There are two columns (M==2) and three rows (N==3). Thus the | ||||
| 3421 | ** result table has 8 entries. Suppose the result table is stored | ||||
| 3422 | ** in an array named azResult. Then azResult holds this content: | ||||
| 3423 | ** | ||||
| 3424 | ** <blockquote><pre> | ||||
| 3425 | ** azResult[0] = "Name"; | ||||
| 3426 | ** azResult[1] = "Age"; | ||||
| 3427 | ** azResult[2] = "Alice"; | ||||
| 3428 | ** azResult[3] = "43"; | ||||
| 3429 | ** azResult[4] = "Bob"; | ||||
| 3430 | ** azResult[5] = "28"; | ||||
| 3431 | ** azResult[6] = "Cindy"; | ||||
| 3432 | ** azResult[7] = "21"; | ||||
| 3433 | ** </pre></blockquote>)^ | ||||
| 3434 | ** | ||||
| 3435 | ** ^The sqlite3_get_table() function evaluates one or more | ||||
| 3436 | ** semicolon-separated SQL statements in the zero-terminated UTF-8 | ||||
| 3437 | ** string of its 2nd parameter and returns a result table to the | ||||
| 3438 | ** pointer given in its 3rd parameter. | ||||
| 3439 | ** | ||||
| 3440 | ** After the application has finished with the result from sqlite3_get_table(), | ||||
| 3441 | ** it must pass the result table pointer to sqlite3_free_table() in order to | ||||
| 3442 | ** release the memory that was malloced. Because of the way the | ||||
| 3443 | ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling | ||||
| 3444 | ** function must not try to call [sqlite3_free()] directly. Only | ||||
| 3445 | ** [sqlite3_free_table()] is able to release the memory properly and safely. | ||||
| 3446 | ** | ||||
| 3447 | ** The sqlite3_get_table() interface is implemented as a wrapper around | ||||
| 3448 | ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access | ||||
| 3449 | ** to any internal data structures of SQLite. It uses only the public | ||||
| 3450 | ** interface defined here. As a consequence, errors that occur in the | ||||
| 3451 | ** wrapper layer outside of the internal [sqlite3_exec()] call are not | ||||
| 3452 | ** reflected in subsequent calls to [sqlite3_errcode()] or | ||||
| 3453 | ** [sqlite3_errmsg()]. | ||||
| 3454 | */ | ||||
| 3455 | SQLITE_API int sqlite3_get_table( | ||||
| 3456 | sqlite3 *db, /* An open database */ | ||||
| 3457 | const char *zSql, /* SQL to be evaluated */ | ||||
| 3458 | char ***pazResult, /* Results of the query */ | ||||
| 3459 | int *pnRow, /* Number of result rows written here */ | ||||
| 3460 | int *pnColumn, /* Number of result columns written here */ | ||||
| 3461 | char **pzErrmsg /* Error msg written here */ | ||||
| 3462 | ); | ||||
| 3463 | SQLITE_API void sqlite3_free_table(char **result); | ||||
| 3464 | |||||
| 3465 | /* | ||||
| 3466 | ** CAPI3REF: Formatted String Printing Functions | ||||
| 3467 | ** | ||||
| 3468 | ** These routines are work-alikes of the "printf()" family of functions | ||||
| 3469 | ** from the standard C library. | ||||
| 3470 | ** These routines understand most of the common formatting options from | ||||
| 3471 | ** the standard library printf() | ||||
| 3472 | ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]). | ||||
| 3473 | ** See the [built-in printf()] documentation for details. | ||||
| 3474 | ** | ||||
| 3475 | ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their | ||||
| 3476 | ** results into memory obtained from [sqlite3_malloc64()]. | ||||
| 3477 | ** The strings returned by these two routines should be | ||||
| 3478 | ** released by [sqlite3_free()]. ^Both routines return a | ||||
| 3479 | ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough | ||||
| 3480 | ** memory to hold the resulting string. | ||||
| 3481 | ** | ||||
| 3482 | ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from | ||||
| 3483 | ** the standard C library. The result is written into the | ||||
| 3484 | ** buffer supplied as the second parameter whose size is given by | ||||
| 3485 | ** the first parameter. Note that the order of the | ||||
| 3486 | ** first two parameters is reversed from snprintf().)^ This is an | ||||
| 3487 | ** historical accident that cannot be fixed without breaking | ||||
| 3488 | ** backwards compatibility. ^(Note also that sqlite3_snprintf() | ||||
| 3489 | ** returns a pointer to its buffer instead of the number of | ||||
| 3490 | ** characters actually written into the buffer.)^ We admit that | ||||
| 3491 | ** the number of characters written would be a more useful return | ||||
| 3492 | ** value but we cannot change the implementation of sqlite3_snprintf() | ||||
| 3493 | ** now without breaking compatibility. | ||||
| 3494 | ** | ||||
| 3495 | ** ^As long as the buffer size is greater than zero, sqlite3_snprintf() | ||||
| 3496 | ** guarantees that the buffer is always zero-terminated. ^The first | ||||
| 3497 | ** parameter "n" is the total size of the buffer, including space for | ||||
| 3498 | ** the zero terminator. So the longest string that can be completely | ||||
| 3499 | ** written will be n-1 characters. | ||||
| 3500 | ** | ||||
| 3501 | ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). | ||||
| 3502 | ** | ||||
| 3503 | ** See also: [built-in printf()], [printf() SQL function] | ||||
| 3504 | */ | ||||
| 3505 | SQLITE_API char *sqlite3_mprintf(const char*,...); | ||||
| 3506 | SQLITE_API char *sqlite3_vmprintf(const char*, va_list); | ||||
| 3507 | SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); | ||||
| 3508 | SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); | ||||
| 3509 | |||||
| 3510 | /* | ||||
| 3511 | ** CAPI3REF: Memory Allocation Subsystem | ||||
| 3512 | ** | ||||
| 3513 | ** The SQLite core uses these three routines for all of its own | ||||
| 3514 | ** internal memory allocation needs. "Core" in the previous sentence | ||||
| 3515 | ** does not include operating-system specific [VFS] implementation. The | ||||
| 3516 | ** Windows VFS uses native malloc() and free() for some operations. | ||||
| 3517 | ** | ||||
| 3518 | ** ^The sqlite3_malloc() routine returns a pointer to a block | ||||
| 3519 | ** of memory at least N bytes in length, where N is the parameter. | ||||
| 3520 | ** ^If sqlite3_malloc() is unable to obtain sufficient free | ||||
| 3521 | ** memory, it returns a NULL pointer. ^If the parameter N to | ||||
| 3522 | ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns | ||||
| 3523 | ** a NULL pointer. | ||||
| 3524 | ** | ||||
| 3525 | ** ^The sqlite3_malloc64(N) routine works just like | ||||
| 3526 | ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead | ||||
| 3527 | ** of a signed 32-bit integer. | ||||
| 3528 | ** | ||||
| 3529 | ** ^Calling sqlite3_free() with a pointer previously returned | ||||
| 3530 | ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so | ||||
| 3531 | ** that it might be reused. ^The sqlite3_free() routine is | ||||
| 3532 | ** a no-op if is called with a NULL pointer. Passing a NULL pointer | ||||
| 3533 | ** to sqlite3_free() is harmless. After being freed, memory | ||||
| 3534 | ** should neither be read nor written. Even reading previously freed | ||||
| 3535 | ** memory might result in a segmentation fault or other severe error. | ||||
| 3536 | ** Memory corruption, a segmentation fault, or other severe error | ||||
| 3537 | ** might result if sqlite3_free() is called with a non-NULL pointer that | ||||
| 3538 | ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). | ||||
| 3539 | ** | ||||
| 3540 | ** ^The sqlite3_realloc(X,N) interface attempts to resize a | ||||
| 3541 | ** prior memory allocation X to be at least N bytes. | ||||
| 3542 | ** ^If the X parameter to sqlite3_realloc(X,N) | ||||
| 3543 | ** is a NULL pointer then its behavior is identical to calling | ||||
| 3544 | ** sqlite3_malloc(N). | ||||
| 3545 | ** ^If the N parameter to sqlite3_realloc(X,N) is zero or | ||||
| 3546 | ** negative then the behavior is exactly the same as calling | ||||
| 3547 | ** sqlite3_free(X). | ||||
| 3548 | ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation | ||||
| 3549 | ** of at least N bytes in size or NULL if insufficient memory is available. | ||||
| 3550 | ** ^If M is the size of the prior allocation, then min(N,M) bytes | ||||
| 3551 | ** of the prior allocation are copied into the beginning of buffer returned | ||||
| 3552 | ** by sqlite3_realloc(X,N) and the prior allocation is freed. | ||||
| 3553 | ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the | ||||
| 3554 | ** prior allocation is not freed. | ||||
| 3555 | ** | ||||
| 3556 | ** ^The sqlite3_realloc64(X,N) interfaces works the same as | ||||
| 3557 | ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead | ||||
| 3558 | ** of a 32-bit signed integer. | ||||
| 3559 | ** | ||||
| 3560 | ** ^If X is a memory allocation previously obtained from sqlite3_malloc(), | ||||
| 3561 | ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then | ||||
| 3562 | ** sqlite3_msize(X) returns the size of that memory allocation in bytes. | ||||
| 3563 | ** ^The value returned by sqlite3_msize(X) might be larger than the number | ||||
| 3564 | ** of bytes requested when X was allocated. ^If X is a NULL pointer then | ||||
| 3565 | ** sqlite3_msize(X) returns zero. If X points to something that is not | ||||
| 3566 | ** the beginning of memory allocation, or if it points to a formerly | ||||
| 3567 | ** valid memory allocation that has now been freed, then the behavior | ||||
| 3568 | ** of sqlite3_msize(X) is undefined and possibly harmful. | ||||
| 3569 | ** | ||||
| 3570 | ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), | ||||
| 3571 | ** sqlite3_malloc64(), and sqlite3_realloc64() | ||||
| 3572 | ** is always aligned to at least an 8 byte boundary, or to a | ||||
| 3573 | ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time | ||||
| 3574 | ** option is used. | ||||
| 3575 | ** | ||||
| 3576 | ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] | ||||
| 3577 | ** must be either NULL or else pointers obtained from a prior | ||||
| 3578 | ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have | ||||
| 3579 | ** not yet been released. | ||||
| 3580 | ** | ||||
| 3581 | ** The application must not read or write any part of | ||||
| 3582 | ** a block of memory after it has been released using | ||||
| 3583 | ** [sqlite3_free()] or [sqlite3_realloc()]. | ||||
| 3584 | */ | ||||
| 3585 | SQLITE_API void *sqlite3_malloc(int); | ||||
| 3586 | SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); | ||||
| 3587 | SQLITE_API void *sqlite3_realloc(void*, int); | ||||
| 3588 | SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); | ||||
| 3589 | SQLITE_API void sqlite3_free(void*); | ||||
| 3590 | SQLITE_API sqlite3_uint64 sqlite3_msize(void*); | ||||
| 3591 | |||||
| 3592 | /* | ||||
| 3593 | ** CAPI3REF: Memory Allocator Statistics | ||||
| 3594 | ** | ||||
| 3595 | ** SQLite provides these two interfaces for reporting on the status | ||||
| 3596 | ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] | ||||
| 3597 | ** routines, which form the built-in memory allocation subsystem. | ||||
| 3598 | ** | ||||
| 3599 | ** ^The [sqlite3_memory_used()] routine returns the number of bytes | ||||
| 3600 | ** of memory currently outstanding (malloced but not freed). | ||||
| 3601 | ** ^The [sqlite3_memory_highwater()] routine returns the maximum | ||||
| 3602 | ** value of [sqlite3_memory_used()] since the high-water mark | ||||
| 3603 | ** was last reset. ^The values returned by [sqlite3_memory_used()] and | ||||
| 3604 | ** [sqlite3_memory_highwater()] include any overhead | ||||
| 3605 | ** added by SQLite in its implementation of [sqlite3_malloc()], | ||||
| 3606 | ** but not overhead added by the any underlying system library | ||||
| 3607 | ** routines that [sqlite3_malloc()] may call. | ||||
| 3608 | ** | ||||
| 3609 | ** ^The memory high-water mark is reset to the current value of | ||||
| 3610 | ** [sqlite3_memory_used()] if and only if the parameter to | ||||
| 3611 | ** [sqlite3_memory_highwater()] is true. ^The value returned | ||||
| 3612 | ** by [sqlite3_memory_highwater(1)] is the high-water mark | ||||
| 3613 | ** prior to the reset. | ||||
| 3614 | */ | ||||
| 3615 | SQLITE_API sqlite3_int64 sqlite3_memory_used(void); | ||||
| 3616 | SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); | ||||
| 3617 | |||||
| 3618 | /* | ||||
| 3619 | ** CAPI3REF: Pseudo-Random Number Generator | ||||
| 3620 | ** | ||||
| 3621 | ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to | ||||
| 3622 | ** select random [ROWID | ROWIDs] when inserting new records into a table that | ||||
| 3623 | ** already uses the largest possible [ROWID]. The PRNG is also used for | ||||
| 3624 | ** the built-in random() and randomblob() SQL functions. This interface allows | ||||
| 3625 | ** applications to access the same PRNG for other purposes. | ||||
| 3626 | ** | ||||
| 3627 | ** ^A call to this routine stores N bytes of randomness into buffer P. | ||||
| 3628 | ** ^The P parameter can be a NULL pointer. | ||||
| 3629 | ** | ||||
| 3630 | ** ^If this routine has not been previously called or if the previous | ||||
| 3631 | ** call had N less than one or a NULL pointer for P, then the PRNG is | ||||
| 3632 | ** seeded using randomness obtained from the xRandomness method of | ||||
| 3633 | ** the default [sqlite3_vfs] object. | ||||
| 3634 | ** ^If the previous call to this routine had an N of 1 or more and a | ||||
| 3635 | ** non-NULL P then the pseudo-randomness is generated | ||||
| 3636 | ** internally and without recourse to the [sqlite3_vfs] xRandomness | ||||
| 3637 | ** method. | ||||
| 3638 | */ | ||||
| 3639 | SQLITE_API void sqlite3_randomness(int N, void *P); | ||||
| 3640 | |||||
| 3641 | /* | ||||
| 3642 | ** CAPI3REF: Compile-Time Authorization Callbacks | ||||
| 3643 | ** METHOD: sqlite3 | ||||
| 3644 | ** KEYWORDS: {authorizer callback} | ||||
| 3645 | ** | ||||
| 3646 | ** ^This routine registers an authorizer callback with a particular | ||||
| 3647 | ** [database connection], supplied in the first argument. | ||||
| 3648 | ** ^The authorizer callback is invoked as SQL statements are being compiled | ||||
| 3649 | ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], | ||||
| 3650 | ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()], | ||||
| 3651 | ** and [sqlite3_prepare16_v3()]. ^At various | ||||
| 3652 | ** points during the compilation process, as logic is being created | ||||
| 3653 | ** to perform various actions, the authorizer callback is invoked to | ||||
| 3654 | ** see if those actions are allowed. ^The authorizer callback should | ||||
| 3655 | ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the | ||||
| 3656 | ** specific action but allow the SQL statement to continue to be | ||||
| 3657 | ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be | ||||
| 3658 | ** rejected with an error. ^If the authorizer callback returns | ||||
| 3659 | ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] | ||||
| 3660 | ** then the [sqlite3_prepare_v2()] or equivalent call that triggered | ||||
| 3661 | ** the authorizer will fail with an error message. | ||||
| 3662 | ** | ||||
| 3663 | ** When the callback returns [SQLITE_OK], that means the operation | ||||
| 3664 | ** requested is ok. ^When the callback returns [SQLITE_DENY], the | ||||
| 3665 | ** [sqlite3_prepare_v2()] or equivalent call that triggered the | ||||
| 3666 | ** authorizer will fail with an error message explaining that | ||||
| 3667 | ** access is denied. | ||||
| 3668 | ** | ||||
| 3669 | ** ^The first parameter to the authorizer callback is a copy of the third | ||||
| 3670 | ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter | ||||
| 3671 | ** to the callback is an integer [SQLITE_COPY | action code] that specifies | ||||
| 3672 | ** the particular action to be authorized. ^The third through sixth parameters | ||||
| 3673 | ** to the callback are either NULL pointers or zero-terminated strings | ||||
| 3674 | ** that contain additional details about the action to be authorized. | ||||
| 3675 | ** Applications must always be prepared to encounter a NULL pointer in any | ||||
| 3676 | ** of the third through the sixth parameters of the authorization callback. | ||||
| 3677 | ** | ||||
| 3678 | ** ^If the action code is [SQLITE_READ] | ||||
| 3679 | ** and the callback returns [SQLITE_IGNORE] then the | ||||
| 3680 | ** [prepared statement] statement is constructed to substitute | ||||
| 3681 | ** a NULL value in place of the table column that would have | ||||
| 3682 | ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] | ||||
| 3683 | ** return can be used to deny an untrusted user access to individual | ||||
| 3684 | ** columns of a table. | ||||
| 3685 | ** ^When a table is referenced by a [SELECT] but no column values are | ||||
| 3686 | ** extracted from that table (for example in a query like | ||||
| 3687 | ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback | ||||
| 3688 | ** is invoked once for that table with a column name that is an empty string. | ||||
| 3689 | ** ^If the action code is [SQLITE_DELETE] and the callback returns | ||||
| 3690 | ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the | ||||
| 3691 | ** [truncate optimization] is disabled and all rows are deleted individually. | ||||
| 3692 | ** | ||||
| 3693 | ** An authorizer is used when [sqlite3_prepare | preparing] | ||||
| 3694 | ** SQL statements from an untrusted source, to ensure that the SQL statements | ||||
| 3695 | ** do not try to access data they are not allowed to see, or that they do not | ||||
| 3696 | ** try to execute malicious statements that damage the database. For | ||||
| 3697 | ** example, an application may allow a user to enter arbitrary | ||||
| 3698 | ** SQL queries for evaluation by a database. But the application does | ||||
| 3699 | ** not want the user to be able to make arbitrary changes to the | ||||
| 3700 | ** database. An authorizer could then be put in place while the | ||||
| 3701 | ** user-entered SQL is being [sqlite3_prepare | prepared] that | ||||
| 3702 | ** disallows everything except [SELECT] statements. | ||||
| 3703 | ** | ||||
| 3704 | ** Applications that need to process SQL from untrusted sources | ||||
| 3705 | ** might also consider lowering resource limits using [sqlite3_limit()] | ||||
| 3706 | ** and limiting database size using the [max_page_count] [PRAGMA] | ||||
| 3707 | ** in addition to using an authorizer. | ||||
| 3708 | ** | ||||
| 3709 | ** ^(Only a single authorizer can be in place on a database connection | ||||
| 3710 | ** at a time. Each call to sqlite3_set_authorizer overrides the | ||||
| 3711 | ** previous call.)^ ^Disable the authorizer by installing a NULL callback. | ||||
| 3712 | ** The authorizer is disabled by default. | ||||
| 3713 | ** | ||||
| 3714 | ** The authorizer callback must not do anything that will modify | ||||
| 3715 | ** the database connection that invoked the authorizer callback. | ||||
| 3716 | ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their | ||||
| 3717 | ** database connections for the meaning of "modify" in this paragraph. | ||||
| 3718 | ** | ||||
| 3719 | ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the | ||||
| 3720 | ** statement might be re-prepared during [sqlite3_step()] due to a | ||||
| 3721 | ** schema change. Hence, the application should ensure that the | ||||
| 3722 | ** correct authorizer callback remains in place during the [sqlite3_step()]. | ||||
| 3723 | ** | ||||
| 3724 | ** ^Note that the authorizer callback is invoked only during | ||||
| 3725 | ** [sqlite3_prepare()] or its variants. Authorization is not | ||||
| 3726 | ** performed during statement evaluation in [sqlite3_step()], unless | ||||
| 3727 | ** as stated in the previous paragraph, sqlite3_step() invokes | ||||
| 3728 | ** sqlite3_prepare_v2() to reprepare a statement after a schema change. | ||||
| 3729 | */ | ||||
| 3730 | SQLITE_API int sqlite3_set_authorizer( | ||||
| 3731 | sqlite3*, | ||||
| 3732 | int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), | ||||
| 3733 | void *pUserData | ||||
| 3734 | ); | ||||
| 3735 | |||||
| 3736 | /* | ||||
| 3737 | ** CAPI3REF: Authorizer Return Codes | ||||
| 3738 | ** | ||||
| 3739 | ** The [sqlite3_set_authorizer | authorizer callback function] must | ||||
| 3740 | ** return either [SQLITE_OK] or one of these two constants in order | ||||
| 3741 | ** to signal SQLite whether or not the action is permitted. See the | ||||
| 3742 | ** [sqlite3_set_authorizer | authorizer documentation] for additional | ||||
| 3743 | ** information. | ||||
| 3744 | ** | ||||
| 3745 | ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] | ||||
| 3746 | ** returned from the [sqlite3_vtab_on_conflict()] interface. | ||||
| 3747 | */ | ||||
| 3748 | #define SQLITE_DENY1 1 /* Abort the SQL statement with an error */ | ||||
| 3749 | #define SQLITE_IGNORE2 2 /* Don't allow access, but don't generate an error */ | ||||
| 3750 | |||||
| 3751 | /* | ||||
| 3752 | ** CAPI3REF: Authorizer Action Codes | ||||
| 3753 | ** | ||||
| 3754 | ** The [sqlite3_set_authorizer()] interface registers a callback function | ||||
| 3755 | ** that is invoked to authorize certain SQL statement actions. The | ||||
| 3756 | ** second parameter to the callback is an integer code that specifies | ||||
| 3757 | ** what action is being authorized. These are the integer action codes that | ||||
| 3758 | ** the authorizer callback may be passed. | ||||
| 3759 | ** | ||||
| 3760 | ** These action code values signify what kind of operation is to be | ||||
| 3761 | ** authorized. The 3rd and 4th parameters to the authorization | ||||
| 3762 | ** callback function will be parameters or NULL depending on which of these | ||||
| 3763 | ** codes is used as the second parameter. ^(The 5th parameter to the | ||||
| 3764 | ** authorizer callback is the name of the database ("main", "temp", | ||||
| 3765 | ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback | ||||
| 3766 | ** is the name of the inner-most trigger or view that is responsible for | ||||
| 3767 | ** the access attempt or NULL if this access attempt is directly from | ||||
| 3768 | ** top-level SQL code. | ||||
| 3769 | */ | ||||
| 3770 | /******************************************* 3rd ************ 4th ***********/ | ||||
| 3771 | #define SQLITE_CREATE_INDEX1 1 /* Index Name Table Name */ | ||||
| 3772 | #define SQLITE_CREATE_TABLE2 2 /* Table Name NULL */ | ||||
| 3773 | #define SQLITE_CREATE_TEMP_INDEX3 3 /* Index Name Table Name */ | ||||
| 3774 | #define SQLITE_CREATE_TEMP_TABLE4 4 /* Table Name NULL */ | ||||
| 3775 | #define SQLITE_CREATE_TEMP_TRIGGER5 5 /* Trigger Name Table Name */ | ||||
| 3776 | #define SQLITE_CREATE_TEMP_VIEW6 6 /* View Name NULL */ | ||||
| 3777 | #define SQLITE_CREATE_TRIGGER7 7 /* Trigger Name Table Name */ | ||||
| 3778 | #define SQLITE_CREATE_VIEW8 8 /* View Name NULL */ | ||||
| 3779 | #define SQLITE_DELETE9 9 /* Table Name NULL */ | ||||
| 3780 | #define SQLITE_DROP_INDEX10 10 /* Index Name Table Name */ | ||||
| 3781 | #define SQLITE_DROP_TABLE11 11 /* Table Name NULL */ | ||||
| 3782 | #define SQLITE_DROP_TEMP_INDEX12 12 /* Index Name Table Name */ | ||||
| 3783 | #define SQLITE_DROP_TEMP_TABLE13 13 /* Table Name NULL */ | ||||
| 3784 | #define SQLITE_DROP_TEMP_TRIGGER14 14 /* Trigger Name Table Name */ | ||||
| 3785 | #define SQLITE_DROP_TEMP_VIEW15 15 /* View Name NULL */ | ||||
| 3786 | #define SQLITE_DROP_TRIGGER16 16 /* Trigger Name Table Name */ | ||||
| 3787 | #define SQLITE_DROP_VIEW17 17 /* View Name NULL */ | ||||
| 3788 | #define SQLITE_INSERT18 18 /* Table Name NULL */ | ||||
| 3789 | #define SQLITE_PRAGMA19 19 /* Pragma Name 1st arg or NULL */ | ||||
| 3790 | #define SQLITE_READ20 20 /* Table Name Column Name */ | ||||
| 3791 | #define SQLITE_SELECT21 21 /* NULL NULL */ | ||||
| 3792 | #define SQLITE_TRANSACTION22 22 /* Operation NULL */ | ||||
| 3793 | #define SQLITE_UPDATE23 23 /* Table Name Column Name */ | ||||
| 3794 | #define SQLITE_ATTACH24 24 /* Filename NULL */ | ||||
| 3795 | #define SQLITE_DETACH25 25 /* Database Name NULL */ | ||||
| 3796 | #define SQLITE_ALTER_TABLE26 26 /* Database Name Table Name */ | ||||
| 3797 | #define SQLITE_REINDEX27 27 /* Index Name NULL */ | ||||
| 3798 | #define SQLITE_ANALYZE28 28 /* Table Name NULL */ | ||||
| 3799 | #define SQLITE_CREATE_VTABLE29 29 /* Table Name Module Name */ | ||||
| 3800 | #define SQLITE_DROP_VTABLE30 30 /* Table Name Module Name */ | ||||
| 3801 | #define SQLITE_FUNCTION31 31 /* NULL Function Name */ | ||||
| 3802 | #define SQLITE_SAVEPOINT32 32 /* Operation Savepoint Name */ | ||||
| 3803 | #define SQLITE_COPY0 0 /* No longer used */ | ||||
| 3804 | #define SQLITE_RECURSIVE33 33 /* NULL NULL */ | ||||
| 3805 | |||||
| 3806 | /* | ||||
| 3807 | ** CAPI3REF: Deprecated Tracing And Profiling Functions | ||||
| 3808 | ** DEPRECATED | ||||
| 3809 | ** | ||||
| 3810 | ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface | ||||
| 3811 | ** instead of the routines described here. | ||||
| 3812 | ** | ||||
| 3813 | ** These routines register callback functions that can be used for | ||||
| 3814 | ** tracing and profiling the execution of SQL statements. | ||||
| 3815 | ** | ||||
| 3816 | ** ^The callback function registered by sqlite3_trace() is invoked at | ||||
| 3817 | ** various times when an SQL statement is being run by [sqlite3_step()]. | ||||
| 3818 | ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the | ||||
| 3819 | ** SQL statement text as the statement first begins executing. | ||||
| 3820 | ** ^(Additional sqlite3_trace() callbacks might occur | ||||
| 3821 | ** as each triggered subprogram is entered. The callbacks for triggers | ||||
| 3822 | ** contain a UTF-8 SQL comment that identifies the trigger.)^ | ||||
| 3823 | ** | ||||
| 3824 | ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit | ||||
| 3825 | ** the length of [bound parameter] expansion in the output of sqlite3_trace(). | ||||
| 3826 | ** | ||||
| 3827 | ** ^The callback function registered by sqlite3_profile() is invoked | ||||
| 3828 | ** as each SQL statement finishes. ^The profile callback contains | ||||
| 3829 | ** the original statement text and an estimate of wall-clock time | ||||
| 3830 | ** of how long that statement took to run. ^The profile callback | ||||
| 3831 | ** time is in units of nanoseconds, however the current implementation | ||||
| 3832 | ** is only capable of millisecond resolution so the six least significant | ||||
| 3833 | ** digits in the time are meaningless. Future versions of SQLite | ||||
| 3834 | ** might provide greater resolution on the profiler callback. Invoking | ||||
| 3835 | ** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the | ||||
| 3836 | ** profile callback. | ||||
| 3837 | */ | ||||
| 3838 | SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*, | ||||
| 3839 | void(*xTrace)(void*,const char*), void*); | ||||
| 3840 | SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*, | ||||
| 3841 | void(*xProfile)(void*,const char*,sqlite3_uint64), void*); | ||||
| 3842 | |||||
| 3843 | /* | ||||
| 3844 | ** CAPI3REF: SQL Trace Event Codes | ||||
| 3845 | ** KEYWORDS: SQLITE_TRACE | ||||
| 3846 | ** | ||||
| 3847 | ** These constants identify classes of events that can be monitored | ||||
| 3848 | ** using the [sqlite3_trace_v2()] tracing logic. The M argument | ||||
| 3849 | ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of | ||||
| 3850 | ** the following constants. ^The first argument to the trace callback | ||||
| 3851 | ** is one of the following constants. | ||||
| 3852 | ** | ||||
| 3853 | ** New tracing constants may be added in future releases. | ||||
| 3854 | ** | ||||
| 3855 | ** ^A trace callback has four arguments: xCallback(T,C,P,X). | ||||
| 3856 | ** ^The T argument is one of the integer type codes above. | ||||
| 3857 | ** ^The C argument is a copy of the context pointer passed in as the | ||||
| 3858 | ** fourth argument to [sqlite3_trace_v2()]. | ||||
| 3859 | ** The P and X arguments are pointers whose meanings depend on T. | ||||
| 3860 | ** | ||||
| 3861 | ** <dl> | ||||
| 3862 | ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt> | ||||
| 3863 | ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement | ||||
| 3864 | ** first begins running and possibly at other times during the | ||||
| 3865 | ** execution of the prepared statement, such as at the start of each | ||||
| 3866 | ** trigger subprogram. ^The P argument is a pointer to the | ||||
| 3867 | ** [prepared statement]. ^The X argument is a pointer to a string which | ||||
| 3868 | ** is the unexpanded SQL text of the prepared statement or an SQL comment | ||||
| 3869 | ** that indicates the invocation of a trigger. ^The callback can compute | ||||
| 3870 | ** the same text that would have been returned by the legacy [sqlite3_trace()] | ||||
| 3871 | ** interface by using the X argument when X begins with "--" and invoking | ||||
| 3872 | ** [sqlite3_expanded_sql(P)] otherwise. | ||||
| 3873 | ** | ||||
| 3874 | ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt> | ||||
| 3875 | ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same | ||||
| 3876 | ** information as is provided by the [sqlite3_profile()] callback. | ||||
| 3877 | ** ^The P argument is a pointer to the [prepared statement] and the | ||||
| 3878 | ** X argument points to a 64-bit integer which is approximately | ||||
| 3879 | ** the number of nanoseconds that the prepared statement took to run. | ||||
| 3880 | ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes. | ||||
| 3881 | ** | ||||
| 3882 | ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt> | ||||
| 3883 | ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared | ||||
| 3884 | ** statement generates a single row of result. | ||||
| 3885 | ** ^The P argument is a pointer to the [prepared statement] and the | ||||
| 3886 | ** X argument is unused. | ||||
| 3887 | ** | ||||
| 3888 | ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt> | ||||
| 3889 | ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database | ||||
| 3890 | ** connection closes. | ||||
| 3891 | ** ^The P argument is a pointer to the [database connection] object | ||||
| 3892 | ** and the X argument is unused. | ||||
| 3893 | ** </dl> | ||||
| 3894 | */ | ||||
| 3895 | #define SQLITE_TRACE_STMT0x01 0x01 | ||||
| 3896 | #define SQLITE_TRACE_PROFILE0x02 0x02 | ||||
| 3897 | #define SQLITE_TRACE_ROW0x04 0x04 | ||||
| 3898 | #define SQLITE_TRACE_CLOSE0x08 0x08 | ||||
| 3899 | |||||
| 3900 | /* | ||||
| 3901 | ** CAPI3REF: SQL Trace Hook | ||||
| 3902 | ** METHOD: sqlite3 | ||||
| 3903 | ** | ||||
| 3904 | ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback | ||||
| 3905 | ** function X against [database connection] D, using property mask M | ||||
| 3906 | ** and context pointer P. ^If the X callback is | ||||
| 3907 | ** NULL or if the M mask is zero, then tracing is disabled. The | ||||
| 3908 | ** M argument should be the bitwise OR-ed combination of | ||||
| 3909 | ** zero or more [SQLITE_TRACE] constants. | ||||
| 3910 | ** | ||||
| 3911 | ** ^Each call to either sqlite3_trace(D,X,P) or sqlite3_trace_v2(D,M,X,P) | ||||
| 3912 | ** overrides (cancels) all prior calls to sqlite3_trace(D,X,P) or | ||||
| 3913 | ** sqlite3_trace_v2(D,M,X,P) for the [database connection] D. Each | ||||
| 3914 | ** database connection may have at most one trace callback. | ||||
| 3915 | ** | ||||
| 3916 | ** ^The X callback is invoked whenever any of the events identified by | ||||
| 3917 | ** mask M occur. ^The integer return value from the callback is currently | ||||
| 3918 | ** ignored, though this may change in future releases. Callback | ||||
| 3919 | ** implementations should return zero to ensure future compatibility. | ||||
| 3920 | ** | ||||
| 3921 | ** ^A trace callback is invoked with four arguments: callback(T,C,P,X). | ||||
| 3922 | ** ^The T argument is one of the [SQLITE_TRACE] | ||||
| 3923 | ** constants to indicate why the callback was invoked. | ||||
| 3924 | ** ^The C argument is a copy of the context pointer. | ||||
| 3925 | ** The P and X arguments are pointers whose meanings depend on T. | ||||
| 3926 | ** | ||||
| 3927 | ** The sqlite3_trace_v2() interface is intended to replace the legacy | ||||
| 3928 | ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which | ||||
| 3929 | ** are deprecated. | ||||
| 3930 | */ | ||||
| 3931 | SQLITE_API int sqlite3_trace_v2( | ||||
| 3932 | sqlite3*, | ||||
| 3933 | unsigned uMask, | ||||
| 3934 | int(*xCallback)(unsigned,void*,void*,void*), | ||||
| 3935 | void *pCtx | ||||
| 3936 | ); | ||||
| 3937 | |||||
| 3938 | /* | ||||
| 3939 | ** CAPI3REF: Query Progress Callbacks | ||||
| 3940 | ** METHOD: sqlite3 | ||||
| 3941 | ** | ||||
| 3942 | ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback | ||||
| 3943 | ** function X to be invoked periodically during long running calls to | ||||
| 3944 | ** [sqlite3_step()] and [sqlite3_prepare()] and similar for | ||||
| 3945 | ** database connection D. An example use for this | ||||
| 3946 | ** interface is to keep a GUI updated during a large query. | ||||
| 3947 | ** | ||||
| 3948 | ** ^The parameter P is passed through as the only parameter to the | ||||
| 3949 | ** callback function X. ^The parameter N is the approximate number of | ||||
| 3950 | ** [virtual machine instructions] that are evaluated between successive | ||||
| 3951 | ** invocations of the callback X. ^If N is less than one then the progress | ||||
| 3952 | ** handler is disabled. | ||||
| 3953 | ** | ||||
| 3954 | ** ^Only a single progress handler may be defined at one time per | ||||
| 3955 | ** [database connection]; setting a new progress handler cancels the | ||||
| 3956 | ** old one. ^Setting parameter X to NULL disables the progress handler. | ||||
| 3957 | ** ^The progress handler is also disabled by setting N to a value less | ||||
| 3958 | ** than 1. | ||||
| 3959 | ** | ||||
| 3960 | ** ^If the progress callback returns non-zero, the operation is | ||||
| 3961 | ** interrupted. This feature can be used to implement a | ||||
| 3962 | ** "Cancel" button on a GUI progress dialog box. | ||||
| 3963 | ** | ||||
| 3964 | ** The progress handler callback must not do anything that will modify | ||||
| 3965 | ** the database connection that invoked the progress handler. | ||||
| 3966 | ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their | ||||
| 3967 | ** database connections for the meaning of "modify" in this paragraph. | ||||
| 3968 | ** | ||||
| 3969 | ** The progress handler callback would originally only be invoked from the | ||||
| 3970 | ** bytecode engine. It still might be invoked during [sqlite3_prepare()] | ||||
| 3971 | ** and similar because those routines might force a reparse of the schema | ||||
| 3972 | ** which involves running the bytecode engine. However, beginning with | ||||
| 3973 | ** SQLite version 3.41.0, the progress handler callback might also be | ||||
| 3974 | ** invoked directly from [sqlite3_prepare()] while analyzing and generating | ||||
| 3975 | ** code for complex queries. | ||||
| 3976 | */ | ||||
| 3977 | SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); | ||||
| 3978 | |||||
| 3979 | /* | ||||
| 3980 | ** CAPI3REF: Opening A New Database Connection | ||||
| 3981 | ** CONSTRUCTOR: sqlite3 | ||||
| 3982 | ** | ||||
| 3983 | ** ^These routines open an SQLite database file as specified by the | ||||
| 3984 | ** filename argument. ^The filename argument is interpreted as UTF-8 for | ||||
| 3985 | ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte | ||||
| 3986 | ** order for sqlite3_open16(). ^(A [database connection] handle is usually | ||||
| 3987 | ** returned in *ppDb, even if an error occurs. The only exception is that | ||||
| 3988 | ** if SQLite is unable to allocate memory to hold the [sqlite3] object, | ||||
| 3989 | ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] | ||||
| 3990 | ** object.)^ ^(If the database is opened (and/or created) successfully, then | ||||
| 3991 | ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The | ||||
| 3992 | ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain | ||||
| 3993 | ** an English language description of the error following a failure of any | ||||
| 3994 | ** of the sqlite3_open() routines. | ||||
| 3995 | ** | ||||
| 3996 | ** ^The default encoding will be UTF-8 for databases created using | ||||
| 3997 | ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases | ||||
| 3998 | ** created using sqlite3_open16() will be UTF-16 in the native byte order. | ||||
| 3999 | ** | ||||
| 4000 | ** Whether or not an error occurs when it is opened, resources | ||||
| 4001 | ** associated with the [database connection] handle should be released by | ||||
| 4002 | ** passing it to [sqlite3_close()] when it is no longer required. | ||||
| 4003 | ** | ||||
| 4004 | ** The sqlite3_open_v2() interface works like sqlite3_open() | ||||
| 4005 | ** except that it accepts two additional parameters for additional control | ||||
| 4006 | ** over the new database connection. ^(The flags parameter to | ||||
| 4007 | ** sqlite3_open_v2() must include, at a minimum, one of the following | ||||
| 4008 | ** three flag combinations:)^ | ||||
| 4009 | ** | ||||
| 4010 | ** <dl> | ||||
| 4011 | ** ^(<dt>[SQLITE_OPEN_READONLY]</dt> | ||||
| 4012 | ** <dd>The database is opened in read-only mode. If the database does | ||||
| 4013 | ** not already exist, an error is returned.</dd>)^ | ||||
| 4014 | ** | ||||
| 4015 | ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt> | ||||
| 4016 | ** <dd>The database is opened for reading and writing if possible, or | ||||
| 4017 | ** reading only if the file is write protected by the operating | ||||
| 4018 | ** system. In either case the database must already exist, otherwise | ||||
| 4019 | ** an error is returned. For historical reasons, if opening in | ||||
| 4020 | ** read-write mode fails due to OS-level permissions, an attempt is | ||||
| 4021 | ** made to open it in read-only mode. [sqlite3_db_readonly()] can be | ||||
| 4022 | ** used to determine whether the database is actually | ||||
| 4023 | ** read-write.</dd>)^ | ||||
| 4024 | ** | ||||
| 4025 | ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt> | ||||
| 4026 | ** <dd>The database is opened for reading and writing, and is created if | ||||
| 4027 | ** it does not already exist. This is the behavior that is always used for | ||||
| 4028 | ** sqlite3_open() and sqlite3_open16().</dd>)^ | ||||
| 4029 | ** </dl> | ||||
| 4030 | ** | ||||
| 4031 | ** In addition to the required flags, the following optional flags are | ||||
| 4032 | ** also supported: | ||||
| 4033 | ** | ||||
| 4034 | ** <dl> | ||||
| 4035 | ** ^(<dt>[SQLITE_OPEN_URI]</dt> | ||||
| 4036 | ** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^ | ||||
| 4037 | ** | ||||
| 4038 | ** ^(<dt>[SQLITE_OPEN_MEMORY]</dt> | ||||
| 4039 | ** <dd>The database will be opened as an in-memory database. The database | ||||
| 4040 | ** is named by the "filename" argument for the purposes of cache-sharing, | ||||
| 4041 | ** if shared cache mode is enabled, but the "filename" is otherwise ignored. | ||||
| 4042 | ** </dd>)^ | ||||
| 4043 | ** | ||||
| 4044 | ** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt> | ||||
| 4045 | ** <dd>The new database connection will use the "multi-thread" | ||||
| 4046 | ** [threading mode].)^ This means that separate threads are allowed | ||||
| 4047 | ** to use SQLite at the same time, as long as each thread is using | ||||
| 4048 | ** a different [database connection]. | ||||
| 4049 | ** | ||||
| 4050 | ** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt> | ||||
| 4051 | ** <dd>The new database connection will use the "serialized" | ||||
| 4052 | ** [threading mode].)^ This means the multiple threads can safely | ||||
| 4053 | ** attempt to use the same database connection at the same time. | ||||
| 4054 | ** (Mutexes will block any actual concurrency, but in this mode | ||||
| 4055 | ** there is no harm in trying.) | ||||
| 4056 | ** | ||||
| 4057 | ** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt> | ||||
| 4058 | ** <dd>The database is opened [shared cache] enabled, overriding | ||||
| 4059 | ** the default shared cache setting provided by | ||||
| 4060 | ** [sqlite3_enable_shared_cache()].)^ | ||||
| 4061 | ** The [use of shared cache mode is discouraged] and hence shared cache | ||||
| 4062 | ** capabilities may be omitted from many builds of SQLite. In such cases, | ||||
| 4063 | ** this option is a no-op. | ||||
| 4064 | ** | ||||
| 4065 | ** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt> | ||||
| 4066 | ** <dd>The database is opened [shared cache] disabled, overriding | ||||
| 4067 | ** the default shared cache setting provided by | ||||
| 4068 | ** [sqlite3_enable_shared_cache()].)^ | ||||
| 4069 | ** | ||||
| 4070 | ** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt> | ||||
| 4071 | ** <dd>The database connection comes up in "extended result code mode". | ||||
| 4072 | ** In other words, the database behaves as if | ||||
| 4073 | ** [sqlite3_extended_result_codes(db,1)] were called on the database | ||||
| 4074 | ** connection as soon as the connection is created. In addition to setting | ||||
| 4075 | ** the extended result code mode, this flag also causes [sqlite3_open_v2()] | ||||
| 4076 | ** to return an extended result code.</dd> | ||||
| 4077 | ** | ||||
| 4078 | ** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt> | ||||
| 4079 | ** <dd>The database filename is not allowed to contain a symbolic link</dd> | ||||
| 4080 | ** </dl>)^ | ||||
| 4081 | ** | ||||
| 4082 | ** If the 3rd parameter to sqlite3_open_v2() is not one of the | ||||
| 4083 | ** required combinations shown above optionally combined with other | ||||
| 4084 | ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] | ||||
| 4085 | ** then the behavior is undefined. Historic versions of SQLite | ||||
| 4086 | ** have silently ignored surplus bits in the flags parameter to | ||||
| 4087 | ** sqlite3_open_v2(), however that behavior might not be carried through | ||||
| 4088 | ** into future versions of SQLite and so applications should not rely | ||||
| 4089 | ** upon it. Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op | ||||
| 4090 | ** for sqlite3_open_v2(). The SQLITE_OPEN_EXCLUSIVE does *not* cause | ||||
| 4091 | ** the open to fail if the database already exists. The SQLITE_OPEN_EXCLUSIVE | ||||
| 4092 | ** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not | ||||
| 4093 | ** by sqlite3_open_v2(). | ||||
| 4094 | ** | ||||
| 4095 | ** ^The fourth parameter to sqlite3_open_v2() is the name of the | ||||
| 4096 | ** [sqlite3_vfs] object that defines the operating system interface that | ||||
| 4097 | ** the new database connection should use. ^If the fourth parameter is | ||||
| 4098 | ** a NULL pointer then the default [sqlite3_vfs] object is used. | ||||
| 4099 | ** | ||||
| 4100 | ** ^If the filename is ":memory:", then a private, temporary in-memory database | ||||
| 4101 | ** is created for the connection. ^This in-memory database will vanish when | ||||
| 4102 | ** the database connection is closed. Future versions of SQLite might | ||||
| 4103 | ** make use of additional special filenames that begin with the ":" character. | ||||
| 4104 | ** It is recommended that when a database filename actually does begin with | ||||
| 4105 | ** a ":" character you should prefix the filename with a pathname such as | ||||
| 4106 | ** "./" to avoid ambiguity. | ||||
| 4107 | ** | ||||
| 4108 | ** ^If the filename is an empty string, then a private, temporary | ||||
| 4109 | ** on-disk database will be created. ^This private database will be | ||||
| 4110 | ** automatically deleted as soon as the database connection is closed. | ||||
| 4111 | ** | ||||
| 4112 | ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3> | ||||
| 4113 | ** | ||||
| 4114 | ** ^If [URI filename] interpretation is enabled, and the filename argument | ||||
| 4115 | ** begins with "file:", then the filename is interpreted as a URI. ^URI | ||||
| 4116 | ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is | ||||
| 4117 | ** set in the third argument to sqlite3_open_v2(), or if it has | ||||
| 4118 | ** been enabled globally using the [SQLITE_CONFIG_URI] option with the | ||||
| 4119 | ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. | ||||
| 4120 | ** URI filename interpretation is turned off | ||||
| 4121 | ** by default, but future releases of SQLite might enable URI filename | ||||
| 4122 | ** interpretation by default. See "[URI filenames]" for additional | ||||
| 4123 | ** information. | ||||
| 4124 | ** | ||||
| 4125 | ** URI filenames are parsed according to RFC 3986. ^If the URI contains an | ||||
| 4126 | ** authority, then it must be either an empty string or the string | ||||
| 4127 | ** "localhost". ^If the authority is not an empty string or "localhost", an | ||||
| 4128 | ** error is returned to the caller. ^The fragment component of a URI, if | ||||
| 4129 | ** present, is ignored. | ||||
| 4130 | ** | ||||
| 4131 | ** ^SQLite uses the path component of the URI as the name of the disk file | ||||
| 4132 | ** which contains the database. ^If the path begins with a '/' character, | ||||
| 4133 | ** then it is interpreted as an absolute path. ^If the path does not begin | ||||
| 4134 | ** with a '/' (meaning that the authority section is omitted from the URI) | ||||
| 4135 | ** then the path is interpreted as a relative path. | ||||
| 4136 | ** ^(On windows, the first component of an absolute path | ||||
| 4137 | ** is a drive specification (e.g. "C:").)^ | ||||
| 4138 | ** | ||||
| 4139 | ** [[core URI query parameters]] | ||||
| 4140 | ** The query component of a URI may contain parameters that are interpreted | ||||
| 4141 | ** either by SQLite itself, or by a [VFS | custom VFS implementation]. | ||||
| 4142 | ** SQLite and its built-in [VFSes] interpret the | ||||
| 4143 | ** following query parameters: | ||||
| 4144 | ** | ||||
| 4145 | ** <ul> | ||||
| 4146 | ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of | ||||
| 4147 | ** a VFS object that provides the operating system interface that should | ||||
| 4148 | ** be used to access the database file on disk. ^If this option is set to | ||||
| 4149 | ** an empty string the default VFS object is used. ^Specifying an unknown | ||||
| 4150 | ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is | ||||
| 4151 | ** present, then the VFS specified by the option takes precedence over | ||||
| 4152 | ** the value passed as the fourth parameter to sqlite3_open_v2(). | ||||
| 4153 | ** | ||||
| 4154 | ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw", | ||||
| 4155 | ** "rwc", or "memory". Attempting to set it to any other value is | ||||
| 4156 | ** an error)^. | ||||
| 4157 | ** ^If "ro" is specified, then the database is opened for read-only | ||||
| 4158 | ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the | ||||
| 4159 | ** third argument to sqlite3_open_v2(). ^If the mode option is set to | ||||
| 4160 | ** "rw", then the database is opened for read-write (but not create) | ||||
| 4161 | ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had | ||||
| 4162 | ** been set. ^Value "rwc" is equivalent to setting both | ||||
| 4163 | ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is | ||||
| 4164 | ** set to "memory" then a pure [in-memory database] that never reads | ||||
| 4165 | ** or writes from disk is used. ^It is an error to specify a value for | ||||
| 4166 | ** the mode parameter that is less restrictive than that specified by | ||||
| 4167 | ** the flags passed in the third parameter to sqlite3_open_v2(). | ||||
| 4168 | ** | ||||
| 4169 | ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or | ||||
| 4170 | ** "private". ^Setting it to "shared" is equivalent to setting the | ||||
| 4171 | ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to | ||||
| 4172 | ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is | ||||
| 4173 | ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. | ||||
| 4174 | ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in | ||||
| 4175 | ** a URI filename, its value overrides any behavior requested by setting | ||||
| 4176 | ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. | ||||
| 4177 | ** | ||||
| 4178 | ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the | ||||
| 4179 | ** [powersafe overwrite] property does or does not apply to the | ||||
| 4180 | ** storage media on which the database file resides. | ||||
| 4181 | ** | ||||
| 4182 | ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter | ||||
| 4183 | ** which if set disables file locking in rollback journal modes. This | ||||
| 4184 | ** is useful for accessing a database on a filesystem that does not | ||||
| 4185 | ** support locking. Caution: Database corruption might result if two | ||||
| 4186 | ** or more processes write to the same database and any one of those | ||||
| 4187 | ** processes uses nolock=1. | ||||
| 4188 | ** | ||||
| 4189 | ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query | ||||
| 4190 | ** parameter that indicates that the database file is stored on | ||||
| 4191 | ** read-only media. ^When immutable is set, SQLite assumes that the | ||||
| 4192 | ** database file cannot be changed, even by a process with higher | ||||
| 4193 | ** privilege, and so the database is opened read-only and all locking | ||||
| 4194 | ** and change detection is disabled. Caution: Setting the immutable | ||||
| 4195 | ** property on a database file that does in fact change can result | ||||
| 4196 | ** in incorrect query results and/or [SQLITE_CORRUPT] errors. | ||||
| 4197 | ** See also: [SQLITE_IOCAP_IMMUTABLE]. | ||||
| 4198 | ** | ||||
| 4199 | ** </ul> | ||||
| 4200 | ** | ||||
| 4201 | ** ^Specifying an unknown parameter in the query component of a URI is not an | ||||
| 4202 | ** error. Future versions of SQLite might understand additional query | ||||
| 4203 | ** parameters. See "[query parameters with special meaning to SQLite]" for | ||||
| 4204 | ** additional information. | ||||
| 4205 | ** | ||||
| 4206 | ** [[URI filename examples]] <h3>URI filename examples</h3> | ||||
| 4207 | ** | ||||
| 4208 | ** <table border="1" align=center cellpadding=5> | ||||
| 4209 | ** <tr><th> URI filenames <th> Results | ||||
| 4210 | ** <tr><td> file:data.db <td> | ||||
| 4211 | ** Open the file "data.db" in the current directory. | ||||
| 4212 | ** <tr><td> file:/home/fred/data.db<br> | ||||
| 4213 | ** file:///home/fred/data.db <br> | ||||
| 4214 | ** file://localhost/home/fred/data.db <br> <td> | ||||
| 4215 | ** Open the database file "/home/fred/data.db". | ||||
| 4216 | ** <tr><td> file://darkstar/home/fred/data.db <td> | ||||
| 4217 | ** An error. "darkstar" is not a recognized authority. | ||||
| 4218 | ** <tr><td style="white-space:nowrap"> | ||||
| 4219 | ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db | ||||
| 4220 | ** <td> Windows only: Open the file "data.db" on fred's desktop on drive | ||||
| 4221 | ** C:. Note that the %20 escaping in this example is not strictly | ||||
| 4222 | ** necessary - space characters can be used literally | ||||
| 4223 | ** in URI filenames. | ||||
| 4224 | ** <tr><td> file:data.db?mode=ro&cache=private <td> | ||||
| 4225 | ** Open file "data.db" in the current directory for read-only access. | ||||
| 4226 | ** Regardless of whether or not shared-cache mode is enabled by | ||||
| 4227 | ** default, use a private cache. | ||||
| 4228 | ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td> | ||||
| 4229 | ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile" | ||||
| 4230 | ** that uses dot-files in place of posix advisory locking. | ||||
| 4231 | ** <tr><td> file:data.db?mode=readonly <td> | ||||
| 4232 | ** An error. "readonly" is not a valid option for the "mode" parameter. | ||||
| 4233 | ** Use "ro" instead: "file:data.db?mode=ro". | ||||
| 4234 | ** </table> | ||||
| 4235 | ** | ||||
| 4236 | ** ^URI hexadecimal escape sequences (%HH) are supported within the path and | ||||
| 4237 | ** query components of a URI. A hexadecimal escape sequence consists of a | ||||
| 4238 | ** percent sign - "%" - followed by exactly two hexadecimal digits | ||||
| 4239 | ** specifying an octet value. ^Before the path or query components of a | ||||
| 4240 | ** URI filename are interpreted, they are encoded using UTF-8 and all | ||||
| 4241 | ** hexadecimal escape sequences replaced by a single byte containing the | ||||
| 4242 | ** corresponding octet. If this process generates an invalid UTF-8 encoding, | ||||
| 4243 | ** the results are undefined. | ||||
| 4244 | ** | ||||
| 4245 | ** <b>Note to Windows users:</b> The encoding used for the filename argument | ||||
| 4246 | ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever | ||||
| 4247 | ** codepage is currently defined. Filenames containing international | ||||
| 4248 | ** characters must be converted to UTF-8 prior to passing them into | ||||
| 4249 | ** sqlite3_open() or sqlite3_open_v2(). | ||||
| 4250 | ** | ||||
| 4251 | ** <b>Note to Windows Runtime users:</b> The temporary directory must be set | ||||
| 4252 | ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various | ||||
| 4253 | ** features that require the use of temporary files may fail. | ||||
| 4254 | ** | ||||
| 4255 | ** See also: [sqlite3_temp_directory] | ||||
| 4256 | */ | ||||
| 4257 | SQLITE_API int sqlite3_open( | ||||
| 4258 | const char *filename, /* Database filename (UTF-8) */ | ||||
| 4259 | sqlite3 **ppDb /* OUT: SQLite db handle */ | ||||
| 4260 | ); | ||||
| 4261 | SQLITE_API int sqlite3_open16( | ||||
| 4262 | const void *filename, /* Database filename (UTF-16) */ | ||||
| 4263 | sqlite3 **ppDb /* OUT: SQLite db handle */ | ||||
| 4264 | ); | ||||
| 4265 | SQLITE_API int sqlite3_open_v2( | ||||
| 4266 | const char *filename, /* Database filename (UTF-8) */ | ||||
| 4267 | sqlite3 **ppDb, /* OUT: SQLite db handle */ | ||||
| 4268 | int flags, /* Flags */ | ||||
| 4269 | const char *zVfs /* Name of VFS module to use */ | ||||
| 4270 | ); | ||||
| 4271 | |||||
| 4272 | /* | ||||
| 4273 | ** CAPI3REF: Obtain Values For URI Parameters | ||||
| 4274 | ** | ||||
| 4275 | ** These are utility routines, useful to [VFS|custom VFS implementations], | ||||
| 4276 | ** that check if a database file was a URI that contained a specific query | ||||
| 4277 | ** parameter, and if so obtains the value of that query parameter. | ||||
| 4278 | ** | ||||
| 4279 | ** The first parameter to these interfaces (hereafter referred to | ||||
| 4280 | ** as F) must be one of: | ||||
| 4281 | ** <ul> | ||||
| 4282 | ** <li> A database filename pointer created by the SQLite core and | ||||
| 4283 | ** passed into the xOpen() method of a VFS implementation, or | ||||
| 4284 | ** <li> A filename obtained from [sqlite3_db_filename()], or | ||||
| 4285 | ** <li> A new filename constructed using [sqlite3_create_filename()]. | ||||
| 4286 | ** </ul> | ||||
| 4287 | ** If the F parameter is not one of the above, then the behavior is | ||||
| 4288 | ** undefined and probably undesirable. Older versions of SQLite were | ||||
| 4289 | ** more tolerant of invalid F parameters than newer versions. | ||||
| 4290 | ** | ||||
| 4291 | ** If F is a suitable filename (as described in the previous paragraph) | ||||
| 4292 | ** and if P is the name of the query parameter, then | ||||
| 4293 | ** sqlite3_uri_parameter(F,P) returns the value of the P | ||||
| 4294 | ** parameter if it exists or a NULL pointer if P does not appear as a | ||||
| 4295 | ** query parameter on F. If P is a query parameter of F and it | ||||
| 4296 | ** has no explicit value, then sqlite3_uri_parameter(F,P) returns | ||||
| 4297 | ** a pointer to an empty string. | ||||
| 4298 | ** | ||||
| 4299 | ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean | ||||
| 4300 | ** parameter and returns true (1) or false (0) according to the value | ||||
| 4301 | ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the | ||||
| 4302 | ** value of query parameter P is one of "yes", "true", or "on" in any | ||||
| 4303 | ** case or if the value begins with a non-zero number. The | ||||
| 4304 | ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of | ||||
| 4305 | ** query parameter P is one of "no", "false", or "off" in any case or | ||||
| 4306 | ** if the value begins with a numeric zero. If P is not a query | ||||
| 4307 | ** parameter on F or if the value of P does not match any of the | ||||
| 4308 | ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). | ||||
| 4309 | ** | ||||
| 4310 | ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a | ||||
| 4311 | ** 64-bit signed integer and returns that integer, or D if P does not | ||||
| 4312 | ** exist. If the value of P is something other than an integer, then | ||||
| 4313 | ** zero is returned. | ||||
| 4314 | ** | ||||
| 4315 | ** The sqlite3_uri_key(F,N) returns a pointer to the name (not | ||||
| 4316 | ** the value) of the N-th query parameter for filename F, or a NULL | ||||
| 4317 | ** pointer if N is less than zero or greater than the number of query | ||||
| 4318 | ** parameters minus 1. The N value is zero-based so N should be 0 to obtain | ||||
| 4319 | ** the name of the first query parameter, 1 for the second parameter, and | ||||
| 4320 | ** so forth. | ||||
| 4321 | ** | ||||
| 4322 | ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and | ||||
| 4323 | ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and | ||||
| 4324 | ** is not a database file pathname pointer that the SQLite core passed | ||||
| 4325 | ** into the xOpen VFS method, then the behavior of this routine is undefined | ||||
| 4326 | ** and probably undesirable. | ||||
| 4327 | ** | ||||
| 4328 | ** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F | ||||
| 4329 | ** parameter can also be the name of a rollback journal file or WAL file | ||||
| 4330 | ** in addition to the main database file. Prior to version 3.31.0, these | ||||
| 4331 | ** routines would only work if F was the name of the main database file. | ||||
| 4332 | ** When the F parameter is the name of the rollback journal or WAL file, | ||||
| 4333 | ** it has access to all the same query parameters as were found on the | ||||
| 4334 | ** main database file. | ||||
| 4335 | ** | ||||
| 4336 | ** See the [URI filename] documentation for additional information. | ||||
| 4337 | */ | ||||
| 4338 | SQLITE_API const char *sqlite3_uri_parameter(sqlite3_filename z, const char *zParam); | ||||
| 4339 | SQLITE_API int sqlite3_uri_boolean(sqlite3_filename z, const char *zParam, int bDefault); | ||||
| 4340 | SQLITE_API sqlite3_int64 sqlite3_uri_int64(sqlite3_filename, const char*, sqlite3_int64); | ||||
| 4341 | SQLITE_API const char *sqlite3_uri_key(sqlite3_filename z, int N); | ||||
| 4342 | |||||
| 4343 | /* | ||||
| 4344 | ** CAPI3REF: Translate filenames | ||||
| 4345 | ** | ||||
| 4346 | ** These routines are available to [VFS|custom VFS implementations] for | ||||
| 4347 | ** translating filenames between the main database file, the journal file, | ||||
| 4348 | ** and the WAL file. | ||||
| 4349 | ** | ||||
| 4350 | ** If F is the name of an sqlite database file, journal file, or WAL file | ||||
| 4351 | ** passed by the SQLite core into the VFS, then sqlite3_filename_database(F) | ||||
| 4352 | ** returns the name of the corresponding database file. | ||||
| 4353 | ** | ||||
| 4354 | ** If F is the name of an sqlite database file, journal file, or WAL file | ||||
| 4355 | ** passed by the SQLite core into the VFS, or if F is a database filename | ||||
| 4356 | ** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F) | ||||
| 4357 | ** returns the name of the corresponding rollback journal file. | ||||
| 4358 | ** | ||||
| 4359 | ** If F is the name of an sqlite database file, journal file, or WAL file | ||||
| 4360 | ** that was passed by the SQLite core into the VFS, or if F is a database | ||||
| 4361 | ** filename obtained from [sqlite3_db_filename()], then | ||||
| 4362 | ** sqlite3_filename_wal(F) returns the name of the corresponding | ||||
| 4363 | ** WAL file. | ||||
| 4364 | ** | ||||
| 4365 | ** In all of the above, if F is not the name of a database, journal or WAL | ||||
| 4366 | ** filename passed into the VFS from the SQLite core and F is not the | ||||
| 4367 | ** return value from [sqlite3_db_filename()], then the result is | ||||
| 4368 | ** undefined and is likely a memory access violation. | ||||
| 4369 | */ | ||||
| 4370 | SQLITE_API const char *sqlite3_filename_database(sqlite3_filename); | ||||
| 4371 | SQLITE_API const char *sqlite3_filename_journal(sqlite3_filename); | ||||
| 4372 | SQLITE_API const char *sqlite3_filename_wal(sqlite3_filename); | ||||
| 4373 | |||||
| 4374 | /* | ||||
| 4375 | ** CAPI3REF: Database File Corresponding To A Journal | ||||
| 4376 | ** | ||||
| 4377 | ** ^If X is the name of a rollback or WAL-mode journal file that is | ||||
| 4378 | ** passed into the xOpen method of [sqlite3_vfs], then | ||||
| 4379 | ** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file] | ||||
| 4380 | ** object that represents the main database file. | ||||
| 4381 | ** | ||||
| 4382 | ** This routine is intended for use in custom [VFS] implementations | ||||
| 4383 | ** only. It is not a general-purpose interface. | ||||
| 4384 | ** The argument sqlite3_file_object(X) must be a filename pointer that | ||||
| 4385 | ** has been passed into [sqlite3_vfs].xOpen method where the | ||||
| 4386 | ** flags parameter to xOpen contains one of the bits | ||||
| 4387 | ** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use | ||||
| 4388 | ** of this routine results in undefined and probably undesirable | ||||
| 4389 | ** behavior. | ||||
| 4390 | */ | ||||
| 4391 | SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*); | ||||
| 4392 | |||||
| 4393 | /* | ||||
| 4394 | ** CAPI3REF: Create and Destroy VFS Filenames | ||||
| 4395 | ** | ||||
| 4396 | ** These interfaces are provided for use by [VFS shim] implementations and | ||||
| 4397 | ** are not useful outside of that context. | ||||
| 4398 | ** | ||||
| 4399 | ** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of | ||||
| 4400 | ** database filename D with corresponding journal file J and WAL file W and | ||||
| 4401 | ** an array P of N URI Key/Value pairs. The result from | ||||
| 4402 | ** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that | ||||
| 4403 | ** is safe to pass to routines like: | ||||
| 4404 | ** <ul> | ||||
| 4405 | ** <li> [sqlite3_uri_parameter()], | ||||
| 4406 | ** <li> [sqlite3_uri_boolean()], | ||||
| 4407 | ** <li> [sqlite3_uri_int64()], | ||||
| 4408 | ** <li> [sqlite3_uri_key()], | ||||
| 4409 | ** <li> [sqlite3_filename_database()], | ||||
| 4410 | ** <li> [sqlite3_filename_journal()], or | ||||
| 4411 | ** <li> [sqlite3_filename_wal()]. | ||||
| 4412 | ** </ul> | ||||
| 4413 | ** If a memory allocation error occurs, sqlite3_create_filename() might | ||||
| 4414 | ** return a NULL pointer. The memory obtained from sqlite3_create_filename(X) | ||||
| 4415 | ** must be released by a corresponding call to sqlite3_free_filename(Y). | ||||
| 4416 | ** | ||||
| 4417 | ** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array | ||||
| 4418 | ** of 2*N pointers to strings. Each pair of pointers in this array corresponds | ||||
| 4419 | ** to a key and value for a query parameter. The P parameter may be a NULL | ||||
| 4420 | ** pointer if N is zero. None of the 2*N pointers in the P array may be | ||||
| 4421 | ** NULL pointers and key pointers should not be empty strings. | ||||
| 4422 | ** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may | ||||
| 4423 | ** be NULL pointers, though they can be empty strings. | ||||
| 4424 | ** | ||||
| 4425 | ** The sqlite3_free_filename(Y) routine releases a memory allocation | ||||
| 4426 | ** previously obtained from sqlite3_create_filename(). Invoking | ||||
| 4427 | ** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op. | ||||
| 4428 | ** | ||||
| 4429 | ** If the Y parameter to sqlite3_free_filename(Y) is anything other | ||||
| 4430 | ** than a NULL pointer or a pointer previously acquired from | ||||
| 4431 | ** sqlite3_create_filename(), then bad things such as heap | ||||
| 4432 | ** corruption or segfaults may occur. The value Y should not be | ||||
| 4433 | ** used again after sqlite3_free_filename(Y) has been called. This means | ||||
| 4434 | ** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y, | ||||
| 4435 | ** then the corresponding [sqlite3_module.xClose() method should also be | ||||
| 4436 | ** invoked prior to calling sqlite3_free_filename(Y). | ||||
| 4437 | */ | ||||
| 4438 | SQLITE_API sqlite3_filename sqlite3_create_filename( | ||||
| 4439 | const char *zDatabase, | ||||
| 4440 | const char *zJournal, | ||||
| 4441 | const char *zWal, | ||||
| 4442 | int nParam, | ||||
| 4443 | const char **azParam | ||||
| 4444 | ); | ||||
| 4445 | SQLITE_API void sqlite3_free_filename(sqlite3_filename); | ||||
| 4446 | |||||
| 4447 | /* | ||||
| 4448 | ** CAPI3REF: Error Codes And Messages | ||||
| 4449 | ** METHOD: sqlite3 | ||||
| 4450 | ** | ||||
| 4451 | ** ^If the most recent sqlite3_* API call associated with | ||||
| 4452 | ** [database connection] D failed, then the sqlite3_errcode(D) interface | ||||
| 4453 | ** returns the numeric [result code] or [extended result code] for that | ||||
| 4454 | ** API call. | ||||
| 4455 | ** ^The sqlite3_extended_errcode() | ||||
| 4456 | ** interface is the same except that it always returns the | ||||
| 4457 | ** [extended result code] even when extended result codes are | ||||
| 4458 | ** disabled. | ||||
| 4459 | ** | ||||
| 4460 | ** The values returned by sqlite3_errcode() and/or | ||||
| 4461 | ** sqlite3_extended_errcode() might change with each API call. | ||||
| 4462 | ** Except, there are some interfaces that are guaranteed to never | ||||
| 4463 | ** change the value of the error code. The error-code preserving | ||||
| 4464 | ** interfaces include the following: | ||||
| 4465 | ** | ||||
| 4466 | ** <ul> | ||||
| 4467 | ** <li> sqlite3_errcode() | ||||
| 4468 | ** <li> sqlite3_extended_errcode() | ||||
| 4469 | ** <li> sqlite3_errmsg() | ||||
| 4470 | ** <li> sqlite3_errmsg16() | ||||
| 4471 | ** <li> sqlite3_error_offset() | ||||
| 4472 | ** </ul> | ||||
| 4473 | ** | ||||
| 4474 | ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language | ||||
| 4475 | ** text that describes the error, as either UTF-8 or UTF-16 respectively, | ||||
| 4476 | ** or NULL if no error message is available. | ||||
| 4477 | ** (See how SQLite handles [invalid UTF] for exceptions to this rule.) | ||||
| 4478 | ** ^(Memory to hold the error message string is managed internally. | ||||
| 4479 | ** The application does not need to worry about freeing the result. | ||||
| 4480 | ** However, the error string might be overwritten or deallocated by | ||||
| 4481 | ** subsequent calls to other SQLite interface functions.)^ | ||||
| 4482 | ** | ||||
| 4483 | ** ^The sqlite3_errstr(E) interface returns the English-language text | ||||
| 4484 | ** that describes the [result code] E, as UTF-8, or NULL if E is not an | ||||
| 4485 | ** result code for which a text error message is available. | ||||
| 4486 | ** ^(Memory to hold the error message string is managed internally | ||||
| 4487 | ** and must not be freed by the application)^. | ||||
| 4488 | ** | ||||
| 4489 | ** ^If the most recent error references a specific token in the input | ||||
| 4490 | ** SQL, the sqlite3_error_offset() interface returns the byte offset | ||||
| 4491 | ** of the start of that token. ^The byte offset returned by | ||||
| 4492 | ** sqlite3_error_offset() assumes that the input SQL is UTF8. | ||||
| 4493 | ** ^If the most recent error does not reference a specific token in the input | ||||
| 4494 | ** SQL, then the sqlite3_error_offset() function returns -1. | ||||
| 4495 | ** | ||||
| 4496 | ** When the serialized [threading mode] is in use, it might be the | ||||
| 4497 | ** case that a second error occurs on a separate thread in between | ||||
| 4498 | ** the time of the first error and the call to these interfaces. | ||||
| 4499 | ** When that happens, the second error will be reported since these | ||||
| 4500 | ** interfaces always report the most recent result. To avoid | ||||
| 4501 | ** this, each thread can obtain exclusive use of the [database connection] D | ||||
| 4502 | ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning | ||||
| 4503 | ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after | ||||
| 4504 | ** all calls to the interfaces listed here are completed. | ||||
| 4505 | ** | ||||
| 4506 | ** If an interface fails with SQLITE_MISUSE, that means the interface | ||||
| 4507 | ** was invoked incorrectly by the application. In that case, the | ||||
| 4508 | ** error code and message may or may not be set. | ||||
| 4509 | */ | ||||
| 4510 | SQLITE_API int sqlite3_errcode(sqlite3 *db); | ||||
| 4511 | SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); | ||||
| 4512 | SQLITE_API const char *sqlite3_errmsg(sqlite3*); | ||||
| 4513 | SQLITE_API const void *sqlite3_errmsg16(sqlite3*); | ||||
| 4514 | SQLITE_API const char *sqlite3_errstr(int); | ||||
| 4515 | SQLITE_API int sqlite3_error_offset(sqlite3 *db); | ||||
| 4516 | |||||
| 4517 | /* | ||||
| 4518 | ** CAPI3REF: Prepared Statement Object | ||||
| 4519 | ** KEYWORDS: {prepared statement} {prepared statements} | ||||
| 4520 | ** | ||||
| 4521 | ** An instance of this object represents a single SQL statement that | ||||
| 4522 | ** has been compiled into binary form and is ready to be evaluated. | ||||
| 4523 | ** | ||||
| 4524 | ** Think of each SQL statement as a separate computer program. The | ||||
| 4525 | ** original SQL text is source code. A prepared statement object | ||||
| 4526 | ** is the compiled object code. All SQL must be converted into a | ||||
| 4527 | ** prepared statement before it can be run. | ||||
| 4528 | ** | ||||
| 4529 | ** The life-cycle of a prepared statement object usually goes like this: | ||||
| 4530 | ** | ||||
| 4531 | ** <ol> | ||||
| 4532 | ** <li> Create the prepared statement object using [sqlite3_prepare_v2()]. | ||||
| 4533 | ** <li> Bind values to [parameters] using the sqlite3_bind_*() | ||||
| 4534 | ** interfaces. | ||||
| 4535 | ** <li> Run the SQL by calling [sqlite3_step()] one or more times. | ||||
| 4536 | ** <li> Reset the prepared statement using [sqlite3_reset()] then go back | ||||
| 4537 | ** to step 2. Do this zero or more times. | ||||
| 4538 | ** <li> Destroy the object using [sqlite3_finalize()]. | ||||
| 4539 | ** </ol> | ||||
| 4540 | */ | ||||
| 4541 | typedef struct sqlite3_stmt sqlite3_stmt; | ||||
| 4542 | |||||
| 4543 | /* | ||||
| 4544 | ** CAPI3REF: Run-time Limits | ||||
| 4545 | ** METHOD: sqlite3 | ||||
| 4546 | ** | ||||
| 4547 | ** ^(This interface allows the size of various constructs to be limited | ||||
| 4548 | ** on a connection by connection basis. The first parameter is the | ||||
| 4549 | ** [database connection] whose limit is to be set or queried. The | ||||
| 4550 | ** second parameter is one of the [limit categories] that define a | ||||
| 4551 | ** class of constructs to be size limited. The third parameter is the | ||||
| 4552 | ** new limit for that construct.)^ | ||||
| 4553 | ** | ||||
| 4554 | ** ^If the new limit is a negative number, the limit is unchanged. | ||||
| 4555 | ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a | ||||
| 4556 | ** [limits | hard upper bound] | ||||
| 4557 | ** set at compile-time by a C preprocessor macro called | ||||
| 4558 | ** [limits | SQLITE_MAX_<i>NAME</i>]. | ||||
| 4559 | ** (The "_LIMIT_" in the name is changed to "_MAX_".))^ | ||||
| 4560 | ** ^Attempts to increase a limit above its hard upper bound are | ||||
| 4561 | ** silently truncated to the hard upper bound. | ||||
| 4562 | ** | ||||
| 4563 | ** ^Regardless of whether or not the limit was changed, the | ||||
| 4564 | ** [sqlite3_limit()] interface returns the prior value of the limit. | ||||
| 4565 | ** ^Hence, to find the current value of a limit without changing it, | ||||
| 4566 | ** simply invoke this interface with the third parameter set to -1. | ||||
| 4567 | ** | ||||
| 4568 | ** Run-time limits are intended for use in applications that manage | ||||
| 4569 | ** both their own internal database and also databases that are controlled | ||||
| 4570 | ** by untrusted external sources. An example application might be a | ||||
| 4571 | ** web browser that has its own databases for storing history and | ||||
| 4572 | ** separate databases controlled by JavaScript applications downloaded | ||||
| 4573 | ** off the Internet. The internal databases can be given the | ||||
| 4574 | ** large, default limits. Databases managed by external sources can | ||||
| 4575 | ** be given much smaller limits designed to prevent a denial of service | ||||
| 4576 | ** attack. Developers might also want to use the [sqlite3_set_authorizer()] | ||||
| 4577 | ** interface to further control untrusted SQL. The size of the database | ||||
| 4578 | ** created by an untrusted script can be contained using the | ||||
| 4579 | ** [max_page_count] [PRAGMA]. | ||||
| 4580 | ** | ||||
| 4581 | ** New run-time limit categories may be added in future releases. | ||||
| 4582 | */ | ||||
| 4583 | SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); | ||||
| 4584 | |||||
| 4585 | /* | ||||
| 4586 | ** CAPI3REF: Run-Time Limit Categories | ||||
| 4587 | ** KEYWORDS: {limit category} {*limit categories} | ||||
| 4588 | ** | ||||
| 4589 | ** These constants define various performance limits | ||||
| 4590 | ** that can be lowered at run-time using [sqlite3_limit()]. | ||||
| 4591 | ** The synopsis of the meanings of the various limits is shown below. | ||||
| 4592 | ** Additional information is available at [limits | Limits in SQLite]. | ||||
| 4593 | ** | ||||
| 4594 | ** <dl> | ||||
| 4595 | ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt> | ||||
| 4596 | ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^ | ||||
| 4597 | ** | ||||
| 4598 | ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt> | ||||
| 4599 | ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^ | ||||
| 4600 | ** | ||||
| 4601 | ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt> | ||||
| 4602 | ** <dd>The maximum number of columns in a table definition or in the | ||||
| 4603 | ** result set of a [SELECT] or the maximum number of columns in an index | ||||
| 4604 | ** or in an ORDER BY or GROUP BY clause.</dd>)^ | ||||
| 4605 | ** | ||||
| 4606 | ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt> | ||||
| 4607 | ** <dd>The maximum depth of the parse tree on any expression.</dd>)^ | ||||
| 4608 | ** | ||||
| 4609 | ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt> | ||||
| 4610 | ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^ | ||||
| 4611 | ** | ||||
| 4612 | ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt> | ||||
| 4613 | ** <dd>The maximum number of instructions in a virtual machine program | ||||
| 4614 | ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or | ||||
| 4615 | ** the equivalent tries to allocate space for more than this many opcodes | ||||
| 4616 | ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^ | ||||
| 4617 | ** | ||||
| 4618 | ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt> | ||||
| 4619 | ** <dd>The maximum number of arguments on a function.</dd>)^ | ||||
| 4620 | ** | ||||
| 4621 | ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt> | ||||
| 4622 | ** <dd>The maximum number of [ATTACH | attached databases].)^</dd> | ||||
| 4623 | ** | ||||
| 4624 | ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] | ||||
| 4625 | ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt> | ||||
| 4626 | ** <dd>The maximum length of the pattern argument to the [LIKE] or | ||||
| 4627 | ** [GLOB] operators.</dd>)^ | ||||
| 4628 | ** | ||||
| 4629 | ** [[SQLITE_LIMIT_VARIABLE_NUMBER]] | ||||
| 4630 | ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt> | ||||
| 4631 | ** <dd>The maximum index number of any [parameter] in an SQL statement.)^ | ||||
| 4632 | ** | ||||
| 4633 | ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt> | ||||
| 4634 | ** <dd>The maximum depth of recursion for triggers.</dd>)^ | ||||
| 4635 | ** | ||||
| 4636 | ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt> | ||||
| 4637 | ** <dd>The maximum number of auxiliary worker threads that a single | ||||
| 4638 | ** [prepared statement] may start.</dd>)^ | ||||
| 4639 | ** </dl> | ||||
| 4640 | */ | ||||
| 4641 | #define SQLITE_LIMIT_LENGTH0 0 | ||||
| 4642 | #define SQLITE_LIMIT_SQL_LENGTH1 1 | ||||
| 4643 | #define SQLITE_LIMIT_COLUMN2 2 | ||||
| 4644 | #define SQLITE_LIMIT_EXPR_DEPTH3 3 | ||||
| 4645 | #define SQLITE_LIMIT_COMPOUND_SELECT4 4 | ||||
| 4646 | #define SQLITE_LIMIT_VDBE_OP5 5 | ||||
| 4647 | #define SQLITE_LIMIT_FUNCTION_ARG6 6 | ||||
| 4648 | #define SQLITE_LIMIT_ATTACHED7 7 | ||||
| 4649 | #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH8 8 | ||||
| 4650 | #define SQLITE_LIMIT_VARIABLE_NUMBER9 9 | ||||
| 4651 | #define SQLITE_LIMIT_TRIGGER_DEPTH10 10 | ||||
| 4652 | #define SQLITE_LIMIT_WORKER_THREADS11 11 | ||||
| 4653 | |||||
| 4654 | /* | ||||
| 4655 | ** CAPI3REF: Prepare Flags | ||||
| 4656 | ** | ||||
| 4657 | ** These constants define various flags that can be passed into | ||||
| 4658 | ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and | ||||
| 4659 | ** [sqlite3_prepare16_v3()] interfaces. | ||||
| 4660 | ** | ||||
| 4661 | ** New flags may be added in future releases of SQLite. | ||||
| 4662 | ** | ||||
| 4663 | ** <dl> | ||||
| 4664 | ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt> | ||||
| 4665 | ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner | ||||
| 4666 | ** that the prepared statement will be retained for a long time and | ||||
| 4667 | ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()] | ||||
| 4668 | ** and [sqlite3_prepare16_v3()] assume that the prepared statement will | ||||
| 4669 | ** be used just once or at most a few times and then destroyed using | ||||
| 4670 | ** [sqlite3_finalize()] relatively soon. The current implementation acts | ||||
| 4671 | ** on this hint by avoiding the use of [lookaside memory] so as not to | ||||
| 4672 | ** deplete the limited store of lookaside memory. Future versions of | ||||
| 4673 | ** SQLite may act on this hint differently. | ||||
| 4674 | ** | ||||
| 4675 | ** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt> | ||||
| 4676 | ** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used | ||||
| 4677 | ** to be required for any prepared statement that wanted to use the | ||||
| 4678 | ** [sqlite3_normalized_sql()] interface. However, the | ||||
| 4679 | ** [sqlite3_normalized_sql()] interface is now available to all | ||||
| 4680 | ** prepared statements, regardless of whether or not they use this | ||||
| 4681 | ** flag. | ||||
| 4682 | ** | ||||
| 4683 | ** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt> | ||||
| 4684 | ** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler | ||||
| 4685 | ** to return an error (error code SQLITE_ERROR) if the statement uses | ||||
| 4686 | ** any virtual tables. | ||||
| 4687 | ** | ||||
| 4688 | ** [[SQLITE_PREPARE_DONT_LOG]] <dt>SQLITE_PREPARE_DONT_LOG</dt> | ||||
| 4689 | ** <dd>The SQLITE_PREPARE_DONT_LOG flag prevents SQL compiler | ||||
| 4690 | ** errors from being sent to the error log defined by | ||||
| 4691 | ** [SQLITE_CONFIG_LOG]. This can be used, for example, to do test | ||||
| 4692 | ** compiles to see if some SQL syntax is well-formed, without generating | ||||
| 4693 | ** messages on the global error log when it is not. If the test compile | ||||
| 4694 | ** fails, the sqlite3_prepare_v3() call returns the same error indications | ||||
| 4695 | ** with or without this flag; it just omits the call to [sqlite3_log()] that | ||||
| 4696 | ** logs the error. | ||||
| 4697 | ** </dl> | ||||
| 4698 | */ | ||||
| 4699 | #define SQLITE_PREPARE_PERSISTENT0x01 0x01 | ||||
| 4700 | #define SQLITE_PREPARE_NORMALIZE0x02 0x02 | ||||
| 4701 | #define SQLITE_PREPARE_NO_VTAB0x04 0x04 | ||||
| 4702 | #define SQLITE_PREPARE_DONT_LOG0x10 0x10 | ||||
| 4703 | |||||
| 4704 | /* | ||||
| 4705 | ** CAPI3REF: Compiling An SQL Statement | ||||
| 4706 | ** KEYWORDS: {SQL statement compiler} | ||||
| 4707 | ** METHOD: sqlite3 | ||||
| 4708 | ** CONSTRUCTOR: sqlite3_stmt | ||||
| 4709 | ** | ||||
| 4710 | ** To execute an SQL statement, it must first be compiled into a byte-code | ||||
| 4711 | ** program using one of these routines. Or, in other words, these routines | ||||
| 4712 | ** are constructors for the [prepared statement] object. | ||||
| 4713 | ** | ||||
| 4714 | ** The preferred routine to use is [sqlite3_prepare_v2()]. The | ||||
| 4715 | ** [sqlite3_prepare()] interface is legacy and should be avoided. | ||||
| 4716 | ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used | ||||
| 4717 | ** for special purposes. | ||||
| 4718 | ** | ||||
| 4719 | ** The use of the UTF-8 interfaces is preferred, as SQLite currently | ||||
| 4720 | ** does all parsing using UTF-8. The UTF-16 interfaces are provided | ||||
| 4721 | ** as a convenience. The UTF-16 interfaces work by converting the | ||||
| 4722 | ** input text into UTF-8, then invoking the corresponding UTF-8 interface. | ||||
| 4723 | ** | ||||
| 4724 | ** The first argument, "db", is a [database connection] obtained from a | ||||
| 4725 | ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or | ||||
| 4726 | ** [sqlite3_open16()]. The database connection must not have been closed. | ||||
| 4727 | ** | ||||
| 4728 | ** The second argument, "zSql", is the statement to be compiled, encoded | ||||
| 4729 | ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(), | ||||
| 4730 | ** and sqlite3_prepare_v3() | ||||
| 4731 | ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(), | ||||
| 4732 | ** and sqlite3_prepare16_v3() use UTF-16. | ||||
| 4733 | ** | ||||
| 4734 | ** ^If the nByte argument is negative, then zSql is read up to the | ||||
| 4735 | ** first zero terminator. ^If nByte is positive, then it is the maximum | ||||
| 4736 | ** number of bytes read from zSql. When nByte is positive, zSql is read | ||||
| 4737 | ** up to the first zero terminator or until the nByte bytes have been read, | ||||
| 4738 | ** whichever comes first. ^If nByte is zero, then no prepared | ||||
| 4739 | ** statement is generated. | ||||
| 4740 | ** If the caller knows that the supplied string is nul-terminated, then | ||||
| 4741 | ** there is a small performance advantage to passing an nByte parameter that | ||||
| 4742 | ** is the number of bytes in the input string <i>including</i> | ||||
| 4743 | ** the nul-terminator. | ||||
| 4744 | ** Note that nByte measure the length of the input in bytes, not | ||||
| 4745 | ** characters, even for the UTF-16 interfaces. | ||||
| 4746 | ** | ||||
| 4747 | ** ^If pzTail is not NULL then *pzTail is made to point to the first byte | ||||
| 4748 | ** past the end of the first SQL statement in zSql. These routines only | ||||
| 4749 | ** compile the first statement in zSql, so *pzTail is left pointing to | ||||
| 4750 | ** what remains uncompiled. | ||||
| 4751 | ** | ||||
| 4752 | ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be | ||||
| 4753 | ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set | ||||
| 4754 | ** to NULL. ^If the input text contains no SQL (if the input is an empty | ||||
| 4755 | ** string or a comment) then *ppStmt is set to NULL. | ||||
| 4756 | ** The calling procedure is responsible for deleting the compiled | ||||
| 4757 | ** SQL statement using [sqlite3_finalize()] after it has finished with it. | ||||
| 4758 | ** ppStmt may not be NULL. | ||||
| 4759 | ** | ||||
| 4760 | ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; | ||||
| 4761 | ** otherwise an [error code] is returned. | ||||
| 4762 | ** | ||||
| 4763 | ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(), | ||||
| 4764 | ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs. | ||||
| 4765 | ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16()) | ||||
| 4766 | ** are retained for backwards compatibility, but their use is discouraged. | ||||
| 4767 | ** ^In the "vX" interfaces, the prepared statement | ||||
| 4768 | ** that is returned (the [sqlite3_stmt] object) contains a copy of the | ||||
| 4769 | ** original SQL text. This causes the [sqlite3_step()] interface to | ||||
| 4770 | ** behave differently in three ways: | ||||
| 4771 | ** | ||||
| 4772 | ** <ol> | ||||
| 4773 | ** <li> | ||||
| 4774 | ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it | ||||
| 4775 | ** always used to do, [sqlite3_step()] will automatically recompile the SQL | ||||
| 4776 | ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] | ||||
| 4777 | ** retries will occur before sqlite3_step() gives up and returns an error. | ||||
| 4778 | ** </li> | ||||
| 4779 | ** | ||||
| 4780 | ** <li> | ||||
| 4781 | ** ^When an error occurs, [sqlite3_step()] will return one of the detailed | ||||
| 4782 | ** [error codes] or [extended error codes]. ^The legacy behavior was that | ||||
| 4783 | ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code | ||||
| 4784 | ** and the application would have to make a second call to [sqlite3_reset()] | ||||
| 4785 | ** in order to find the underlying cause of the problem. With the "v2" prepare | ||||
| 4786 | ** interfaces, the underlying reason for the error is returned immediately. | ||||
| 4787 | ** </li> | ||||
| 4788 | ** | ||||
| 4789 | ** <li> | ||||
| 4790 | ** ^If the specific value bound to a [parameter | host parameter] in the | ||||
| 4791 | ** WHERE clause might influence the choice of query plan for a statement, | ||||
| 4792 | ** then the statement will be automatically recompiled, as if there had been | ||||
| 4793 | ** a schema change, on the first [sqlite3_step()] call following any change | ||||
| 4794 | ** to the [sqlite3_bind_text | bindings] of that [parameter]. | ||||
| 4795 | ** ^The specific value of a WHERE-clause [parameter] might influence the | ||||
| 4796 | ** choice of query plan if the parameter is the left-hand side of a [LIKE] | ||||
| 4797 | ** or [GLOB] operator or if the parameter is compared to an indexed column | ||||
| 4798 | ** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled. | ||||
| 4799 | ** </li> | ||||
| 4800 | ** </ol> | ||||
| 4801 | ** | ||||
| 4802 | ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having | ||||
| 4803 | ** the extra prepFlags parameter, which is a bit array consisting of zero or | ||||
| 4804 | ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The | ||||
| 4805 | ** sqlite3_prepare_v2() interface works exactly the same as | ||||
| 4806 | ** sqlite3_prepare_v3() with a zero prepFlags parameter. | ||||
| 4807 | */ | ||||
| 4808 | SQLITE_API int sqlite3_prepare( | ||||
| 4809 | sqlite3 *db, /* Database handle */ | ||||
| 4810 | const char *zSql, /* SQL statement, UTF-8 encoded */ | ||||
| 4811 | int nByte, /* Maximum length of zSql in bytes. */ | ||||
| 4812 | sqlite3_stmt **ppStmt, /* OUT: Statement handle */ | ||||
| 4813 | const char **pzTail /* OUT: Pointer to unused portion of zSql */ | ||||
| 4814 | ); | ||||
| 4815 | SQLITE_API int sqlite3_prepare_v2( | ||||
| 4816 | sqlite3 *db, /* Database handle */ | ||||
| 4817 | const char *zSql, /* SQL statement, UTF-8 encoded */ | ||||
| 4818 | int nByte, /* Maximum length of zSql in bytes. */ | ||||
| 4819 | sqlite3_stmt **ppStmt, /* OUT: Statement handle */ | ||||
| 4820 | const char **pzTail /* OUT: Pointer to unused portion of zSql */ | ||||
| 4821 | ); | ||||
| 4822 | SQLITE_API int sqlite3_prepare_v3( | ||||
| 4823 | sqlite3 *db, /* Database handle */ | ||||
| 4824 | const char *zSql, /* SQL statement, UTF-8 encoded */ | ||||
| 4825 | int nByte, /* Maximum length of zSql in bytes. */ | ||||
| 4826 | unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ | ||||
| 4827 | sqlite3_stmt **ppStmt, /* OUT: Statement handle */ | ||||
| 4828 | const char **pzTail /* OUT: Pointer to unused portion of zSql */ | ||||
| 4829 | ); | ||||
| 4830 | SQLITE_API int sqlite3_prepare16( | ||||
| 4831 | sqlite3 *db, /* Database handle */ | ||||
| 4832 | const void *zSql, /* SQL statement, UTF-16 encoded */ | ||||
| 4833 | int nByte, /* Maximum length of zSql in bytes. */ | ||||
| 4834 | sqlite3_stmt **ppStmt, /* OUT: Statement handle */ | ||||
| 4835 | const void **pzTail /* OUT: Pointer to unused portion of zSql */ | ||||
| 4836 | ); | ||||
| 4837 | SQLITE_API int sqlite3_prepare16_v2( | ||||
| 4838 | sqlite3 *db, /* Database handle */ | ||||
| 4839 | const void *zSql, /* SQL statement, UTF-16 encoded */ | ||||
| 4840 | int nByte, /* Maximum length of zSql in bytes. */ | ||||
| 4841 | sqlite3_stmt **ppStmt, /* OUT: Statement handle */ | ||||
| 4842 | const void **pzTail /* OUT: Pointer to unused portion of zSql */ | ||||
| 4843 | ); | ||||
| 4844 | SQLITE_API int sqlite3_prepare16_v3( | ||||
| 4845 | sqlite3 *db, /* Database handle */ | ||||
| 4846 | const void *zSql, /* SQL statement, UTF-16 encoded */ | ||||
| 4847 | int nByte, /* Maximum length of zSql in bytes. */ | ||||
| 4848 | unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */ | ||||
| 4849 | sqlite3_stmt **ppStmt, /* OUT: Statement handle */ | ||||
| 4850 | const void **pzTail /* OUT: Pointer to unused portion of zSql */ | ||||
| 4851 | ); | ||||
| 4852 | |||||
| 4853 | /* | ||||
| 4854 | ** CAPI3REF: Retrieving Statement SQL | ||||
| 4855 | ** METHOD: sqlite3_stmt | ||||
| 4856 | ** | ||||
| 4857 | ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8 | ||||
| 4858 | ** SQL text used to create [prepared statement] P if P was | ||||
| 4859 | ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], | ||||
| 4860 | ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()]. | ||||
| 4861 | ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8 | ||||
| 4862 | ** string containing the SQL text of prepared statement P with | ||||
| 4863 | ** [bound parameters] expanded. | ||||
| 4864 | ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8 | ||||
| 4865 | ** string containing the normalized SQL text of prepared statement P. The | ||||
| 4866 | ** semantics used to normalize a SQL statement are unspecified and subject | ||||
| 4867 | ** to change. At a minimum, literal values will be replaced with suitable | ||||
| 4868 | ** placeholders. | ||||
| 4869 | ** | ||||
| 4870 | ** ^(For example, if a prepared statement is created using the SQL | ||||
| 4871 | ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345 | ||||
| 4872 | ** and parameter :xyz is unbound, then sqlite3_sql() will return | ||||
| 4873 | ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql() | ||||
| 4874 | ** will return "SELECT 2345,NULL".)^ | ||||
| 4875 | ** | ||||
| 4876 | ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory | ||||
| 4877 | ** is available to hold the result, or if the result would exceed the | ||||
| 4878 | ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. | ||||
| 4879 | ** | ||||
| 4880 | ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of | ||||
| 4881 | ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time | ||||
| 4882 | ** option causes sqlite3_expanded_sql() to always return NULL. | ||||
| 4883 | ** | ||||
| 4884 | ** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P) | ||||
| 4885 | ** are managed by SQLite and are automatically freed when the prepared | ||||
| 4886 | ** statement is finalized. | ||||
| 4887 | ** ^The string returned by sqlite3_expanded_sql(P), on the other hand, | ||||
| 4888 | ** is obtained from [sqlite3_malloc()] and must be freed by the application | ||||
| 4889 | ** by passing it to [sqlite3_free()]. | ||||
| 4890 | ** | ||||
| 4891 | ** ^The sqlite3_normalized_sql() interface is only available if | ||||
| 4892 | ** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined. | ||||
| 4893 | */ | ||||
| 4894 | SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); | ||||
| 4895 | SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt); | ||||
| 4896 | #ifdef SQLITE_ENABLE_NORMALIZE | ||||
| 4897 | SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt); | ||||
| 4898 | #endif | ||||
| 4899 | |||||
| 4900 | /* | ||||
| 4901 | ** CAPI3REF: Determine If An SQL Statement Writes The Database | ||||
| 4902 | ** METHOD: sqlite3_stmt | ||||
| 4903 | ** | ||||
| 4904 | ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if | ||||
| 4905 | ** and only if the [prepared statement] X makes no direct changes to | ||||
| 4906 | ** the content of the database file. | ||||
| 4907 | ** | ||||
| 4908 | ** Note that [application-defined SQL functions] or | ||||
| 4909 | ** [virtual tables] might change the database indirectly as a side effect. | ||||
| 4910 | ** ^(For example, if an application defines a function "eval()" that | ||||
| 4911 | ** calls [sqlite3_exec()], then the following SQL statement would | ||||
| 4912 | ** change the database file through side-effects: | ||||
| 4913 | ** | ||||
| 4914 | ** <blockquote><pre> | ||||
| 4915 | ** SELECT eval('DELETE FROM t1') FROM t2; | ||||
| 4916 | ** </pre></blockquote> | ||||
| 4917 | ** | ||||
| 4918 | ** But because the [SELECT] statement does not change the database file | ||||
| 4919 | ** directly, sqlite3_stmt_readonly() would still return true.)^ | ||||
| 4920 | ** | ||||
| 4921 | ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], | ||||
| 4922 | ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, | ||||
| 4923 | ** since the statements themselves do not actually modify the database but | ||||
| 4924 | ** rather they control the timing of when other statements modify the | ||||
| 4925 | ** database. ^The [ATTACH] and [DETACH] statements also cause | ||||
| 4926 | ** sqlite3_stmt_readonly() to return true since, while those statements | ||||
| 4927 | ** change the configuration of a database connection, they do not make | ||||
| 4928 | ** changes to the content of the database files on disk. | ||||
| 4929 | ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since | ||||
| 4930 | ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and | ||||
| 4931 | ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so | ||||
| 4932 | ** sqlite3_stmt_readonly() returns false for those commands. | ||||
| 4933 | ** | ||||
| 4934 | ** ^This routine returns false if there is any possibility that the | ||||
| 4935 | ** statement might change the database file. ^A false return does | ||||
| 4936 | ** not guarantee that the statement will change the database file. | ||||
| 4937 | ** ^For example, an UPDATE statement might have a WHERE clause that | ||||
| 4938 | ** makes it a no-op, but the sqlite3_stmt_readonly() result would still | ||||
| 4939 | ** be false. ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a | ||||
| 4940 | ** read-only no-op if the table already exists, but | ||||
| 4941 | ** sqlite3_stmt_readonly() still returns false for such a statement. | ||||
| 4942 | ** | ||||
| 4943 | ** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN] | ||||
| 4944 | ** statement, then sqlite3_stmt_readonly(X) returns the same value as | ||||
| 4945 | ** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted. | ||||
| 4946 | */ | ||||
| 4947 | SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); | ||||
| 4948 | |||||
| 4949 | /* | ||||
| 4950 | ** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement | ||||
| 4951 | ** METHOD: sqlite3_stmt | ||||
| 4952 | ** | ||||
| 4953 | ** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the | ||||
| 4954 | ** prepared statement S is an EXPLAIN statement, or 2 if the | ||||
| 4955 | ** statement S is an EXPLAIN QUERY PLAN. | ||||
| 4956 | ** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is | ||||
| 4957 | ** an ordinary statement or a NULL pointer. | ||||
| 4958 | */ | ||||
| 4959 | SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt); | ||||
| 4960 | |||||
| 4961 | /* | ||||
| 4962 | ** CAPI3REF: Change The EXPLAIN Setting For A Prepared Statement | ||||
| 4963 | ** METHOD: sqlite3_stmt | ||||
| 4964 | ** | ||||
| 4965 | ** The sqlite3_stmt_explain(S,E) interface changes the EXPLAIN | ||||
| 4966 | ** setting for [prepared statement] S. If E is zero, then S becomes | ||||
| 4967 | ** a normal prepared statement. If E is 1, then S behaves as if | ||||
| 4968 | ** its SQL text began with "[EXPLAIN]". If E is 2, then S behaves as if | ||||
| 4969 | ** its SQL text began with "[EXPLAIN QUERY PLAN]". | ||||
| 4970 | ** | ||||
| 4971 | ** Calling sqlite3_stmt_explain(S,E) might cause S to be reprepared. | ||||
| 4972 | ** SQLite tries to avoid a reprepare, but a reprepare might be necessary | ||||
| 4973 | ** on the first transition into EXPLAIN or EXPLAIN QUERY PLAN mode. | ||||
| 4974 | ** | ||||
| 4975 | ** Because of the potential need to reprepare, a call to | ||||
| 4976 | ** sqlite3_stmt_explain(S,E) will fail with SQLITE_ERROR if S cannot be | ||||
| 4977 | ** reprepared because it was created using [sqlite3_prepare()] instead of | ||||
| 4978 | ** the newer [sqlite3_prepare_v2()] or [sqlite3_prepare_v3()] interfaces and | ||||
| 4979 | ** hence has no saved SQL text with which to reprepare. | ||||
| 4980 | ** | ||||
| 4981 | ** Changing the explain setting for a prepared statement does not change | ||||
| 4982 | ** the original SQL text for the statement. Hence, if the SQL text originally | ||||
| 4983 | ** began with EXPLAIN or EXPLAIN QUERY PLAN, but sqlite3_stmt_explain(S,0) | ||||
| 4984 | ** is called to convert the statement into an ordinary statement, the EXPLAIN | ||||
| 4985 | ** or EXPLAIN QUERY PLAN keywords will still appear in the sqlite3_sql(S) | ||||
| 4986 | ** output, even though the statement now acts like a normal SQL statement. | ||||
| 4987 | ** | ||||
| 4988 | ** This routine returns SQLITE_OK if the explain mode is successfully | ||||
| 4989 | ** changed, or an error code if the explain mode could not be changed. | ||||
| 4990 | ** The explain mode cannot be changed while a statement is active. | ||||
| 4991 | ** Hence, it is good practice to call [sqlite3_reset(S)] | ||||
| 4992 | ** immediately prior to calling sqlite3_stmt_explain(S,E). | ||||
| 4993 | */ | ||||
| 4994 | SQLITE_API int sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode); | ||||
| 4995 | |||||
| 4996 | /* | ||||
| 4997 | ** CAPI3REF: Determine If A Prepared Statement Has Been Reset | ||||
| 4998 | ** METHOD: sqlite3_stmt | ||||
| 4999 | ** | ||||
| 5000 | ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the | ||||
| 5001 | ** [prepared statement] S has been stepped at least once using | ||||
| 5002 | ** [sqlite3_step(S)] but has neither run to completion (returned | ||||
| 5003 | ** [SQLITE_DONE] from [sqlite3_step(S)]) nor | ||||
| 5004 | ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) | ||||
| 5005 | ** interface returns false if S is a NULL pointer. If S is not a | ||||
| 5006 | ** NULL pointer and is not a pointer to a valid [prepared statement] | ||||
| 5007 | ** object, then the behavior is undefined and probably undesirable. | ||||
| 5008 | ** | ||||
| 5009 | ** This interface can be used in combination [sqlite3_next_stmt()] | ||||
| 5010 | ** to locate all prepared statements associated with a database | ||||
| 5011 | ** connection that are in need of being reset. This can be used, | ||||
| 5012 | ** for example, in diagnostic routines to search for prepared | ||||
| 5013 | ** statements that are holding a transaction open. | ||||
| 5014 | */ | ||||
| 5015 | SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); | ||||
| 5016 | |||||
| 5017 | /* | ||||
| 5018 | ** CAPI3REF: Dynamically Typed Value Object | ||||
| 5019 | ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} | ||||
| 5020 | ** | ||||
| 5021 | ** SQLite uses the sqlite3_value object to represent all values | ||||
| 5022 | ** that can be stored in a database table. SQLite uses dynamic typing | ||||
| 5023 | ** for the values it stores. ^Values stored in sqlite3_value objects | ||||
| 5024 | ** can be integers, floating point values, strings, BLOBs, or NULL. | ||||
| 5025 | ** | ||||
| 5026 | ** An sqlite3_value object may be either "protected" or "unprotected". | ||||
| 5027 | ** Some interfaces require a protected sqlite3_value. Other interfaces | ||||
| 5028 | ** will accept either a protected or an unprotected sqlite3_value. | ||||
| 5029 | ** Every interface that accepts sqlite3_value arguments specifies | ||||
| 5030 | ** whether or not it requires a protected sqlite3_value. The | ||||
| 5031 | ** [sqlite3_value_dup()] interface can be used to construct a new | ||||
| 5032 | ** protected sqlite3_value from an unprotected sqlite3_value. | ||||
| 5033 | ** | ||||
| 5034 | ** The terms "protected" and "unprotected" refer to whether or not | ||||
| 5035 | ** a mutex is held. An internal mutex is held for a protected | ||||
| 5036 | ** sqlite3_value object but no mutex is held for an unprotected | ||||
| 5037 | ** sqlite3_value object. If SQLite is compiled to be single-threaded | ||||
| 5038 | ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) | ||||
| 5039 | ** or if SQLite is run in one of reduced mutex modes | ||||
| 5040 | ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] | ||||
| 5041 | ** then there is no distinction between protected and unprotected | ||||
| 5042 | ** sqlite3_value objects and they can be used interchangeably. However, | ||||
| 5043 | ** for maximum code portability it is recommended that applications | ||||
| 5044 | ** still make the distinction between protected and unprotected | ||||
| 5045 | ** sqlite3_value objects even when not strictly required. | ||||
| 5046 | ** | ||||
| 5047 | ** ^The sqlite3_value objects that are passed as parameters into the | ||||
| 5048 | ** implementation of [application-defined SQL functions] are protected. | ||||
| 5049 | ** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()] | ||||
| 5050 | ** are protected. | ||||
| 5051 | ** ^The sqlite3_value object returned by | ||||
| 5052 | ** [sqlite3_column_value()] is unprotected. | ||||
| 5053 | ** Unprotected sqlite3_value objects may only be used as arguments | ||||
| 5054 | ** to [sqlite3_result_value()], [sqlite3_bind_value()], and | ||||
| 5055 | ** [sqlite3_value_dup()]. | ||||
| 5056 | ** The [sqlite3_value_blob | sqlite3_value_type()] family of | ||||
| 5057 | ** interfaces require protected sqlite3_value objects. | ||||
| 5058 | */ | ||||
| 5059 | typedef struct sqlite3_value sqlite3_value; | ||||
| 5060 | |||||
| 5061 | /* | ||||
| 5062 | ** CAPI3REF: SQL Function Context Object | ||||
| 5063 | ** | ||||
| 5064 | ** The context in which an SQL function executes is stored in an | ||||
| 5065 | ** sqlite3_context object. ^A pointer to an sqlite3_context object | ||||
| 5066 | ** is always first parameter to [application-defined SQL functions]. | ||||
| 5067 | ** The application-defined SQL function implementation will pass this | ||||
| 5068 | ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], | ||||
| 5069 | ** [sqlite3_aggregate_context()], [sqlite3_user_data()], | ||||
| 5070 | ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], | ||||
| 5071 | ** and/or [sqlite3_set_auxdata()]. | ||||
| 5072 | */ | ||||
| 5073 | typedef struct sqlite3_context sqlite3_context; | ||||
| 5074 | |||||
| 5075 | /* | ||||
| 5076 | ** CAPI3REF: Binding Values To Prepared Statements | ||||
| 5077 | ** KEYWORDS: {host parameter} {host parameters} {host parameter name} | ||||
| 5078 | ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} | ||||
| 5079 | ** METHOD: sqlite3_stmt | ||||
| 5080 | ** | ||||
| 5081 | ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, | ||||
| 5082 | ** literals may be replaced by a [parameter] that matches one of the following | ||||
| 5083 | ** templates: | ||||
| 5084 | ** | ||||
| 5085 | ** <ul> | ||||
| 5086 | ** <li> ? | ||||
| 5087 | ** <li> ?NNN | ||||
| 5088 | ** <li> :VVV | ||||
| 5089 | ** <li> @VVV | ||||
| 5090 | ** <li> $VVV | ||||
| 5091 | ** </ul> | ||||
| 5092 | ** | ||||
| 5093 | ** In the templates above, NNN represents an integer literal, | ||||
| 5094 | ** and VVV represents an alphanumeric identifier.)^ ^The values of these | ||||
| 5095 | ** parameters (also called "host parameter names" or "SQL parameters") | ||||
| 5096 | ** can be set using the sqlite3_bind_*() routines defined here. | ||||
| 5097 | ** | ||||
| 5098 | ** ^The first argument to the sqlite3_bind_*() routines is always | ||||
| 5099 | ** a pointer to the [sqlite3_stmt] object returned from | ||||
| 5100 | ** [sqlite3_prepare_v2()] or its variants. | ||||
| 5101 | ** | ||||
| 5102 | ** ^The second argument is the index of the SQL parameter to be set. | ||||
| 5103 | ** ^The leftmost SQL parameter has an index of 1. ^When the same named | ||||
| 5104 | ** SQL parameter is used more than once, second and subsequent | ||||
| 5105 | ** occurrences have the same index as the first occurrence. | ||||
| 5106 | ** ^The index for named parameters can be looked up using the | ||||
| 5107 | ** [sqlite3_bind_parameter_index()] API if desired. ^The index | ||||
| 5108 | ** for "?NNN" parameters is the value of NNN. | ||||
| 5109 | ** ^The NNN value must be between 1 and the [sqlite3_limit()] | ||||
| 5110 | ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766). | ||||
| 5111 | ** | ||||
| 5112 | ** ^The third argument is the value to bind to the parameter. | ||||
| 5113 | ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() | ||||
| 5114 | ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter | ||||
| 5115 | ** is ignored and the end result is the same as sqlite3_bind_null(). | ||||
| 5116 | ** ^If the third parameter to sqlite3_bind_text() is not NULL, then | ||||
| 5117 | ** it should be a pointer to well-formed UTF8 text. | ||||
| 5118 | ** ^If the third parameter to sqlite3_bind_text16() is not NULL, then | ||||
| 5119 | ** it should be a pointer to well-formed UTF16 text. | ||||
| 5120 | ** ^If the third parameter to sqlite3_bind_text64() is not NULL, then | ||||
| 5121 | ** it should be a pointer to a well-formed unicode string that is | ||||
| 5122 | ** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16 | ||||
| 5123 | ** otherwise. | ||||
| 5124 | ** | ||||
| 5125 | ** [[byte-order determination rules]] ^The byte-order of | ||||
| 5126 | ** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF) | ||||
| 5127 | ** found in the first character, which is removed, or in the absence of a BOM | ||||
| 5128 | ** the byte order is the native byte order of the host | ||||
| 5129 | ** machine for sqlite3_bind_text16() or the byte order specified in | ||||
| 5130 | ** the 6th parameter for sqlite3_bind_text64().)^ | ||||
| 5131 | ** ^If UTF16 input text contains invalid unicode | ||||
| 5132 | ** characters, then SQLite might change those invalid characters | ||||
| 5133 | ** into the unicode replacement character: U+FFFD. | ||||
| 5134 | ** | ||||
| 5135 | ** ^(In those routines that have a fourth argument, its value is the | ||||
| 5136 | ** number of bytes in the parameter. To be clear: the value is the | ||||
| 5137 | ** number of <u>bytes</u> in the value, not the number of characters.)^ | ||||
| 5138 | ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() | ||||
| 5139 | ** is negative, then the length of the string is | ||||
| 5140 | ** the number of bytes up to the first zero terminator. | ||||
| 5141 | ** If the fourth parameter to sqlite3_bind_blob() is negative, then | ||||
| 5142 | ** the behavior is undefined. | ||||
| 5143 | ** If a non-negative fourth parameter is provided to sqlite3_bind_text() | ||||
| 5144 | ** or sqlite3_bind_text16() or sqlite3_bind_text64() then | ||||
| 5145 | ** that parameter must be the byte offset | ||||
| 5146 | ** where the NUL terminator would occur assuming the string were NUL | ||||
| 5147 | ** terminated. If any NUL characters occur at byte offsets less than | ||||
| 5148 | ** the value of the fourth parameter then the resulting string value will | ||||
| 5149 | ** contain embedded NULs. The result of expressions involving strings | ||||
| 5150 | ** with embedded NULs is undefined. | ||||
| 5151 | ** | ||||
| 5152 | ** ^The fifth argument to the BLOB and string binding interfaces controls | ||||
| 5153 | ** or indicates the lifetime of the object referenced by the third parameter. | ||||
| 5154 | ** These three options exist: | ||||
| 5155 | ** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished | ||||
| 5156 | ** with it may be passed. ^It is called to dispose of the BLOB or string even | ||||
| 5157 | ** if the call to the bind API fails, except the destructor is not called if | ||||
| 5158 | ** the third parameter is a NULL pointer or the fourth parameter is negative. | ||||
| 5159 | ** ^ (2) The special constant, [SQLITE_STATIC], may be passed to indicate that | ||||
| 5160 | ** the application remains responsible for disposing of the object. ^In this | ||||
| 5161 | ** case, the object and the provided pointer to it must remain valid until | ||||
| 5162 | ** either the prepared statement is finalized or the same SQL parameter is | ||||
| 5163 | ** bound to something else, whichever occurs sooner. | ||||
| 5164 | ** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the | ||||
| 5165 | ** object is to be copied prior to the return from sqlite3_bind_*(). ^The | ||||
| 5166 | ** object and pointer to it must remain valid until then. ^SQLite will then | ||||
| 5167 | ** manage the lifetime of its private copy. | ||||
| 5168 | ** | ||||
| 5169 | ** ^The sixth argument to sqlite3_bind_text64() must be one of | ||||
| 5170 | ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] | ||||
| 5171 | ** to specify the encoding of the text in the third parameter. If | ||||
| 5172 | ** the sixth argument to sqlite3_bind_text64() is not one of the | ||||
| 5173 | ** allowed values shown above, or if the text encoding is different | ||||
| 5174 | ** from the encoding specified by the sixth parameter, then the behavior | ||||
| 5175 | ** is undefined. | ||||
| 5176 | ** | ||||
| 5177 | ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that | ||||
| 5178 | ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory | ||||
| 5179 | ** (just an integer to hold its size) while it is being processed. | ||||
| 5180 | ** Zeroblobs are intended to serve as placeholders for BLOBs whose | ||||
| 5181 | ** content is later written using | ||||
| 5182 | ** [sqlite3_blob_open | incremental BLOB I/O] routines. | ||||
| 5183 | ** ^A negative value for the zeroblob results in a zero-length BLOB. | ||||
| 5184 | ** | ||||
| 5185 | ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in | ||||
| 5186 | ** [prepared statement] S to have an SQL value of NULL, but to also be | ||||
| 5187 | ** associated with the pointer P of type T. ^D is either a NULL pointer or | ||||
| 5188 | ** a pointer to a destructor function for P. ^SQLite will invoke the | ||||
| 5189 | ** destructor D with a single argument of P when it is finished using | ||||
| 5190 | ** P. The T parameter should be a static string, preferably a string | ||||
| 5191 | ** literal. The sqlite3_bind_pointer() routine is part of the | ||||
| 5192 | ** [pointer passing interface] added for SQLite 3.20.0. | ||||
| 5193 | ** | ||||
| 5194 | ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer | ||||
| 5195 | ** for the [prepared statement] or with a prepared statement for which | ||||
| 5196 | ** [sqlite3_step()] has been called more recently than [sqlite3_reset()], | ||||
| 5197 | ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() | ||||
| 5198 | ** routine is passed a [prepared statement] that has been finalized, the | ||||
| 5199 | ** result is undefined and probably harmful. | ||||
| 5200 | ** | ||||
| 5201 | ** ^Bindings are not cleared by the [sqlite3_reset()] routine. | ||||
| 5202 | ** ^Unbound parameters are interpreted as NULL. | ||||
| 5203 | ** | ||||
| 5204 | ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an | ||||
| 5205 | ** [error code] if anything goes wrong. | ||||
| 5206 | ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB | ||||
| 5207 | ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or | ||||
| 5208 | ** [SQLITE_MAX_LENGTH]. | ||||
| 5209 | ** ^[SQLITE_RANGE] is returned if the parameter | ||||
| 5210 | ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. | ||||
| 5211 | ** | ||||
| 5212 | ** See also: [sqlite3_bind_parameter_count()], | ||||
| 5213 | ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. | ||||
| 5214 | */ | ||||
| 5215 | SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); | ||||
| 5216 | SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, | ||||
| 5217 | void(*)(void*)); | ||||
| 5218 | SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); | ||||
| 5219 | SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); | ||||
| 5220 | SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); | ||||
| 5221 | SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); | ||||
| 5222 | SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); | ||||
| 5223 | SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); | ||||
| 5224 | SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, | ||||
| 5225 | void(*)(void*), unsigned char encoding); | ||||
| 5226 | SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); | ||||
| 5227 | SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*)); | ||||
| 5228 | SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); | ||||
| 5229 | SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); | ||||
| 5230 | |||||
| 5231 | /* | ||||
| 5232 | ** CAPI3REF: Number Of SQL Parameters | ||||
| 5233 | ** METHOD: sqlite3_stmt | ||||
| 5234 | ** | ||||
| 5235 | ** ^This routine can be used to find the number of [SQL parameters] | ||||
| 5236 | ** in a [prepared statement]. SQL parameters are tokens of the | ||||
| 5237 | ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as | ||||
| 5238 | ** placeholders for values that are [sqlite3_bind_blob | bound] | ||||
| 5239 | ** to the parameters at a later time. | ||||
| 5240 | ** | ||||
| 5241 | ** ^(This routine actually returns the index of the largest (rightmost) | ||||
| 5242 | ** parameter. For all forms except ?NNN, this will correspond to the | ||||
| 5243 | ** number of unique parameters. If parameters of the ?NNN form are used, | ||||
| 5244 | ** there may be gaps in the list.)^ | ||||
| 5245 | ** | ||||
| 5246 | ** See also: [sqlite3_bind_blob|sqlite3_bind()], | ||||
| 5247 | ** [sqlite3_bind_parameter_name()], and | ||||
| 5248 | ** [sqlite3_bind_parameter_index()]. | ||||
| 5249 | */ | ||||
| 5250 | SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); | ||||
| 5251 | |||||
| 5252 | /* | ||||
| 5253 | ** CAPI3REF: Name Of A Host Parameter | ||||
| 5254 | ** METHOD: sqlite3_stmt | ||||
| 5255 | ** | ||||
| 5256 | ** ^The sqlite3_bind_parameter_name(P,N) interface returns | ||||
| 5257 | ** the name of the N-th [SQL parameter] in the [prepared statement] P. | ||||
| 5258 | ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" | ||||
| 5259 | ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" | ||||
| 5260 | ** respectively. | ||||
| 5261 | ** In other words, the initial ":" or "$" or "@" or "?" | ||||
| 5262 | ** is included as part of the name.)^ | ||||
| 5263 | ** ^Parameters of the form "?" without a following integer have no name | ||||
| 5264 | ** and are referred to as "nameless" or "anonymous parameters". | ||||
| 5265 | ** | ||||
| 5266 | ** ^The first host parameter has an index of 1, not 0. | ||||
| 5267 | ** | ||||
| 5268 | ** ^If the value N is out of range or if the N-th parameter is | ||||
| 5269 | ** nameless, then NULL is returned. ^The returned string is | ||||
| 5270 | ** always in UTF-8 encoding even if the named parameter was | ||||
| 5271 | ** originally specified as UTF-16 in [sqlite3_prepare16()], | ||||
| 5272 | ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()]. | ||||
| 5273 | ** | ||||
| 5274 | ** See also: [sqlite3_bind_blob|sqlite3_bind()], | ||||
| 5275 | ** [sqlite3_bind_parameter_count()], and | ||||
| 5276 | ** [sqlite3_bind_parameter_index()]. | ||||
| 5277 | */ | ||||
| 5278 | SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); | ||||
| 5279 | |||||
| 5280 | /* | ||||
| 5281 | ** CAPI3REF: Index Of A Parameter With A Given Name | ||||
| 5282 | ** METHOD: sqlite3_stmt | ||||
| 5283 | ** | ||||
| 5284 | ** ^Return the index of an SQL parameter given its name. ^The | ||||
| 5285 | ** index value returned is suitable for use as the second | ||||
| 5286 | ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero | ||||
| 5287 | ** is returned if no matching parameter is found. ^The parameter | ||||
| 5288 | ** name must be given in UTF-8 even if the original statement | ||||
| 5289 | ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or | ||||
| 5290 | ** [sqlite3_prepare16_v3()]. | ||||
| 5291 | ** | ||||
| 5292 | ** See also: [sqlite3_bind_blob|sqlite3_bind()], | ||||
| 5293 | ** [sqlite3_bind_parameter_count()], and | ||||
| 5294 | ** [sqlite3_bind_parameter_name()]. | ||||
| 5295 | */ | ||||
| 5296 | SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); | ||||
| 5297 | |||||
| 5298 | /* | ||||
| 5299 | ** CAPI3REF: Reset All Bindings On A Prepared Statement | ||||
| 5300 | ** METHOD: sqlite3_stmt | ||||
| 5301 | ** | ||||
| 5302 | ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset | ||||
| 5303 | ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. | ||||
| 5304 | ** ^Use this routine to reset all host parameters to NULL. | ||||
| 5305 | */ | ||||
| 5306 | SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); | ||||
| 5307 | |||||
| 5308 | /* | ||||
| 5309 | ** CAPI3REF: Number Of Columns In A Result Set | ||||
| 5310 | ** METHOD: sqlite3_stmt | ||||
| 5311 | ** | ||||
| 5312 | ** ^Return the number of columns in the result set returned by the | ||||
| 5313 | ** [prepared statement]. ^If this routine returns 0, that means the | ||||
| 5314 | ** [prepared statement] returns no data (for example an [UPDATE]). | ||||
| 5315 | ** ^However, just because this routine returns a positive number does not | ||||
| 5316 | ** mean that one or more rows of data will be returned. ^A SELECT statement | ||||
| 5317 | ** will always have a positive sqlite3_column_count() but depending on the | ||||
| 5318 | ** WHERE clause constraints and the table content, it might return no rows. | ||||
| 5319 | ** | ||||
| 5320 | ** See also: [sqlite3_data_count()] | ||||
| 5321 | */ | ||||
| 5322 | SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); | ||||
| 5323 | |||||
| 5324 | /* | ||||
| 5325 | ** CAPI3REF: Column Names In A Result Set | ||||
| 5326 | ** METHOD: sqlite3_stmt | ||||
| 5327 | ** | ||||
| 5328 | ** ^These routines return the name assigned to a particular column | ||||
| 5329 | ** in the result set of a [SELECT] statement. ^The sqlite3_column_name() | ||||
| 5330 | ** interface returns a pointer to a zero-terminated UTF-8 string | ||||
| 5331 | ** and sqlite3_column_name16() returns a pointer to a zero-terminated | ||||
| 5332 | ** UTF-16 string. ^The first parameter is the [prepared statement] | ||||
| 5333 | ** that implements the [SELECT] statement. ^The second parameter is the | ||||
| 5334 | ** column number. ^The leftmost column is number 0. | ||||
| 5335 | ** | ||||
| 5336 | ** ^The returned string pointer is valid until either the [prepared statement] | ||||
| 5337 | ** is destroyed by [sqlite3_finalize()] or until the statement is automatically | ||||
| 5338 | ** reprepared by the first call to [sqlite3_step()] for a particular run | ||||
| 5339 | ** or until the next call to | ||||
| 5340 | ** sqlite3_column_name() or sqlite3_column_name16() on the same column. | ||||
| 5341 | ** | ||||
| 5342 | ** ^If sqlite3_malloc() fails during the processing of either routine | ||||
| 5343 | ** (for example during a conversion from UTF-8 to UTF-16) then a | ||||
| 5344 | ** NULL pointer is returned. | ||||
| 5345 | ** | ||||
| 5346 | ** ^The name of a result column is the value of the "AS" clause for | ||||
| 5347 | ** that column, if there is an AS clause. If there is no AS clause | ||||
| 5348 | ** then the name of the column is unspecified and may change from | ||||
| 5349 | ** one release of SQLite to the next. | ||||
| 5350 | */ | ||||
| 5351 | SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); | ||||
| 5352 | SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); | ||||
| 5353 | |||||
| 5354 | /* | ||||
| 5355 | ** CAPI3REF: Source Of Data In A Query Result | ||||
| 5356 | ** METHOD: sqlite3_stmt | ||||
| 5357 | ** | ||||
| 5358 | ** ^These routines provide a means to determine the database, table, and | ||||
| 5359 | ** table column that is the origin of a particular result column in a | ||||
| 5360 | ** [SELECT] statement. | ||||
| 5361 | ** ^The name of the database or table or column can be returned as | ||||
| 5362 | ** either a UTF-8 or UTF-16 string. ^The _database_ routines return | ||||
| 5363 | ** the database name, the _table_ routines return the table name, and | ||||
| 5364 | ** the origin_ routines return the column name. | ||||
| 5365 | ** ^The returned string is valid until the [prepared statement] is destroyed | ||||
| 5366 | ** using [sqlite3_finalize()] or until the statement is automatically | ||||
| 5367 | ** reprepared by the first call to [sqlite3_step()] for a particular run | ||||
| 5368 | ** or until the same information is requested | ||||
| 5369 | ** again in a different encoding. | ||||
| 5370 | ** | ||||
| 5371 | ** ^The names returned are the original un-aliased names of the | ||||
| 5372 | ** database, table, and column. | ||||
| 5373 | ** | ||||
| 5374 | ** ^The first argument to these interfaces is a [prepared statement]. | ||||
| 5375 | ** ^These functions return information about the Nth result column returned by | ||||
| 5376 | ** the statement, where N is the second function argument. | ||||
| 5377 | ** ^The left-most column is column 0 for these routines. | ||||
| 5378 | ** | ||||
| 5379 | ** ^If the Nth column returned by the statement is an expression or | ||||
| 5380 | ** subquery and is not a column value, then all of these functions return | ||||
| 5381 | ** NULL. ^These routines might also return NULL if a memory allocation error | ||||
| 5382 | ** occurs. ^Otherwise, they return the name of the attached database, table, | ||||
| 5383 | ** or column that query result column was extracted from. | ||||
| 5384 | ** | ||||
| 5385 | ** ^As with all other SQLite APIs, those whose names end with "16" return | ||||
| 5386 | ** UTF-16 encoded strings and the other functions return UTF-8. | ||||
| 5387 | ** | ||||
| 5388 | ** ^These APIs are only available if the library was compiled with the | ||||
| 5389 | ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. | ||||
| 5390 | ** | ||||
| 5391 | ** If two or more threads call one or more | ||||
| 5392 | ** [sqlite3_column_database_name | column metadata interfaces] | ||||
| 5393 | ** for the same [prepared statement] and result column | ||||
| 5394 | ** at the same time then the results are undefined. | ||||
| 5395 | */ | ||||
| 5396 | SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); | ||||
| 5397 | SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); | ||||
| 5398 | SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); | ||||
| 5399 | SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); | ||||
| 5400 | SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); | ||||
| 5401 | SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); | ||||
| 5402 | |||||
| 5403 | /* | ||||
| 5404 | ** CAPI3REF: Declared Datatype Of A Query Result | ||||
| 5405 | ** METHOD: sqlite3_stmt | ||||
| 5406 | ** | ||||
| 5407 | ** ^(The first parameter is a [prepared statement]. | ||||
| 5408 | ** If this statement is a [SELECT] statement and the Nth column of the | ||||
| 5409 | ** returned result set of that [SELECT] is a table column (not an | ||||
| 5410 | ** expression or subquery) then the declared type of the table | ||||
| 5411 | ** column is returned.)^ ^If the Nth column of the result set is an | ||||
| 5412 | ** expression or subquery, then a NULL pointer is returned. | ||||
| 5413 | ** ^The returned string is always UTF-8 encoded. | ||||
| 5414 | ** | ||||
| 5415 | ** ^(For example, given the database schema: | ||||
| 5416 | ** | ||||
| 5417 | ** CREATE TABLE t1(c1 VARIANT); | ||||
| 5418 | ** | ||||
| 5419 | ** and the following statement to be compiled: | ||||
| 5420 | ** | ||||
| 5421 | ** SELECT c1 + 1, c1 FROM t1; | ||||
| 5422 | ** | ||||
| 5423 | ** this routine would return the string "VARIANT" for the second result | ||||
| 5424 | ** column (i==1), and a NULL pointer for the first result column (i==0).)^ | ||||
| 5425 | ** | ||||
| 5426 | ** ^SQLite uses dynamic run-time typing. ^So just because a column | ||||
| 5427 | ** is declared to contain a particular type does not mean that the | ||||
| 5428 | ** data stored in that column is of the declared type. SQLite is | ||||
| 5429 | ** strongly typed, but the typing is dynamic not static. ^Type | ||||
| 5430 | ** is associated with individual values, not with the containers | ||||
| 5431 | ** used to hold those values. | ||||
| 5432 | */ | ||||
| 5433 | SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); | ||||
| 5434 | SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); | ||||
| 5435 | |||||
| 5436 | /* | ||||
| 5437 | ** CAPI3REF: Evaluate An SQL Statement | ||||
| 5438 | ** METHOD: sqlite3_stmt | ||||
| 5439 | ** | ||||
| 5440 | ** After a [prepared statement] has been prepared using any of | ||||
| 5441 | ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()], | ||||
| 5442 | ** or [sqlite3_prepare16_v3()] or one of the legacy | ||||
| 5443 | ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function | ||||
| 5444 | ** must be called one or more times to evaluate the statement. | ||||
| 5445 | ** | ||||
| 5446 | ** The details of the behavior of the sqlite3_step() interface depend | ||||
| 5447 | ** on whether the statement was prepared using the newer "vX" interfaces | ||||
| 5448 | ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()], | ||||
| 5449 | ** [sqlite3_prepare16_v2()] or the older legacy | ||||
| 5450 | ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the | ||||
| 5451 | ** new "vX" interface is recommended for new applications but the legacy | ||||
| 5452 | ** interface will continue to be supported. | ||||
| 5453 | ** | ||||
| 5454 | ** ^In the legacy interface, the return value will be either [SQLITE_BUSY], | ||||
| 5455 | ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. | ||||
| 5456 | ** ^With the "v2" interface, any of the other [result codes] or | ||||
| 5457 | ** [extended result codes] might be returned as well. | ||||
| 5458 | ** | ||||
| 5459 | ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the | ||||
| 5460 | ** database locks it needs to do its job. ^If the statement is a [COMMIT] | ||||
| 5461 | ** or occurs outside of an explicit transaction, then you can retry the | ||||
| 5462 | ** statement. If the statement is not a [COMMIT] and occurs within an | ||||
| 5463 | ** explicit transaction then you should rollback the transaction before | ||||
| 5464 | ** continuing. | ||||
| 5465 | ** | ||||
| 5466 | ** ^[SQLITE_DONE] means that the statement has finished executing | ||||
| 5467 | ** successfully. sqlite3_step() should not be called again on this virtual | ||||
| 5468 | ** machine without first calling [sqlite3_reset()] to reset the virtual | ||||
| 5469 | ** machine back to its initial state. | ||||
| 5470 | ** | ||||
| 5471 | ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] | ||||
| 5472 | ** is returned each time a new row of data is ready for processing by the | ||||
| 5473 | ** caller. The values may be accessed using the [column access functions]. | ||||
| 5474 | ** sqlite3_step() is called again to retrieve the next row of data. | ||||
| 5475 | ** | ||||
| 5476 | ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint | ||||
| 5477 | ** violation) has occurred. sqlite3_step() should not be called again on | ||||
| 5478 | ** the VM. More information may be found by calling [sqlite3_errmsg()]. | ||||
| 5479 | ** ^With the legacy interface, a more specific error code (for example, | ||||
| 5480 | ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) | ||||
| 5481 | ** can be obtained by calling [sqlite3_reset()] on the | ||||
| 5482 | ** [prepared statement]. ^In the "v2" interface, | ||||
| 5483 | ** the more specific error code is returned directly by sqlite3_step(). | ||||
| 5484 | ** | ||||
| 5485 | ** [SQLITE_MISUSE] means that the this routine was called inappropriately. | ||||
| 5486 | ** Perhaps it was called on a [prepared statement] that has | ||||
| 5487 | ** already been [sqlite3_finalize | finalized] or on one that had | ||||
| 5488 | ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could | ||||
| 5489 | ** be the case that the same database connection is being used by two or | ||||
| 5490 | ** more threads at the same moment in time. | ||||
| 5491 | ** | ||||
| 5492 | ** For all versions of SQLite up to and including 3.6.23.1, a call to | ||||
| 5493 | ** [sqlite3_reset()] was required after sqlite3_step() returned anything | ||||
| 5494 | ** other than [SQLITE_ROW] before any subsequent invocation of | ||||
| 5495 | ** sqlite3_step(). Failure to reset the prepared statement using | ||||
| 5496 | ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from | ||||
| 5497 | ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]), | ||||
| 5498 | ** sqlite3_step() began | ||||
| 5499 | ** calling [sqlite3_reset()] automatically in this circumstance rather | ||||
| 5500 | ** than returning [SQLITE_MISUSE]. This is not considered a compatibility | ||||
| 5501 | ** break because any application that ever receives an SQLITE_MISUSE error | ||||
| 5502 | ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option | ||||
| 5503 | ** can be used to restore the legacy behavior. | ||||
| 5504 | ** | ||||
| 5505 | ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step() | ||||
| 5506 | ** API always returns a generic error code, [SQLITE_ERROR], following any | ||||
| 5507 | ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call | ||||
| 5508 | ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the | ||||
| 5509 | ** specific [error codes] that better describes the error. | ||||
| 5510 | ** We admit that this is a goofy design. The problem has been fixed | ||||
| 5511 | ** with the "v2" interface. If you prepare all of your SQL statements | ||||
| 5512 | ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()] | ||||
| 5513 | ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead | ||||
| 5514 | ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, | ||||
| 5515 | ** then the more specific [error codes] are returned directly | ||||
| 5516 | ** by sqlite3_step(). The use of the "vX" interfaces is recommended. | ||||
| 5517 | */ | ||||
| 5518 | SQLITE_API int sqlite3_step(sqlite3_stmt*); | ||||
| 5519 | |||||
| 5520 | /* | ||||
| 5521 | ** CAPI3REF: Number of columns in a result set | ||||
| 5522 | ** METHOD: sqlite3_stmt | ||||
| 5523 | ** | ||||
| 5524 | ** ^The sqlite3_data_count(P) interface returns the number of columns in the | ||||
| 5525 | ** current row of the result set of [prepared statement] P. | ||||
| 5526 | ** ^If prepared statement P does not have results ready to return | ||||
| 5527 | ** (via calls to the [sqlite3_column_int | sqlite3_column()] family of | ||||
| 5528 | ** interfaces) then sqlite3_data_count(P) returns 0. | ||||
| 5529 | ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. | ||||
| 5530 | ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to | ||||
| 5531 | ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) | ||||
| 5532 | ** will return non-zero if previous call to [sqlite3_step](P) returned | ||||
| 5533 | ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] | ||||
| 5534 | ** where it always returns zero since each step of that multi-step | ||||
| 5535 | ** pragma returns 0 columns of data. | ||||
| 5536 | ** | ||||
| 5537 | ** See also: [sqlite3_column_count()] | ||||
| 5538 | */ | ||||
| 5539 | SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); | ||||
| 5540 | |||||
| 5541 | /* | ||||
| 5542 | ** CAPI3REF: Fundamental Datatypes | ||||
| 5543 | ** KEYWORDS: SQLITE_TEXT | ||||
| 5544 | ** | ||||
| 5545 | ** ^(Every value in SQLite has one of five fundamental datatypes: | ||||
| 5546 | ** | ||||
| 5547 | ** <ul> | ||||
| 5548 | ** <li> 64-bit signed integer | ||||
| 5549 | ** <li> 64-bit IEEE floating point number | ||||
| 5550 | ** <li> string | ||||
| 5551 | ** <li> BLOB | ||||
| 5552 | ** <li> NULL | ||||
| 5553 | ** </ul>)^ | ||||
| 5554 | ** | ||||
| 5555 | ** These constants are codes for each of those types. | ||||
| 5556 | ** | ||||
| 5557 | ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 | ||||
| 5558 | ** for a completely different meaning. Software that links against both | ||||
| 5559 | ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not | ||||
| 5560 | ** SQLITE_TEXT. | ||||
| 5561 | */ | ||||
| 5562 | #define SQLITE_INTEGER1 1 | ||||
| 5563 | #define SQLITE_FLOAT2 2 | ||||
| 5564 | #define SQLITE_BLOB4 4 | ||||
| 5565 | #define SQLITE_NULL5 5 | ||||
| 5566 | #ifdef SQLITE_TEXT3 | ||||
| 5567 | # undef SQLITE_TEXT3 | ||||
| 5568 | #else | ||||
| 5569 | # define SQLITE_TEXT3 3 | ||||
| 5570 | #endif | ||||
| 5571 | #define SQLITE3_TEXT3 3 | ||||
| 5572 | |||||
| 5573 | /* | ||||
| 5574 | ** CAPI3REF: Result Values From A Query | ||||
| 5575 | ** KEYWORDS: {column access functions} | ||||
| 5576 | ** METHOD: sqlite3_stmt | ||||
| 5577 | ** | ||||
| 5578 | ** <b>Summary:</b> | ||||
| 5579 | ** <blockquote><table border=0 cellpadding=0 cellspacing=0> | ||||
| 5580 | ** <tr><td><b>sqlite3_column_blob</b><td>→<td>BLOB result | ||||
| 5581 | ** <tr><td><b>sqlite3_column_double</b><td>→<td>REAL result | ||||
| 5582 | ** <tr><td><b>sqlite3_column_int</b><td>→<td>32-bit INTEGER result | ||||
| 5583 | ** <tr><td><b>sqlite3_column_int64</b><td>→<td>64-bit INTEGER result | ||||
| 5584 | ** <tr><td><b>sqlite3_column_text</b><td>→<td>UTF-8 TEXT result | ||||
| 5585 | ** <tr><td><b>sqlite3_column_text16</b><td>→<td>UTF-16 TEXT result | ||||
| 5586 | ** <tr><td><b>sqlite3_column_value</b><td>→<td>The result as an | ||||
| 5587 | ** [sqlite3_value|unprotected sqlite3_value] object. | ||||
| 5588 | ** <tr><td> <td> <td> | ||||
| 5589 | ** <tr><td><b>sqlite3_column_bytes</b><td>→<td>Size of a BLOB | ||||
| 5590 | ** or a UTF-8 TEXT result in bytes | ||||
| 5591 | ** <tr><td><b>sqlite3_column_bytes16 </b> | ||||
| 5592 | ** <td>→ <td>Size of UTF-16 | ||||
| 5593 | ** TEXT in bytes | ||||
| 5594 | ** <tr><td><b>sqlite3_column_type</b><td>→<td>Default | ||||
| 5595 | ** datatype of the result | ||||
| 5596 | ** </table></blockquote> | ||||
| 5597 | ** | ||||
| 5598 | ** <b>Details:</b> | ||||
| 5599 | ** | ||||
| 5600 | ** ^These routines return information about a single column of the current | ||||
| 5601 | ** result row of a query. ^In every case the first argument is a pointer | ||||
| 5602 | ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] | ||||
| 5603 | ** that was returned from [sqlite3_prepare_v2()] or one of its variants) | ||||
| 5604 | ** and the second argument is the index of the column for which information | ||||
| 5605 | ** should be returned. ^The leftmost column of the result set has the index 0. | ||||
| 5606 | ** ^The number of columns in the result can be determined using | ||||
| 5607 | ** [sqlite3_column_count()]. | ||||
| 5608 | ** | ||||
| 5609 | ** If the SQL statement does not currently point to a valid row, or if the | ||||
| 5610 | ** column index is out of range, the result is undefined. | ||||
| 5611 | ** These routines may only be called when the most recent call to | ||||
| 5612 | ** [sqlite3_step()] has returned [SQLITE_ROW] and neither | ||||
| 5613 | ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. | ||||
| 5614 | ** If any of these routines are called after [sqlite3_reset()] or | ||||
| 5615 | ** [sqlite3_finalize()] or after [sqlite3_step()] has returned | ||||
| 5616 | ** something other than [SQLITE_ROW], the results are undefined. | ||||
| 5617 | ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] | ||||
| 5618 | ** are called from a different thread while any of these routines | ||||
| 5619 | ** are pending, then the results are undefined. | ||||
| 5620 | ** | ||||
| 5621 | ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16) | ||||
| 5622 | ** each return the value of a result column in a specific data format. If | ||||
| 5623 | ** the result column is not initially in the requested format (for example, | ||||
| 5624 | ** if the query returns an integer but the sqlite3_column_text() interface | ||||
| 5625 | ** is used to extract the value) then an automatic type conversion is performed. | ||||
| 5626 | ** | ||||
| 5627 | ** ^The sqlite3_column_type() routine returns the | ||||
| 5628 | ** [SQLITE_INTEGER | datatype code] for the initial data type | ||||
| 5629 | ** of the result column. ^The returned value is one of [SQLITE_INTEGER], | ||||
| 5630 | ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. | ||||
| 5631 | ** The return value of sqlite3_column_type() can be used to decide which | ||||
| 5632 | ** of the first six interface should be used to extract the column value. | ||||
| 5633 | ** The value returned by sqlite3_column_type() is only meaningful if no | ||||
| 5634 | ** automatic type conversions have occurred for the value in question. | ||||
| 5635 | ** After a type conversion, the result of calling sqlite3_column_type() | ||||
| 5636 | ** is undefined, though harmless. Future | ||||
| 5637 | ** versions of SQLite may change the behavior of sqlite3_column_type() | ||||
| 5638 | ** following a type conversion. | ||||
| 5639 | ** | ||||
| 5640 | ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes() | ||||
| 5641 | ** or sqlite3_column_bytes16() interfaces can be used to determine the size | ||||
| 5642 | ** of that BLOB or string. | ||||
| 5643 | ** | ||||
| 5644 | ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() | ||||
| 5645 | ** routine returns the number of bytes in that BLOB or string. | ||||
| 5646 | ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts | ||||
| 5647 | ** the string to UTF-8 and then returns the number of bytes. | ||||
| 5648 | ** ^If the result is a numeric value then sqlite3_column_bytes() uses | ||||
| 5649 | ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns | ||||
| 5650 | ** the number of bytes in that string. | ||||
| 5651 | ** ^If the result is NULL, then sqlite3_column_bytes() returns zero. | ||||
| 5652 | ** | ||||
| 5653 | ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() | ||||
| 5654 | ** routine returns the number of bytes in that BLOB or string. | ||||
| 5655 | ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts | ||||
| 5656 | ** the string to UTF-16 and then returns the number of bytes. | ||||
| 5657 | ** ^If the result is a numeric value then sqlite3_column_bytes16() uses | ||||
| 5658 | ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns | ||||
| 5659 | ** the number of bytes in that string. | ||||
| 5660 | ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. | ||||
| 5661 | ** | ||||
| 5662 | ** ^The values returned by [sqlite3_column_bytes()] and | ||||
| 5663 | ** [sqlite3_column_bytes16()] do not include the zero terminators at the end | ||||
| 5664 | ** of the string. ^For clarity: the values returned by | ||||
| 5665 | ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of | ||||
| 5666 | ** bytes in the string, not the number of characters. | ||||
| 5667 | ** | ||||
| 5668 | ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), | ||||
| 5669 | ** even empty strings, are always zero-terminated. ^The return | ||||
| 5670 | ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. | ||||
| 5671 | ** | ||||
| 5672 | ** ^Strings returned by sqlite3_column_text16() always have the endianness | ||||
| 5673 | ** which is native to the platform, regardless of the text encoding set | ||||
| 5674 | ** for the database. | ||||
| 5675 | ** | ||||
| 5676 | ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an | ||||
| 5677 | ** [unprotected sqlite3_value] object. In a multithreaded environment, | ||||
| 5678 | ** an unprotected sqlite3_value object may only be used safely with | ||||
| 5679 | ** [sqlite3_bind_value()] and [sqlite3_result_value()]. | ||||
| 5680 | ** If the [unprotected sqlite3_value] object returned by | ||||
| 5681 | ** [sqlite3_column_value()] is used in any other way, including calls | ||||
| 5682 | ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], | ||||
| 5683 | ** or [sqlite3_value_bytes()], the behavior is not threadsafe. | ||||
| 5684 | ** Hence, the sqlite3_column_value() interface | ||||
| 5685 | ** is normally only useful within the implementation of | ||||
| 5686 | ** [application-defined SQL functions] or [virtual tables], not within | ||||
| 5687 | ** top-level application code. | ||||
| 5688 | ** | ||||
| 5689 | ** These routines may attempt to convert the datatype of the result. | ||||
| 5690 | ** ^For example, if the internal representation is FLOAT and a text result | ||||
| 5691 | ** is requested, [sqlite3_snprintf()] is used internally to perform the | ||||
| 5692 | ** conversion automatically. ^(The following table details the conversions | ||||
| 5693 | ** that are applied: | ||||
| 5694 | ** | ||||
| 5695 | ** <blockquote> | ||||
| 5696 | ** <table border="1"> | ||||
| 5697 | ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion | ||||
| 5698 | ** | ||||
| 5699 | ** <tr><td> NULL <td> INTEGER <td> Result is 0 | ||||
| 5700 | ** <tr><td> NULL <td> FLOAT <td> Result is 0.0 | ||||
| 5701 | ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer | ||||
| 5702 | ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer | ||||
| 5703 | ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float | ||||
| 5704 | ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer | ||||
| 5705 | ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT | ||||
| 5706 | ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER | ||||
| 5707 | ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float | ||||
| 5708 | ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB | ||||
| 5709 | ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER | ||||
| 5710 | ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL | ||||
| 5711 | ** <tr><td> TEXT <td> BLOB <td> No change | ||||
| 5712 | ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER | ||||
| 5713 | ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL | ||||
| 5714 | ** <tr><td> BLOB <td> TEXT <td> [CAST] to TEXT, ensure zero terminator | ||||
| 5715 | ** </table> | ||||
| 5716 | ** </blockquote>)^ | ||||
| 5717 | ** | ||||
| 5718 | ** Note that when type conversions occur, pointers returned by prior | ||||
| 5719 | ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or | ||||
| 5720 | ** sqlite3_column_text16() may be invalidated. | ||||
| 5721 | ** Type conversions and pointer invalidations might occur | ||||
| 5722 | ** in the following cases: | ||||
| 5723 | ** | ||||
| 5724 | ** <ul> | ||||
| 5725 | ** <li> The initial content is a BLOB and sqlite3_column_text() or | ||||
| 5726 | ** sqlite3_column_text16() is called. A zero-terminator might | ||||
| 5727 | ** need to be added to the string.</li> | ||||
| 5728 | ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or | ||||
| 5729 | ** sqlite3_column_text16() is called. The content must be converted | ||||
| 5730 | ** to UTF-16.</li> | ||||
| 5731 | ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or | ||||
| 5732 | ** sqlite3_column_text() is called. The content must be converted | ||||
| 5733 | ** to UTF-8.</li> | ||||
| 5734 | ** </ul> | ||||
| 5735 | ** | ||||
| 5736 | ** ^Conversions between UTF-16be and UTF-16le are always done in place and do | ||||
| 5737 | ** not invalidate a prior pointer, though of course the content of the buffer | ||||
| 5738 | ** that the prior pointer references will have been modified. Other kinds | ||||
| 5739 | ** of conversion are done in place when it is possible, but sometimes they | ||||
| 5740 | ** are not possible and in those cases prior pointers are invalidated. | ||||
| 5741 | ** | ||||
| 5742 | ** The safest policy is to invoke these routines | ||||
| 5743 | ** in one of the following ways: | ||||
| 5744 | ** | ||||
| 5745 | ** <ul> | ||||
| 5746 | ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> | ||||
| 5747 | ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> | ||||
| 5748 | ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> | ||||
| 5749 | ** </ul> | ||||
| 5750 | ** | ||||
| 5751 | ** In other words, you should call sqlite3_column_text(), | ||||
| 5752 | ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result | ||||
| 5753 | ** into the desired format, then invoke sqlite3_column_bytes() or | ||||
| 5754 | ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls | ||||
| 5755 | ** to sqlite3_column_text() or sqlite3_column_blob() with calls to | ||||
| 5756 | ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() | ||||
| 5757 | ** with calls to sqlite3_column_bytes(). | ||||
| 5758 | ** | ||||
| 5759 | ** ^The pointers returned are valid until a type conversion occurs as | ||||
| 5760 | ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or | ||||
| 5761 | ** [sqlite3_finalize()] is called. ^The memory space used to hold strings | ||||
| 5762 | ** and BLOBs is freed automatically. Do not pass the pointers returned | ||||
| 5763 | ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into | ||||
| 5764 | ** [sqlite3_free()]. | ||||
| 5765 | ** | ||||
| 5766 | ** As long as the input parameters are correct, these routines will only | ||||
| 5767 | ** fail if an out-of-memory error occurs during a format conversion. | ||||
| 5768 | ** Only the following subset of interfaces are subject to out-of-memory | ||||
| 5769 | ** errors: | ||||
| 5770 | ** | ||||
| 5771 | ** <ul> | ||||
| 5772 | ** <li> sqlite3_column_blob() | ||||
| 5773 | ** <li> sqlite3_column_text() | ||||
| 5774 | ** <li> sqlite3_column_text16() | ||||
| 5775 | ** <li> sqlite3_column_bytes() | ||||
| 5776 | ** <li> sqlite3_column_bytes16() | ||||
| 5777 | ** </ul> | ||||
| 5778 | ** | ||||
| 5779 | ** If an out-of-memory error occurs, then the return value from these | ||||
| 5780 | ** routines is the same as if the column had contained an SQL NULL value. | ||||
| 5781 | ** Valid SQL NULL returns can be distinguished from out-of-memory errors | ||||
| 5782 | ** by invoking the [sqlite3_errcode()] immediately after the suspect | ||||
| 5783 | ** return value is obtained and before any | ||||
| 5784 | ** other SQLite interface is called on the same [database connection]. | ||||
| 5785 | */ | ||||
| 5786 | SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); | ||||
| 5787 | SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); | ||||
| 5788 | SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); | ||||
| 5789 | SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); | ||||
| 5790 | SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); | ||||
| 5791 | SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); | ||||
| 5792 | SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); | ||||
| 5793 | SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); | ||||
| 5794 | SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); | ||||
| 5795 | SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); | ||||
| 5796 | |||||
| 5797 | /* | ||||
| 5798 | ** CAPI3REF: Destroy A Prepared Statement Object | ||||
| 5799 | ** DESTRUCTOR: sqlite3_stmt | ||||
| 5800 | ** | ||||
| 5801 | ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. | ||||
| 5802 | ** ^If the most recent evaluation of the statement encountered no errors | ||||
| 5803 | ** or if the statement is never been evaluated, then sqlite3_finalize() returns | ||||
| 5804 | ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then | ||||
| 5805 | ** sqlite3_finalize(S) returns the appropriate [error code] or | ||||
| 5806 | ** [extended error code]. | ||||
| 5807 | ** | ||||
| 5808 | ** ^The sqlite3_finalize(S) routine can be called at any point during | ||||
| 5809 | ** the life cycle of [prepared statement] S: | ||||
| 5810 | ** before statement S is ever evaluated, after | ||||
| 5811 | ** one or more calls to [sqlite3_reset()], or after any call | ||||
| 5812 | ** to [sqlite3_step()] regardless of whether or not the statement has | ||||
| 5813 | ** completed execution. | ||||
| 5814 | ** | ||||
| 5815 | ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. | ||||
| 5816 | ** | ||||
| 5817 | ** The application must finalize every [prepared statement] in order to avoid | ||||
| 5818 | ** resource leaks. It is a grievous error for the application to try to use | ||||
| 5819 | ** a prepared statement after it has been finalized. Any use of a prepared | ||||
| 5820 | ** statement after it has been finalized can result in undefined and | ||||
| 5821 | ** undesirable behavior such as segfaults and heap corruption. | ||||
| 5822 | */ | ||||
| 5823 | SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); | ||||
| 5824 | |||||
| 5825 | /* | ||||
| 5826 | ** CAPI3REF: Reset A Prepared Statement Object | ||||
| 5827 | ** METHOD: sqlite3_stmt | ||||
| 5828 | ** | ||||
| 5829 | ** The sqlite3_reset() function is called to reset a [prepared statement] | ||||
| 5830 | ** object back to its initial state, ready to be re-executed. | ||||
| 5831 | ** ^Any SQL statement variables that had values bound to them using | ||||
| 5832 | ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. | ||||
| 5833 | ** Use [sqlite3_clear_bindings()] to reset the bindings. | ||||
| 5834 | ** | ||||
| 5835 | ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S | ||||
| 5836 | ** back to the beginning of its program. | ||||
| 5837 | ** | ||||
| 5838 | ** ^The return code from [sqlite3_reset(S)] indicates whether or not | ||||
| 5839 | ** the previous evaluation of prepared statement S completed successfully. | ||||
| 5840 | ** ^If [sqlite3_step(S)] has never before been called on S or if | ||||
| 5841 | ** [sqlite3_step(S)] has not been called since the previous call | ||||
| 5842 | ** to [sqlite3_reset(S)], then [sqlite3_reset(S)] will return | ||||
| 5843 | ** [SQLITE_OK]. | ||||
| 5844 | ** | ||||
| 5845 | ** ^If the most recent call to [sqlite3_step(S)] for the | ||||
| 5846 | ** [prepared statement] S indicated an error, then | ||||
| 5847 | ** [sqlite3_reset(S)] returns an appropriate [error code]. | ||||
| 5848 | ** ^The [sqlite3_reset(S)] interface might also return an [error code] | ||||
| 5849 | ** if there were no prior errors but the process of resetting | ||||
| 5850 | ** the prepared statement caused a new error. ^For example, if an | ||||
| 5851 | ** [INSERT] statement with a [RETURNING] clause is only stepped one time, | ||||
| 5852 | ** that one call to [sqlite3_step(S)] might return SQLITE_ROW but | ||||
| 5853 | ** the overall statement might still fail and the [sqlite3_reset(S)] call | ||||
| 5854 | ** might return SQLITE_BUSY if locking constraints prevent the | ||||
| 5855 | ** database change from committing. Therefore, it is important that | ||||
| 5856 | ** applications check the return code from [sqlite3_reset(S)] even if | ||||
| 5857 | ** no prior call to [sqlite3_step(S)] indicated a problem. | ||||
| 5858 | ** | ||||
| 5859 | ** ^The [sqlite3_reset(S)] interface does not change the values | ||||
| 5860 | ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. | ||||
| 5861 | */ | ||||
| 5862 | SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); | ||||
| 5863 | |||||
| 5864 | |||||
| 5865 | /* | ||||
| 5866 | ** CAPI3REF: Create Or Redefine SQL Functions | ||||
| 5867 | ** KEYWORDS: {function creation routines} | ||||
| 5868 | ** METHOD: sqlite3 | ||||
| 5869 | ** | ||||
| 5870 | ** ^These functions (collectively known as "function creation routines") | ||||
| 5871 | ** are used to add SQL functions or aggregates or to redefine the behavior | ||||
| 5872 | ** of existing SQL functions or aggregates. The only differences between | ||||
| 5873 | ** the three "sqlite3_create_function*" routines are the text encoding | ||||
| 5874 | ** expected for the second parameter (the name of the function being | ||||
| 5875 | ** created) and the presence or absence of a destructor callback for | ||||
| 5876 | ** the application data pointer. Function sqlite3_create_window_function() | ||||
| 5877 | ** is similar, but allows the user to supply the extra callback functions | ||||
| 5878 | ** needed by [aggregate window functions]. | ||||
| 5879 | ** | ||||
| 5880 | ** ^The first parameter is the [database connection] to which the SQL | ||||
| 5881 | ** function is to be added. ^If an application uses more than one database | ||||
| 5882 | ** connection then application-defined SQL functions must be added | ||||
| 5883 | ** to each database connection separately. | ||||
| 5884 | ** | ||||
| 5885 | ** ^The second parameter is the name of the SQL function to be created or | ||||
| 5886 | ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 | ||||
| 5887 | ** representation, exclusive of the zero-terminator. ^Note that the name | ||||
| 5888 | ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. | ||||
| 5889 | ** ^Any attempt to create a function with a longer name | ||||
| 5890 | ** will result in [SQLITE_MISUSE] being returned. | ||||
| 5891 | ** | ||||
| 5892 | ** ^The third parameter (nArg) | ||||
| 5893 | ** is the number of arguments that the SQL function or | ||||
| 5894 | ** aggregate takes. ^If this parameter is -1, then the SQL function or | ||||
| 5895 | ** aggregate may take any number of arguments between 0 and the limit | ||||
| 5896 | ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third | ||||
| 5897 | ** parameter is less than -1 or greater than 127 then the behavior is | ||||
| 5898 | ** undefined. | ||||
| 5899 | ** | ||||
| 5900 | ** ^The fourth parameter, eTextRep, specifies what | ||||
| 5901 | ** [SQLITE_UTF8 | text encoding] this SQL function prefers for | ||||
| 5902 | ** its parameters. The application should set this parameter to | ||||
| 5903 | ** [SQLITE_UTF16LE] if the function implementation invokes | ||||
| 5904 | ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the | ||||
| 5905 | ** implementation invokes [sqlite3_value_text16be()] on an input, or | ||||
| 5906 | ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] | ||||
| 5907 | ** otherwise. ^The same SQL function may be registered multiple times using | ||||
| 5908 | ** different preferred text encodings, with different implementations for | ||||
| 5909 | ** each encoding. | ||||
| 5910 | ** ^When multiple implementations of the same function are available, SQLite | ||||
| 5911 | ** will pick the one that involves the least amount of data conversion. | ||||
| 5912 | ** | ||||
| 5913 | ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC] | ||||
| 5914 | ** to signal that the function will always return the same result given | ||||
| 5915 | ** the same inputs within a single SQL statement. Most SQL functions are | ||||
| 5916 | ** deterministic. The built-in [random()] SQL function is an example of a | ||||
| 5917 | ** function that is not deterministic. The SQLite query planner is able to | ||||
| 5918 | ** perform additional optimizations on deterministic functions, so use | ||||
| 5919 | ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. | ||||
| 5920 | ** | ||||
| 5921 | ** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY] | ||||
| 5922 | ** flag, which if present prevents the function from being invoked from | ||||
| 5923 | ** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions, | ||||
| 5924 | ** index expressions, or the WHERE clause of partial indexes. | ||||
| 5925 | ** | ||||
| 5926 | ** For best security, the [SQLITE_DIRECTONLY] flag is recommended for | ||||
| 5927 | ** all application-defined SQL functions that do not need to be | ||||
| 5928 | ** used inside of triggers, views, CHECK constraints, or other elements of | ||||
| 5929 | ** the database schema. This flag is especially recommended for SQL | ||||
| 5930 | ** functions that have side effects or reveal internal application state. | ||||
| 5931 | ** Without this flag, an attacker might be able to modify the schema of | ||||
| 5932 | ** a database file to include invocations of the function with parameters | ||||
| 5933 | ** chosen by the attacker, which the application will then execute when | ||||
| 5934 | ** the database file is opened and read. | ||||
| 5935 | ** | ||||
| 5936 | ** ^(The fifth parameter is an arbitrary pointer. The implementation of the | ||||
| 5937 | ** function can gain access to this pointer using [sqlite3_user_data()].)^ | ||||
| 5938 | ** | ||||
| 5939 | ** ^The sixth, seventh and eighth parameters passed to the three | ||||
| 5940 | ** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are | ||||
| 5941 | ** pointers to C-language functions that implement the SQL function or | ||||
| 5942 | ** aggregate. ^A scalar SQL function requires an implementation of the xFunc | ||||
| 5943 | ** callback only; NULL pointers must be passed as the xStep and xFinal | ||||
| 5944 | ** parameters. ^An aggregate SQL function requires an implementation of xStep | ||||
| 5945 | ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing | ||||
| 5946 | ** SQL function or aggregate, pass NULL pointers for all three function | ||||
| 5947 | ** callbacks. | ||||
| 5948 | ** | ||||
| 5949 | ** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue | ||||
| 5950 | ** and xInverse) passed to sqlite3_create_window_function are pointers to | ||||
| 5951 | ** C-language callbacks that implement the new function. xStep and xFinal | ||||
| 5952 | ** must both be non-NULL. xValue and xInverse may either both be NULL, in | ||||
| 5953 | ** which case a regular aggregate function is created, or must both be | ||||
| 5954 | ** non-NULL, in which case the new function may be used as either an aggregate | ||||
| 5955 | ** or aggregate window function. More details regarding the implementation | ||||
| 5956 | ** of aggregate window functions are | ||||
| 5957 | ** [user-defined window functions|available here]. | ||||
| 5958 | ** | ||||
| 5959 | ** ^(If the final parameter to sqlite3_create_function_v2() or | ||||
| 5960 | ** sqlite3_create_window_function() is not NULL, then it is the destructor for | ||||
| 5961 | ** the application data pointer. The destructor is invoked when the function | ||||
| 5962 | ** is deleted, either by being overloaded or when the database connection | ||||
| 5963 | ** closes.)^ ^The destructor is also invoked if the call to | ||||
| 5964 | ** sqlite3_create_function_v2() fails. ^When the destructor callback is | ||||
| 5965 | ** invoked, it is passed a single argument which is a copy of the application | ||||
| 5966 | ** data pointer which was the fifth parameter to sqlite3_create_function_v2(). | ||||
| 5967 | ** | ||||
| 5968 | ** ^It is permitted to register multiple implementations of the same | ||||
| 5969 | ** functions with the same name but with either differing numbers of | ||||
| 5970 | ** arguments or differing preferred text encodings. ^SQLite will use | ||||
| 5971 | ** the implementation that most closely matches the way in which the | ||||
| 5972 | ** SQL function is used. ^A function implementation with a non-negative | ||||
| 5973 | ** nArg parameter is a better match than a function implementation with | ||||
| 5974 | ** a negative nArg. ^A function where the preferred text encoding | ||||
| 5975 | ** matches the database encoding is a better | ||||
| 5976 | ** match than a function where the encoding is different. | ||||
| 5977 | ** ^A function where the encoding difference is between UTF16le and UTF16be | ||||
| 5978 | ** is a closer match than a function where the encoding difference is | ||||
| 5979 | ** between UTF8 and UTF16. | ||||
| 5980 | ** | ||||
| 5981 | ** ^Built-in functions may be overloaded by new application-defined functions. | ||||
| 5982 | ** | ||||
| 5983 | ** ^An application-defined function is permitted to call other | ||||
| 5984 | ** SQLite interfaces. However, such calls must not | ||||
| 5985 | ** close the database connection nor finalize or reset the prepared | ||||
| 5986 | ** statement in which the function is running. | ||||
| 5987 | */ | ||||
| 5988 | SQLITE_API int sqlite3_create_function( | ||||
| 5989 | sqlite3 *db, | ||||
| 5990 | const char *zFunctionName, | ||||
| 5991 | int nArg, | ||||
| 5992 | int eTextRep, | ||||
| 5993 | void *pApp, | ||||
| 5994 | void (*xFunc)(sqlite3_context*,int,sqlite3_value**), | ||||
| 5995 | void (*xStep)(sqlite3_context*,int,sqlite3_value**), | ||||
| 5996 | void (*xFinal)(sqlite3_context*) | ||||
| 5997 | ); | ||||
| 5998 | SQLITE_API int sqlite3_create_function16( | ||||
| 5999 | sqlite3 *db, | ||||
| 6000 | const void *zFunctionName, | ||||
| 6001 | int nArg, | ||||
| 6002 | int eTextRep, | ||||
| 6003 | void *pApp, | ||||
| 6004 | void (*xFunc)(sqlite3_context*,int,sqlite3_value**), | ||||
| 6005 | void (*xStep)(sqlite3_context*,int,sqlite3_value**), | ||||
| 6006 | void (*xFinal)(sqlite3_context*) | ||||
| 6007 | ); | ||||
| 6008 | SQLITE_API int sqlite3_create_function_v2( | ||||
| 6009 | sqlite3 *db, | ||||
| 6010 | const char *zFunctionName, | ||||
| 6011 | int nArg, | ||||
| 6012 | int eTextRep, | ||||
| 6013 | void *pApp, | ||||
| 6014 | void (*xFunc)(sqlite3_context*,int,sqlite3_value**), | ||||
| 6015 | void (*xStep)(sqlite3_context*,int,sqlite3_value**), | ||||
| 6016 | void (*xFinal)(sqlite3_context*), | ||||
| 6017 | void(*xDestroy)(void*) | ||||
| 6018 | ); | ||||
| 6019 | SQLITE_API int sqlite3_create_window_function( | ||||
| 6020 | sqlite3 *db, | ||||
| 6021 | const char *zFunctionName, | ||||
| 6022 | int nArg, | ||||
| 6023 | int eTextRep, | ||||
| 6024 | void *pApp, | ||||
| 6025 | void (*xStep)(sqlite3_context*,int,sqlite3_value**), | ||||
| 6026 | void (*xFinal)(sqlite3_context*), | ||||
| 6027 | void (*xValue)(sqlite3_context*), | ||||
| 6028 | void (*xInverse)(sqlite3_context*,int,sqlite3_value**), | ||||
| 6029 | void(*xDestroy)(void*) | ||||
| 6030 | ); | ||||
| 6031 | |||||
| 6032 | /* | ||||
| 6033 | ** CAPI3REF: Text Encodings | ||||
| 6034 | ** | ||||
| 6035 | ** These constant define integer codes that represent the various | ||||
| 6036 | ** text encodings supported by SQLite. | ||||
| 6037 | */ | ||||
| 6038 | #define SQLITE_UTF81 1 /* IMP: R-37514-35566 */ | ||||
| 6039 | #define SQLITE_UTF16LE2 2 /* IMP: R-03371-37637 */ | ||||
| 6040 | #define SQLITE_UTF16BE3 3 /* IMP: R-51971-34154 */ | ||||
| 6041 | #define SQLITE_UTF164 4 /* Use native byte order */ | ||||
| 6042 | #define SQLITE_ANY5 5 /* Deprecated */ | ||||
| 6043 | #define SQLITE_UTF16_ALIGNED8 8 /* sqlite3_create_collation only */ | ||||
| 6044 | |||||
| 6045 | /* | ||||
| 6046 | ** CAPI3REF: Function Flags | ||||
| 6047 | ** | ||||
| 6048 | ** These constants may be ORed together with the | ||||
| 6049 | ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument | ||||
| 6050 | ** to [sqlite3_create_function()], [sqlite3_create_function16()], or | ||||
| 6051 | ** [sqlite3_create_function_v2()]. | ||||
| 6052 | ** | ||||
| 6053 | ** <dl> | ||||
| 6054 | ** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd> | ||||
| 6055 | ** The SQLITE_DETERMINISTIC flag means that the new function always gives | ||||
| 6056 | ** the same output when the input parameters are the same. | ||||
| 6057 | ** The [abs|abs() function] is deterministic, for example, but | ||||
| 6058 | ** [randomblob|randomblob()] is not. Functions must | ||||
| 6059 | ** be deterministic in order to be used in certain contexts such as | ||||
| 6060 | ** with the WHERE clause of [partial indexes] or in [generated columns]. | ||||
| 6061 | ** SQLite might also optimize deterministic functions by factoring them | ||||
| 6062 | ** out of inner loops. | ||||
| 6063 | ** </dd> | ||||
| 6064 | ** | ||||
| 6065 | ** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd> | ||||
| 6066 | ** The SQLITE_DIRECTONLY flag means that the function may only be invoked | ||||
| 6067 | ** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in | ||||
| 6068 | ** schema structures such as [CHECK constraints], [DEFAULT clauses], | ||||
| 6069 | ** [expression indexes], [partial indexes], or [generated columns]. | ||||
| 6070 | ** <p> | ||||
| 6071 | ** The SQLITE_DIRECTONLY flag is recommended for any | ||||
| 6072 | ** [application-defined SQL function] | ||||
| 6073 | ** that has side-effects or that could potentially leak sensitive information. | ||||
| 6074 | ** This will prevent attacks in which an application is tricked | ||||
| 6075 | ** into using a database file that has had its schema surreptitiously | ||||
| 6076 | ** modified to invoke the application-defined function in ways that are | ||||
| 6077 | ** harmful. | ||||
| 6078 | ** <p> | ||||
| 6079 | ** Some people say it is good practice to set SQLITE_DIRECTONLY on all | ||||
| 6080 | ** [application-defined SQL functions], regardless of whether or not they | ||||
| 6081 | ** are security sensitive, as doing so prevents those functions from being used | ||||
| 6082 | ** inside of the database schema, and thus ensures that the database | ||||
| 6083 | ** can be inspected and modified using generic tools (such as the [CLI]) | ||||
| 6084 | ** that do not have access to the application-defined functions. | ||||
| 6085 | ** </dd> | ||||
| 6086 | ** | ||||
| 6087 | ** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd> | ||||
| 6088 | ** The SQLITE_INNOCUOUS flag means that the function is unlikely | ||||
| 6089 | ** to cause problems even if misused. An innocuous function should have | ||||
| 6090 | ** no side effects and should not depend on any values other than its | ||||
| 6091 | ** input parameters. The [abs|abs() function] is an example of an | ||||
| 6092 | ** innocuous function. | ||||
| 6093 | ** The [load_extension() SQL function] is not innocuous because of its | ||||
| 6094 | ** side effects. | ||||
| 6095 | ** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not | ||||
| 6096 | ** exactly the same. The [random|random() function] is an example of a | ||||
| 6097 | ** function that is innocuous but not deterministic. | ||||
| 6098 | ** <p>Some heightened security settings | ||||
| 6099 | ** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF]) | ||||
| 6100 | ** disable the use of SQL functions inside views and triggers and in | ||||
| 6101 | ** schema structures such as [CHECK constraints], [DEFAULT clauses], | ||||
| 6102 | ** [expression indexes], [partial indexes], and [generated columns] unless | ||||
| 6103 | ** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions | ||||
| 6104 | ** are innocuous. Developers are advised to avoid using the | ||||
| 6105 | ** SQLITE_INNOCUOUS flag for application-defined functions unless the | ||||
| 6106 | ** function has been carefully audited and found to be free of potentially | ||||
| 6107 | ** security-adverse side-effects and information-leaks. | ||||
| 6108 | ** </dd> | ||||
| 6109 | ** | ||||
| 6110 | ** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd> | ||||
| 6111 | ** The SQLITE_SUBTYPE flag indicates to SQLite that a function might call | ||||
| 6112 | ** [sqlite3_value_subtype()] to inspect the sub-types of its arguments. | ||||
| 6113 | ** This flag instructs SQLite to omit some corner-case optimizations that | ||||
| 6114 | ** might disrupt the operation of the [sqlite3_value_subtype()] function, | ||||
| 6115 | ** causing it to return zero rather than the correct subtype(). | ||||
| 6116 | ** All SQL functions that invoke [sqlite3_value_subtype()] should have this | ||||
| 6117 | ** property. If the SQLITE_SUBTYPE property is omitted, then the return | ||||
| 6118 | ** value from [sqlite3_value_subtype()] might sometimes be zero even though | ||||
| 6119 | ** a non-zero subtype was specified by the function argument expression. | ||||
| 6120 | ** | ||||
| 6121 | ** [[SQLITE_RESULT_SUBTYPE]] <dt>SQLITE_RESULT_SUBTYPE</dt><dd> | ||||
| 6122 | ** The SQLITE_RESULT_SUBTYPE flag indicates to SQLite that a function might call | ||||
| 6123 | ** [sqlite3_result_subtype()] to cause a sub-type to be associated with its | ||||
| 6124 | ** result. | ||||
| 6125 | ** Every function that invokes [sqlite3_result_subtype()] should have this | ||||
| 6126 | ** property. If it does not, then the call to [sqlite3_result_subtype()] | ||||
| 6127 | ** might become a no-op if the function is used as term in an | ||||
| 6128 | ** [expression index]. On the other hand, SQL functions that never invoke | ||||
| 6129 | ** [sqlite3_result_subtype()] should avoid setting this property, as the | ||||
| 6130 | ** purpose of this property is to disable certain optimizations that are | ||||
| 6131 | ** incompatible with subtypes. | ||||
| 6132 | ** | ||||
| 6133 | ** [[SQLITE_SELFORDER1]] <dt>SQLITE_SELFORDER1</dt><dd> | ||||
| 6134 | ** The SQLITE_SELFORDER1 flag indicates that the function is an aggregate | ||||
| 6135 | ** that internally orders the values provided to the first argument. The | ||||
| 6136 | ** ordered-set aggregate SQL notation with a single ORDER BY term can be | ||||
| 6137 | ** used to invoke this function. If the ordered-set aggregate notation is | ||||
| 6138 | ** used on a function that lacks this flag, then an error is raised. Note | ||||
| 6139 | ** that the ordered-set aggregate syntax is only available if SQLite is | ||||
| 6140 | ** built using the -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES compile-time option. | ||||
| 6141 | ** </dd> | ||||
| 6142 | ** </dl> | ||||
| 6143 | */ | ||||
| 6144 | #define SQLITE_DETERMINISTIC0x000000800 0x000000800 | ||||
| 6145 | #define SQLITE_DIRECTONLY0x000080000 0x000080000 | ||||
| 6146 | #define SQLITE_SUBTYPE0x000100000 0x000100000 | ||||
| 6147 | #define SQLITE_INNOCUOUS0x000200000 0x000200000 | ||||
| 6148 | #define SQLITE_RESULT_SUBTYPE0x001000000 0x001000000 | ||||
| 6149 | #define SQLITE_SELFORDER10x002000000 0x002000000 | ||||
| 6150 | |||||
| 6151 | /* | ||||
| 6152 | ** CAPI3REF: Deprecated Functions | ||||
| 6153 | ** DEPRECATED | ||||
| 6154 | ** | ||||
| 6155 | ** These functions are [deprecated]. In order to maintain | ||||
| 6156 | ** backwards compatibility with older code, these functions continue | ||||
| 6157 | ** to be supported. However, new applications should avoid | ||||
| 6158 | ** the use of these functions. To encourage programmers to avoid | ||||
| 6159 | ** these functions, we will not explain what they do. | ||||
| 6160 | */ | ||||
| 6161 | #ifndef SQLITE_OMIT_DEPRECATED1 | ||||
| 6162 | SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); | ||||
| 6163 | SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); | ||||
| 6164 | SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); | ||||
| 6165 | SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); | ||||
| 6166 | SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); | ||||
| 6167 | SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), | ||||
| 6168 | void*,sqlite3_int64); | ||||
| 6169 | #endif | ||||
| 6170 | |||||
| 6171 | /* | ||||
| 6172 | ** CAPI3REF: Obtaining SQL Values | ||||
| 6173 | ** METHOD: sqlite3_value | ||||
| 6174 | ** | ||||
| 6175 | ** <b>Summary:</b> | ||||
| 6176 | ** <blockquote><table border=0 cellpadding=0 cellspacing=0> | ||||
| 6177 | ** <tr><td><b>sqlite3_value_blob</b><td>→<td>BLOB value | ||||
| 6178 | ** <tr><td><b>sqlite3_value_double</b><td>→<td>REAL value | ||||
| 6179 | ** <tr><td><b>sqlite3_value_int</b><td>→<td>32-bit INTEGER value | ||||
| 6180 | ** <tr><td><b>sqlite3_value_int64</b><td>→<td>64-bit INTEGER value | ||||
| 6181 | ** <tr><td><b>sqlite3_value_pointer</b><td>→<td>Pointer value | ||||
| 6182 | ** <tr><td><b>sqlite3_value_text</b><td>→<td>UTF-8 TEXT value | ||||
| 6183 | ** <tr><td><b>sqlite3_value_text16</b><td>→<td>UTF-16 TEXT value in | ||||
| 6184 | ** the native byteorder | ||||
| 6185 | ** <tr><td><b>sqlite3_value_text16be</b><td>→<td>UTF-16be TEXT value | ||||
| 6186 | ** <tr><td><b>sqlite3_value_text16le</b><td>→<td>UTF-16le TEXT value | ||||
| 6187 | ** <tr><td> <td> <td> | ||||
| 6188 | ** <tr><td><b>sqlite3_value_bytes</b><td>→<td>Size of a BLOB | ||||
| 6189 | ** or a UTF-8 TEXT in bytes | ||||
| 6190 | ** <tr><td><b>sqlite3_value_bytes16 </b> | ||||
| 6191 | ** <td>→ <td>Size of UTF-16 | ||||
| 6192 | ** TEXT in bytes | ||||
| 6193 | ** <tr><td><b>sqlite3_value_type</b><td>→<td>Default | ||||
| 6194 | ** datatype of the value | ||||
| 6195 | ** <tr><td><b>sqlite3_value_numeric_type </b> | ||||
| 6196 | ** <td>→ <td>Best numeric datatype of the value | ||||
| 6197 | ** <tr><td><b>sqlite3_value_nochange </b> | ||||
| 6198 | ** <td>→ <td>True if the column is unchanged in an UPDATE | ||||
| 6199 | ** against a virtual table. | ||||
| 6200 | ** <tr><td><b>sqlite3_value_frombind </b> | ||||
| 6201 | ** <td>→ <td>True if value originated from a [bound parameter] | ||||
| 6202 | ** </table></blockquote> | ||||
| 6203 | ** | ||||
| 6204 | ** <b>Details:</b> | ||||
| 6205 | ** | ||||
| 6206 | ** These routines extract type, size, and content information from | ||||
| 6207 | ** [protected sqlite3_value] objects. Protected sqlite3_value objects | ||||
| 6208 | ** are used to pass parameter information into the functions that | ||||
| 6209 | ** implement [application-defined SQL functions] and [virtual tables]. | ||||
| 6210 | ** | ||||
| 6211 | ** These routines work only with [protected sqlite3_value] objects. | ||||
| 6212 | ** Any attempt to use these routines on an [unprotected sqlite3_value] | ||||
| 6213 | ** is not threadsafe. | ||||
| 6214 | ** | ||||
| 6215 | ** ^These routines work just like the corresponding [column access functions] | ||||
| 6216 | ** except that these routines take a single [protected sqlite3_value] object | ||||
| 6217 | ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. | ||||
| 6218 | ** | ||||
| 6219 | ** ^The sqlite3_value_text16() interface extracts a UTF-16 string | ||||
| 6220 | ** in the native byte-order of the host machine. ^The | ||||
| 6221 | ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces | ||||
| 6222 | ** extract UTF-16 strings as big-endian and little-endian respectively. | ||||
| 6223 | ** | ||||
| 6224 | ** ^If [sqlite3_value] object V was initialized | ||||
| 6225 | ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)] | ||||
| 6226 | ** and if X and Y are strings that compare equal according to strcmp(X,Y), | ||||
| 6227 | ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise, | ||||
| 6228 | ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() | ||||
| 6229 | ** routine is part of the [pointer passing interface] added for SQLite 3.20.0. | ||||
| 6230 | ** | ||||
| 6231 | ** ^(The sqlite3_value_type(V) interface returns the | ||||
| 6232 | ** [SQLITE_INTEGER | datatype code] for the initial datatype of the | ||||
| 6233 | ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER], | ||||
| 6234 | ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^ | ||||
| 6235 | ** Other interfaces might change the datatype for an sqlite3_value object. | ||||
| 6236 | ** For example, if the datatype is initially SQLITE_INTEGER and | ||||
| 6237 | ** sqlite3_value_text(V) is called to extract a text value for that | ||||
| 6238 | ** integer, then subsequent calls to sqlite3_value_type(V) might return | ||||
| 6239 | ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion | ||||
| 6240 | ** occurs is undefined and may change from one release of SQLite to the next. | ||||
| 6241 | ** | ||||
| 6242 | ** ^(The sqlite3_value_numeric_type() interface attempts to apply | ||||
| 6243 | ** numeric affinity to the value. This means that an attempt is | ||||
| 6244 | ** made to convert the value to an integer or floating point. If | ||||
| 6245 | ** such a conversion is possible without loss of information (in other | ||||
| 6246 | ** words, if the value is a string that looks like a number) | ||||
| 6247 | ** then the conversion is performed. Otherwise no conversion occurs. | ||||
| 6248 | ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ | ||||
| 6249 | ** | ||||
| 6250 | ** ^Within the [xUpdate] method of a [virtual table], the | ||||
| 6251 | ** sqlite3_value_nochange(X) interface returns true if and only if | ||||
| 6252 | ** the column corresponding to X is unchanged by the UPDATE operation | ||||
| 6253 | ** that the xUpdate method call was invoked to implement and if | ||||
| 6254 | ** and the prior [xColumn] method call that was invoked to extracted | ||||
| 6255 | ** the value for that column returned without setting a result (probably | ||||
| 6256 | ** because it queried [sqlite3_vtab_nochange()] and found that the column | ||||
| 6257 | ** was unchanging). ^Within an [xUpdate] method, any value for which | ||||
| 6258 | ** sqlite3_value_nochange(X) is true will in all other respects appear | ||||
| 6259 | ** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other | ||||
| 6260 | ** than within an [xUpdate] method call for an UPDATE statement, then | ||||
| 6261 | ** the return value is arbitrary and meaningless. | ||||
| 6262 | ** | ||||
| 6263 | ** ^The sqlite3_value_frombind(X) interface returns non-zero if the | ||||
| 6264 | ** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()] | ||||
| 6265 | ** interfaces. ^If X comes from an SQL literal value, or a table column, | ||||
| 6266 | ** or an expression, then sqlite3_value_frombind(X) returns zero. | ||||
| 6267 | ** | ||||
| 6268 | ** Please pay particular attention to the fact that the pointer returned | ||||
| 6269 | ** from [sqlite3_value_blob()], [sqlite3_value_text()], or | ||||
| 6270 | ** [sqlite3_value_text16()] can be invalidated by a subsequent call to | ||||
| 6271 | ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], | ||||
| 6272 | ** or [sqlite3_value_text16()]. | ||||
| 6273 | ** | ||||
| 6274 | ** These routines must be called from the same thread as | ||||
| 6275 | ** the SQL function that supplied the [sqlite3_value*] parameters. | ||||
| 6276 | ** | ||||
| 6277 | ** As long as the input parameter is correct, these routines can only | ||||
| 6278 | ** fail if an out-of-memory error occurs during a format conversion. | ||||
| 6279 | ** Only the following subset of interfaces are subject to out-of-memory | ||||
| 6280 | ** errors: | ||||
| 6281 | ** | ||||
| 6282 | ** <ul> | ||||
| 6283 | ** <li> sqlite3_value_blob() | ||||
| 6284 | ** <li> sqlite3_value_text() | ||||
| 6285 | ** <li> sqlite3_value_text16() | ||||
| 6286 | ** <li> sqlite3_value_text16le() | ||||
| 6287 | ** <li> sqlite3_value_text16be() | ||||
| 6288 | ** <li> sqlite3_value_bytes() | ||||
| 6289 | ** <li> sqlite3_value_bytes16() | ||||
| 6290 | ** </ul> | ||||
| 6291 | ** | ||||
| 6292 | ** If an out-of-memory error occurs, then the return value from these | ||||
| 6293 | ** routines is the same as if the column had contained an SQL NULL value. | ||||
| 6294 | ** Valid SQL NULL returns can be distinguished from out-of-memory errors | ||||
| 6295 | ** by invoking the [sqlite3_errcode()] immediately after the suspect | ||||
| 6296 | ** return value is obtained and before any | ||||
| 6297 | ** other SQLite interface is called on the same [database connection]. | ||||
| 6298 | */ | ||||
| 6299 | SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); | ||||
| 6300 | SQLITE_API double sqlite3_value_double(sqlite3_value*); | ||||
| 6301 | SQLITE_API int sqlite3_value_int(sqlite3_value*); | ||||
| 6302 | SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); | ||||
| 6303 | SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*); | ||||
| 6304 | SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); | ||||
| 6305 | SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); | ||||
| 6306 | SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); | ||||
| 6307 | SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); | ||||
| 6308 | SQLITE_API int sqlite3_value_bytes(sqlite3_value*); | ||||
| 6309 | SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); | ||||
| 6310 | SQLITE_API int sqlite3_value_type(sqlite3_value*); | ||||
| 6311 | SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); | ||||
| 6312 | SQLITE_API int sqlite3_value_nochange(sqlite3_value*); | ||||
| 6313 | SQLITE_API int sqlite3_value_frombind(sqlite3_value*); | ||||
| 6314 | |||||
| 6315 | /* | ||||
| 6316 | ** CAPI3REF: Report the internal text encoding state of an sqlite3_value object | ||||
| 6317 | ** METHOD: sqlite3_value | ||||
| 6318 | ** | ||||
| 6319 | ** ^(The sqlite3_value_encoding(X) interface returns one of [SQLITE_UTF8], | ||||
| 6320 | ** [SQLITE_UTF16BE], or [SQLITE_UTF16LE] according to the current text encoding | ||||
| 6321 | ** of the value X, assuming that X has type TEXT.)^ If sqlite3_value_type(X) | ||||
| 6322 | ** returns something other than SQLITE_TEXT, then the return value from | ||||
| 6323 | ** sqlite3_value_encoding(X) is meaningless. ^Calls to | ||||
| 6324 | ** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], [sqlite3_value_text16be(X)], | ||||
| 6325 | ** [sqlite3_value_text16le(X)], [sqlite3_value_bytes(X)], or | ||||
| 6326 | ** [sqlite3_value_bytes16(X)] might change the encoding of the value X and | ||||
| 6327 | ** thus change the return from subsequent calls to sqlite3_value_encoding(X). | ||||
| 6328 | ** | ||||
| 6329 | ** This routine is intended for used by applications that test and validate | ||||
| 6330 | ** the SQLite implementation. This routine is inquiring about the opaque | ||||
| 6331 | ** internal state of an [sqlite3_value] object. Ordinary applications should | ||||
| 6332 | ** not need to know what the internal state of an sqlite3_value object is and | ||||
| 6333 | ** hence should not need to use this interface. | ||||
| 6334 | */ | ||||
| 6335 | SQLITE_API int sqlite3_value_encoding(sqlite3_value*); | ||||
| 6336 | |||||
| 6337 | /* | ||||
| 6338 | ** CAPI3REF: Finding The Subtype Of SQL Values | ||||
| 6339 | ** METHOD: sqlite3_value | ||||
| 6340 | ** | ||||
| 6341 | ** The sqlite3_value_subtype(V) function returns the subtype for | ||||
| 6342 | ** an [application-defined SQL function] argument V. The subtype | ||||
| 6343 | ** information can be used to pass a limited amount of context from | ||||
| 6344 | ** one SQL function to another. Use the [sqlite3_result_subtype()] | ||||
| 6345 | ** routine to set the subtype for the return value of an SQL function. | ||||
| 6346 | ** | ||||
| 6347 | ** Every [application-defined SQL function] that invokes this interface | ||||
| 6348 | ** should include the [SQLITE_SUBTYPE] property in the text | ||||
| 6349 | ** encoding argument when the function is [sqlite3_create_function|registered]. | ||||
| 6350 | ** If the [SQLITE_SUBTYPE] property is omitted, then sqlite3_value_subtype() | ||||
| 6351 | ** might return zero instead of the upstream subtype in some corner cases. | ||||
| 6352 | */ | ||||
| 6353 | SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); | ||||
| 6354 | |||||
| 6355 | /* | ||||
| 6356 | ** CAPI3REF: Copy And Free SQL Values | ||||
| 6357 | ** METHOD: sqlite3_value | ||||
| 6358 | ** | ||||
| 6359 | ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] | ||||
| 6360 | ** object V and returns a pointer to that copy. ^The [sqlite3_value] returned | ||||
| 6361 | ** is a [protected sqlite3_value] object even if the input is not. | ||||
| 6362 | ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a | ||||
| 6363 | ** memory allocation fails. ^If V is a [pointer value], then the result | ||||
| 6364 | ** of sqlite3_value_dup(V) is a NULL value. | ||||
| 6365 | ** | ||||
| 6366 | ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object | ||||
| 6367 | ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer | ||||
| 6368 | ** then sqlite3_value_free(V) is a harmless no-op. | ||||
| 6369 | */ | ||||
| 6370 | SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); | ||||
| 6371 | SQLITE_API void sqlite3_value_free(sqlite3_value*); | ||||
| 6372 | |||||
| 6373 | /* | ||||
| 6374 | ** CAPI3REF: Obtain Aggregate Function Context | ||||
| 6375 | ** METHOD: sqlite3_context | ||||
| 6376 | ** | ||||
| 6377 | ** Implementations of aggregate SQL functions use this | ||||
| 6378 | ** routine to allocate memory for storing their state. | ||||
| 6379 | ** | ||||
| 6380 | ** ^The first time the sqlite3_aggregate_context(C,N) routine is called | ||||
| 6381 | ** for a particular aggregate function, SQLite allocates | ||||
| 6382 | ** N bytes of memory, zeroes out that memory, and returns a pointer | ||||
| 6383 | ** to the new memory. ^On second and subsequent calls to | ||||
| 6384 | ** sqlite3_aggregate_context() for the same aggregate function instance, | ||||
| 6385 | ** the same buffer is returned. Sqlite3_aggregate_context() is normally | ||||
| 6386 | ** called once for each invocation of the xStep callback and then one | ||||
| 6387 | ** last time when the xFinal callback is invoked. ^(When no rows match | ||||
| 6388 | ** an aggregate query, the xStep() callback of the aggregate function | ||||
| 6389 | ** implementation is never called and xFinal() is called exactly once. | ||||
| 6390 | ** In those cases, sqlite3_aggregate_context() might be called for the | ||||
| 6391 | ** first time from within xFinal().)^ | ||||
| 6392 | ** | ||||
| 6393 | ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer | ||||
| 6394 | ** when first called if N is less than or equal to zero or if a memory | ||||
| 6395 | ** allocation error occurs. | ||||
| 6396 | ** | ||||
| 6397 | ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is | ||||
| 6398 | ** determined by the N parameter on the first successful call. Changing the | ||||
| 6399 | ** value of N in any subsequent call to sqlite3_aggregate_context() within | ||||
| 6400 | ** the same aggregate function instance will not resize the memory | ||||
| 6401 | ** allocation.)^ Within the xFinal callback, it is customary to set | ||||
| 6402 | ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no | ||||
| 6403 | ** pointless memory allocations occur. | ||||
| 6404 | ** | ||||
| 6405 | ** ^SQLite automatically frees the memory allocated by | ||||
| 6406 | ** sqlite3_aggregate_context() when the aggregate query concludes. | ||||
| 6407 | ** | ||||
| 6408 | ** The first parameter must be a copy of the | ||||
| 6409 | ** [sqlite3_context | SQL function context] that is the first parameter | ||||
| 6410 | ** to the xStep or xFinal callback routine that implements the aggregate | ||||
| 6411 | ** function. | ||||
| 6412 | ** | ||||
| 6413 | ** This routine must be called from the same thread in which | ||||
| 6414 | ** the aggregate SQL function is running. | ||||
| 6415 | */ | ||||
| 6416 | SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); | ||||
| 6417 | |||||
| 6418 | /* | ||||
| 6419 | ** CAPI3REF: User Data For Functions | ||||
| 6420 | ** METHOD: sqlite3_context | ||||
| 6421 | ** | ||||
| 6422 | ** ^The sqlite3_user_data() interface returns a copy of | ||||
| 6423 | ** the pointer that was the pUserData parameter (the 5th parameter) | ||||
| 6424 | ** of the [sqlite3_create_function()] | ||||
| 6425 | ** and [sqlite3_create_function16()] routines that originally | ||||
| 6426 | ** registered the application defined function. | ||||
| 6427 | ** | ||||
| 6428 | ** This routine must be called from the same thread in which | ||||
| 6429 | ** the application-defined function is running. | ||||
| 6430 | */ | ||||
| 6431 | SQLITE_API void *sqlite3_user_data(sqlite3_context*); | ||||
| 6432 | |||||
| 6433 | /* | ||||
| 6434 | ** CAPI3REF: Database Connection For Functions | ||||
| 6435 | ** METHOD: sqlite3_context | ||||
| 6436 | ** | ||||
| 6437 | ** ^The sqlite3_context_db_handle() interface returns a copy of | ||||
| 6438 | ** the pointer to the [database connection] (the 1st parameter) | ||||
| 6439 | ** of the [sqlite3_create_function()] | ||||
| 6440 | ** and [sqlite3_create_function16()] routines that originally | ||||
| 6441 | ** registered the application defined function. | ||||
| 6442 | */ | ||||
| 6443 | SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); | ||||
| 6444 | |||||
| 6445 | /* | ||||
| 6446 | ** CAPI3REF: Function Auxiliary Data | ||||
| 6447 | ** METHOD: sqlite3_context | ||||
| 6448 | ** | ||||
| 6449 | ** These functions may be used by (non-aggregate) SQL functions to | ||||
| 6450 | ** associate auxiliary data with argument values. If the same argument | ||||
| 6451 | ** value is passed to multiple invocations of the same SQL function during | ||||
| 6452 | ** query execution, under some circumstances the associated auxiliary data | ||||
| 6453 | ** might be preserved. An example of where this might be useful is in a | ||||
| 6454 | ** regular-expression matching function. The compiled version of the regular | ||||
| 6455 | ** expression can be stored as auxiliary data associated with the pattern string. | ||||
| 6456 | ** Then as long as the pattern string remains the same, | ||||
| 6457 | ** the compiled regular expression can be reused on multiple | ||||
| 6458 | ** invocations of the same function. | ||||
| 6459 | ** | ||||
| 6460 | ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data | ||||
| 6461 | ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument | ||||
| 6462 | ** value to the application-defined function. ^N is zero for the left-most | ||||
| 6463 | ** function argument. ^If there is no auxiliary data | ||||
| 6464 | ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface | ||||
| 6465 | ** returns a NULL pointer. | ||||
| 6466 | ** | ||||
| 6467 | ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the | ||||
| 6468 | ** N-th argument of the application-defined function. ^Subsequent | ||||
| 6469 | ** calls to sqlite3_get_auxdata(C,N) return P from the most recent | ||||
| 6470 | ** sqlite3_set_auxdata(C,N,P,X) call if the auxiliary data is still valid or | ||||
| 6471 | ** NULL if the auxiliary data has been discarded. | ||||
| 6472 | ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, | ||||
| 6473 | ** SQLite will invoke the destructor function X with parameter P exactly | ||||
| 6474 | ** once, when the auxiliary data is discarded. | ||||
| 6475 | ** SQLite is free to discard the auxiliary data at any time, including: <ul> | ||||
| 6476 | ** <li> ^(when the corresponding function parameter changes)^, or | ||||
| 6477 | ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the | ||||
| 6478 | ** SQL statement)^, or | ||||
| 6479 | ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same | ||||
| 6480 | ** parameter)^, or | ||||
| 6481 | ** <li> ^(during the original sqlite3_set_auxdata() call when a memory | ||||
| 6482 | ** allocation error occurs.)^ | ||||
| 6483 | ** <li> ^(during the original sqlite3_set_auxdata() call if the function | ||||
| 6484 | ** is evaluated during query planning instead of during query execution, | ||||
| 6485 | ** as sometimes happens with [SQLITE_ENABLE_STAT4].)^ </ul> | ||||
| 6486 | ** | ||||
| 6487 | ** Note the last two bullets in particular. The destructor X in | ||||
| 6488 | ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the | ||||
| 6489 | ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() | ||||
| 6490 | ** should be called near the end of the function implementation and the | ||||
| 6491 | ** function implementation should not make any use of P after | ||||
| 6492 | ** sqlite3_set_auxdata() has been called. Furthermore, a call to | ||||
| 6493 | ** sqlite3_get_auxdata() that occurs immediately after a corresponding call | ||||
| 6494 | ** to sqlite3_set_auxdata() might still return NULL if an out-of-memory | ||||
| 6495 | ** condition occurred during the sqlite3_set_auxdata() call or if the | ||||
| 6496 | ** function is being evaluated during query planning rather than during | ||||
| 6497 | ** query execution. | ||||
| 6498 | ** | ||||
| 6499 | ** ^(In practice, auxiliary data is preserved between function calls for | ||||
| 6500 | ** function parameters that are compile-time constants, including literal | ||||
| 6501 | ** values and [parameters] and expressions composed from the same.)^ | ||||
| 6502 | ** | ||||
| 6503 | ** The value of the N parameter to these interfaces should be non-negative. | ||||
| 6504 | ** Future enhancements may make use of negative N values to define new | ||||
| 6505 | ** kinds of function caching behavior. | ||||
| 6506 | ** | ||||
| 6507 | ** These routines must be called from the same thread in which | ||||
| 6508 | ** the SQL function is running. | ||||
| 6509 | ** | ||||
| 6510 | ** See also: [sqlite3_get_clientdata()] and [sqlite3_set_clientdata()]. | ||||
| 6511 | */ | ||||
| 6512 | SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); | ||||
| 6513 | SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); | ||||
| 6514 | |||||
| 6515 | /* | ||||
| 6516 | ** CAPI3REF: Database Connection Client Data | ||||
| 6517 | ** METHOD: sqlite3 | ||||
| 6518 | ** | ||||
| 6519 | ** These functions are used to associate one or more named pointers | ||||
| 6520 | ** with a [database connection]. | ||||
| 6521 | ** A call to sqlite3_set_clientdata(D,N,P,X) causes the pointer P | ||||
| 6522 | ** to be attached to [database connection] D using name N. Subsequent | ||||
| 6523 | ** calls to sqlite3_get_clientdata(D,N) will return a copy of pointer P | ||||
| 6524 | ** or a NULL pointer if there were no prior calls to | ||||
| 6525 | ** sqlite3_set_clientdata() with the same values of D and N. | ||||
| 6526 | ** Names are compared using strcmp() and are thus case sensitive. | ||||
| 6527 | ** | ||||
| 6528 | ** If P and X are both non-NULL, then the destructor X is invoked with | ||||
| 6529 | ** argument P on the first of the following occurrences: | ||||
| 6530 | ** <ul> | ||||
| 6531 | ** <li> An out-of-memory error occurs during the call to | ||||
| 6532 | ** sqlite3_set_clientdata() which attempts to register pointer P. | ||||
| 6533 | ** <li> A subsequent call to sqlite3_set_clientdata(D,N,P,X) is made | ||||
| 6534 | ** with the same D and N parameters. | ||||
| 6535 | ** <li> The database connection closes. SQLite does not make any guarantees | ||||
| 6536 | ** about the order in which destructors are called, only that all | ||||
| 6537 | ** destructors will be called exactly once at some point during the | ||||
| 6538 | ** database connection closing process. | ||||
| 6539 | ** </ul> | ||||
| 6540 | ** | ||||
| 6541 | ** SQLite does not do anything with client data other than invoke | ||||
| 6542 | ** destructors on the client data at the appropriate time. The intended | ||||
| 6543 | ** use for client data is to provide a mechanism for wrapper libraries | ||||
| 6544 | ** to store additional information about an SQLite database connection. | ||||
| 6545 | ** | ||||
| 6546 | ** There is no limit (other than available memory) on the number of different | ||||
| 6547 | ** client data pointers (with different names) that can be attached to a | ||||
| 6548 | ** single database connection. However, the implementation is optimized | ||||
| 6549 | ** for the case of having only one or two different client data names. | ||||
| 6550 | ** Applications and wrapper libraries are discouraged from using more than | ||||
| 6551 | ** one client data name each. | ||||
| 6552 | ** | ||||
| 6553 | ** There is no way to enumerate the client data pointers | ||||
| 6554 | ** associated with a database connection. The N parameter can be thought | ||||
| 6555 | ** of as a secret key such that only code that knows the secret key is able | ||||
| 6556 | ** to access the associated data. | ||||
| 6557 | ** | ||||
| 6558 | ** Security Warning: These interfaces should not be exposed in scripting | ||||
| 6559 | ** languages or in other circumstances where it might be possible for an | ||||
| 6560 | ** attacker to invoke them. Any agent that can invoke these interfaces | ||||
| 6561 | ** can probably also take control of the process. | ||||
| 6562 | ** | ||||
| 6563 | ** Database connection client data is only available for SQLite | ||||
| 6564 | ** version 3.44.0 ([dateof:3.44.0]) and later. | ||||
| 6565 | ** | ||||
| 6566 | ** See also: [sqlite3_set_auxdata()] and [sqlite3_get_auxdata()]. | ||||
| 6567 | */ | ||||
| 6568 | SQLITE_API void *sqlite3_get_clientdata(sqlite3*,const char*); | ||||
| 6569 | SQLITE_API int sqlite3_set_clientdata(sqlite3*, const char*, void*, void(*)(void*)); | ||||
| 6570 | |||||
| 6571 | /* | ||||
| 6572 | ** CAPI3REF: Constants Defining Special Destructor Behavior | ||||
| 6573 | ** | ||||
| 6574 | ** These are special values for the destructor that is passed in as the | ||||
| 6575 | ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor | ||||
| 6576 | ** argument is SQLITE_STATIC, it means that the content pointer is constant | ||||
| 6577 | ** and will never change. It does not need to be destroyed. ^The | ||||
| 6578 | ** SQLITE_TRANSIENT value means that the content will likely change in | ||||
| 6579 | ** the near future and that SQLite should make its own private copy of | ||||
| 6580 | ** the content before returning. | ||||
| 6581 | ** | ||||
| 6582 | ** The typedef is necessary to work around problems in certain | ||||
| 6583 | ** C++ compilers. | ||||
| 6584 | */ | ||||
| 6585 | typedef void (*sqlite3_destructor_type)(void*); | ||||
| 6586 | #define SQLITE_STATIC((sqlite3_destructor_type)0) ((sqlite3_destructor_type)0) | ||||
| 6587 | #define SQLITE_TRANSIENT((sqlite3_destructor_type)-1) ((sqlite3_destructor_type)-1) | ||||
| 6588 | |||||
| 6589 | /* | ||||
| 6590 | ** CAPI3REF: Setting The Result Of An SQL Function | ||||
| 6591 | ** METHOD: sqlite3_context | ||||
| 6592 | ** | ||||
| 6593 | ** These routines are used by the xFunc or xFinal callbacks that | ||||
| 6594 | ** implement SQL functions and aggregates. See | ||||
| 6595 | ** [sqlite3_create_function()] and [sqlite3_create_function16()] | ||||
| 6596 | ** for additional information. | ||||
| 6597 | ** | ||||
| 6598 | ** These functions work very much like the [parameter binding] family of | ||||
| 6599 | ** functions used to bind values to host parameters in prepared statements. | ||||
| 6600 | ** Refer to the [SQL parameter] documentation for additional information. | ||||
| 6601 | ** | ||||
| 6602 | ** ^The sqlite3_result_blob() interface sets the result from | ||||
| 6603 | ** an application-defined function to be the BLOB whose content is pointed | ||||
| 6604 | ** to by the second parameter and which is N bytes long where N is the | ||||
| 6605 | ** third parameter. | ||||
| 6606 | ** | ||||
| 6607 | ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) | ||||
| 6608 | ** interfaces set the result of the application-defined function to be | ||||
| 6609 | ** a BLOB containing all zero bytes and N bytes in size. | ||||
| 6610 | ** | ||||
| 6611 | ** ^The sqlite3_result_double() interface sets the result from | ||||
| 6612 | ** an application-defined function to be a floating point value specified | ||||
| 6613 | ** by its 2nd argument. | ||||
| 6614 | ** | ||||
| 6615 | ** ^The sqlite3_result_error() and sqlite3_result_error16() functions | ||||
| 6616 | ** cause the implemented SQL function to throw an exception. | ||||
| 6617 | ** ^SQLite uses the string pointed to by the | ||||
| 6618 | ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() | ||||
| 6619 | ** as the text of an error message. ^SQLite interprets the error | ||||
| 6620 | ** message string from sqlite3_result_error() as UTF-8. ^SQLite | ||||
| 6621 | ** interprets the string from sqlite3_result_error16() as UTF-16 using | ||||
| 6622 | ** the same [byte-order determination rules] as [sqlite3_bind_text16()]. | ||||
| 6623 | ** ^If the third parameter to sqlite3_result_error() | ||||
| 6624 | ** or sqlite3_result_error16() is negative then SQLite takes as the error | ||||
| 6625 | ** message all text up through the first zero character. | ||||
| 6626 | ** ^If the third parameter to sqlite3_result_error() or | ||||
| 6627 | ** sqlite3_result_error16() is non-negative then SQLite takes that many | ||||
| 6628 | ** bytes (not characters) from the 2nd parameter as the error message. | ||||
| 6629 | ** ^The sqlite3_result_error() and sqlite3_result_error16() | ||||
| 6630 | ** routines make a private copy of the error message text before | ||||
| 6631 | ** they return. Hence, the calling function can deallocate or | ||||
| 6632 | ** modify the text after they return without harm. | ||||
| 6633 | ** ^The sqlite3_result_error_code() function changes the error code | ||||
| 6634 | ** returned by SQLite as a result of an error in a function. ^By default, | ||||
| 6635 | ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() | ||||
| 6636 | ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. | ||||
| 6637 | ** | ||||
| 6638 | ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an | ||||
| 6639 | ** error indicating that a string or BLOB is too long to represent. | ||||
| 6640 | ** | ||||
| 6641 | ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an | ||||
| 6642 | ** error indicating that a memory allocation failed. | ||||
| 6643 | ** | ||||
| 6644 | ** ^The sqlite3_result_int() interface sets the return value | ||||
| 6645 | ** of the application-defined function to be the 32-bit signed integer | ||||
| 6646 | ** value given in the 2nd argument. | ||||
| 6647 | ** ^The sqlite3_result_int64() interface sets the return value | ||||
| 6648 | ** of the application-defined function to be the 64-bit signed integer | ||||
| 6649 | ** value given in the 2nd argument. | ||||
| 6650 | ** | ||||
| 6651 | ** ^The sqlite3_result_null() interface sets the return value | ||||
| 6652 | ** of the application-defined function to be NULL. | ||||
| 6653 | ** | ||||
| 6654 | ** ^The sqlite3_result_text(), sqlite3_result_text16(), | ||||
| 6655 | ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces | ||||
| 6656 | ** set the return value of the application-defined function to be | ||||
| 6657 | ** a text string which is represented as UTF-8, UTF-16 native byte order, | ||||
| 6658 | ** UTF-16 little endian, or UTF-16 big endian, respectively. | ||||
| 6659 | ** ^The sqlite3_result_text64() interface sets the return value of an | ||||
| 6660 | ** application-defined function to be a text string in an encoding | ||||
| 6661 | ** specified by the fifth (and last) parameter, which must be one | ||||
| 6662 | ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. | ||||
| 6663 | ** ^SQLite takes the text result from the application from | ||||
| 6664 | ** the 2nd parameter of the sqlite3_result_text* interfaces. | ||||
| 6665 | ** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces | ||||
| 6666 | ** other than sqlite3_result_text64() is negative, then SQLite computes | ||||
| 6667 | ** the string length itself by searching the 2nd parameter for the first | ||||
| 6668 | ** zero character. | ||||
| 6669 | ** ^If the 3rd parameter to the sqlite3_result_text* interfaces | ||||
| 6670 | ** is non-negative, then as many bytes (not characters) of the text | ||||
| 6671 | ** pointed to by the 2nd parameter are taken as the application-defined | ||||
| 6672 | ** function result. If the 3rd parameter is non-negative, then it | ||||
| 6673 | ** must be the byte offset into the string where the NUL terminator would | ||||
| 6674 | ** appear if the string were NUL terminated. If any NUL characters occur | ||||
| 6675 | ** in the string at a byte offset that is less than the value of the 3rd | ||||
| 6676 | ** parameter, then the resulting string will contain embedded NULs and the | ||||
| 6677 | ** result of expressions operating on strings with embedded NULs is undefined. | ||||
| 6678 | ** ^If the 4th parameter to the sqlite3_result_text* interfaces | ||||
| 6679 | ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that | ||||
| 6680 | ** function as the destructor on the text or BLOB result when it has | ||||
| 6681 | ** finished using that result. | ||||
| 6682 | ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to | ||||
| 6683 | ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite | ||||
| 6684 | ** assumes that the text or BLOB result is in constant space and does not | ||||
| 6685 | ** copy the content of the parameter nor call a destructor on the content | ||||
| 6686 | ** when it has finished using that result. | ||||
| 6687 | ** ^If the 4th parameter to the sqlite3_result_text* interfaces | ||||
| 6688 | ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT | ||||
| 6689 | ** then SQLite makes a copy of the result into space obtained | ||||
| 6690 | ** from [sqlite3_malloc()] before it returns. | ||||
| 6691 | ** | ||||
| 6692 | ** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and | ||||
| 6693 | ** sqlite3_result_text16be() routines, and for sqlite3_result_text64() | ||||
| 6694 | ** when the encoding is not UTF8, if the input UTF16 begins with a | ||||
| 6695 | ** byte-order mark (BOM, U+FEFF) then the BOM is removed from the | ||||
| 6696 | ** string and the rest of the string is interpreted according to the | ||||
| 6697 | ** byte-order specified by the BOM. ^The byte-order specified by | ||||
| 6698 | ** the BOM at the beginning of the text overrides the byte-order | ||||
| 6699 | ** specified by the interface procedure. ^So, for example, if | ||||
| 6700 | ** sqlite3_result_text16le() is invoked with text that begins | ||||
| 6701 | ** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the | ||||
| 6702 | ** first two bytes of input are skipped and the remaining input | ||||
| 6703 | ** is interpreted as UTF16BE text. | ||||
| 6704 | ** | ||||
| 6705 | ** ^For UTF16 input text to the sqlite3_result_text16(), | ||||
| 6706 | ** sqlite3_result_text16be(), sqlite3_result_text16le(), and | ||||
| 6707 | ** sqlite3_result_text64() routines, if the text contains invalid | ||||
| 6708 | ** UTF16 characters, the invalid characters might be converted | ||||
| 6709 | ** into the unicode replacement character, U+FFFD. | ||||
| 6710 | ** | ||||
| 6711 | ** ^The sqlite3_result_value() interface sets the result of | ||||
| 6712 | ** the application-defined function to be a copy of the | ||||
| 6713 | ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The | ||||
| 6714 | ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] | ||||
| 6715 | ** so that the [sqlite3_value] specified in the parameter may change or | ||||
| 6716 | ** be deallocated after sqlite3_result_value() returns without harm. | ||||
| 6717 | ** ^A [protected sqlite3_value] object may always be used where an | ||||
| 6718 | ** [unprotected sqlite3_value] object is required, so either | ||||
| 6719 | ** kind of [sqlite3_value] object can be used with this interface. | ||||
| 6720 | ** | ||||
| 6721 | ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an | ||||
| 6722 | ** SQL NULL value, just like [sqlite3_result_null(C)], except that it | ||||
| 6723 | ** also associates the host-language pointer P or type T with that | ||||
| 6724 | ** NULL value such that the pointer can be retrieved within an | ||||
| 6725 | ** [application-defined SQL function] using [sqlite3_value_pointer()]. | ||||
| 6726 | ** ^If the D parameter is not NULL, then it is a pointer to a destructor | ||||
| 6727 | ** for the P parameter. ^SQLite invokes D with P as its only argument | ||||
| 6728 | ** when SQLite is finished with P. The T parameter should be a static | ||||
| 6729 | ** string and preferably a string literal. The sqlite3_result_pointer() | ||||
| 6730 | ** routine is part of the [pointer passing interface] added for SQLite 3.20.0. | ||||
| 6731 | ** | ||||
| 6732 | ** If these routines are called from within a different thread | ||||
| 6733 | ** than the one containing the application-defined function that received | ||||
| 6734 | ** the [sqlite3_context] pointer, the results are undefined. | ||||
| 6735 | */ | ||||
| 6736 | SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); | ||||
| 6737 | SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, | ||||
| 6738 | sqlite3_uint64,void(*)(void*)); | ||||
| 6739 | SQLITE_API void sqlite3_result_double(sqlite3_context*, double); | ||||
| 6740 | SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); | ||||
| 6741 | SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); | ||||
| 6742 | SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); | ||||
| 6743 | SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); | ||||
| 6744 | SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); | ||||
| 6745 | SQLITE_API void sqlite3_result_int(sqlite3_context*, int); | ||||
| 6746 | SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); | ||||
| 6747 | SQLITE_API void sqlite3_result_null(sqlite3_context*); | ||||
| 6748 | SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); | ||||
| 6749 | SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, | ||||
| 6750 | void(*)(void*), unsigned char encoding); | ||||
| 6751 | SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); | ||||
| 6752 | SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); | ||||
| 6753 | SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); | ||||
| 6754 | SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); | ||||
| 6755 | SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*)); | ||||
| 6756 | SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); | ||||
| 6757 | SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); | ||||
| 6758 | |||||
| 6759 | |||||
| 6760 | /* | ||||
| 6761 | ** CAPI3REF: Setting The Subtype Of An SQL Function | ||||
| 6762 | ** METHOD: sqlite3_context | ||||
| 6763 | ** | ||||
| 6764 | ** The sqlite3_result_subtype(C,T) function causes the subtype of | ||||
| 6765 | ** the result from the [application-defined SQL function] with | ||||
| 6766 | ** [sqlite3_context] C to be the value T. Only the lower 8 bits | ||||
| 6767 | ** of the subtype T are preserved in current versions of SQLite; | ||||
| 6768 | ** higher order bits are discarded. | ||||
| 6769 | ** The number of subtype bytes preserved by SQLite might increase | ||||
| 6770 | ** in future releases of SQLite. | ||||
| 6771 | ** | ||||
| 6772 | ** Every [application-defined SQL function] that invokes this interface | ||||
| 6773 | ** should include the [SQLITE_RESULT_SUBTYPE] property in its | ||||
| 6774 | ** text encoding argument when the SQL function is | ||||
| 6775 | ** [sqlite3_create_function|registered]. If the [SQLITE_RESULT_SUBTYPE] | ||||
| 6776 | ** property is omitted from the function that invokes sqlite3_result_subtype(), | ||||
| 6777 | ** then in some cases the sqlite3_result_subtype() might fail to set | ||||
| 6778 | ** the result subtype. | ||||
| 6779 | ** | ||||
| 6780 | ** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any | ||||
| 6781 | ** SQL function that invokes the sqlite3_result_subtype() interface | ||||
| 6782 | ** and that does not have the SQLITE_RESULT_SUBTYPE property will raise | ||||
| 6783 | ** an error. Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1 | ||||
| 6784 | ** by default. | ||||
| 6785 | */ | ||||
| 6786 | SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); | ||||
| 6787 | |||||
| 6788 | /* | ||||
| 6789 | ** CAPI3REF: Define New Collating Sequences | ||||
| 6790 | ** METHOD: sqlite3 | ||||
| 6791 | ** | ||||
| 6792 | ** ^These functions add, remove, or modify a [collation] associated | ||||
| 6793 | ** with the [database connection] specified as the first argument. | ||||
| 6794 | ** | ||||
| 6795 | ** ^The name of the collation is a UTF-8 string | ||||
| 6796 | ** for sqlite3_create_collation() and sqlite3_create_collation_v2() | ||||
| 6797 | ** and a UTF-16 string in native byte order for sqlite3_create_collation16(). | ||||
| 6798 | ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are | ||||
| 6799 | ** considered to be the same name. | ||||
| 6800 | ** | ||||
| 6801 | ** ^(The third argument (eTextRep) must be one of the constants: | ||||
| 6802 | ** <ul> | ||||
| 6803 | ** <li> [SQLITE_UTF8], | ||||
| 6804 | ** <li> [SQLITE_UTF16LE], | ||||
| 6805 | ** <li> [SQLITE_UTF16BE], | ||||
| 6806 | ** <li> [SQLITE_UTF16], or | ||||
| 6807 | ** <li> [SQLITE_UTF16_ALIGNED]. | ||||
| 6808 | ** </ul>)^ | ||||
| 6809 | ** ^The eTextRep argument determines the encoding of strings passed | ||||
| 6810 | ** to the collating function callback, xCompare. | ||||
| 6811 | ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep | ||||
| 6812 | ** force strings to be UTF16 with native byte order. | ||||
| 6813 | ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin | ||||
| 6814 | ** on an even byte address. | ||||
| 6815 | ** | ||||
| 6816 | ** ^The fourth argument, pArg, is an application data pointer that is passed | ||||
| 6817 | ** through as the first argument to the collating function callback. | ||||
| 6818 | ** | ||||
| 6819 | ** ^The fifth argument, xCompare, is a pointer to the collating function. | ||||
| 6820 | ** ^Multiple collating functions can be registered using the same name but | ||||
| 6821 | ** with different eTextRep parameters and SQLite will use whichever | ||||
| 6822 | ** function requires the least amount of data transformation. | ||||
| 6823 | ** ^If the xCompare argument is NULL then the collating function is | ||||
| 6824 | ** deleted. ^When all collating functions having the same name are deleted, | ||||
| 6825 | ** that collation is no longer usable. | ||||
| 6826 | ** | ||||
| 6827 | ** ^The collating function callback is invoked with a copy of the pArg | ||||
| 6828 | ** application data pointer and with two strings in the encoding specified | ||||
| 6829 | ** by the eTextRep argument. The two integer parameters to the collating | ||||
| 6830 | ** function callback are the length of the two strings, in bytes. The collating | ||||
| 6831 | ** function must return an integer that is negative, zero, or positive | ||||
| 6832 | ** if the first string is less than, equal to, or greater than the second, | ||||
| 6833 | ** respectively. A collating function must always return the same answer | ||||
| 6834 | ** given the same inputs. If two or more collating functions are registered | ||||
| 6835 | ** to the same collation name (using different eTextRep values) then all | ||||
| 6836 | ** must give an equivalent answer when invoked with equivalent strings. | ||||
| 6837 | ** The collating function must obey the following properties for all | ||||
| 6838 | ** strings A, B, and C: | ||||
| 6839 | ** | ||||
| 6840 | ** <ol> | ||||
| 6841 | ** <li> If A==B then B==A. | ||||
| 6842 | ** <li> If A==B and B==C then A==C. | ||||
| 6843 | ** <li> If A<B THEN B>A. | ||||
| 6844 | ** <li> If A<B and B<C then A<C. | ||||
| 6845 | ** </ol> | ||||
| 6846 | ** | ||||
| 6847 | ** If a collating function fails any of the above constraints and that | ||||
| 6848 | ** collating function is registered and used, then the behavior of SQLite | ||||
| 6849 | ** is undefined. | ||||
| 6850 | ** | ||||
| 6851 | ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() | ||||
| 6852 | ** with the addition that the xDestroy callback is invoked on pArg when | ||||
| 6853 | ** the collating function is deleted. | ||||
| 6854 | ** ^Collating functions are deleted when they are overridden by later | ||||
| 6855 | ** calls to the collation creation functions or when the | ||||
| 6856 | ** [database connection] is closed using [sqlite3_close()]. | ||||
| 6857 | ** | ||||
| 6858 | ** ^The xDestroy callback is <u>not</u> called if the | ||||
| 6859 | ** sqlite3_create_collation_v2() function fails. Applications that invoke | ||||
| 6860 | ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should | ||||
| 6861 | ** check the return code and dispose of the application data pointer | ||||
| 6862 | ** themselves rather than expecting SQLite to deal with it for them. | ||||
| 6863 | ** This is different from every other SQLite interface. The inconsistency | ||||
| 6864 | ** is unfortunate but cannot be changed without breaking backwards | ||||
| 6865 | ** compatibility. | ||||
| 6866 | ** | ||||
| 6867 | ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. | ||||
| 6868 | */ | ||||
| 6869 | SQLITE_API int sqlite3_create_collation( | ||||
| 6870 | sqlite3*, | ||||
| 6871 | const char *zName, | ||||
| 6872 | int eTextRep, | ||||
| 6873 | void *pArg, | ||||
| 6874 | int(*xCompare)(void*,int,const void*,int,const void*) | ||||
| 6875 | ); | ||||
| 6876 | SQLITE_API int sqlite3_create_collation_v2( | ||||
| 6877 | sqlite3*, | ||||
| 6878 | const char *zName, | ||||
| 6879 | int eTextRep, | ||||
| 6880 | void *pArg, | ||||
| 6881 | int(*xCompare)(void*,int,const void*,int,const void*), | ||||
| 6882 | void(*xDestroy)(void*) | ||||
| 6883 | ); | ||||
| 6884 | SQLITE_API int sqlite3_create_collation16( | ||||
| 6885 | sqlite3*, | ||||
| 6886 | const void *zName, | ||||
| 6887 | int eTextRep, | ||||
| 6888 | void *pArg, | ||||
| 6889 | int(*xCompare)(void*,int,const void*,int,const void*) | ||||
| 6890 | ); | ||||
| 6891 | |||||
| 6892 | /* | ||||
| 6893 | ** CAPI3REF: Collation Needed Callbacks | ||||
| 6894 | ** METHOD: sqlite3 | ||||
| 6895 | ** | ||||
| 6896 | ** ^To avoid having to register all collation sequences before a database | ||||
| 6897 | ** can be used, a single callback function may be registered with the | ||||
| 6898 | ** [database connection] to be invoked whenever an undefined collation | ||||
| 6899 | ** sequence is required. | ||||
| 6900 | ** | ||||
| 6901 | ** ^If the function is registered using the sqlite3_collation_needed() API, | ||||
| 6902 | ** then it is passed the names of undefined collation sequences as strings | ||||
| 6903 | ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, | ||||
| 6904 | ** the names are passed as UTF-16 in machine native byte order. | ||||
| 6905 | ** ^A call to either function replaces the existing collation-needed callback. | ||||
| 6906 | ** | ||||
| 6907 | ** ^(When the callback is invoked, the first argument passed is a copy | ||||
| 6908 | ** of the second argument to sqlite3_collation_needed() or | ||||
| 6909 | ** sqlite3_collation_needed16(). The second argument is the database | ||||
| 6910 | ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], | ||||
| 6911 | ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation | ||||
| 6912 | ** sequence function required. The fourth parameter is the name of the | ||||
| 6913 | ** required collation sequence.)^ | ||||
| 6914 | ** | ||||
| 6915 | ** The callback function should register the desired collation using | ||||
| 6916 | ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or | ||||
| 6917 | ** [sqlite3_create_collation_v2()]. | ||||
| 6918 | */ | ||||
| 6919 | SQLITE_API int sqlite3_collation_needed( | ||||
| 6920 | sqlite3*, | ||||
| 6921 | void*, | ||||
| 6922 | void(*)(void*,sqlite3*,int eTextRep,const char*) | ||||
| 6923 | ); | ||||
| 6924 | SQLITE_API int sqlite3_collation_needed16( | ||||
| 6925 | sqlite3*, | ||||
| 6926 | void*, | ||||
| 6927 | void(*)(void*,sqlite3*,int eTextRep,const void*) | ||||
| 6928 | ); | ||||
| 6929 | |||||
| 6930 | #ifdef SQLITE_ENABLE_CEROD | ||||
| 6931 | /* | ||||
| 6932 | ** Specify the activation key for a CEROD database. Unless | ||||
| 6933 | ** activated, none of the CEROD routines will work. | ||||
| 6934 | */ | ||||
| 6935 | SQLITE_API void sqlite3_activate_cerod( | ||||
| 6936 | const char *zPassPhrase /* Activation phrase */ | ||||
| 6937 | ); | ||||
| 6938 | #endif | ||||
| 6939 | |||||
| 6940 | /* | ||||
| 6941 | ** CAPI3REF: Suspend Execution For A Short Time | ||||
| 6942 | ** | ||||
| 6943 | ** The sqlite3_sleep() function causes the current thread to suspend execution | ||||
| 6944 | ** for at least a number of milliseconds specified in its parameter. | ||||
| 6945 | ** | ||||
| 6946 | ** If the operating system does not support sleep requests with | ||||
| 6947 | ** millisecond time resolution, then the time will be rounded up to | ||||
| 6948 | ** the nearest second. The number of milliseconds of sleep actually | ||||
| 6949 | ** requested from the operating system is returned. | ||||
| 6950 | ** | ||||
| 6951 | ** ^SQLite implements this interface by calling the xSleep() | ||||
| 6952 | ** method of the default [sqlite3_vfs] object. If the xSleep() method | ||||
| 6953 | ** of the default VFS is not implemented correctly, or not implemented at | ||||
| 6954 | ** all, then the behavior of sqlite3_sleep() may deviate from the description | ||||
| 6955 | ** in the previous paragraphs. | ||||
| 6956 | ** | ||||
| 6957 | ** If a negative argument is passed to sqlite3_sleep() the results vary by | ||||
| 6958 | ** VFS and operating system. Some system treat a negative argument as an | ||||
| 6959 | ** instruction to sleep forever. Others understand it to mean do not sleep | ||||
| 6960 | ** at all. ^In SQLite version 3.42.0 and later, a negative | ||||
| 6961 | ** argument passed into sqlite3_sleep() is changed to zero before it is relayed | ||||
| 6962 | ** down into the xSleep method of the VFS. | ||||
| 6963 | */ | ||||
| 6964 | SQLITE_API int sqlite3_sleep(int); | ||||
| 6965 | |||||
| 6966 | /* | ||||
| 6967 | ** CAPI3REF: Name Of The Folder Holding Temporary Files | ||||
| 6968 | ** | ||||
| 6969 | ** ^(If this global variable is made to point to a string which is | ||||
| 6970 | ** the name of a folder (a.k.a. directory), then all temporary files | ||||
| 6971 | ** created by SQLite when using a built-in [sqlite3_vfs | VFS] | ||||
| 6972 | ** will be placed in that directory.)^ ^If this variable | ||||
| 6973 | ** is a NULL pointer, then SQLite performs a search for an appropriate | ||||
| 6974 | ** temporary file directory. | ||||
| 6975 | ** | ||||
| 6976 | ** Applications are strongly discouraged from using this global variable. | ||||
| 6977 | ** It is required to set a temporary folder on Windows Runtime (WinRT). | ||||
| 6978 | ** But for all other platforms, it is highly recommended that applications | ||||
| 6979 | ** neither read nor write this variable. This global variable is a relic | ||||
| 6980 | ** that exists for backwards compatibility of legacy applications and should | ||||
| 6981 | ** be avoided in new projects. | ||||
| 6982 | ** | ||||
| 6983 | ** It is not safe to read or modify this variable in more than one | ||||
| 6984 | ** thread at a time. It is not safe to read or modify this variable | ||||
| 6985 | ** if a [database connection] is being used at the same time in a separate | ||||
| 6986 | ** thread. | ||||
| 6987 | ** It is intended that this variable be set once | ||||
| 6988 | ** as part of process initialization and before any SQLite interface | ||||
| 6989 | ** routines have been called and that this variable remain unchanged | ||||
| 6990 | ** thereafter. | ||||
| 6991 | ** | ||||
| 6992 | ** ^The [temp_store_directory pragma] may modify this variable and cause | ||||
| 6993 | ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, | ||||
| 6994 | ** the [temp_store_directory pragma] always assumes that any string | ||||
| 6995 | ** that this variable points to is held in memory obtained from | ||||
| 6996 | ** [sqlite3_malloc] and the pragma may attempt to free that memory | ||||
| 6997 | ** using [sqlite3_free]. | ||||
| 6998 | ** Hence, if this variable is modified directly, either it should be | ||||
| 6999 | ** made NULL or made to point to memory obtained from [sqlite3_malloc] | ||||
| 7000 | ** or else the use of the [temp_store_directory pragma] should be avoided. | ||||
| 7001 | ** Except when requested by the [temp_store_directory pragma], SQLite | ||||
| 7002 | ** does not free the memory that sqlite3_temp_directory points to. If | ||||
| 7003 | ** the application wants that memory to be freed, it must do | ||||
| 7004 | ** so itself, taking care to only do so after all [database connection] | ||||
| 7005 | ** objects have been destroyed. | ||||
| 7006 | ** | ||||
| 7007 | ** <b>Note to Windows Runtime users:</b> The temporary directory must be set | ||||
| 7008 | ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various | ||||
| 7009 | ** features that require the use of temporary files may fail. Here is an | ||||
| 7010 | ** example of how to do this using C++ with the Windows Runtime: | ||||
| 7011 | ** | ||||
| 7012 | ** <blockquote><pre> | ||||
| 7013 | ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current-> | ||||
| 7014 | ** TemporaryFolder->Path->Data(); | ||||
| 7015 | ** char zPathBuf[MAX_PATH + 1]; | ||||
| 7016 | ** memset(zPathBuf, 0, sizeof(zPathBuf)); | ||||
| 7017 | ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf), | ||||
| 7018 | ** NULL, NULL); | ||||
| 7019 | ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf); | ||||
| 7020 | ** </pre></blockquote> | ||||
| 7021 | */ | ||||
| 7022 | SQLITE_API char *sqlite3_temp_directory; | ||||
| 7023 | |||||
| 7024 | /* | ||||
| 7025 | ** CAPI3REF: Name Of The Folder Holding Database Files | ||||
| 7026 | ** | ||||
| 7027 | ** ^(If this global variable is made to point to a string which is | ||||
| 7028 | ** the name of a folder (a.k.a. directory), then all database files | ||||
| 7029 | ** specified with a relative pathname and created or accessed by | ||||
| 7030 | ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed | ||||
| 7031 | ** to be relative to that directory.)^ ^If this variable is a NULL | ||||
| 7032 | ** pointer, then SQLite assumes that all database files specified | ||||
| 7033 | ** with a relative pathname are relative to the current directory | ||||
| 7034 | ** for the process. Only the windows VFS makes use of this global | ||||
| 7035 | ** variable; it is ignored by the unix VFS. | ||||
| 7036 | ** | ||||
| 7037 | ** Changing the value of this variable while a database connection is | ||||
| 7038 | ** open can result in a corrupt database. | ||||
| 7039 | ** | ||||
| 7040 | ** It is not safe to read or modify this variable in more than one | ||||
| 7041 | ** thread at a time. It is not safe to read or modify this variable | ||||
| 7042 | ** if a [database connection] is being used at the same time in a separate | ||||
| 7043 | ** thread. | ||||
| 7044 | ** It is intended that this variable be set once | ||||
| 7045 | ** as part of process initialization and before any SQLite interface | ||||
| 7046 | ** routines have been called and that this variable remain unchanged | ||||
| 7047 | ** thereafter. | ||||
| 7048 | ** | ||||
| 7049 | ** ^The [data_store_directory pragma] may modify this variable and cause | ||||
| 7050 | ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, | ||||
| 7051 | ** the [data_store_directory pragma] always assumes that any string | ||||
| 7052 | ** that this variable points to is held in memory obtained from | ||||
| 7053 | ** [sqlite3_malloc] and the pragma may attempt to free that memory | ||||
| 7054 | ** using [sqlite3_free]. | ||||
| 7055 | ** Hence, if this variable is modified directly, either it should be | ||||
| 7056 | ** made NULL or made to point to memory obtained from [sqlite3_malloc] | ||||
| 7057 | ** or else the use of the [data_store_directory pragma] should be avoided. | ||||
| 7058 | */ | ||||
| 7059 | SQLITE_API char *sqlite3_data_directory; | ||||
| 7060 | |||||
| 7061 | /* | ||||
| 7062 | ** CAPI3REF: Win32 Specific Interface | ||||
| 7063 | ** | ||||
| 7064 | ** These interfaces are available only on Windows. The | ||||
| 7065 | ** [sqlite3_win32_set_directory] interface is used to set the value associated | ||||
| 7066 | ** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to | ||||
| 7067 | ** zValue, depending on the value of the type parameter. The zValue parameter | ||||
| 7068 | ** should be NULL to cause the previous value to be freed via [sqlite3_free]; | ||||
| 7069 | ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc] | ||||
| 7070 | ** prior to being used. The [sqlite3_win32_set_directory] interface returns | ||||
| 7071 | ** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported, | ||||
| 7072 | ** or [SQLITE_NOMEM] if memory could not be allocated. The value of the | ||||
| 7073 | ** [sqlite3_data_directory] variable is intended to act as a replacement for | ||||
| 7074 | ** the current directory on the sub-platforms of Win32 where that concept is | ||||
| 7075 | ** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and | ||||
| 7076 | ** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the | ||||
| 7077 | ** sqlite3_win32_set_directory interface except the string parameter must be | ||||
| 7078 | ** UTF-8 or UTF-16, respectively. | ||||
| 7079 | */ | ||||
| 7080 | SQLITE_API int sqlite3_win32_set_directory( | ||||
| 7081 | unsigned long type, /* Identifier for directory being set or reset */ | ||||
| 7082 | void *zValue /* New value for directory being set or reset */ | ||||
| 7083 | ); | ||||
| 7084 | SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue); | ||||
| 7085 | SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue); | ||||
| 7086 | |||||
| 7087 | /* | ||||
| 7088 | ** CAPI3REF: Win32 Directory Types | ||||
| 7089 | ** | ||||
| 7090 | ** These macros are only available on Windows. They define the allowed values | ||||
| 7091 | ** for the type argument to the [sqlite3_win32_set_directory] interface. | ||||
| 7092 | */ | ||||
| 7093 | #define SQLITE_WIN32_DATA_DIRECTORY_TYPE1 1 | ||||
| 7094 | #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE2 2 | ||||
| 7095 | |||||
| 7096 | /* | ||||
| 7097 | ** CAPI3REF: Test For Auto-Commit Mode | ||||
| 7098 | ** KEYWORDS: {autocommit mode} | ||||
| 7099 | ** METHOD: sqlite3 | ||||
| 7100 | ** | ||||
| 7101 | ** ^The sqlite3_get_autocommit() interface returns non-zero or | ||||
| 7102 | ** zero if the given database connection is or is not in autocommit mode, | ||||
| 7103 | ** respectively. ^Autocommit mode is on by default. | ||||
| 7104 | ** ^Autocommit mode is disabled by a [BEGIN] statement. | ||||
| 7105 | ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. | ||||
| 7106 | ** | ||||
| 7107 | ** If certain kinds of errors occur on a statement within a multi-statement | ||||
| 7108 | ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], | ||||
| 7109 | ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the | ||||
| 7110 | ** transaction might be rolled back automatically. The only way to | ||||
| 7111 | ** find out whether SQLite automatically rolled back the transaction after | ||||
| 7112 | ** an error is to use this function. | ||||
| 7113 | ** | ||||
| 7114 | ** If another thread changes the autocommit status of the database | ||||
| 7115 | ** connection while this routine is running, then the return value | ||||
| 7116 | ** is undefined. | ||||
| 7117 | */ | ||||
| 7118 | SQLITE_API int sqlite3_get_autocommit(sqlite3*); | ||||
| 7119 | |||||
| 7120 | /* | ||||
| 7121 | ** CAPI3REF: Find The Database Handle Of A Prepared Statement | ||||
| 7122 | ** METHOD: sqlite3_stmt | ||||
| 7123 | ** | ||||
| 7124 | ** ^The sqlite3_db_handle interface returns the [database connection] handle | ||||
| 7125 | ** to which a [prepared statement] belongs. ^The [database connection] | ||||
| 7126 | ** returned by sqlite3_db_handle is the same [database connection] | ||||
| 7127 | ** that was the first argument | ||||
| 7128 | ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to | ||||
| 7129 | ** create the statement in the first place. | ||||
| 7130 | */ | ||||
| 7131 | SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); | ||||
| 7132 | |||||
| 7133 | /* | ||||
| 7134 | ** CAPI3REF: Return The Schema Name For A Database Connection | ||||
| 7135 | ** METHOD: sqlite3 | ||||
| 7136 | ** | ||||
| 7137 | ** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name | ||||
| 7138 | ** for the N-th database on database connection D, or a NULL pointer if N is | ||||
| 7139 | ** out of range. An N value of 0 means the main database file. An N of 1 is | ||||
| 7140 | ** the "temp" schema. Larger values of N correspond to various ATTACH-ed | ||||
| 7141 | ** databases. | ||||
| 7142 | ** | ||||
| 7143 | ** Space to hold the string that is returned by sqlite3_db_name() is managed | ||||
| 7144 | ** by SQLite itself. The string might be deallocated by any operation that | ||||
| 7145 | ** changes the schema, including [ATTACH] or [DETACH] or calls to | ||||
| 7146 | ** [sqlite3_serialize()] or [sqlite3_deserialize()], even operations that | ||||
| 7147 | ** occur on a different thread. Applications that need to | ||||
| 7148 | ** remember the string long-term should make their own copy. Applications that | ||||
| 7149 | ** are accessing the same database connection simultaneously on multiple | ||||
| 7150 | ** threads should mutex-protect calls to this API and should make their own | ||||
| 7151 | ** private copy of the result prior to releasing the mutex. | ||||
| 7152 | */ | ||||
| 7153 | SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N); | ||||
| 7154 | |||||
| 7155 | /* | ||||
| 7156 | ** CAPI3REF: Return The Filename For A Database Connection | ||||
| 7157 | ** METHOD: sqlite3 | ||||
| 7158 | ** | ||||
| 7159 | ** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename | ||||
| 7160 | ** associated with database N of connection D. | ||||
| 7161 | ** ^If there is no attached database N on the database | ||||
| 7162 | ** connection D, or if database N is a temporary or in-memory database, then | ||||
| 7163 | ** this function will return either a NULL pointer or an empty string. | ||||
| 7164 | ** | ||||
| 7165 | ** ^The string value returned by this routine is owned and managed by | ||||
| 7166 | ** the database connection. ^The value will be valid until the database N | ||||
| 7167 | ** is [DETACH]-ed or until the database connection closes. | ||||
| 7168 | ** | ||||
| 7169 | ** ^The filename returned by this function is the output of the | ||||
| 7170 | ** xFullPathname method of the [VFS]. ^In other words, the filename | ||||
| 7171 | ** will be an absolute pathname, even if the filename used | ||||
| 7172 | ** to open the database originally was a URI or relative pathname. | ||||
| 7173 | ** | ||||
| 7174 | ** If the filename pointer returned by this routine is not NULL, then it | ||||
| 7175 | ** can be used as the filename input parameter to these routines: | ||||
| 7176 | ** <ul> | ||||
| 7177 | ** <li> [sqlite3_uri_parameter()] | ||||
| 7178 | ** <li> [sqlite3_uri_boolean()] | ||||
| 7179 | ** <li> [sqlite3_uri_int64()] | ||||
| 7180 | ** <li> [sqlite3_filename_database()] | ||||
| 7181 | ** <li> [sqlite3_filename_journal()] | ||||
| 7182 | ** <li> [sqlite3_filename_wal()] | ||||
| 7183 | ** </ul> | ||||
| 7184 | */ | ||||
| 7185 | SQLITE_API sqlite3_filename sqlite3_db_filename(sqlite3 *db, const char *zDbName); | ||||
| 7186 | |||||
| 7187 | /* | ||||
| 7188 | ** CAPI3REF: Determine if a database is read-only | ||||
| 7189 | ** METHOD: sqlite3 | ||||
| 7190 | ** | ||||
| 7191 | ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N | ||||
| 7192 | ** of connection D is read-only, 0 if it is read/write, or -1 if N is not | ||||
| 7193 | ** the name of a database on connection D. | ||||
| 7194 | */ | ||||
| 7195 | SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); | ||||
| 7196 | |||||
| 7197 | /* | ||||
| 7198 | ** CAPI3REF: Determine the transaction state of a database | ||||
| 7199 | ** METHOD: sqlite3 | ||||
| 7200 | ** | ||||
| 7201 | ** ^The sqlite3_txn_state(D,S) interface returns the current | ||||
| 7202 | ** [transaction state] of schema S in database connection D. ^If S is NULL, | ||||
| 7203 | ** then the highest transaction state of any schema on database connection D | ||||
| 7204 | ** is returned. Transaction states are (in order of lowest to highest): | ||||
| 7205 | ** <ol> | ||||
| 7206 | ** <li value="0"> SQLITE_TXN_NONE | ||||
| 7207 | ** <li value="1"> SQLITE_TXN_READ | ||||
| 7208 | ** <li value="2"> SQLITE_TXN_WRITE | ||||
| 7209 | ** </ol> | ||||
| 7210 | ** ^If the S argument to sqlite3_txn_state(D,S) is not the name of | ||||
| 7211 | ** a valid schema, then -1 is returned. | ||||
| 7212 | */ | ||||
| 7213 | SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema); | ||||
| 7214 | |||||
| 7215 | /* | ||||
| 7216 | ** CAPI3REF: Allowed return values from sqlite3_txn_state() | ||||
| 7217 | ** KEYWORDS: {transaction state} | ||||
| 7218 | ** | ||||
| 7219 | ** These constants define the current transaction state of a database file. | ||||
| 7220 | ** ^The [sqlite3_txn_state(D,S)] interface returns one of these | ||||
| 7221 | ** constants in order to describe the transaction state of schema S | ||||
| 7222 | ** in [database connection] D. | ||||
| 7223 | ** | ||||
| 7224 | ** <dl> | ||||
| 7225 | ** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt> | ||||
| 7226 | ** <dd>The SQLITE_TXN_NONE state means that no transaction is currently | ||||
| 7227 | ** pending.</dd> | ||||
| 7228 | ** | ||||
| 7229 | ** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt> | ||||
| 7230 | ** <dd>The SQLITE_TXN_READ state means that the database is currently | ||||
| 7231 | ** in a read transaction. Content has been read from the database file | ||||
| 7232 | ** but nothing in the database file has changed. The transaction state | ||||
| 7233 | ** will be advanced to SQLITE_TXN_WRITE if any changes occur and there are | ||||
| 7234 | ** no other conflicting concurrent write transactions. The transaction | ||||
| 7235 | ** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or | ||||
| 7236 | ** [COMMIT].</dd> | ||||
| 7237 | ** | ||||
| 7238 | ** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt> | ||||
| 7239 | ** <dd>The SQLITE_TXN_WRITE state means that the database is currently | ||||
| 7240 | ** in a write transaction. Content has been written to the database file | ||||
| 7241 | ** but has not yet committed. The transaction state will change to | ||||
| 7242 | ** SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd> | ||||
| 7243 | */ | ||||
| 7244 | #define SQLITE_TXN_NONE0 0 | ||||
| 7245 | #define SQLITE_TXN_READ1 1 | ||||
| 7246 | #define SQLITE_TXN_WRITE2 2 | ||||
| 7247 | |||||
| 7248 | /* | ||||
| 7249 | ** CAPI3REF: Find the next prepared statement | ||||
| 7250 | ** METHOD: sqlite3 | ||||
| 7251 | ** | ||||
| 7252 | ** ^This interface returns a pointer to the next [prepared statement] after | ||||
| 7253 | ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL | ||||
| 7254 | ** then this interface returns a pointer to the first prepared statement | ||||
| 7255 | ** associated with the database connection pDb. ^If no prepared statement | ||||
| 7256 | ** satisfies the conditions of this routine, it returns NULL. | ||||
| 7257 | ** | ||||
| 7258 | ** The [database connection] pointer D in a call to | ||||
| 7259 | ** [sqlite3_next_stmt(D,S)] must refer to an open database | ||||
| 7260 | ** connection and in particular must not be a NULL pointer. | ||||
| 7261 | */ | ||||
| 7262 | SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); | ||||
| 7263 | |||||
| 7264 | /* | ||||
| 7265 | ** CAPI3REF: Commit And Rollback Notification Callbacks | ||||
| 7266 | ** METHOD: sqlite3 | ||||
| 7267 | ** | ||||
| 7268 | ** ^The sqlite3_commit_hook() interface registers a callback | ||||
| 7269 | ** function to be invoked whenever a transaction is [COMMIT | committed]. | ||||
| 7270 | ** ^Any callback set by a previous call to sqlite3_commit_hook() | ||||
| 7271 | ** for the same database connection is overridden. | ||||
| 7272 | ** ^The sqlite3_rollback_hook() interface registers a callback | ||||
| 7273 | ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. | ||||
| 7274 | ** ^Any callback set by a previous call to sqlite3_rollback_hook() | ||||
| 7275 | ** for the same database connection is overridden. | ||||
| 7276 | ** ^The pArg argument is passed through to the callback. | ||||
| 7277 | ** ^If the callback on a commit hook function returns non-zero, | ||||
| 7278 | ** then the commit is converted into a rollback. | ||||
| 7279 | ** | ||||
| 7280 | ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions | ||||
| 7281 | ** return the P argument from the previous call of the same function | ||||
| 7282 | ** on the same [database connection] D, or NULL for | ||||
| 7283 | ** the first call for each function on D. | ||||
| 7284 | ** | ||||
| 7285 | ** The commit and rollback hook callbacks are not reentrant. | ||||
| 7286 | ** The callback implementation must not do anything that will modify | ||||
| 7287 | ** the database connection that invoked the callback. Any actions | ||||
| 7288 | ** to modify the database connection must be deferred until after the | ||||
| 7289 | ** completion of the [sqlite3_step()] call that triggered the commit | ||||
| 7290 | ** or rollback hook in the first place. | ||||
| 7291 | ** Note that running any other SQL statements, including SELECT statements, | ||||
| 7292 | ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify | ||||
| 7293 | ** the database connections for the meaning of "modify" in this paragraph. | ||||
| 7294 | ** | ||||
| 7295 | ** ^Registering a NULL function disables the callback. | ||||
| 7296 | ** | ||||
| 7297 | ** ^When the commit hook callback routine returns zero, the [COMMIT] | ||||
| 7298 | ** operation is allowed to continue normally. ^If the commit hook | ||||
| 7299 | ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. | ||||
| 7300 | ** ^The rollback hook is invoked on a rollback that results from a commit | ||||
| 7301 | ** hook returning non-zero, just as it would be with any other rollback. | ||||
| 7302 | ** | ||||
| 7303 | ** ^For the purposes of this API, a transaction is said to have been | ||||
| 7304 | ** rolled back if an explicit "ROLLBACK" statement is executed, or | ||||
| 7305 | ** an error or constraint causes an implicit rollback to occur. | ||||
| 7306 | ** ^The rollback callback is not invoked if a transaction is | ||||
| 7307 | ** automatically rolled back because the database connection is closed. | ||||
| 7308 | ** | ||||
| 7309 | ** See also the [sqlite3_update_hook()] interface. | ||||
| 7310 | */ | ||||
| 7311 | SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); | ||||
| 7312 | SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); | ||||
| 7313 | |||||
| 7314 | /* | ||||
| 7315 | ** CAPI3REF: Autovacuum Compaction Amount Callback | ||||
| 7316 | ** METHOD: sqlite3 | ||||
| 7317 | ** | ||||
| 7318 | ** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback | ||||
| 7319 | ** function C that is invoked prior to each autovacuum of the database | ||||
| 7320 | ** file. ^The callback is passed a copy of the generic data pointer (P), | ||||
| 7321 | ** the schema-name of the attached database that is being autovacuumed, | ||||
| 7322 | ** the size of the database file in pages, the number of free pages, | ||||
| 7323 | ** and the number of bytes per page, respectively. The callback should | ||||
| 7324 | ** return the number of free pages that should be removed by the | ||||
| 7325 | ** autovacuum. ^If the callback returns zero, then no autovacuum happens. | ||||
| 7326 | ** ^If the value returned is greater than or equal to the number of | ||||
| 7327 | ** free pages, then a complete autovacuum happens. | ||||
| 7328 | ** | ||||
| 7329 | ** <p>^If there are multiple ATTACH-ed database files that are being | ||||
| 7330 | ** modified as part of a transaction commit, then the autovacuum pages | ||||
| 7331 | ** callback is invoked separately for each file. | ||||
| 7332 | ** | ||||
| 7333 | ** <p><b>The callback is not reentrant.</b> The callback function should | ||||
| 7334 | ** not attempt to invoke any other SQLite interface. If it does, bad | ||||
| 7335 | ** things may happen, including segmentation faults and corrupt database | ||||
| 7336 | ** files. The callback function should be a simple function that | ||||
| 7337 | ** does some arithmetic on its input parameters and returns a result. | ||||
| 7338 | ** | ||||
| 7339 | ** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional | ||||
| 7340 | ** destructor for the P parameter. ^If X is not NULL, then X(P) is | ||||
| 7341 | ** invoked whenever the database connection closes or when the callback | ||||
| 7342 | ** is overwritten by another invocation of sqlite3_autovacuum_pages(). | ||||
| 7343 | ** | ||||
| 7344 | ** <p>^There is only one autovacuum pages callback per database connection. | ||||
| 7345 | ** ^Each call to the sqlite3_autovacuum_pages() interface overrides all | ||||
| 7346 | ** previous invocations for that database connection. ^If the callback | ||||
| 7347 | ** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer, | ||||
| 7348 | ** then the autovacuum steps callback is canceled. The return value | ||||
| 7349 | ** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might | ||||
| 7350 | ** be some other error code if something goes wrong. The current | ||||
| 7351 | ** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other | ||||
| 7352 | ** return codes might be added in future releases. | ||||
| 7353 | ** | ||||
| 7354 | ** <p>If no autovacuum pages callback is specified (the usual case) or | ||||
| 7355 | ** a NULL pointer is provided for the callback, | ||||
| 7356 | ** then the default behavior is to vacuum all free pages. So, in other | ||||
| 7357 | ** words, the default behavior is the same as if the callback function | ||||
| 7358 | ** were something like this: | ||||
| 7359 | ** | ||||
| 7360 | ** <blockquote><pre> | ||||
| 7361 | ** unsigned int demonstration_autovac_pages_callback( | ||||
| 7362 | ** void *pClientData, | ||||
| 7363 | ** const char *zSchema, | ||||
| 7364 | ** unsigned int nDbPage, | ||||
| 7365 | ** unsigned int nFreePage, | ||||
| 7366 | ** unsigned int nBytePerPage | ||||
| 7367 | ** ){ | ||||
| 7368 | ** return nFreePage; | ||||
| 7369 | ** } | ||||
| 7370 | ** </pre></blockquote> | ||||
| 7371 | */ | ||||
| 7372 | SQLITE_API int sqlite3_autovacuum_pages( | ||||
| 7373 | sqlite3 *db, | ||||
| 7374 | unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int), | ||||
| 7375 | void*, | ||||
| 7376 | void(*)(void*) | ||||
| 7377 | ); | ||||
| 7378 | |||||
| 7379 | |||||
| 7380 | /* | ||||
| 7381 | ** CAPI3REF: Data Change Notification Callbacks | ||||
| 7382 | ** METHOD: sqlite3 | ||||
| 7383 | ** | ||||
| 7384 | ** ^The sqlite3_update_hook() interface registers a callback function | ||||
| 7385 | ** with the [database connection] identified by the first argument | ||||
| 7386 | ** to be invoked whenever a row is updated, inserted or deleted in | ||||
| 7387 | ** a [rowid table]. | ||||
| 7388 | ** ^Any callback set by a previous call to this function | ||||
| 7389 | ** for the same database connection is overridden. | ||||
| 7390 | ** | ||||
| 7391 | ** ^The second argument is a pointer to the function to invoke when a | ||||
| 7392 | ** row is updated, inserted or deleted in a rowid table. | ||||
| 7393 | ** ^The update hook is disabled by invoking sqlite3_update_hook() | ||||
| 7394 | ** with a NULL pointer as the second parameter. | ||||
| 7395 | ** ^The first argument to the callback is a copy of the third argument | ||||
| 7396 | ** to sqlite3_update_hook(). | ||||
| 7397 | ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], | ||||
| 7398 | ** or [SQLITE_UPDATE], depending on the operation that caused the callback | ||||
| 7399 | ** to be invoked. | ||||
| 7400 | ** ^The third and fourth arguments to the callback contain pointers to the | ||||
| 7401 | ** database and table name containing the affected row. | ||||
| 7402 | ** ^The final callback parameter is the [rowid] of the row. | ||||
| 7403 | ** ^In the case of an update, this is the [rowid] after the update takes place. | ||||
| 7404 | ** | ||||
| 7405 | ** ^(The update hook is not invoked when internal system tables are | ||||
| 7406 | ** modified (i.e. sqlite_sequence).)^ | ||||
| 7407 | ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. | ||||
| 7408 | ** | ||||
| 7409 | ** ^In the current implementation, the update hook | ||||
| 7410 | ** is not invoked when conflicting rows are deleted because of an | ||||
| 7411 | ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook | ||||
| 7412 | ** invoked when rows are deleted using the [truncate optimization]. | ||||
| 7413 | ** The exceptions defined in this paragraph might change in a future | ||||
| 7414 | ** release of SQLite. | ||||
| 7415 | ** | ||||
| 7416 | ** Whether the update hook is invoked before or after the | ||||
| 7417 | ** corresponding change is currently unspecified and may differ | ||||
| 7418 | ** depending on the type of change. Do not rely on the order of the | ||||
| 7419 | ** hook call with regards to the final result of the operation which | ||||
| 7420 | ** triggers the hook. | ||||
| 7421 | ** | ||||
| 7422 | ** The update hook implementation must not do anything that will modify | ||||
| 7423 | ** the database connection that invoked the update hook. Any actions | ||||
| 7424 | ** to modify the database connection must be deferred until after the | ||||
| 7425 | ** completion of the [sqlite3_step()] call that triggered the update hook. | ||||
| 7426 | ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their | ||||
| 7427 | ** database connections for the meaning of "modify" in this paragraph. | ||||
| 7428 | ** | ||||
| 7429 | ** ^The sqlite3_update_hook(D,C,P) function | ||||
| 7430 | ** returns the P argument from the previous call | ||||
| 7431 | ** on the same [database connection] D, or NULL for | ||||
| 7432 | ** the first call on D. | ||||
| 7433 | ** | ||||
| 7434 | ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], | ||||
| 7435 | ** and [sqlite3_preupdate_hook()] interfaces. | ||||
| 7436 | */ | ||||
| 7437 | SQLITE_API void *sqlite3_update_hook( | ||||
| 7438 | sqlite3*, | ||||
| 7439 | void(*)(void *,int ,char const *,char const *,sqlite3_int64), | ||||
| 7440 | void* | ||||
| 7441 | ); | ||||
| 7442 | |||||
| 7443 | /* | ||||
| 7444 | ** CAPI3REF: Enable Or Disable Shared Pager Cache | ||||
| 7445 | ** | ||||
| 7446 | ** ^(This routine enables or disables the sharing of the database cache | ||||
| 7447 | ** and schema data structures between [database connection | connections] | ||||
| 7448 | ** to the same database. Sharing is enabled if the argument is true | ||||
| 7449 | ** and disabled if the argument is false.)^ | ||||
| 7450 | ** | ||||
| 7451 | ** This interface is omitted if SQLite is compiled with | ||||
| 7452 | ** [-DSQLITE_OMIT_SHARED_CACHE]. The [-DSQLITE_OMIT_SHARED_CACHE] | ||||
| 7453 | ** compile-time option is recommended because the | ||||
| 7454 | ** [use of shared cache mode is discouraged]. | ||||
| 7455 | ** | ||||
| 7456 | ** ^Cache sharing is enabled and disabled for an entire process. | ||||
| 7457 | ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). | ||||
| 7458 | ** In prior versions of SQLite, | ||||
| 7459 | ** sharing was enabled or disabled for each thread separately. | ||||
| 7460 | ** | ||||
| 7461 | ** ^(The cache sharing mode set by this interface effects all subsequent | ||||
| 7462 | ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. | ||||
| 7463 | ** Existing database connections continue to use the sharing mode | ||||
| 7464 | ** that was in effect at the time they were opened.)^ | ||||
| 7465 | ** | ||||
| 7466 | ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled | ||||
| 7467 | ** successfully. An [error code] is returned otherwise.)^ | ||||
| 7468 | ** | ||||
| 7469 | ** ^Shared cache is disabled by default. It is recommended that it stay | ||||
| 7470 | ** that way. In other words, do not use this routine. This interface | ||||
| 7471 | ** continues to be provided for historical compatibility, but its use is | ||||
| 7472 | ** discouraged. Any use of shared cache is discouraged. If shared cache | ||||
| 7473 | ** must be used, it is recommended that shared cache only be enabled for | ||||
| 7474 | ** individual database connections using the [sqlite3_open_v2()] interface | ||||
| 7475 | ** with the [SQLITE_OPEN_SHAREDCACHE] flag. | ||||
| 7476 | ** | ||||
| 7477 | ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 | ||||
| 7478 | ** and will always return SQLITE_MISUSE. On those systems, | ||||
| 7479 | ** shared cache mode should be enabled per-database connection via | ||||
| 7480 | ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. | ||||
| 7481 | ** | ||||
| 7482 | ** This interface is threadsafe on processors where writing a | ||||
| 7483 | ** 32-bit integer is atomic. | ||||
| 7484 | ** | ||||
| 7485 | ** See Also: [SQLite Shared-Cache Mode] | ||||
| 7486 | */ | ||||
| 7487 | SQLITE_API int sqlite3_enable_shared_cache(int); | ||||
| 7488 | |||||
| 7489 | /* | ||||
| 7490 | ** CAPI3REF: Attempt To Free Heap Memory | ||||
| 7491 | ** | ||||
| 7492 | ** ^The sqlite3_release_memory() interface attempts to free N bytes | ||||
| 7493 | ** of heap memory by deallocating non-essential memory allocations | ||||
| 7494 | ** held by the database library. Memory used to cache database | ||||
| 7495 | ** pages to improve performance is an example of non-essential memory. | ||||
| 7496 | ** ^sqlite3_release_memory() returns the number of bytes actually freed, | ||||
| 7497 | ** which might be more or less than the amount requested. | ||||
| 7498 | ** ^The sqlite3_release_memory() routine is a no-op returning zero | ||||
| 7499 | ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. | ||||
| 7500 | ** | ||||
| 7501 | ** See also: [sqlite3_db_release_memory()] | ||||
| 7502 | */ | ||||
| 7503 | SQLITE_API int sqlite3_release_memory(int); | ||||
| 7504 | |||||
| 7505 | /* | ||||
| 7506 | ** CAPI3REF: Free Memory Used By A Database Connection | ||||
| 7507 | ** METHOD: sqlite3 | ||||
| 7508 | ** | ||||
| 7509 | ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap | ||||
| 7510 | ** memory as possible from database connection D. Unlike the | ||||
| 7511 | ** [sqlite3_release_memory()] interface, this interface is in effect even | ||||
| 7512 | ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is | ||||
| 7513 | ** omitted. | ||||
| 7514 | ** | ||||
| 7515 | ** See also: [sqlite3_release_memory()] | ||||
| 7516 | */ | ||||
| 7517 | SQLITE_API int sqlite3_db_release_memory(sqlite3*); | ||||
| 7518 | |||||
| 7519 | /* | ||||
| 7520 | ** CAPI3REF: Impose A Limit On Heap Size | ||||
| 7521 | ** | ||||
| 7522 | ** These interfaces impose limits on the amount of heap memory that will be | ||||
| 7523 | ** used by all database connections within a single process. | ||||
| 7524 | ** | ||||
| 7525 | ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the | ||||
| 7526 | ** soft limit on the amount of heap memory that may be allocated by SQLite. | ||||
| 7527 | ** ^SQLite strives to keep heap memory utilization below the soft heap | ||||
| 7528 | ** limit by reducing the number of pages held in the page cache | ||||
| 7529 | ** as heap memory usages approaches the limit. | ||||
| 7530 | ** ^The soft heap limit is "soft" because even though SQLite strives to stay | ||||
| 7531 | ** below the limit, it will exceed the limit rather than generate | ||||
| 7532 | ** an [SQLITE_NOMEM] error. In other words, the soft heap limit | ||||
| 7533 | ** is advisory only. | ||||
| 7534 | ** | ||||
| 7535 | ** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of | ||||
| 7536 | ** N bytes on the amount of memory that will be allocated. ^The | ||||
| 7537 | ** sqlite3_hard_heap_limit64(N) interface is similar to | ||||
| 7538 | ** sqlite3_soft_heap_limit64(N) except that memory allocations will fail | ||||
| 7539 | ** when the hard heap limit is reached. | ||||
| 7540 | ** | ||||
| 7541 | ** ^The return value from both sqlite3_soft_heap_limit64() and | ||||
| 7542 | ** sqlite3_hard_heap_limit64() is the size of | ||||
| 7543 | ** the heap limit prior to the call, or negative in the case of an | ||||
| 7544 | ** error. ^If the argument N is negative | ||||
| 7545 | ** then no change is made to the heap limit. Hence, the current | ||||
| 7546 | ** size of heap limits can be determined by invoking | ||||
| 7547 | ** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1). | ||||
| 7548 | ** | ||||
| 7549 | ** ^Setting the heap limits to zero disables the heap limiter mechanism. | ||||
| 7550 | ** | ||||
| 7551 | ** ^The soft heap limit may not be greater than the hard heap limit. | ||||
| 7552 | ** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N) | ||||
| 7553 | ** is invoked with a value of N that is greater than the hard heap limit, | ||||
| 7554 | ** the soft heap limit is set to the value of the hard heap limit. | ||||
| 7555 | ** ^The soft heap limit is automatically enabled whenever the hard heap | ||||
| 7556 | ** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and | ||||
| 7557 | ** the soft heap limit is outside the range of 1..N, then the soft heap | ||||
| 7558 | ** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the | ||||
| 7559 | ** hard heap limit is enabled makes the soft heap limit equal to the | ||||
| 7560 | ** hard heap limit. | ||||
| 7561 | ** | ||||
| 7562 | ** The memory allocation limits can also be adjusted using | ||||
| 7563 | ** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit]. | ||||
| 7564 | ** | ||||
| 7565 | ** ^(The heap limits are not enforced in the current implementation | ||||
| 7566 | ** if one or more of following conditions are true: | ||||
| 7567 | ** | ||||
| 7568 | ** <ul> | ||||
| 7569 | ** <li> The limit value is set to zero. | ||||
| 7570 | ** <li> Memory accounting is disabled using a combination of the | ||||
| 7571 | ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and | ||||
| 7572 | ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. | ||||
| 7573 | ** <li> An alternative page cache implementation is specified using | ||||
| 7574 | ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). | ||||
| 7575 | ** <li> The page cache allocates from its own memory pool supplied | ||||
| 7576 | ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than | ||||
| 7577 | ** from the heap. | ||||
| 7578 | ** </ul>)^ | ||||
| 7579 | ** | ||||
| 7580 | ** The circumstances under which SQLite will enforce the heap limits may | ||||
| 7581 | ** change in future releases of SQLite. | ||||
| 7582 | */ | ||||
| 7583 | SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); | ||||
| 7584 | SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N); | ||||
| 7585 | |||||
| 7586 | /* | ||||
| 7587 | ** CAPI3REF: Deprecated Soft Heap Limit Interface | ||||
| 7588 | ** DEPRECATED | ||||
| 7589 | ** | ||||
| 7590 | ** This is a deprecated version of the [sqlite3_soft_heap_limit64()] | ||||
| 7591 | ** interface. This routine is provided for historical compatibility | ||||
| 7592 | ** only. All new applications should use the | ||||
| 7593 | ** [sqlite3_soft_heap_limit64()] interface rather than this one. | ||||
| 7594 | */ | ||||
| 7595 | SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); | ||||
| 7596 | |||||
| 7597 | |||||
| 7598 | /* | ||||
| 7599 | ** CAPI3REF: Extract Metadata About A Column Of A Table | ||||
| 7600 | ** METHOD: sqlite3 | ||||
| 7601 | ** | ||||
| 7602 | ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns | ||||
| 7603 | ** information about column C of table T in database D | ||||
| 7604 | ** on [database connection] X.)^ ^The sqlite3_table_column_metadata() | ||||
| 7605 | ** interface returns SQLITE_OK and fills in the non-NULL pointers in | ||||
| 7606 | ** the final five arguments with appropriate values if the specified | ||||
| 7607 | ** column exists. ^The sqlite3_table_column_metadata() interface returns | ||||
| 7608 | ** SQLITE_ERROR if the specified column does not exist. | ||||
| 7609 | ** ^If the column-name parameter to sqlite3_table_column_metadata() is a | ||||
| 7610 | ** NULL pointer, then this routine simply checks for the existence of the | ||||
| 7611 | ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it | ||||
| 7612 | ** does not. If the table name parameter T in a call to | ||||
| 7613 | ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is | ||||
| 7614 | ** undefined behavior. | ||||
| 7615 | ** | ||||
| 7616 | ** ^The column is identified by the second, third and fourth parameters to | ||||
| 7617 | ** this function. ^(The second parameter is either the name of the database | ||||
| 7618 | ** (i.e. "main", "temp", or an attached database) containing the specified | ||||
| 7619 | ** table or NULL.)^ ^If it is NULL, then all attached databases are searched | ||||
| 7620 | ** for the table using the same algorithm used by the database engine to | ||||
| 7621 | ** resolve unqualified table references. | ||||
| 7622 | ** | ||||
| 7623 | ** ^The third and fourth parameters to this function are the table and column | ||||
| 7624 | ** name of the desired column, respectively. | ||||
| 7625 | ** | ||||
| 7626 | ** ^Metadata is returned by writing to the memory locations passed as the 5th | ||||
| 7627 | ** and subsequent parameters to this function. ^Any of these arguments may be | ||||
| 7628 | ** NULL, in which case the corresponding element of metadata is omitted. | ||||
| 7629 | ** | ||||
| 7630 | ** ^(<blockquote> | ||||
| 7631 | ** <table border="1"> | ||||
| 7632 | ** <tr><th> Parameter <th> Output<br>Type <th> Description | ||||
| 7633 | ** | ||||
| 7634 | ** <tr><td> 5th <td> const char* <td> Data type | ||||
| 7635 | ** <tr><td> 6th <td> const char* <td> Name of default collation sequence | ||||
| 7636 | ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint | ||||
| 7637 | ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY | ||||
| 7638 | ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT] | ||||
| 7639 | ** </table> | ||||
| 7640 | ** </blockquote>)^ | ||||
| 7641 | ** | ||||
| 7642 | ** ^The memory pointed to by the character pointers returned for the | ||||
| 7643 | ** declaration type and collation sequence is valid until the next | ||||
| 7644 | ** call to any SQLite API function. | ||||
| 7645 | ** | ||||
| 7646 | ** ^If the specified table is actually a view, an [error code] is returned. | ||||
| 7647 | ** | ||||
| 7648 | ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table | ||||
| 7649 | ** is not a [WITHOUT ROWID] table and an | ||||
| 7650 | ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output | ||||
| 7651 | ** parameters are set for the explicitly declared column. ^(If there is no | ||||
| 7652 | ** [INTEGER PRIMARY KEY] column, then the outputs | ||||
| 7653 | ** for the [rowid] are set as follows: | ||||
| 7654 | ** | ||||
| 7655 | ** <pre> | ||||
| 7656 | ** data type: "INTEGER" | ||||
| 7657 | ** collation sequence: "BINARY" | ||||
| 7658 | ** not null: 0 | ||||
| 7659 | ** primary key: 1 | ||||
| 7660 | ** auto increment: 0 | ||||
| 7661 | ** </pre>)^ | ||||
| 7662 | ** | ||||
| 7663 | ** ^This function causes all database schemas to be read from disk and | ||||
| 7664 | ** parsed, if that has not already been done, and returns an error if | ||||
| 7665 | ** any errors are encountered while loading the schema. | ||||
| 7666 | */ | ||||
| 7667 | SQLITE_API int sqlite3_table_column_metadata( | ||||
| 7668 | sqlite3 *db, /* Connection handle */ | ||||
| 7669 | const char *zDbName, /* Database name or NULL */ | ||||
| 7670 | const char *zTableName, /* Table name */ | ||||
| 7671 | const char *zColumnName, /* Column name */ | ||||
| 7672 | char const **pzDataType, /* OUTPUT: Declared data type */ | ||||
| 7673 | char const **pzCollSeq, /* OUTPUT: Collation sequence name */ | ||||
| 7674 | int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ | ||||
| 7675 | int *pPrimaryKey, /* OUTPUT: True if column part of PK */ | ||||
| 7676 | int *pAutoinc /* OUTPUT: True if column is auto-increment */ | ||||
| 7677 | ); | ||||
| 7678 | |||||
| 7679 | /* | ||||
| 7680 | ** CAPI3REF: Load An Extension | ||||
| 7681 | ** METHOD: sqlite3 | ||||
| 7682 | ** | ||||
| 7683 | ** ^This interface loads an SQLite extension library from the named file. | ||||
| 7684 | ** | ||||
| 7685 | ** ^The sqlite3_load_extension() interface attempts to load an | ||||
| 7686 | ** [SQLite extension] library contained in the file zFile. If | ||||
| 7687 | ** the file cannot be loaded directly, attempts are made to load | ||||
| 7688 | ** with various operating-system specific extensions added. | ||||
| 7689 | ** So for example, if "samplelib" cannot be loaded, then names like | ||||
| 7690 | ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might | ||||
| 7691 | ** be tried also. | ||||
| 7692 | ** | ||||
| 7693 | ** ^The entry point is zProc. | ||||
| 7694 | ** ^(zProc may be 0, in which case SQLite will try to come up with an | ||||
| 7695 | ** entry point name on its own. It first tries "sqlite3_extension_init". | ||||
| 7696 | ** If that does not work, it constructs a name "sqlite3_X_init" where | ||||
| 7697 | ** X consists of the lower-case equivalent of all ASCII alphabetic | ||||
| 7698 | ** characters in the filename from the last "/" to the first following | ||||
| 7699 | ** "." and omitting any initial "lib".)^ | ||||
| 7700 | ** ^The sqlite3_load_extension() interface returns | ||||
| 7701 | ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. | ||||
| 7702 | ** ^If an error occurs and pzErrMsg is not 0, then the | ||||
| 7703 | ** [sqlite3_load_extension()] interface shall attempt to | ||||
| 7704 | ** fill *pzErrMsg with error message text stored in memory | ||||
| 7705 | ** obtained from [sqlite3_malloc()]. The calling function | ||||
| 7706 | ** should free this memory by calling [sqlite3_free()]. | ||||
| 7707 | ** | ||||
| 7708 | ** ^Extension loading must be enabled using | ||||
| 7709 | ** [sqlite3_enable_load_extension()] or | ||||
| 7710 | ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) | ||||
| 7711 | ** prior to calling this API, | ||||
| 7712 | ** otherwise an error will be returned. | ||||
| 7713 | ** | ||||
| 7714 | ** <b>Security warning:</b> It is recommended that the | ||||
| 7715 | ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this | ||||
| 7716 | ** interface. The use of the [sqlite3_enable_load_extension()] interface | ||||
| 7717 | ** should be avoided. This will keep the SQL function [load_extension()] | ||||
| 7718 | ** disabled and prevent SQL injections from giving attackers | ||||
| 7719 | ** access to extension loading capabilities. | ||||
| 7720 | ** | ||||
| 7721 | ** See also the [load_extension() SQL function]. | ||||
| 7722 | */ | ||||
| 7723 | SQLITE_API int sqlite3_load_extension( | ||||
| 7724 | sqlite3 *db, /* Load the extension into this database connection */ | ||||
| 7725 | const char *zFile, /* Name of the shared library containing extension */ | ||||
| 7726 | const char *zProc, /* Entry point. Derived from zFile if 0 */ | ||||
| 7727 | char **pzErrMsg /* Put error message here if not 0 */ | ||||
| 7728 | ); | ||||
| 7729 | |||||
| 7730 | /* | ||||
| 7731 | ** CAPI3REF: Enable Or Disable Extension Loading | ||||
| 7732 | ** METHOD: sqlite3 | ||||
| 7733 | ** | ||||
| 7734 | ** ^So as not to open security holes in older applications that are | ||||
| 7735 | ** unprepared to deal with [extension loading], and as a means of disabling | ||||
| 7736 | ** [extension loading] while evaluating user-entered SQL, the following API | ||||
| 7737 | ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. | ||||
| 7738 | ** | ||||
| 7739 | ** ^Extension loading is off by default. | ||||
| 7740 | ** ^Call the sqlite3_enable_load_extension() routine with onoff==1 | ||||
| 7741 | ** to turn extension loading on and call it with onoff==0 to turn | ||||
| 7742 | ** it back off again. | ||||
| 7743 | ** | ||||
| 7744 | ** ^This interface enables or disables both the C-API | ||||
| 7745 | ** [sqlite3_load_extension()] and the SQL function [load_extension()]. | ||||
| 7746 | ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) | ||||
| 7747 | ** to enable or disable only the C-API.)^ | ||||
| 7748 | ** | ||||
| 7749 | ** <b>Security warning:</b> It is recommended that extension loading | ||||
| 7750 | ** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method | ||||
| 7751 | ** rather than this interface, so the [load_extension()] SQL function | ||||
| 7752 | ** remains disabled. This will prevent SQL injections from giving attackers | ||||
| 7753 | ** access to extension loading capabilities. | ||||
| 7754 | */ | ||||
| 7755 | SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); | ||||
| 7756 | |||||
| 7757 | /* | ||||
| 7758 | ** CAPI3REF: Automatically Load Statically Linked Extensions | ||||
| 7759 | ** | ||||
| 7760 | ** ^This interface causes the xEntryPoint() function to be invoked for | ||||
| 7761 | ** each new [database connection] that is created. The idea here is that | ||||
| 7762 | ** xEntryPoint() is the entry point for a statically linked [SQLite extension] | ||||
| 7763 | ** that is to be automatically loaded into all new database connections. | ||||
| 7764 | ** | ||||
| 7765 | ** ^(Even though the function prototype shows that xEntryPoint() takes | ||||
| 7766 | ** no arguments and returns void, SQLite invokes xEntryPoint() with three | ||||
| 7767 | ** arguments and expects an integer result as if the signature of the | ||||
| 7768 | ** entry point were as follows: | ||||
| 7769 | ** | ||||
| 7770 | ** <blockquote><pre> | ||||
| 7771 | ** int xEntryPoint( | ||||
| 7772 | ** sqlite3 *db, | ||||
| 7773 | ** const char **pzErrMsg, | ||||
| 7774 | ** const struct sqlite3_api_routines *pThunk | ||||
| 7775 | ** ); | ||||
| 7776 | ** </pre></blockquote>)^ | ||||
| 7777 | ** | ||||
| 7778 | ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg | ||||
| 7779 | ** point to an appropriate error message (obtained from [sqlite3_mprintf()]) | ||||
| 7780 | ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg | ||||
| 7781 | ** is NULL before calling the xEntryPoint(). ^SQLite will invoke | ||||
| 7782 | ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any | ||||
| 7783 | ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], | ||||
| 7784 | ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. | ||||
| 7785 | ** | ||||
| 7786 | ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already | ||||
| 7787 | ** on the list of automatic extensions is a harmless no-op. ^No entry point | ||||
| 7788 | ** will be called more than once for each database connection that is opened. | ||||
| 7789 | ** | ||||
| 7790 | ** See also: [sqlite3_reset_auto_extension()] | ||||
| 7791 | ** and [sqlite3_cancel_auto_extension()] | ||||
| 7792 | */ | ||||
| 7793 | SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); | ||||
| 7794 | |||||
| 7795 | /* | ||||
| 7796 | ** CAPI3REF: Cancel Automatic Extension Loading | ||||
| 7797 | ** | ||||
| 7798 | ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the | ||||
| 7799 | ** initialization routine X that was registered using a prior call to | ||||
| 7800 | ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] | ||||
| 7801 | ** routine returns 1 if initialization routine X was successfully | ||||
| 7802 | ** unregistered and it returns 0 if X was not on the list of initialization | ||||
| 7803 | ** routines. | ||||
| 7804 | */ | ||||
| 7805 | SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); | ||||
| 7806 | |||||
| 7807 | /* | ||||
| 7808 | ** CAPI3REF: Reset Automatic Extension Loading | ||||
| 7809 | ** | ||||
| 7810 | ** ^This interface disables all automatic extensions previously | ||||
| 7811 | ** registered using [sqlite3_auto_extension()]. | ||||
| 7812 | */ | ||||
| 7813 | SQLITE_API void sqlite3_reset_auto_extension(void); | ||||
| 7814 | |||||
| 7815 | /* | ||||
| 7816 | ** Structures used by the virtual table interface | ||||
| 7817 | */ | ||||
| 7818 | typedef struct sqlite3_vtab sqlite3_vtab; | ||||
| 7819 | typedef struct sqlite3_index_info sqlite3_index_info; | ||||
| 7820 | typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; | ||||
| 7821 | typedef struct sqlite3_module sqlite3_module; | ||||
| 7822 | |||||
| 7823 | /* | ||||
| 7824 | ** CAPI3REF: Virtual Table Object | ||||
| 7825 | ** KEYWORDS: sqlite3_module {virtual table module} | ||||
| 7826 | ** | ||||
| 7827 | ** This structure, sometimes called a "virtual table module", | ||||
| 7828 | ** defines the implementation of a [virtual table]. | ||||
| 7829 | ** This structure consists mostly of methods for the module. | ||||
| 7830 | ** | ||||
| 7831 | ** ^A virtual table module is created by filling in a persistent | ||||
| 7832 | ** instance of this structure and passing a pointer to that instance | ||||
| 7833 | ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. | ||||
| 7834 | ** ^The registration remains valid until it is replaced by a different | ||||
| 7835 | ** module or until the [database connection] closes. The content | ||||
| 7836 | ** of this structure must not change while it is registered with | ||||
| 7837 | ** any database connection. | ||||
| 7838 | */ | ||||
| 7839 | struct sqlite3_module { | ||||
| 7840 | int iVersion; | ||||
| 7841 | int (*xCreate)(sqlite3*, void *pAux, | ||||
| 7842 | int argc, const char *const*argv, | ||||
| 7843 | sqlite3_vtab **ppVTab, char**); | ||||
| 7844 | int (*xConnect)(sqlite3*, void *pAux, | ||||
| 7845 | int argc, const char *const*argv, | ||||
| 7846 | sqlite3_vtab **ppVTab, char**); | ||||
| 7847 | int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); | ||||
| 7848 | int (*xDisconnect)(sqlite3_vtab *pVTab); | ||||
| 7849 | int (*xDestroy)(sqlite3_vtab *pVTab); | ||||
| 7850 | int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); | ||||
| 7851 | int (*xClose)(sqlite3_vtab_cursor*); | ||||
| 7852 | int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, | ||||
| 7853 | int argc, sqlite3_value **argv); | ||||
| 7854 | int (*xNext)(sqlite3_vtab_cursor*); | ||||
| 7855 | int (*xEof)(sqlite3_vtab_cursor*); | ||||
| 7856 | int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); | ||||
| 7857 | int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); | ||||
| 7858 | int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); | ||||
| 7859 | int (*xBegin)(sqlite3_vtab *pVTab); | ||||
| 7860 | int (*xSync)(sqlite3_vtab *pVTab); | ||||
| 7861 | int (*xCommit)(sqlite3_vtab *pVTab); | ||||
| 7862 | int (*xRollback)(sqlite3_vtab *pVTab); | ||||
| 7863 | int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, | ||||
| 7864 | void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), | ||||
| 7865 | void **ppArg); | ||||
| 7866 | int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); | ||||
| 7867 | /* The methods above are in version 1 of the sqlite_module object. Those | ||||
| 7868 | ** below are for version 2 and greater. */ | ||||
| 7869 | int (*xSavepoint)(sqlite3_vtab *pVTab, int); | ||||
| 7870 | int (*xRelease)(sqlite3_vtab *pVTab, int); | ||||
| 7871 | int (*xRollbackTo)(sqlite3_vtab *pVTab, int); | ||||
| 7872 | /* The methods above are in versions 1 and 2 of the sqlite_module object. | ||||
| 7873 | ** Those below are for version 3 and greater. */ | ||||
| 7874 | int (*xShadowName)(const char*); | ||||
| 7875 | /* The methods above are in versions 1 through 3 of the sqlite_module object. | ||||
| 7876 | ** Those below are for version 4 and greater. */ | ||||
| 7877 | int (*xIntegrity)(sqlite3_vtab *pVTab, const char *zSchema, | ||||
| 7878 | const char *zTabName, int mFlags, char **pzErr); | ||||
| 7879 | }; | ||||
| 7880 | |||||
| 7881 | /* | ||||
| 7882 | ** CAPI3REF: Virtual Table Indexing Information | ||||
| 7883 | ** KEYWORDS: sqlite3_index_info | ||||
| 7884 | ** | ||||
| 7885 | ** The sqlite3_index_info structure and its substructures is used as part | ||||
| 7886 | ** of the [virtual table] interface to | ||||
| 7887 | ** pass information into and receive the reply from the [xBestIndex] | ||||
| 7888 | ** method of a [virtual table module]. The fields under **Inputs** are the | ||||
| 7889 | ** inputs to xBestIndex and are read-only. xBestIndex inserts its | ||||
| 7890 | ** results into the **Outputs** fields. | ||||
| 7891 | ** | ||||
| 7892 | ** ^(The aConstraint[] array records WHERE clause constraints of the form: | ||||
| 7893 | ** | ||||
| 7894 | ** <blockquote>column OP expr</blockquote> | ||||
| 7895 | ** | ||||
| 7896 | ** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is | ||||
| 7897 | ** stored in aConstraint[].op using one of the | ||||
| 7898 | ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ | ||||
| 7899 | ** ^(The index of the column is stored in | ||||
| 7900 | ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the | ||||
| 7901 | ** expr on the right-hand side can be evaluated (and thus the constraint | ||||
| 7902 | ** is usable) and false if it cannot.)^ | ||||
| 7903 | ** | ||||
| 7904 | ** ^The optimizer automatically inverts terms of the form "expr OP column" | ||||
| 7905 | ** and makes other simplifications to the WHERE clause in an attempt to | ||||
| 7906 | ** get as many WHERE clause terms into the form shown above as possible. | ||||
| 7907 | ** ^The aConstraint[] array only reports WHERE clause terms that are | ||||
| 7908 | ** relevant to the particular virtual table being queried. | ||||
| 7909 | ** | ||||
| 7910 | ** ^Information about the ORDER BY clause is stored in aOrderBy[]. | ||||
| 7911 | ** ^Each term of aOrderBy records a column of the ORDER BY clause. | ||||
| 7912 | ** | ||||
| 7913 | ** The colUsed field indicates which columns of the virtual table may be | ||||
| 7914 | ** required by the current scan. Virtual table columns are numbered from | ||||
| 7915 | ** zero in the order in which they appear within the CREATE TABLE statement | ||||
| 7916 | ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), | ||||
| 7917 | ** the corresponding bit is set within the colUsed mask if the column may be | ||||
| 7918 | ** required by SQLite. If the table has at least 64 columns and any column | ||||
| 7919 | ** to the right of the first 63 is required, then bit 63 of colUsed is also | ||||
| 7920 | ** set. In other words, column iCol may be required if the expression | ||||
| 7921 | ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to | ||||
| 7922 | ** non-zero. | ||||
| 7923 | ** | ||||
| 7924 | ** The [xBestIndex] method must fill aConstraintUsage[] with information | ||||
| 7925 | ** about what parameters to pass to xFilter. ^If argvIndex>0 then | ||||
| 7926 | ** the right-hand side of the corresponding aConstraint[] is evaluated | ||||
| 7927 | ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit | ||||
| 7928 | ** is true, then the constraint is assumed to be fully handled by the | ||||
| 7929 | ** virtual table and might not be checked again by the byte code.)^ ^(The | ||||
| 7930 | ** aConstraintUsage[].omit flag is an optimization hint. When the omit flag | ||||
| 7931 | ** is left in its default setting of false, the constraint will always be | ||||
| 7932 | ** checked separately in byte code. If the omit flag is changed to true, then | ||||
| 7933 | ** the constraint may or may not be checked in byte code. In other words, | ||||
| 7934 | ** when the omit flag is true there is no guarantee that the constraint will | ||||
| 7935 | ** not be checked again using byte code.)^ | ||||
| 7936 | ** | ||||
| 7937 | ** ^The idxNum and idxStr values are recorded and passed into the | ||||
| 7938 | ** [xFilter] method. | ||||
| 7939 | ** ^[sqlite3_free()] is used to free idxStr if and only if | ||||
| 7940 | ** needToFreeIdxStr is true. | ||||
| 7941 | ** | ||||
| 7942 | ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in | ||||
| 7943 | ** the correct order to satisfy the ORDER BY clause so that no separate | ||||
| 7944 | ** sorting step is required. | ||||
| 7945 | ** | ||||
| 7946 | ** ^The estimatedCost value is an estimate of the cost of a particular | ||||
| 7947 | ** strategy. A cost of N indicates that the cost of the strategy is similar | ||||
| 7948 | ** to a linear scan of an SQLite table with N rows. A cost of log(N) | ||||
| 7949 | ** indicates that the expense of the operation is similar to that of a | ||||
| 7950 | ** binary search on a unique indexed field of an SQLite table with N rows. | ||||
| 7951 | ** | ||||
| 7952 | ** ^The estimatedRows value is an estimate of the number of rows that | ||||
| 7953 | ** will be returned by the strategy. | ||||
| 7954 | ** | ||||
| 7955 | ** The xBestIndex method may optionally populate the idxFlags field with a | ||||
| 7956 | ** mask of SQLITE_INDEX_SCAN_* flags. One such flag is | ||||
| 7957 | ** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN] | ||||
| 7958 | ** output to show the idxNum as hex instead of as decimal. Another flag is | ||||
| 7959 | ** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will | ||||
| 7960 | ** return at most one row. | ||||
| 7961 | ** | ||||
| 7962 | ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then | ||||
| 7963 | ** SQLite also assumes that if a call to the xUpdate() method is made as | ||||
| 7964 | ** part of the same statement to delete or update a virtual table row and the | ||||
| 7965 | ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback | ||||
| 7966 | ** any database changes. In other words, if the xUpdate() returns | ||||
| 7967 | ** SQLITE_CONSTRAINT, the database contents must be exactly as they were | ||||
| 7968 | ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not | ||||
| 7969 | ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by | ||||
| 7970 | ** the xUpdate method are automatically rolled back by SQLite. | ||||
| 7971 | ** | ||||
| 7972 | ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info | ||||
| 7973 | ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). | ||||
| 7974 | ** If a virtual table extension is | ||||
| 7975 | ** used with an SQLite version earlier than 3.8.2, the results of attempting | ||||
| 7976 | ** to read or write the estimatedRows field are undefined (but are likely | ||||
| 7977 | ** to include crashing the application). The estimatedRows field should | ||||
| 7978 | ** therefore only be used if [sqlite3_libversion_number()] returns a | ||||
| 7979 | ** value greater than or equal to 3008002. Similarly, the idxFlags field | ||||
| 7980 | ** was added for [version 3.9.0] ([dateof:3.9.0]). | ||||
| 7981 | ** It may therefore only be used if | ||||
| 7982 | ** sqlite3_libversion_number() returns a value greater than or equal to | ||||
| 7983 | ** 3009000. | ||||
| 7984 | */ | ||||
| 7985 | struct sqlite3_index_info { | ||||
| 7986 | /* Inputs */ | ||||
| 7987 | int nConstraint; /* Number of entries in aConstraint */ | ||||
| 7988 | struct sqlite3_index_constraint { | ||||
| 7989 | int iColumn; /* Column constrained. -1 for ROWID */ | ||||
| 7990 | unsigned char op; /* Constraint operator */ | ||||
| 7991 | unsigned char usable; /* True if this constraint is usable */ | ||||
| 7992 | int iTermOffset; /* Used internally - xBestIndex should ignore */ | ||||
| 7993 | } *aConstraint; /* Table of WHERE clause constraints */ | ||||
| 7994 | int nOrderBy; /* Number of terms in the ORDER BY clause */ | ||||
| 7995 | struct sqlite3_index_orderby { | ||||
| 7996 | int iColumn; /* Column number */ | ||||
| 7997 | unsigned char desc; /* True for DESC. False for ASC. */ | ||||
| 7998 | } *aOrderBy; /* The ORDER BY clause */ | ||||
| 7999 | /* Outputs */ | ||||
| 8000 | struct sqlite3_index_constraint_usage { | ||||
| 8001 | int argvIndex; /* if >0, constraint is part of argv to xFilter */ | ||||
| 8002 | unsigned char omit; /* Do not code a test for this constraint */ | ||||
| 8003 | } *aConstraintUsage; | ||||
| 8004 | int idxNum; /* Number used to identify the index */ | ||||
| 8005 | char *idxStr; /* String, possibly obtained from sqlite3_malloc */ | ||||
| 8006 | int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ | ||||
| 8007 | int orderByConsumed; /* True if output is already ordered */ | ||||
| 8008 | double estimatedCost; /* Estimated cost of using this index */ | ||||
| 8009 | /* Fields below are only available in SQLite 3.8.2 and later */ | ||||
| 8010 | sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ | ||||
| 8011 | /* Fields below are only available in SQLite 3.9.0 and later */ | ||||
| 8012 | int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ | ||||
| 8013 | /* Fields below are only available in SQLite 3.10.0 and later */ | ||||
| 8014 | sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ | ||||
| 8015 | }; | ||||
| 8016 | |||||
| 8017 | /* | ||||
| 8018 | ** CAPI3REF: Virtual Table Scan Flags | ||||
| 8019 | ** | ||||
| 8020 | ** Virtual table implementations are allowed to set the | ||||
| 8021 | ** [sqlite3_index_info].idxFlags field to some combination of | ||||
| 8022 | ** these bits. | ||||
| 8023 | */ | ||||
| 8024 | #define SQLITE_INDEX_SCAN_UNIQUE0x00000001 0x00000001 /* Scan visits at most 1 row */ | ||||
| 8025 | #define SQLITE_INDEX_SCAN_HEX0x00000002 0x00000002 /* Display idxNum as hex */ | ||||
| 8026 | /* in EXPLAIN QUERY PLAN */ | ||||
| 8027 | |||||
| 8028 | /* | ||||
| 8029 | ** CAPI3REF: Virtual Table Constraint Operator Codes | ||||
| 8030 | ** | ||||
| 8031 | ** These macros define the allowed values for the | ||||
| 8032 | ** [sqlite3_index_info].aConstraint[].op field. Each value represents | ||||
| 8033 | ** an operator that is part of a constraint term in the WHERE clause of | ||||
| 8034 | ** a query that uses a [virtual table]. | ||||
| 8035 | ** | ||||
| 8036 | ** ^The left-hand operand of the operator is given by the corresponding | ||||
| 8037 | ** aConstraint[].iColumn field. ^An iColumn of -1 indicates the left-hand | ||||
| 8038 | ** operand is the rowid. | ||||
| 8039 | ** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET | ||||
| 8040 | ** operators have no left-hand operand, and so for those operators the | ||||
| 8041 | ** corresponding aConstraint[].iColumn is meaningless and should not be | ||||
| 8042 | ** used. | ||||
| 8043 | ** | ||||
| 8044 | ** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through | ||||
| 8045 | ** value 255 are reserved to represent functions that are overloaded | ||||
| 8046 | ** by the [xFindFunction|xFindFunction method] of the virtual table | ||||
| 8047 | ** implementation. | ||||
| 8048 | ** | ||||
| 8049 | ** The right-hand operands for each constraint might be accessible using | ||||
| 8050 | ** the [sqlite3_vtab_rhs_value()] interface. Usually the right-hand | ||||
| 8051 | ** operand is only available if it appears as a single constant literal | ||||
| 8052 | ** in the input SQL. If the right-hand operand is another column or an | ||||
| 8053 | ** expression (even a constant expression) or a parameter, then the | ||||
| 8054 | ** sqlite3_vtab_rhs_value() probably will not be able to extract it. | ||||
| 8055 | ** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and | ||||
| 8056 | ** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand | ||||
| 8057 | ** and hence calls to sqlite3_vtab_rhs_value() for those operators will | ||||
| 8058 | ** always return SQLITE_NOTFOUND. | ||||
| 8059 | ** | ||||
| 8060 | ** The collating sequence to be used for comparison can be found using | ||||
| 8061 | ** the [sqlite3_vtab_collation()] interface. For most real-world virtual | ||||
| 8062 | ** tables, the collating sequence of constraints does not matter (for example | ||||
| 8063 | ** because the constraints are numeric) and so the sqlite3_vtab_collation() | ||||
| 8064 | ** interface is not commonly needed. | ||||
| 8065 | */ | ||||
| 8066 | #define SQLITE_INDEX_CONSTRAINT_EQ2 2 | ||||
| 8067 | #define SQLITE_INDEX_CONSTRAINT_GT4 4 | ||||
| 8068 | #define SQLITE_INDEX_CONSTRAINT_LE8 8 | ||||
| 8069 | #define SQLITE_INDEX_CONSTRAINT_LT16 16 | ||||
| 8070 | #define SQLITE_INDEX_CONSTRAINT_GE32 32 | ||||
| 8071 | #define SQLITE_INDEX_CONSTRAINT_MATCH64 64 | ||||
| 8072 | #define SQLITE_INDEX_CONSTRAINT_LIKE65 65 | ||||
| 8073 | #define SQLITE_INDEX_CONSTRAINT_GLOB66 66 | ||||
| 8074 | #define SQLITE_INDEX_CONSTRAINT_REGEXP67 67 | ||||
| 8075 | #define SQLITE_INDEX_CONSTRAINT_NE68 68 | ||||
| 8076 | #define SQLITE_INDEX_CONSTRAINT_ISNOT69 69 | ||||
| 8077 | #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL70 70 | ||||
| 8078 | #define SQLITE_INDEX_CONSTRAINT_ISNULL71 71 | ||||
| 8079 | #define SQLITE_INDEX_CONSTRAINT_IS72 72 | ||||
| 8080 | #define SQLITE_INDEX_CONSTRAINT_LIMIT73 73 | ||||
| 8081 | #define SQLITE_INDEX_CONSTRAINT_OFFSET74 74 | ||||
| 8082 | #define SQLITE_INDEX_CONSTRAINT_FUNCTION150 150 | ||||
| 8083 | |||||
| 8084 | /* | ||||
| 8085 | ** CAPI3REF: Register A Virtual Table Implementation | ||||
| 8086 | ** METHOD: sqlite3 | ||||
| 8087 | ** | ||||
| 8088 | ** ^These routines are used to register a new [virtual table module] name. | ||||
| 8089 | ** ^Module names must be registered before | ||||
| 8090 | ** creating a new [virtual table] using the module and before using a | ||||
| 8091 | ** preexisting [virtual table] for the module. | ||||
| 8092 | ** | ||||
| 8093 | ** ^The module name is registered on the [database connection] specified | ||||
| 8094 | ** by the first parameter. ^The name of the module is given by the | ||||
| 8095 | ** second parameter. ^The third parameter is a pointer to | ||||
| 8096 | ** the implementation of the [virtual table module]. ^The fourth | ||||
| 8097 | ** parameter is an arbitrary client data pointer that is passed through | ||||
| 8098 | ** into the [xCreate] and [xConnect] methods of the virtual table module | ||||
| 8099 | ** when a new virtual table is being created or reinitialized. | ||||
| 8100 | ** | ||||
| 8101 | ** ^The sqlite3_create_module_v2() interface has a fifth parameter which | ||||
| 8102 | ** is a pointer to a destructor for the pClientData. ^SQLite will | ||||
| 8103 | ** invoke the destructor function (if it is not NULL) when SQLite | ||||
| 8104 | ** no longer needs the pClientData pointer. ^The destructor will also | ||||
| 8105 | ** be invoked if the call to sqlite3_create_module_v2() fails. | ||||
| 8106 | ** ^The sqlite3_create_module() | ||||
| 8107 | ** interface is equivalent to sqlite3_create_module_v2() with a NULL | ||||
| 8108 | ** destructor. | ||||
| 8109 | ** | ||||
| 8110 | ** ^If the third parameter (the pointer to the sqlite3_module object) is | ||||
| 8111 | ** NULL then no new module is created and any existing modules with the | ||||
| 8112 | ** same name are dropped. | ||||
| 8113 | ** | ||||
| 8114 | ** See also: [sqlite3_drop_modules()] | ||||
| 8115 | */ | ||||
| 8116 | SQLITE_API int sqlite3_create_module( | ||||
| 8117 | sqlite3 *db, /* SQLite connection to register module with */ | ||||
| 8118 | const char *zName, /* Name of the module */ | ||||
| 8119 | const sqlite3_module *p, /* Methods for the module */ | ||||
| 8120 | void *pClientData /* Client data for xCreate/xConnect */ | ||||
| 8121 | ); | ||||
| 8122 | SQLITE_API int sqlite3_create_module_v2( | ||||
| 8123 | sqlite3 *db, /* SQLite connection to register module with */ | ||||
| 8124 | const char *zName, /* Name of the module */ | ||||
| 8125 | const sqlite3_module *p, /* Methods for the module */ | ||||
| 8126 | void *pClientData, /* Client data for xCreate/xConnect */ | ||||
| 8127 | void(*xDestroy)(void*) /* Module destructor function */ | ||||
| 8128 | ); | ||||
| 8129 | |||||
| 8130 | /* | ||||
| 8131 | ** CAPI3REF: Remove Unnecessary Virtual Table Implementations | ||||
| 8132 | ** METHOD: sqlite3 | ||||
| 8133 | ** | ||||
| 8134 | ** ^The sqlite3_drop_modules(D,L) interface removes all virtual | ||||
| 8135 | ** table modules from database connection D except those named on list L. | ||||
| 8136 | ** The L parameter must be either NULL or a pointer to an array of pointers | ||||
| 8137 | ** to strings where the array is terminated by a single NULL pointer. | ||||
| 8138 | ** ^If the L parameter is NULL, then all virtual table modules are removed. | ||||
| 8139 | ** | ||||
| 8140 | ** See also: [sqlite3_create_module()] | ||||
| 8141 | */ | ||||
| 8142 | SQLITE_API int sqlite3_drop_modules( | ||||
| 8143 | sqlite3 *db, /* Remove modules from this connection */ | ||||
| 8144 | const char **azKeep /* Except, do not remove the ones named here */ | ||||
| 8145 | ); | ||||
| 8146 | |||||
| 8147 | /* | ||||
| 8148 | ** CAPI3REF: Virtual Table Instance Object | ||||
| 8149 | ** KEYWORDS: sqlite3_vtab | ||||
| 8150 | ** | ||||
| 8151 | ** Every [virtual table module] implementation uses a subclass | ||||
| 8152 | ** of this object to describe a particular instance | ||||
| 8153 | ** of the [virtual table]. Each subclass will | ||||
| 8154 | ** be tailored to the specific needs of the module implementation. | ||||
| 8155 | ** The purpose of this superclass is to define certain fields that are | ||||
| 8156 | ** common to all module implementations. | ||||
| 8157 | ** | ||||
| 8158 | ** ^Virtual tables methods can set an error message by assigning a | ||||
| 8159 | ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should | ||||
| 8160 | ** take care that any prior string is freed by a call to [sqlite3_free()] | ||||
| 8161 | ** prior to assigning a new string to zErrMsg. ^After the error message | ||||
| 8162 | ** is delivered up to the client application, the string will be automatically | ||||
| 8163 | ** freed by sqlite3_free() and the zErrMsg field will be zeroed. | ||||
| 8164 | */ | ||||
| 8165 | struct sqlite3_vtab { | ||||
| 8166 | const sqlite3_module *pModule; /* The module for this virtual table */ | ||||
| 8167 | int nRef; /* Number of open cursors */ | ||||
| 8168 | char *zErrMsg; /* Error message from sqlite3_mprintf() */ | ||||
| 8169 | /* Virtual table implementations will typically add additional fields */ | ||||
| 8170 | }; | ||||
| 8171 | |||||
| 8172 | /* | ||||
| 8173 | ** CAPI3REF: Virtual Table Cursor Object | ||||
| 8174 | ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} | ||||
| 8175 | ** | ||||
| 8176 | ** Every [virtual table module] implementation uses a subclass of the | ||||
| 8177 | ** following structure to describe cursors that point into the | ||||
| 8178 | ** [virtual table] and are used | ||||
| 8179 | ** to loop through the virtual table. Cursors are created using the | ||||
| 8180 | ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed | ||||
| 8181 | ** by the [sqlite3_module.xClose | xClose] method. Cursors are used | ||||
| 8182 | ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods | ||||
| 8183 | ** of the module. Each module implementation will define | ||||
| 8184 | ** the content of a cursor structure to suit its own needs. | ||||
| 8185 | ** | ||||
| 8186 | ** This superclass exists in order to define fields of the cursor that | ||||
| 8187 | ** are common to all implementations. | ||||
| 8188 | */ | ||||
| 8189 | struct sqlite3_vtab_cursor { | ||||
| 8190 | sqlite3_vtab *pVtab; /* Virtual table of this cursor */ | ||||
| 8191 | /* Virtual table implementations will typically add additional fields */ | ||||
| 8192 | }; | ||||
| 8193 | |||||
| 8194 | /* | ||||
| 8195 | ** CAPI3REF: Declare The Schema Of A Virtual Table | ||||
| 8196 | ** | ||||
| 8197 | ** ^The [xCreate] and [xConnect] methods of a | ||||
| 8198 | ** [virtual table module] call this interface | ||||
| 8199 | ** to declare the format (the names and datatypes of the columns) of | ||||
| 8200 | ** the virtual tables they implement. | ||||
| 8201 | */ | ||||
| 8202 | SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); | ||||
| 8203 | |||||
| 8204 | /* | ||||
| 8205 | ** CAPI3REF: Overload A Function For A Virtual Table | ||||
| 8206 | ** METHOD: sqlite3 | ||||
| 8207 | ** | ||||
| 8208 | ** ^(Virtual tables can provide alternative implementations of functions | ||||
| 8209 | ** using the [xFindFunction] method of the [virtual table module]. | ||||
| 8210 | ** But global versions of those functions | ||||
| 8211 | ** must exist in order to be overloaded.)^ | ||||
| 8212 | ** | ||||
| 8213 | ** ^(This API makes sure a global version of a function with a particular | ||||
| 8214 | ** name and number of parameters exists. If no such function exists | ||||
| 8215 | ** before this API is called, a new function is created.)^ ^The implementation | ||||
| 8216 | ** of the new function always causes an exception to be thrown. So | ||||
| 8217 | ** the new function is not good for anything by itself. Its only | ||||
| 8218 | ** purpose is to be a placeholder function that can be overloaded | ||||
| 8219 | ** by a [virtual table]. | ||||
| 8220 | */ | ||||
| 8221 | SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); | ||||
| 8222 | |||||
| 8223 | /* | ||||
| 8224 | ** CAPI3REF: A Handle To An Open BLOB | ||||
| 8225 | ** KEYWORDS: {BLOB handle} {BLOB handles} | ||||
| 8226 | ** | ||||
| 8227 | ** An instance of this object represents an open BLOB on which | ||||
| 8228 | ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. | ||||
| 8229 | ** ^Objects of this type are created by [sqlite3_blob_open()] | ||||
| 8230 | ** and destroyed by [sqlite3_blob_close()]. | ||||
| 8231 | ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces | ||||
| 8232 | ** can be used to read or write small subsections of the BLOB. | ||||
| 8233 | ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. | ||||
| 8234 | */ | ||||
| 8235 | typedef struct sqlite3_blob sqlite3_blob; | ||||
| 8236 | |||||
| 8237 | /* | ||||
| 8238 | ** CAPI3REF: Open A BLOB For Incremental I/O | ||||
| 8239 | ** METHOD: sqlite3 | ||||
| 8240 | ** CONSTRUCTOR: sqlite3_blob | ||||
| 8241 | ** | ||||
| 8242 | ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located | ||||
| 8243 | ** in row iRow, column zColumn, table zTable in database zDb; | ||||
| 8244 | ** in other words, the same BLOB that would be selected by: | ||||
| 8245 | ** | ||||
| 8246 | ** <pre> | ||||
| 8247 | ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow; | ||||
| 8248 | ** </pre>)^ | ||||
| 8249 | ** | ||||
| 8250 | ** ^(Parameter zDb is not the filename that contains the database, but | ||||
| 8251 | ** rather the symbolic name of the database. For attached databases, this is | ||||
| 8252 | ** the name that appears after the AS keyword in the [ATTACH] statement. | ||||
| 8253 | ** For the main database file, the database name is "main". For TEMP | ||||
| 8254 | ** tables, the database name is "temp".)^ | ||||
| 8255 | ** | ||||
| 8256 | ** ^If the flags parameter is non-zero, then the BLOB is opened for read | ||||
| 8257 | ** and write access. ^If the flags parameter is zero, the BLOB is opened for | ||||
| 8258 | ** read-only access. | ||||
| 8259 | ** | ||||
| 8260 | ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored | ||||
| 8261 | ** in *ppBlob. Otherwise an [error code] is returned and, unless the error | ||||
| 8262 | ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided | ||||
| 8263 | ** the API is not misused, it is always safe to call [sqlite3_blob_close()] | ||||
| 8264 | ** on *ppBlob after this function returns. | ||||
| 8265 | ** | ||||
| 8266 | ** This function fails with SQLITE_ERROR if any of the following are true: | ||||
| 8267 | ** <ul> | ||||
| 8268 | ** <li> ^(Database zDb does not exist)^, | ||||
| 8269 | ** <li> ^(Table zTable does not exist within database zDb)^, | ||||
| 8270 | ** <li> ^(Table zTable is a WITHOUT ROWID table)^, | ||||
| 8271 | ** <li> ^(Column zColumn does not exist)^, | ||||
| 8272 | ** <li> ^(Row iRow is not present in the table)^, | ||||
| 8273 | ** <li> ^(The specified column of row iRow contains a value that is not | ||||
| 8274 | ** a TEXT or BLOB value)^, | ||||
| 8275 | ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE | ||||
| 8276 | ** constraint and the blob is being opened for read/write access)^, | ||||
| 8277 | ** <li> ^([foreign key constraints | Foreign key constraints] are enabled, | ||||
| 8278 | ** column zColumn is part of a [child key] definition and the blob is | ||||
| 8279 | ** being opened for read/write access)^. | ||||
| 8280 | ** </ul> | ||||
| 8281 | ** | ||||
| 8282 | ** ^Unless it returns SQLITE_MISUSE, this function sets the | ||||
| 8283 | ** [database connection] error code and message accessible via | ||||
| 8284 | ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. | ||||
| 8285 | ** | ||||
| 8286 | ** A BLOB referenced by sqlite3_blob_open() may be read using the | ||||
| 8287 | ** [sqlite3_blob_read()] interface and modified by using | ||||
| 8288 | ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a | ||||
| 8289 | ** different row of the same table using the [sqlite3_blob_reopen()] | ||||
| 8290 | ** interface. However, the column, table, or database of a [BLOB handle] | ||||
| 8291 | ** cannot be changed after the [BLOB handle] is opened. | ||||
| 8292 | ** | ||||
| 8293 | ** ^(If the row that a BLOB handle points to is modified by an | ||||
| 8294 | ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects | ||||
| 8295 | ** then the BLOB handle is marked as "expired". | ||||
| 8296 | ** This is true if any column of the row is changed, even a column | ||||
| 8297 | ** other than the one the BLOB handle is open on.)^ | ||||
| 8298 | ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for | ||||
| 8299 | ** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. | ||||
| 8300 | ** ^(Changes written into a BLOB prior to the BLOB expiring are not | ||||
| 8301 | ** rolled back by the expiration of the BLOB. Such changes will eventually | ||||
| 8302 | ** commit if the transaction continues to completion.)^ | ||||
| 8303 | ** | ||||
| 8304 | ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of | ||||
| 8305 | ** the opened blob. ^The size of a blob may not be changed by this | ||||
| 8306 | ** interface. Use the [UPDATE] SQL command to change the size of a | ||||
| 8307 | ** blob. | ||||
| 8308 | ** | ||||
| 8309 | ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces | ||||
| 8310 | ** and the built-in [zeroblob] SQL function may be used to create a | ||||
| 8311 | ** zero-filled blob to read or write using the incremental-blob interface. | ||||
| 8312 | ** | ||||
| 8313 | ** To avoid a resource leak, every open [BLOB handle] should eventually | ||||
| 8314 | ** be released by a call to [sqlite3_blob_close()]. | ||||
| 8315 | ** | ||||
| 8316 | ** See also: [sqlite3_blob_close()], | ||||
| 8317 | ** [sqlite3_blob_reopen()], [sqlite3_blob_read()], | ||||
| 8318 | ** [sqlite3_blob_bytes()], [sqlite3_blob_write()]. | ||||
| 8319 | */ | ||||
| 8320 | SQLITE_API int sqlite3_blob_open( | ||||
| 8321 | sqlite3*, | ||||
| 8322 | const char *zDb, | ||||
| 8323 | const char *zTable, | ||||
| 8324 | const char *zColumn, | ||||
| 8325 | sqlite3_int64 iRow, | ||||
| 8326 | int flags, | ||||
| 8327 | sqlite3_blob **ppBlob | ||||
| 8328 | ); | ||||
| 8329 | |||||
| 8330 | /* | ||||
| 8331 | ** CAPI3REF: Move a BLOB Handle to a New Row | ||||
| 8332 | ** METHOD: sqlite3_blob | ||||
| 8333 | ** | ||||
| 8334 | ** ^This function is used to move an existing [BLOB handle] so that it points | ||||
| 8335 | ** to a different row of the same database table. ^The new row is identified | ||||
| 8336 | ** by the rowid value passed as the second argument. Only the row can be | ||||
| 8337 | ** changed. ^The database, table and column on which the blob handle is open | ||||
| 8338 | ** remain the same. Moving an existing [BLOB handle] to a new row is | ||||
| 8339 | ** faster than closing the existing handle and opening a new one. | ||||
| 8340 | ** | ||||
| 8341 | ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - | ||||
| 8342 | ** it must exist and there must be either a blob or text value stored in | ||||
| 8343 | ** the nominated column.)^ ^If the new row is not present in the table, or if | ||||
| 8344 | ** it does not contain a blob or text value, or if another error occurs, an | ||||
| 8345 | ** SQLite error code is returned and the blob handle is considered aborted. | ||||
| 8346 | ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or | ||||
| 8347 | ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return | ||||
| 8348 | ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle | ||||
| 8349 | ** always returns zero. | ||||
| 8350 | ** | ||||
| 8351 | ** ^This function sets the database handle error code and message. | ||||
| 8352 | */ | ||||
| 8353 | SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); | ||||
| 8354 | |||||
| 8355 | /* | ||||
| 8356 | ** CAPI3REF: Close A BLOB Handle | ||||
| 8357 | ** DESTRUCTOR: sqlite3_blob | ||||
| 8358 | ** | ||||
| 8359 | ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed | ||||
| 8360 | ** unconditionally. Even if this routine returns an error code, the | ||||
| 8361 | ** handle is still closed.)^ | ||||
| 8362 | ** | ||||
| 8363 | ** ^If the blob handle being closed was opened for read-write access, and if | ||||
| 8364 | ** the database is in auto-commit mode and there are no other open read-write | ||||
| 8365 | ** blob handles or active write statements, the current transaction is | ||||
| 8366 | ** committed. ^If an error occurs while committing the transaction, an error | ||||
| 8367 | ** code is returned and the transaction rolled back. | ||||
| 8368 | ** | ||||
| 8369 | ** Calling this function with an argument that is not a NULL pointer or an | ||||
| 8370 | ** open blob handle results in undefined behavior. ^Calling this routine | ||||
| 8371 | ** with a null pointer (such as would be returned by a failed call to | ||||
| 8372 | ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function | ||||
| 8373 | ** is passed a valid open blob handle, the values returned by the | ||||
| 8374 | ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. | ||||
| 8375 | */ | ||||
| 8376 | SQLITE_API int sqlite3_blob_close(sqlite3_blob *); | ||||
| 8377 | |||||
| 8378 | /* | ||||
| 8379 | ** CAPI3REF: Return The Size Of An Open BLOB | ||||
| 8380 | ** METHOD: sqlite3_blob | ||||
| 8381 | ** | ||||
| 8382 | ** ^Returns the size in bytes of the BLOB accessible via the | ||||
| 8383 | ** successfully opened [BLOB handle] in its only argument. ^The | ||||
| 8384 | ** incremental blob I/O routines can only read or overwrite existing | ||||
| 8385 | ** blob content; they cannot change the size of a blob. | ||||
| 8386 | ** | ||||
| 8387 | ** This routine only works on a [BLOB handle] which has been created | ||||
| 8388 | ** by a prior successful call to [sqlite3_blob_open()] and which has not | ||||
| 8389 | ** been closed by [sqlite3_blob_close()]. Passing any other pointer in | ||||
| 8390 | ** to this routine results in undefined and probably undesirable behavior. | ||||
| 8391 | */ | ||||
| 8392 | SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); | ||||
| 8393 | |||||
| 8394 | /* | ||||
| 8395 | ** CAPI3REF: Read Data From A BLOB Incrementally | ||||
| 8396 | ** METHOD: sqlite3_blob | ||||
| 8397 | ** | ||||
| 8398 | ** ^(This function is used to read data from an open [BLOB handle] into a | ||||
| 8399 | ** caller-supplied buffer. N bytes of data are copied into buffer Z | ||||
| 8400 | ** from the open BLOB, starting at offset iOffset.)^ | ||||
| 8401 | ** | ||||
| 8402 | ** ^If offset iOffset is less than N bytes from the end of the BLOB, | ||||
| 8403 | ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is | ||||
| 8404 | ** less than zero, [SQLITE_ERROR] is returned and no data is read. | ||||
| 8405 | ** ^The size of the blob (and hence the maximum value of N+iOffset) | ||||
| 8406 | ** can be determined using the [sqlite3_blob_bytes()] interface. | ||||
| 8407 | ** | ||||
| 8408 | ** ^An attempt to read from an expired [BLOB handle] fails with an | ||||
| 8409 | ** error code of [SQLITE_ABORT]. | ||||
| 8410 | ** | ||||
| 8411 | ** ^(On success, sqlite3_blob_read() returns SQLITE_OK. | ||||
| 8412 | ** Otherwise, an [error code] or an [extended error code] is returned.)^ | ||||
| 8413 | ** | ||||
| 8414 | ** This routine only works on a [BLOB handle] which has been created | ||||
| 8415 | ** by a prior successful call to [sqlite3_blob_open()] and which has not | ||||
| 8416 | ** been closed by [sqlite3_blob_close()]. Passing any other pointer in | ||||
| 8417 | ** to this routine results in undefined and probably undesirable behavior. | ||||
| 8418 | ** | ||||
| 8419 | ** See also: [sqlite3_blob_write()]. | ||||
| 8420 | */ | ||||
| 8421 | SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); | ||||
| 8422 | |||||
| 8423 | /* | ||||
| 8424 | ** CAPI3REF: Write Data Into A BLOB Incrementally | ||||
| 8425 | ** METHOD: sqlite3_blob | ||||
| 8426 | ** | ||||
| 8427 | ** ^(This function is used to write data into an open [BLOB handle] from a | ||||
| 8428 | ** caller-supplied buffer. N bytes of data are copied from the buffer Z | ||||
| 8429 | ** into the open BLOB, starting at offset iOffset.)^ | ||||
| 8430 | ** | ||||
| 8431 | ** ^(On success, sqlite3_blob_write() returns SQLITE_OK. | ||||
| 8432 | ** Otherwise, an [error code] or an [extended error code] is returned.)^ | ||||
| 8433 | ** ^Unless SQLITE_MISUSE is returned, this function sets the | ||||
| 8434 | ** [database connection] error code and message accessible via | ||||
| 8435 | ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. | ||||
| 8436 | ** | ||||
| 8437 | ** ^If the [BLOB handle] passed as the first argument was not opened for | ||||
| 8438 | ** writing (the flags parameter to [sqlite3_blob_open()] was zero), | ||||
| 8439 | ** this function returns [SQLITE_READONLY]. | ||||
| 8440 | ** | ||||
| 8441 | ** This function may only modify the contents of the BLOB; it is | ||||
| 8442 | ** not possible to increase the size of a BLOB using this API. | ||||
| 8443 | ** ^If offset iOffset is less than N bytes from the end of the BLOB, | ||||
| 8444 | ** [SQLITE_ERROR] is returned and no data is written. The size of the | ||||
| 8445 | ** BLOB (and hence the maximum value of N+iOffset) can be determined | ||||
| 8446 | ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less | ||||
| 8447 | ** than zero [SQLITE_ERROR] is returned and no data is written. | ||||
| 8448 | ** | ||||
| 8449 | ** ^An attempt to write to an expired [BLOB handle] fails with an | ||||
| 8450 | ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred | ||||
| 8451 | ** before the [BLOB handle] expired are not rolled back by the | ||||
| 8452 | ** expiration of the handle, though of course those changes might | ||||
| 8453 | ** have been overwritten by the statement that expired the BLOB handle | ||||
| 8454 | ** or by other independent statements. | ||||
| 8455 | ** | ||||
| 8456 | ** This routine only works on a [BLOB handle] which has been created | ||||
| 8457 | ** by a prior successful call to [sqlite3_blob_open()] and which has not | ||||
| 8458 | ** been closed by [sqlite3_blob_close()]. Passing any other pointer in | ||||
| 8459 | ** to this routine results in undefined and probably undesirable behavior. | ||||
| 8460 | ** | ||||
| 8461 | ** See also: [sqlite3_blob_read()]. | ||||
| 8462 | */ | ||||
| 8463 | SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); | ||||
| 8464 | |||||
| 8465 | /* | ||||
| 8466 | ** CAPI3REF: Virtual File System Objects | ||||
| 8467 | ** | ||||
| 8468 | ** A virtual filesystem (VFS) is an [sqlite3_vfs] object | ||||
| 8469 | ** that SQLite uses to interact | ||||
| 8470 | ** with the underlying operating system. Most SQLite builds come with a | ||||
| 8471 | ** single default VFS that is appropriate for the host computer. | ||||
| 8472 | ** New VFSes can be registered and existing VFSes can be unregistered. | ||||
| 8473 | ** The following interfaces are provided. | ||||
| 8474 | ** | ||||
| 8475 | ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. | ||||
| 8476 | ** ^Names are case sensitive. | ||||
| 8477 | ** ^Names are zero-terminated UTF-8 strings. | ||||
| 8478 | ** ^If there is no match, a NULL pointer is returned. | ||||
| 8479 | ** ^If zVfsName is NULL then the default VFS is returned. | ||||
| 8480 | ** | ||||
| 8481 | ** ^New VFSes are registered with sqlite3_vfs_register(). | ||||
| 8482 | ** ^Each new VFS becomes the default VFS if the makeDflt flag is set. | ||||
| 8483 | ** ^The same VFS can be registered multiple times without injury. | ||||
| 8484 | ** ^To make an existing VFS into the default VFS, register it again | ||||
| 8485 | ** with the makeDflt flag set. If two different VFSes with the | ||||
| 8486 | ** same name are registered, the behavior is undefined. If a | ||||
| 8487 | ** VFS is registered with a name that is NULL or an empty string, | ||||
| 8488 | ** then the behavior is undefined. | ||||
| 8489 | ** | ||||
| 8490 | ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. | ||||
| 8491 | ** ^(If the default VFS is unregistered, another VFS is chosen as | ||||
| 8492 | ** the default. The choice for the new VFS is arbitrary.)^ | ||||
| 8493 | */ | ||||
| 8494 | SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); | ||||
| 8495 | SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); | ||||
| 8496 | SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); | ||||
| 8497 | |||||
| 8498 | /* | ||||
| 8499 | ** CAPI3REF: Mutexes | ||||
| 8500 | ** | ||||
| 8501 | ** The SQLite core uses these routines for thread | ||||
| 8502 | ** synchronization. Though they are intended for internal | ||||
| 8503 | ** use by SQLite, code that links against SQLite is | ||||
| 8504 | ** permitted to use any of these routines. | ||||
| 8505 | ** | ||||
| 8506 | ** The SQLite source code contains multiple implementations | ||||
| 8507 | ** of these mutex routines. An appropriate implementation | ||||
| 8508 | ** is selected automatically at compile-time. The following | ||||
| 8509 | ** implementations are available in the SQLite core: | ||||
| 8510 | ** | ||||
| 8511 | ** <ul> | ||||
| 8512 | ** <li> SQLITE_MUTEX_PTHREADS | ||||
| 8513 | ** <li> SQLITE_MUTEX_W32 | ||||
| 8514 | ** <li> SQLITE_MUTEX_NOOP | ||||
| 8515 | ** </ul> | ||||
| 8516 | ** | ||||
| 8517 | ** The SQLITE_MUTEX_NOOP implementation is a set of routines | ||||
| 8518 | ** that does no real locking and is appropriate for use in | ||||
| 8519 | ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and | ||||
| 8520 | ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix | ||||
| 8521 | ** and Windows. | ||||
| 8522 | ** | ||||
| 8523 | ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor | ||||
| 8524 | ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex | ||||
| 8525 | ** implementation is included with the library. In this case the | ||||
| 8526 | ** application must supply a custom mutex implementation using the | ||||
| 8527 | ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function | ||||
| 8528 | ** before calling sqlite3_initialize() or any other public sqlite3_ | ||||
| 8529 | ** function that calls sqlite3_initialize(). | ||||
| 8530 | ** | ||||
| 8531 | ** ^The sqlite3_mutex_alloc() routine allocates a new | ||||
| 8532 | ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() | ||||
| 8533 | ** routine returns NULL if it is unable to allocate the requested | ||||
| 8534 | ** mutex. The argument to sqlite3_mutex_alloc() must be one of these | ||||
| 8535 | ** integer constants: | ||||
| 8536 | ** | ||||
| 8537 | ** <ul> | ||||
| 8538 | ** <li> SQLITE_MUTEX_FAST | ||||
| 8539 | ** <li> SQLITE_MUTEX_RECURSIVE | ||||
| 8540 | ** <li> SQLITE_MUTEX_STATIC_MAIN | ||||
| 8541 | ** <li> SQLITE_MUTEX_STATIC_MEM | ||||
| 8542 | ** <li> SQLITE_MUTEX_STATIC_OPEN | ||||
| 8543 | ** <li> SQLITE_MUTEX_STATIC_PRNG | ||||
| 8544 | ** <li> SQLITE_MUTEX_STATIC_LRU | ||||
| 8545 | ** <li> SQLITE_MUTEX_STATIC_PMEM | ||||
| 8546 | ** <li> SQLITE_MUTEX_STATIC_APP1 | ||||
| 8547 | ** <li> SQLITE_MUTEX_STATIC_APP2 | ||||
| 8548 | ** <li> SQLITE_MUTEX_STATIC_APP3 | ||||
| 8549 | ** <li> SQLITE_MUTEX_STATIC_VFS1 | ||||
| 8550 | ** <li> SQLITE_MUTEX_STATIC_VFS2 | ||||
| 8551 | ** <li> SQLITE_MUTEX_STATIC_VFS3 | ||||
| 8552 | ** </ul> | ||||
| 8553 | ** | ||||
| 8554 | ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) | ||||
| 8555 | ** cause sqlite3_mutex_alloc() to create | ||||
| 8556 | ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE | ||||
| 8557 | ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. | ||||
| 8558 | ** The mutex implementation does not need to make a distinction | ||||
| 8559 | ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does | ||||
| 8560 | ** not want to. SQLite will only request a recursive mutex in | ||||
| 8561 | ** cases where it really needs one. If a faster non-recursive mutex | ||||
| 8562 | ** implementation is available on the host platform, the mutex subsystem | ||||
| 8563 | ** might return such a mutex in response to SQLITE_MUTEX_FAST. | ||||
| 8564 | ** | ||||
| 8565 | ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other | ||||
| 8566 | ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return | ||||
| 8567 | ** a pointer to a static preexisting mutex. ^Nine static mutexes are | ||||
| 8568 | ** used by the current version of SQLite. Future versions of SQLite | ||||
| 8569 | ** may add additional static mutexes. Static mutexes are for internal | ||||
| 8570 | ** use by SQLite only. Applications that use SQLite mutexes should | ||||
| 8571 | ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or | ||||
| 8572 | ** SQLITE_MUTEX_RECURSIVE. | ||||
| 8573 | ** | ||||
| 8574 | ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST | ||||
| 8575 | ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() | ||||
| 8576 | ** returns a different mutex on every call. ^For the static | ||||
| 8577 | ** mutex types, the same mutex is returned on every call that has | ||||
| 8578 | ** the same type number. | ||||
| 8579 | ** | ||||
| 8580 | ** ^The sqlite3_mutex_free() routine deallocates a previously | ||||
| 8581 | ** allocated dynamic mutex. Attempting to deallocate a static | ||||
| 8582 | ** mutex results in undefined behavior. | ||||
| 8583 | ** | ||||
| 8584 | ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt | ||||
| 8585 | ** to enter a mutex. ^If another thread is already within the mutex, | ||||
| 8586 | ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return | ||||
| 8587 | ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] | ||||
| 8588 | ** upon successful entry. ^(Mutexes created using | ||||
| 8589 | ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. | ||||
| 8590 | ** In such cases, the | ||||
| 8591 | ** mutex must be exited an equal number of times before another thread | ||||
| 8592 | ** can enter.)^ If the same thread tries to enter any mutex other | ||||
| 8593 | ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. | ||||
| 8594 | ** | ||||
| 8595 | ** ^(Some systems (for example, Windows 95) do not support the operation | ||||
| 8596 | ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() | ||||
| 8597 | ** will always return SQLITE_BUSY. In most cases the SQLite core only uses | ||||
| 8598 | ** sqlite3_mutex_try() as an optimization, so this is acceptable | ||||
| 8599 | ** behavior. The exceptions are unix builds that set the | ||||
| 8600 | ** SQLITE_ENABLE_SETLK_TIMEOUT build option. In that case a working | ||||
| 8601 | ** sqlite3_mutex_try() is required.)^ | ||||
| 8602 | ** | ||||
| 8603 | ** ^The sqlite3_mutex_leave() routine exits a mutex that was | ||||
| 8604 | ** previously entered by the same thread. The behavior | ||||
| 8605 | ** is undefined if the mutex is not currently entered by the | ||||
| 8606 | ** calling thread or is not currently allocated. | ||||
| 8607 | ** | ||||
| 8608 | ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), | ||||
| 8609 | ** sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer, | ||||
| 8610 | ** then any of the four routines behaves as a no-op. | ||||
| 8611 | ** | ||||
| 8612 | ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. | ||||
| 8613 | */ | ||||
| 8614 | SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); | ||||
| 8615 | SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); | ||||
| 8616 | SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); | ||||
| 8617 | SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); | ||||
| 8618 | SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); | ||||
| 8619 | |||||
| 8620 | /* | ||||
| 8621 | ** CAPI3REF: Mutex Methods Object | ||||
| 8622 | ** | ||||
| 8623 | ** An instance of this structure defines the low-level routines | ||||
| 8624 | ** used to allocate and use mutexes. | ||||
| 8625 | ** | ||||
| 8626 | ** Usually, the default mutex implementations provided by SQLite are | ||||
| 8627 | ** sufficient, however the application has the option of substituting a custom | ||||
| 8628 | ** implementation for specialized deployments or systems for which SQLite | ||||
| 8629 | ** does not provide a suitable implementation. In this case, the application | ||||
| 8630 | ** creates and populates an instance of this structure to pass | ||||
| 8631 | ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. | ||||
| 8632 | ** Additionally, an instance of this structure can be used as an | ||||
| 8633 | ** output variable when querying the system for the current mutex | ||||
| 8634 | ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. | ||||
| 8635 | ** | ||||
| 8636 | ** ^The xMutexInit method defined by this structure is invoked as | ||||
| 8637 | ** part of system initialization by the sqlite3_initialize() function. | ||||
| 8638 | ** ^The xMutexInit routine is called by SQLite exactly once for each | ||||
| 8639 | ** effective call to [sqlite3_initialize()]. | ||||
| 8640 | ** | ||||
| 8641 | ** ^The xMutexEnd method defined by this structure is invoked as | ||||
| 8642 | ** part of system shutdown by the sqlite3_shutdown() function. The | ||||
| 8643 | ** implementation of this method is expected to release all outstanding | ||||
| 8644 | ** resources obtained by the mutex methods implementation, especially | ||||
| 8645 | ** those obtained by the xMutexInit method. ^The xMutexEnd() | ||||
| 8646 | ** interface is invoked exactly once for each call to [sqlite3_shutdown()]. | ||||
| 8647 | ** | ||||
| 8648 | ** ^(The remaining seven methods defined by this structure (xMutexAlloc, | ||||
| 8649 | ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and | ||||
| 8650 | ** xMutexNotheld) implement the following interfaces (respectively): | ||||
| 8651 | ** | ||||
| 8652 | ** <ul> | ||||
| 8653 | ** <li> [sqlite3_mutex_alloc()] </li> | ||||
| 8654 | ** <li> [sqlite3_mutex_free()] </li> | ||||
| 8655 | ** <li> [sqlite3_mutex_enter()] </li> | ||||
| 8656 | ** <li> [sqlite3_mutex_try()] </li> | ||||
| 8657 | ** <li> [sqlite3_mutex_leave()] </li> | ||||
| 8658 | ** <li> [sqlite3_mutex_held()] </li> | ||||
| 8659 | ** <li> [sqlite3_mutex_notheld()] </li> | ||||
| 8660 | ** </ul>)^ | ||||
| 8661 | ** | ||||
| 8662 | ** The only difference is that the public sqlite3_XXX functions enumerated | ||||
| 8663 | ** above silently ignore any invocations that pass a NULL pointer instead | ||||
| 8664 | ** of a valid mutex handle. The implementations of the methods defined | ||||
| 8665 | ** by this structure are not required to handle this case. The results | ||||
| 8666 | ** of passing a NULL pointer instead of a valid mutex handle are undefined | ||||
| 8667 | ** (i.e. it is acceptable to provide an implementation that segfaults if | ||||
| 8668 | ** it is passed a NULL pointer). | ||||
| 8669 | ** | ||||
| 8670 | ** The xMutexInit() method must be threadsafe. It must be harmless to | ||||
| 8671 | ** invoke xMutexInit() multiple times within the same process and without | ||||
| 8672 | ** intervening calls to xMutexEnd(). Second and subsequent calls to | ||||
| 8673 | ** xMutexInit() must be no-ops. | ||||
| 8674 | ** | ||||
| 8675 | ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] | ||||
| 8676 | ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory | ||||
| 8677 | ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite | ||||
| 8678 | ** memory allocation for a fast or recursive mutex. | ||||
| 8679 | ** | ||||
| 8680 | ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is | ||||
| 8681 | ** called, but only if the prior call to xMutexInit returned SQLITE_OK. | ||||
| 8682 | ** If xMutexInit fails in any way, it is expected to clean up after itself | ||||
| 8683 | ** prior to returning. | ||||
| 8684 | */ | ||||
| 8685 | typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; | ||||
| 8686 | struct sqlite3_mutex_methods { | ||||
| 8687 | int (*xMutexInit)(void); | ||||
| 8688 | int (*xMutexEnd)(void); | ||||
| 8689 | sqlite3_mutex *(*xMutexAlloc)(int); | ||||
| 8690 | void (*xMutexFree)(sqlite3_mutex *); | ||||
| 8691 | void (*xMutexEnter)(sqlite3_mutex *); | ||||
| 8692 | int (*xMutexTry)(sqlite3_mutex *); | ||||
| 8693 | void (*xMutexLeave)(sqlite3_mutex *); | ||||
| 8694 | int (*xMutexHeld)(sqlite3_mutex *); | ||||
| 8695 | int (*xMutexNotheld)(sqlite3_mutex *); | ||||
| 8696 | }; | ||||
| 8697 | |||||
| 8698 | /* | ||||
| 8699 | ** CAPI3REF: Mutex Verification Routines | ||||
| 8700 | ** | ||||
| 8701 | ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines | ||||
| 8702 | ** are intended for use inside assert() statements. The SQLite core | ||||
| 8703 | ** never uses these routines except inside an assert() and applications | ||||
| 8704 | ** are advised to follow the lead of the core. The SQLite core only | ||||
| 8705 | ** provides implementations for these routines when it is compiled | ||||
| 8706 | ** with the SQLITE_DEBUG flag. External mutex implementations | ||||
| 8707 | ** are only required to provide these routines if SQLITE_DEBUG is | ||||
| 8708 | ** defined and if NDEBUG is not defined. | ||||
| 8709 | ** | ||||
| 8710 | ** These routines should return true if the mutex in their argument | ||||
| 8711 | ** is held or not held, respectively, by the calling thread. | ||||
| 8712 | ** | ||||
| 8713 | ** The implementation is not required to provide versions of these | ||||
| 8714 | ** routines that actually work. If the implementation does not provide working | ||||
| 8715 | ** versions of these routines, it should at least provide stubs that always | ||||
| 8716 | ** return true so that one does not get spurious assertion failures. | ||||
| 8717 | ** | ||||
| 8718 | ** If the argument to sqlite3_mutex_held() is a NULL pointer then | ||||
| 8719 | ** the routine should return 1. This seems counter-intuitive since | ||||
| 8720 | ** clearly the mutex cannot be held if it does not exist. But | ||||
| 8721 | ** the reason the mutex does not exist is because the build is not | ||||
| 8722 | ** using mutexes. And we do not want the assert() containing the | ||||
| 8723 | ** call to sqlite3_mutex_held() to fail, so a non-zero return is | ||||
| 8724 | ** the appropriate thing to do. The sqlite3_mutex_notheld() | ||||
| 8725 | ** interface should also return 1 when given a NULL pointer. | ||||
| 8726 | */ | ||||
| 8727 | #ifndef NDEBUG1 | ||||
| 8728 | SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); | ||||
| 8729 | SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); | ||||
| 8730 | #endif | ||||
| 8731 | |||||
| 8732 | /* | ||||
| 8733 | ** CAPI3REF: Mutex Types | ||||
| 8734 | ** | ||||
| 8735 | ** The [sqlite3_mutex_alloc()] interface takes a single argument | ||||
| 8736 | ** which is one of these integer constants. | ||||
| 8737 | ** | ||||
| 8738 | ** The set of static mutexes may change from one SQLite release to the | ||||
| 8739 | ** next. Applications that override the built-in mutex logic must be | ||||
| 8740 | ** prepared to accommodate additional static mutexes. | ||||
| 8741 | */ | ||||
| 8742 | #define SQLITE_MUTEX_FAST0 0 | ||||
| 8743 | #define SQLITE_MUTEX_RECURSIVE1 1 | ||||
| 8744 | #define SQLITE_MUTEX_STATIC_MAIN2 2 | ||||
| 8745 | #define SQLITE_MUTEX_STATIC_MEM3 3 /* sqlite3_malloc() */ | ||||
| 8746 | #define SQLITE_MUTEX_STATIC_MEM24 4 /* NOT USED */ | ||||
| 8747 | #define SQLITE_MUTEX_STATIC_OPEN4 4 /* sqlite3BtreeOpen() */ | ||||
| 8748 | #define SQLITE_MUTEX_STATIC_PRNG5 5 /* sqlite3_randomness() */ | ||||
| 8749 | #define SQLITE_MUTEX_STATIC_LRU6 6 /* lru page list */ | ||||
| 8750 | #define SQLITE_MUTEX_STATIC_LRU27 7 /* NOT USED */ | ||||
| 8751 | #define SQLITE_MUTEX_STATIC_PMEM7 7 /* sqlite3PageMalloc() */ | ||||
| 8752 | #define SQLITE_MUTEX_STATIC_APP18 8 /* For use by application */ | ||||
| 8753 | #define SQLITE_MUTEX_STATIC_APP29 9 /* For use by application */ | ||||
| 8754 | #define SQLITE_MUTEX_STATIC_APP310 10 /* For use by application */ | ||||
| 8755 | #define SQLITE_MUTEX_STATIC_VFS111 11 /* For use by built-in VFS */ | ||||
| 8756 | #define SQLITE_MUTEX_STATIC_VFS212 12 /* For use by extension VFS */ | ||||
| 8757 | #define SQLITE_MUTEX_STATIC_VFS313 13 /* For use by application VFS */ | ||||
| 8758 | |||||
| 8759 | /* Legacy compatibility: */ | ||||
| 8760 | #define SQLITE_MUTEX_STATIC_MASTER2 2 | ||||
| 8761 | |||||
| 8762 | |||||
| 8763 | /* | ||||
| 8764 | ** CAPI3REF: Retrieve the mutex for a database connection | ||||
| 8765 | ** METHOD: sqlite3 | ||||
| 8766 | ** | ||||
| 8767 | ** ^This interface returns a pointer to the [sqlite3_mutex] object that | ||||
| 8768 | ** serializes access to the [database connection] given in the argument | ||||
| 8769 | ** when the [threading mode] is Serialized. | ||||
| 8770 | ** ^If the [threading mode] is Single-thread or Multi-thread then this | ||||
| 8771 | ** routine returns a NULL pointer. | ||||
| 8772 | */ | ||||
| 8773 | SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); | ||||
| 8774 | |||||
| 8775 | /* | ||||
| 8776 | ** CAPI3REF: Low-Level Control Of Database Files | ||||
| 8777 | ** METHOD: sqlite3 | ||||
| 8778 | ** KEYWORDS: {file control} | ||||
| 8779 | ** | ||||
| 8780 | ** ^The [sqlite3_file_control()] interface makes a direct call to the | ||||
| 8781 | ** xFileControl method for the [sqlite3_io_methods] object associated | ||||
| 8782 | ** with a particular database identified by the second argument. ^The | ||||
| 8783 | ** name of the database is "main" for the main database or "temp" for the | ||||
| 8784 | ** TEMP database, or the name that appears after the AS keyword for | ||||
| 8785 | ** databases that are added using the [ATTACH] SQL command. | ||||
| 8786 | ** ^A NULL pointer can be used in place of "main" to refer to the | ||||
| 8787 | ** main database file. | ||||
| 8788 | ** ^The third and fourth parameters to this routine | ||||
| 8789 | ** are passed directly through to the second and third parameters of | ||||
| 8790 | ** the xFileControl method. ^The return value of the xFileControl | ||||
| 8791 | ** method becomes the return value of this routine. | ||||
| 8792 | ** | ||||
| 8793 | ** A few opcodes for [sqlite3_file_control()] are handled directly | ||||
| 8794 | ** by the SQLite core and never invoke the | ||||
| 8795 | ** sqlite3_io_methods.xFileControl method. | ||||
| 8796 | ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes | ||||
| 8797 | ** a pointer to the underlying [sqlite3_file] object to be written into | ||||
| 8798 | ** the space pointed to by the 4th parameter. The | ||||
| 8799 | ** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns | ||||
| 8800 | ** the [sqlite3_file] object associated with the journal file instead of | ||||
| 8801 | ** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns | ||||
| 8802 | ** a pointer to the underlying [sqlite3_vfs] object for the file. | ||||
| 8803 | ** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter | ||||
| 8804 | ** from the pager. | ||||
| 8805 | ** | ||||
| 8806 | ** ^If the second parameter (zDbName) does not match the name of any | ||||
| 8807 | ** open database file, then SQLITE_ERROR is returned. ^This error | ||||
| 8808 | ** code is not remembered and will not be recalled by [sqlite3_errcode()] | ||||
| 8809 | ** or [sqlite3_errmsg()]. The underlying xFileControl method might | ||||
| 8810 | ** also return SQLITE_ERROR. There is no way to distinguish between | ||||
| 8811 | ** an incorrect zDbName and an SQLITE_ERROR return from the underlying | ||||
| 8812 | ** xFileControl method. | ||||
| 8813 | ** | ||||
| 8814 | ** See also: [file control opcodes] | ||||
| 8815 | */ | ||||
| 8816 | SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); | ||||
| 8817 | |||||
| 8818 | /* | ||||
| 8819 | ** CAPI3REF: Testing Interface | ||||
| 8820 | ** | ||||
| 8821 | ** ^The sqlite3_test_control() interface is used to read out internal | ||||
| 8822 | ** state of SQLite and to inject faults into SQLite for testing | ||||
| 8823 | ** purposes. ^The first parameter is an operation code that determines | ||||
| 8824 | ** the number, meaning, and operation of all subsequent parameters. | ||||
| 8825 | ** | ||||
| 8826 | ** This interface is not for use by applications. It exists solely | ||||
| 8827 | ** for verifying the correct operation of the SQLite library. Depending | ||||
| 8828 | ** on how the SQLite library is compiled, this interface might not exist. | ||||
| 8829 | ** | ||||
| 8830 | ** The details of the operation codes, their meanings, the parameters | ||||
| 8831 | ** they take, and what they do are all subject to change without notice. | ||||
| 8832 | ** Unlike most of the SQLite API, this function is not guaranteed to | ||||
| 8833 | ** operate consistently from one release to the next. | ||||
| 8834 | */ | ||||
| 8835 | SQLITE_API int sqlite3_test_control(int op, ...); | ||||
| 8836 | |||||
| 8837 | /* | ||||
| 8838 | ** CAPI3REF: Testing Interface Operation Codes | ||||
| 8839 | ** | ||||
| 8840 | ** These constants are the valid operation code parameters used | ||||
| 8841 | ** as the first argument to [sqlite3_test_control()]. | ||||
| 8842 | ** | ||||
| 8843 | ** These parameters and their meanings are subject to change | ||||
| 8844 | ** without notice. These values are for testing purposes only. | ||||
| 8845 | ** Applications should not use any of these parameters or the | ||||
| 8846 | ** [sqlite3_test_control()] interface. | ||||
| 8847 | */ | ||||
| 8848 | #define SQLITE_TESTCTRL_FIRST5 5 | ||||
| 8849 | #define SQLITE_TESTCTRL_PRNG_SAVE5 5 | ||||
| 8850 | #define SQLITE_TESTCTRL_PRNG_RESTORE6 6 | ||||
| 8851 | #define SQLITE_TESTCTRL_PRNG_RESET7 7 /* NOT USED */ | ||||
| 8852 | #define SQLITE_TESTCTRL_FK_NO_ACTION7 7 | ||||
| 8853 | #define SQLITE_TESTCTRL_BITVEC_TEST8 8 | ||||
| 8854 | #define SQLITE_TESTCTRL_FAULT_INSTALL9 9 | ||||
| 8855 | #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS10 10 | ||||
| 8856 | #define SQLITE_TESTCTRL_PENDING_BYTE11 11 | ||||
| 8857 | #define SQLITE_TESTCTRL_ASSERT12 12 | ||||
| 8858 | #define SQLITE_TESTCTRL_ALWAYS13 13 | ||||
| 8859 | #define SQLITE_TESTCTRL_RESERVE14 14 /* NOT USED */ | ||||
| 8860 | #define SQLITE_TESTCTRL_JSON_SELFCHECK14 14 | ||||
| 8861 | #define SQLITE_TESTCTRL_OPTIMIZATIONS15 15 | ||||
| 8862 | #define SQLITE_TESTCTRL_ISKEYWORD16 16 /* NOT USED */ | ||||
| 8863 | #define SQLITE_TESTCTRL_GETOPT16 16 | ||||
| 8864 | #define SQLITE_TESTCTRL_SCRATCHMALLOC17 17 /* NOT USED */ | ||||
| 8865 | #define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS17 17 | ||||
| 8866 | #define SQLITE_TESTCTRL_LOCALTIME_FAULT18 18 | ||||
| 8867 | #define SQLITE_TESTCTRL_EXPLAIN_STMT19 19 /* NOT USED */ | ||||
| 8868 | #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD19 19 | ||||
| 8869 | #define SQLITE_TESTCTRL_NEVER_CORRUPT20 20 | ||||
| 8870 | #define SQLITE_TESTCTRL_VDBE_COVERAGE21 21 | ||||
| 8871 | #define SQLITE_TESTCTRL_BYTEORDER22 22 | ||||
| 8872 | #define SQLITE_TESTCTRL_ISINIT23 23 | ||||
| 8873 | #define SQLITE_TESTCTRL_SORTER_MMAP24 24 | ||||
| 8874 | #define SQLITE_TESTCTRL_IMPOSTER25 25 | ||||
| 8875 | #define SQLITE_TESTCTRL_PARSER_COVERAGE26 26 | ||||
| 8876 | #define SQLITE_TESTCTRL_RESULT_INTREAL27 27 | ||||
| 8877 | #define SQLITE_TESTCTRL_PRNG_SEED28 28 | ||||
| 8878 | #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS29 29 | ||||
| 8879 | #define SQLITE_TESTCTRL_SEEK_COUNT30 30 | ||||
| 8880 | #define SQLITE_TESTCTRL_TRACEFLAGS31 31 | ||||
| 8881 | #define SQLITE_TESTCTRL_TUNE32 32 | ||||
| 8882 | #define SQLITE_TESTCTRL_LOGEST33 33 | ||||
| 8883 | #define SQLITE_TESTCTRL_USELONGDOUBLE34 34 /* NOT USED */ | ||||
| 8884 | #define SQLITE_TESTCTRL_LAST34 34 /* Largest TESTCTRL */ | ||||
| 8885 | |||||
| 8886 | /* | ||||
| 8887 | ** CAPI3REF: SQL Keyword Checking | ||||
| 8888 | ** | ||||
| 8889 | ** These routines provide access to the set of SQL language keywords | ||||
| 8890 | ** recognized by SQLite. Applications can use these routines to determine | ||||
| 8891 | ** whether or not a specific identifier needs to be escaped (for example, | ||||
| 8892 | ** by enclosing in double-quotes) so as not to confuse the parser. | ||||
| 8893 | ** | ||||
| 8894 | ** The sqlite3_keyword_count() interface returns the number of distinct | ||||
| 8895 | ** keywords understood by SQLite. | ||||
| 8896 | ** | ||||
| 8897 | ** The sqlite3_keyword_name(N,Z,L) interface finds the 0-based N-th keyword and | ||||
| 8898 | ** makes *Z point to that keyword expressed as UTF8 and writes the number | ||||
| 8899 | ** of bytes in the keyword into *L. The string that *Z points to is not | ||||
| 8900 | ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns | ||||
| 8901 | ** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z | ||||
| 8902 | ** or L are NULL or invalid pointers then calls to | ||||
| 8903 | ** sqlite3_keyword_name(N,Z,L) result in undefined behavior. | ||||
| 8904 | ** | ||||
| 8905 | ** The sqlite3_keyword_check(Z,L) interface checks to see whether or not | ||||
| 8906 | ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero | ||||
| 8907 | ** if it is and zero if not. | ||||
| 8908 | ** | ||||
| 8909 | ** The parser used by SQLite is forgiving. It is often possible to use | ||||
| 8910 | ** a keyword as an identifier as long as such use does not result in a | ||||
| 8911 | ** parsing ambiguity. For example, the statement | ||||
| 8912 | ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and | ||||
| 8913 | ** creates a new table named "BEGIN" with three columns named | ||||
| 8914 | ** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid | ||||
| 8915 | ** using keywords as identifiers. Common techniques used to avoid keyword | ||||
| 8916 | ** name collisions include: | ||||
| 8917 | ** <ul> | ||||
| 8918 | ** <li> Put all identifier names inside double-quotes. This is the official | ||||
| 8919 | ** SQL way to escape identifier names. | ||||
| 8920 | ** <li> Put identifier names inside [...]. This is not standard SQL, | ||||
| 8921 | ** but it is what SQL Server does and so lots of programmers use this | ||||
| 8922 | ** technique. | ||||
| 8923 | ** <li> Begin every identifier with the letter "Z" as no SQL keywords start | ||||
| 8924 | ** with "Z". | ||||
| 8925 | ** <li> Include a digit somewhere in every identifier name. | ||||
| 8926 | ** </ul> | ||||
| 8927 | ** | ||||
| 8928 | ** Note that the number of keywords understood by SQLite can depend on | ||||
| 8929 | ** compile-time options. For example, "VACUUM" is not a keyword if | ||||
| 8930 | ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also, | ||||
| 8931 | ** new keywords may be added to future releases of SQLite. | ||||
| 8932 | */ | ||||
| 8933 | SQLITE_API int sqlite3_keyword_count(void); | ||||
| 8934 | SQLITE_API int sqlite3_keyword_name(int,const char**,int*); | ||||
| 8935 | SQLITE_API int sqlite3_keyword_check(const char*,int); | ||||
| 8936 | |||||
| 8937 | /* | ||||
| 8938 | ** CAPI3REF: Dynamic String Object | ||||
| 8939 | ** KEYWORDS: {dynamic string} | ||||
| 8940 | ** | ||||
| 8941 | ** An instance of the sqlite3_str object contains a dynamically-sized | ||||
| 8942 | ** string under construction. | ||||
| 8943 | ** | ||||
| 8944 | ** The lifecycle of an sqlite3_str object is as follows: | ||||
| 8945 | ** <ol> | ||||
| 8946 | ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()]. | ||||
| 8947 | ** <li> ^Text is appended to the sqlite3_str object using various | ||||
| 8948 | ** methods, such as [sqlite3_str_appendf()]. | ||||
| 8949 | ** <li> ^The sqlite3_str object is destroyed and the string it created | ||||
| 8950 | ** is returned using the [sqlite3_str_finish()] interface. | ||||
| 8951 | ** </ol> | ||||
| 8952 | */ | ||||
| 8953 | typedef struct sqlite3_str sqlite3_str; | ||||
| 8954 | |||||
| 8955 | /* | ||||
| 8956 | ** CAPI3REF: Create A New Dynamic String Object | ||||
| 8957 | ** CONSTRUCTOR: sqlite3_str | ||||
| 8958 | ** | ||||
| 8959 | ** ^The [sqlite3_str_new(D)] interface allocates and initializes | ||||
| 8960 | ** a new [sqlite3_str] object. To avoid memory leaks, the object returned by | ||||
| 8961 | ** [sqlite3_str_new()] must be freed by a subsequent call to | ||||
| 8962 | ** [sqlite3_str_finish(X)]. | ||||
| 8963 | ** | ||||
| 8964 | ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a | ||||
| 8965 | ** valid [sqlite3_str] object, though in the event of an out-of-memory | ||||
| 8966 | ** error the returned object might be a special singleton that will | ||||
| 8967 | ** silently reject new text, always return SQLITE_NOMEM from | ||||
| 8968 | ** [sqlite3_str_errcode()], always return 0 for | ||||
| 8969 | ** [sqlite3_str_length()], and always return NULL from | ||||
| 8970 | ** [sqlite3_str_finish(X)]. It is always safe to use the value | ||||
| 8971 | ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter | ||||
| 8972 | ** to any of the other [sqlite3_str] methods. | ||||
| 8973 | ** | ||||
| 8974 | ** The D parameter to [sqlite3_str_new(D)] may be NULL. If the | ||||
| 8975 | ** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum | ||||
| 8976 | ** length of the string contained in the [sqlite3_str] object will be | ||||
| 8977 | ** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead | ||||
| 8978 | ** of [SQLITE_MAX_LENGTH]. | ||||
| 8979 | */ | ||||
| 8980 | SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*); | ||||
| 8981 | |||||
| 8982 | /* | ||||
| 8983 | ** CAPI3REF: Finalize A Dynamic String | ||||
| 8984 | ** DESTRUCTOR: sqlite3_str | ||||
| 8985 | ** | ||||
| 8986 | ** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X | ||||
| 8987 | ** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()] | ||||
| 8988 | ** that contains the constructed string. The calling application should | ||||
| 8989 | ** pass the returned value to [sqlite3_free()] to avoid a memory leak. | ||||
| 8990 | ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any | ||||
| 8991 | ** errors were encountered during construction of the string. ^The | ||||
| 8992 | ** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the | ||||
| 8993 | ** string in [sqlite3_str] object X is zero bytes long. | ||||
| 8994 | */ | ||||
| 8995 | SQLITE_API char *sqlite3_str_finish(sqlite3_str*); | ||||
| 8996 | |||||
| 8997 | /* | ||||
| 8998 | ** CAPI3REF: Add Content To A Dynamic String | ||||
| 8999 | ** METHOD: sqlite3_str | ||||
| 9000 | ** | ||||
| 9001 | ** These interfaces add content to an sqlite3_str object previously obtained | ||||
| 9002 | ** from [sqlite3_str_new()]. | ||||
| 9003 | ** | ||||
| 9004 | ** ^The [sqlite3_str_appendf(X,F,...)] and | ||||
| 9005 | ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf] | ||||
| 9006 | ** functionality of SQLite to append formatted text onto the end of | ||||
| 9007 | ** [sqlite3_str] object X. | ||||
| 9008 | ** | ||||
| 9009 | ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S | ||||
| 9010 | ** onto the end of the [sqlite3_str] object X. N must be non-negative. | ||||
| 9011 | ** S must contain at least N non-zero bytes of content. To append a | ||||
| 9012 | ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()] | ||||
| 9013 | ** method instead. | ||||
| 9014 | ** | ||||
| 9015 | ** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of | ||||
| 9016 | ** zero-terminated string S onto the end of [sqlite3_str] object X. | ||||
| 9017 | ** | ||||
| 9018 | ** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the | ||||
| 9019 | ** single-byte character C onto the end of [sqlite3_str] object X. | ||||
| 9020 | ** ^This method can be used, for example, to add whitespace indentation. | ||||
| 9021 | ** | ||||
| 9022 | ** ^The [sqlite3_str_reset(X)] method resets the string under construction | ||||
| 9023 | ** inside [sqlite3_str] object X back to zero bytes in length. | ||||
| 9024 | ** | ||||
| 9025 | ** These methods do not return a result code. ^If an error occurs, that fact | ||||
| 9026 | ** is recorded in the [sqlite3_str] object and can be recovered by a | ||||
| 9027 | ** subsequent call to [sqlite3_str_errcode(X)]. | ||||
| 9028 | */ | ||||
| 9029 | SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...); | ||||
| 9030 | SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list); | ||||
| 9031 | SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N); | ||||
| 9032 | SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn); | ||||
| 9033 | SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C); | ||||
| 9034 | SQLITE_API void sqlite3_str_reset(sqlite3_str*); | ||||
| 9035 | |||||
| 9036 | /* | ||||
| 9037 | ** CAPI3REF: Status Of A Dynamic String | ||||
| 9038 | ** METHOD: sqlite3_str | ||||
| 9039 | ** | ||||
| 9040 | ** These interfaces return the current status of an [sqlite3_str] object. | ||||
| 9041 | ** | ||||
| 9042 | ** ^If any prior errors have occurred while constructing the dynamic string | ||||
| 9043 | ** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return | ||||
| 9044 | ** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns | ||||
| 9045 | ** [SQLITE_NOMEM] following any out-of-memory error, or | ||||
| 9046 | ** [SQLITE_TOOBIG] if the size of the dynamic string exceeds | ||||
| 9047 | ** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors. | ||||
| 9048 | ** | ||||
| 9049 | ** ^The [sqlite3_str_length(X)] method returns the current length, in bytes, | ||||
| 9050 | ** of the dynamic string under construction in [sqlite3_str] object X. | ||||
| 9051 | ** ^The length returned by [sqlite3_str_length(X)] does not include the | ||||
| 9052 | ** zero-termination byte. | ||||
| 9053 | ** | ||||
| 9054 | ** ^The [sqlite3_str_value(X)] method returns a pointer to the current | ||||
| 9055 | ** content of the dynamic string under construction in X. The value | ||||
| 9056 | ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X | ||||
| 9057 | ** and might be freed or altered by any subsequent method on the same | ||||
| 9058 | ** [sqlite3_str] object. Applications must not use the pointer returned by | ||||
| 9059 | ** [sqlite3_str_value(X)] after any subsequent method call on the same | ||||
| 9060 | ** object. ^Applications may change the content of the string returned | ||||
| 9061 | ** by [sqlite3_str_value(X)] as long as they do not write into any bytes | ||||
| 9062 | ** outside the range of 0 to [sqlite3_str_length(X)] and do not read or | ||||
| 9063 | ** write any byte after any subsequent sqlite3_str method call. | ||||
| 9064 | */ | ||||
| 9065 | SQLITE_API int sqlite3_str_errcode(sqlite3_str*); | ||||
| 9066 | SQLITE_API int sqlite3_str_length(sqlite3_str*); | ||||
| 9067 | SQLITE_API char *sqlite3_str_value(sqlite3_str*); | ||||
| 9068 | |||||
| 9069 | /* | ||||
| 9070 | ** CAPI3REF: SQLite Runtime Status | ||||
| 9071 | ** | ||||
| 9072 | ** ^These interfaces are used to retrieve runtime status information | ||||
| 9073 | ** about the performance of SQLite, and optionally to reset various | ||||
| 9074 | ** highwater marks. ^The first argument is an integer code for | ||||
| 9075 | ** the specific parameter to measure. ^(Recognized integer codes | ||||
| 9076 | ** are of the form [status parameters | SQLITE_STATUS_...].)^ | ||||
| 9077 | ** ^The current value of the parameter is returned into *pCurrent. | ||||
| 9078 | ** ^The highest recorded value is returned in *pHighwater. ^If the | ||||
| 9079 | ** resetFlag is true, then the highest record value is reset after | ||||
| 9080 | ** *pHighwater is written. ^(Some parameters do not record the highest | ||||
| 9081 | ** value. For those parameters | ||||
| 9082 | ** nothing is written into *pHighwater and the resetFlag is ignored.)^ | ||||
| 9083 | ** ^(Other parameters record only the highwater mark and not the current | ||||
| 9084 | ** value. For these latter parameters nothing is written into *pCurrent.)^ | ||||
| 9085 | ** | ||||
| 9086 | ** ^The sqlite3_status() and sqlite3_status64() routines return | ||||
| 9087 | ** SQLITE_OK on success and a non-zero [error code] on failure. | ||||
| 9088 | ** | ||||
| 9089 | ** If either the current value or the highwater mark is too large to | ||||
| 9090 | ** be represented by a 32-bit integer, then the values returned by | ||||
| 9091 | ** sqlite3_status() are undefined. | ||||
| 9092 | ** | ||||
| 9093 | ** See also: [sqlite3_db_status()] | ||||
| 9094 | */ | ||||
| 9095 | SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); | ||||
| 9096 | SQLITE_API int sqlite3_status64( | ||||
| 9097 | int op, | ||||
| 9098 | sqlite3_int64 *pCurrent, | ||||
| 9099 | sqlite3_int64 *pHighwater, | ||||
| 9100 | int resetFlag | ||||
| 9101 | ); | ||||
| 9102 | |||||
| 9103 | |||||
| 9104 | /* | ||||
| 9105 | ** CAPI3REF: Status Parameters | ||||
| 9106 | ** KEYWORDS: {status parameters} | ||||
| 9107 | ** | ||||
| 9108 | ** These integer constants designate various run-time status parameters | ||||
| 9109 | ** that can be returned by [sqlite3_status()]. | ||||
| 9110 | ** | ||||
| 9111 | ** <dl> | ||||
| 9112 | ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt> | ||||
| 9113 | ** <dd>This parameter is the current amount of memory checked out | ||||
| 9114 | ** using [sqlite3_malloc()], either directly or indirectly. The | ||||
| 9115 | ** figure includes calls made to [sqlite3_malloc()] by the application | ||||
| 9116 | ** and internal memory usage by the SQLite library. Auxiliary page-cache | ||||
| 9117 | ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in | ||||
| 9118 | ** this parameter. The amount returned is the sum of the allocation | ||||
| 9119 | ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^ | ||||
| 9120 | ** | ||||
| 9121 | ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt> | ||||
| 9122 | ** <dd>This parameter records the largest memory allocation request | ||||
| 9123 | ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their | ||||
| 9124 | ** internal equivalents). Only the value returned in the | ||||
| 9125 | ** *pHighwater parameter to [sqlite3_status()] is of interest. | ||||
| 9126 | ** The value written into the *pCurrent parameter is undefined.</dd>)^ | ||||
| 9127 | ** | ||||
| 9128 | ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt> | ||||
| 9129 | ** <dd>This parameter records the number of separate memory allocations | ||||
| 9130 | ** currently checked out.</dd>)^ | ||||
| 9131 | ** | ||||
| 9132 | ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt> | ||||
| 9133 | ** <dd>This parameter returns the number of pages used out of the | ||||
| 9134 | ** [pagecache memory allocator] that was configured using | ||||
| 9135 | ** [SQLITE_CONFIG_PAGECACHE]. The | ||||
| 9136 | ** value returned is in pages, not in bytes.</dd>)^ | ||||
| 9137 | ** | ||||
| 9138 | ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] | ||||
| 9139 | ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt> | ||||
| 9140 | ** <dd>This parameter returns the number of bytes of page cache | ||||
| 9141 | ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] | ||||
| 9142 | ** buffer and where forced to overflow to [sqlite3_malloc()]. The | ||||
| 9143 | ** returned value includes allocations that overflowed because they | ||||
| 9144 | ** were too large (they were larger than the "sz" parameter to | ||||
| 9145 | ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because | ||||
| 9146 | ** no space was left in the page cache.</dd>)^ | ||||
| 9147 | ** | ||||
| 9148 | ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt> | ||||
| 9149 | ** <dd>This parameter records the largest memory allocation request | ||||
| 9150 | ** handed to the [pagecache memory allocator]. Only the value returned in the | ||||
| 9151 | ** *pHighwater parameter to [sqlite3_status()] is of interest. | ||||
| 9152 | ** The value written into the *pCurrent parameter is undefined.</dd>)^ | ||||
| 9153 | ** | ||||
| 9154 | ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt> | ||||
| 9155 | ** <dd>No longer used.</dd> | ||||
| 9156 | ** | ||||
| 9157 | ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt> | ||||
| 9158 | ** <dd>No longer used.</dd> | ||||
| 9159 | ** | ||||
| 9160 | ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt> | ||||
| 9161 | ** <dd>No longer used.</dd> | ||||
| 9162 | ** | ||||
| 9163 | ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt> | ||||
| 9164 | ** <dd>The *pHighwater parameter records the deepest parser stack. | ||||
| 9165 | ** The *pCurrent value is undefined. The *pHighwater value is only | ||||
| 9166 | ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^ | ||||
| 9167 | ** </dl> | ||||
| 9168 | ** | ||||
| 9169 | ** New status parameters may be added from time to time. | ||||
| 9170 | */ | ||||
| 9171 | #define SQLITE_STATUS_MEMORY_USED0 0 | ||||
| 9172 | #define SQLITE_STATUS_PAGECACHE_USED1 1 | ||||
| 9173 | #define SQLITE_STATUS_PAGECACHE_OVERFLOW2 2 | ||||
| 9174 | #define SQLITE_STATUS_SCRATCH_USED3 3 /* NOT USED */ | ||||
| 9175 | #define SQLITE_STATUS_SCRATCH_OVERFLOW4 4 /* NOT USED */ | ||||
| 9176 | #define SQLITE_STATUS_MALLOC_SIZE5 5 | ||||
| 9177 | #define SQLITE_STATUS_PARSER_STACK6 6 | ||||
| 9178 | #define SQLITE_STATUS_PAGECACHE_SIZE7 7 | ||||
| 9179 | #define SQLITE_STATUS_SCRATCH_SIZE8 8 /* NOT USED */ | ||||
| 9180 | #define SQLITE_STATUS_MALLOC_COUNT9 9 | ||||
| 9181 | |||||
| 9182 | /* | ||||
| 9183 | ** CAPI3REF: Database Connection Status | ||||
| 9184 | ** METHOD: sqlite3 | ||||
| 9185 | ** | ||||
| 9186 | ** ^This interface is used to retrieve runtime status information | ||||
| 9187 | ** about a single [database connection]. ^The first argument is the | ||||
| 9188 | ** database connection object to be interrogated. ^The second argument | ||||
| 9189 | ** is an integer constant, taken from the set of | ||||
| 9190 | ** [SQLITE_DBSTATUS options], that | ||||
| 9191 | ** determines the parameter to interrogate. The set of | ||||
| 9192 | ** [SQLITE_DBSTATUS options] is likely | ||||
| 9193 | ** to grow in future releases of SQLite. | ||||
| 9194 | ** | ||||
| 9195 | ** ^The current value of the requested parameter is written into *pCur | ||||
| 9196 | ** and the highest instantaneous value is written into *pHiwtr. ^If | ||||
| 9197 | ** the resetFlg is true, then the highest instantaneous value is | ||||
| 9198 | ** reset back down to the current value. | ||||
| 9199 | ** | ||||
| 9200 | ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a | ||||
| 9201 | ** non-zero [error code] on failure. | ||||
| 9202 | ** | ||||
| 9203 | ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. | ||||
| 9204 | */ | ||||
| 9205 | SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); | ||||
| 9206 | |||||
| 9207 | /* | ||||
| 9208 | ** CAPI3REF: Status Parameters for database connections | ||||
| 9209 | ** KEYWORDS: {SQLITE_DBSTATUS options} | ||||
| 9210 | ** | ||||
| 9211 | ** These constants are the available integer "verbs" that can be passed as | ||||
| 9212 | ** the second argument to the [sqlite3_db_status()] interface. | ||||
| 9213 | ** | ||||
| 9214 | ** New verbs may be added in future releases of SQLite. Existing verbs | ||||
| 9215 | ** might be discontinued. Applications should check the return code from | ||||
| 9216 | ** [sqlite3_db_status()] to make sure that the call worked. | ||||
| 9217 | ** The [sqlite3_db_status()] interface will return a non-zero error code | ||||
| 9218 | ** if a discontinued or unsupported verb is invoked. | ||||
| 9219 | ** | ||||
| 9220 | ** <dl> | ||||
| 9221 | ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt> | ||||
| 9222 | ** <dd>This parameter returns the number of lookaside memory slots currently | ||||
| 9223 | ** checked out.</dd>)^ | ||||
| 9224 | ** | ||||
| 9225 | ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt> | ||||
| 9226 | ** <dd>This parameter returns the number of malloc attempts that were | ||||
| 9227 | ** satisfied using lookaside memory. Only the high-water value is meaningful; | ||||
| 9228 | ** the current value is always zero.</dd>)^ | ||||
| 9229 | ** | ||||
| 9230 | ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] | ||||
| 9231 | ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt> | ||||
| 9232 | ** <dd>This parameter returns the number of malloc attempts that might have | ||||
| 9233 | ** been satisfied using lookaside memory but failed due to the amount of | ||||
| 9234 | ** memory requested being larger than the lookaside slot size. | ||||
| 9235 | ** Only the high-water value is meaningful; | ||||
| 9236 | ** the current value is always zero.</dd>)^ | ||||
| 9237 | ** | ||||
| 9238 | ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] | ||||
| 9239 | ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt> | ||||
| 9240 | ** <dd>This parameter returns the number of malloc attempts that might have | ||||
| 9241 | ** been satisfied using lookaside memory but failed due to all lookaside | ||||
| 9242 | ** memory already being in use. | ||||
| 9243 | ** Only the high-water value is meaningful; | ||||
| 9244 | ** the current value is always zero.</dd>)^ | ||||
| 9245 | ** | ||||
| 9246 | ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt> | ||||
| 9247 | ** <dd>This parameter returns the approximate number of bytes of heap | ||||
| 9248 | ** memory used by all pager caches associated with the database connection.)^ | ||||
| 9249 | ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. | ||||
| 9250 | ** </dd> | ||||
| 9251 | ** | ||||
| 9252 | ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] | ||||
| 9253 | ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt> | ||||
| 9254 | ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a | ||||
| 9255 | ** pager cache is shared between two or more connections the bytes of heap | ||||
| 9256 | ** memory used by that pager cache is divided evenly between the attached | ||||
| 9257 | ** connections.)^ In other words, if none of the pager caches associated | ||||
| 9258 | ** with the database connection are shared, this request returns the same | ||||
| 9259 | ** value as DBSTATUS_CACHE_USED. Or, if one or more of the pager caches are | ||||
| 9260 | ** shared, the value returned by this call will be smaller than that returned | ||||
| 9261 | ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with | ||||
| 9262 | ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.</dd> | ||||
| 9263 | ** | ||||
| 9264 | ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt> | ||||
| 9265 | ** <dd>This parameter returns the approximate number of bytes of heap | ||||
| 9266 | ** memory used to store the schema for all databases associated | ||||
| 9267 | ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ | ||||
| 9268 | ** ^The full amount of memory used by the schemas is reported, even if the | ||||
| 9269 | ** schema memory is shared with other database connections due to | ||||
| 9270 | ** [shared cache mode] being enabled. | ||||
| 9271 | ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. | ||||
| 9272 | ** </dd> | ||||
| 9273 | ** | ||||
| 9274 | ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt> | ||||
| 9275 | ** <dd>This parameter returns the approximate number of bytes of heap | ||||
| 9276 | ** and lookaside memory used by all prepared statements associated with | ||||
| 9277 | ** the database connection.)^ | ||||
| 9278 | ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. | ||||
| 9279 | ** </dd> | ||||
| 9280 | ** | ||||
| 9281 | ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt> | ||||
| 9282 | ** <dd>This parameter returns the number of pager cache hits that have | ||||
| 9283 | ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT | ||||
| 9284 | ** is always 0. | ||||
| 9285 | ** </dd> | ||||
| 9286 | ** | ||||
| 9287 | ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt> | ||||
| 9288 | ** <dd>This parameter returns the number of pager cache misses that have | ||||
| 9289 | ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS | ||||
| 9290 | ** is always 0. | ||||
| 9291 | ** </dd> | ||||
| 9292 | ** | ||||
| 9293 | ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt> | ||||
| 9294 | ** <dd>This parameter returns the number of dirty cache entries that have | ||||
| 9295 | ** been written to disk. Specifically, the number of pages written to the | ||||
| 9296 | ** wal file in wal mode databases, or the number of pages written to the | ||||
| 9297 | ** database file in rollback mode databases. Any pages written as part of | ||||
| 9298 | ** transaction rollback or database recovery operations are not included. | ||||
| 9299 | ** If an IO or other error occurs while writing a page to disk, the effect | ||||
| 9300 | ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The | ||||
| 9301 | ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. | ||||
| 9302 | ** </dd> | ||||
| 9303 | ** | ||||
| 9304 | ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt> | ||||
| 9305 | ** <dd>This parameter returns the number of dirty cache entries that have | ||||
| 9306 | ** been written to disk in the middle of a transaction due to the page | ||||
| 9307 | ** cache overflowing. Transactions are more efficient if they are written | ||||
| 9308 | ** to disk all at once. When pages spill mid-transaction, that introduces | ||||
| 9309 | ** additional overhead. This parameter can be used to help identify | ||||
| 9310 | ** inefficiencies that can be resolved by increasing the cache size. | ||||
| 9311 | ** </dd> | ||||
| 9312 | ** | ||||
| 9313 | ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt> | ||||
| 9314 | ** <dd>This parameter returns zero for the current value if and only if | ||||
| 9315 | ** all foreign key constraints (deferred or immediate) have been | ||||
| 9316 | ** resolved.)^ ^The highwater mark is always 0. | ||||
| 9317 | ** </dd> | ||||
| 9318 | ** </dl> | ||||
| 9319 | */ | ||||
| 9320 | #define SQLITE_DBSTATUS_LOOKASIDE_USED0 0 | ||||
| 9321 | #define SQLITE_DBSTATUS_CACHE_USED1 1 | ||||
| 9322 | #define SQLITE_DBSTATUS_SCHEMA_USED2 2 | ||||
| 9323 | #define SQLITE_DBSTATUS_STMT_USED3 3 | ||||
| 9324 | #define SQLITE_DBSTATUS_LOOKASIDE_HIT4 4 | ||||
| 9325 | #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE5 5 | ||||
| 9326 | #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL6 6 | ||||
| 9327 | #define SQLITE_DBSTATUS_CACHE_HIT7 7 | ||||
| 9328 | #define SQLITE_DBSTATUS_CACHE_MISS8 8 | ||||
| 9329 | #define SQLITE_DBSTATUS_CACHE_WRITE9 9 | ||||
| 9330 | #define SQLITE_DBSTATUS_DEFERRED_FKS10 10 | ||||
| 9331 | #define SQLITE_DBSTATUS_CACHE_USED_SHARED11 11 | ||||
| 9332 | #define SQLITE_DBSTATUS_CACHE_SPILL12 12 | ||||
| 9333 | #define SQLITE_DBSTATUS_MAX12 12 /* Largest defined DBSTATUS */ | ||||
| 9334 | |||||
| 9335 | |||||
| 9336 | /* | ||||
| 9337 | ** CAPI3REF: Prepared Statement Status | ||||
| 9338 | ** METHOD: sqlite3_stmt | ||||
| 9339 | ** | ||||
| 9340 | ** ^(Each prepared statement maintains various | ||||
| 9341 | ** [SQLITE_STMTSTATUS counters] that measure the number | ||||
| 9342 | ** of times it has performed specific operations.)^ These counters can | ||||
| 9343 | ** be used to monitor the performance characteristics of the prepared | ||||
| 9344 | ** statements. For example, if the number of table steps greatly exceeds | ||||
| 9345 | ** the number of table searches or result rows, that would tend to indicate | ||||
| 9346 | ** that the prepared statement is using a full table scan rather than | ||||
| 9347 | ** an index. | ||||
| 9348 | ** | ||||
| 9349 | ** ^(This interface is used to retrieve and reset counter values from | ||||
| 9350 | ** a [prepared statement]. The first argument is the prepared statement | ||||
| 9351 | ** object to be interrogated. The second argument | ||||
| 9352 | ** is an integer code for a specific [SQLITE_STMTSTATUS counter] | ||||
| 9353 | ** to be interrogated.)^ | ||||
| 9354 | ** ^The current value of the requested counter is returned. | ||||
| 9355 | ** ^If the resetFlg is true, then the counter is reset to zero after this | ||||
| 9356 | ** interface call returns. | ||||
| 9357 | ** | ||||
| 9358 | ** See also: [sqlite3_status()] and [sqlite3_db_status()]. | ||||
| 9359 | */ | ||||
| 9360 | SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); | ||||
| 9361 | |||||
| 9362 | /* | ||||
| 9363 | ** CAPI3REF: Status Parameters for prepared statements | ||||
| 9364 | ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} | ||||
| 9365 | ** | ||||
| 9366 | ** These preprocessor macros define integer codes that name counter | ||||
| 9367 | ** values associated with the [sqlite3_stmt_status()] interface. | ||||
| 9368 | ** The meanings of the various counters are as follows: | ||||
| 9369 | ** | ||||
| 9370 | ** <dl> | ||||
| 9371 | ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt> | ||||
| 9372 | ** <dd>^This is the number of times that SQLite has stepped forward in | ||||
| 9373 | ** a table as part of a full table scan. Large numbers for this counter | ||||
| 9374 | ** may indicate opportunities for performance improvement through | ||||
| 9375 | ** careful use of indices.</dd> | ||||
| 9376 | ** | ||||
| 9377 | ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt> | ||||
| 9378 | ** <dd>^This is the number of sort operations that have occurred. | ||||
| 9379 | ** A non-zero value in this counter may indicate an opportunity to | ||||
| 9380 | ** improve performance through careful use of indices.</dd> | ||||
| 9381 | ** | ||||
| 9382 | ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt> | ||||
| 9383 | ** <dd>^This is the number of rows inserted into transient indices that | ||||
| 9384 | ** were created automatically in order to help joins run faster. | ||||
| 9385 | ** A non-zero value in this counter may indicate an opportunity to | ||||
| 9386 | ** improve performance by adding permanent indices that do not | ||||
| 9387 | ** need to be reinitialized each time the statement is run.</dd> | ||||
| 9388 | ** | ||||
| 9389 | ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt> | ||||
| 9390 | ** <dd>^This is the number of virtual machine operations executed | ||||
| 9391 | ** by the prepared statement if that number is less than or equal | ||||
| 9392 | ** to 2147483647. The number of virtual machine operations can be | ||||
| 9393 | ** used as a proxy for the total work done by the prepared statement. | ||||
| 9394 | ** If the number of virtual machine operations exceeds 2147483647 | ||||
| 9395 | ** then the value returned by this statement status code is undefined.</dd> | ||||
| 9396 | ** | ||||
| 9397 | ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt> | ||||
| 9398 | ** <dd>^This is the number of times that the prepare statement has been | ||||
| 9399 | ** automatically regenerated due to schema changes or changes to | ||||
| 9400 | ** [bound parameters] that might affect the query plan.</dd> | ||||
| 9401 | ** | ||||
| 9402 | ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt> | ||||
| 9403 | ** <dd>^This is the number of times that the prepared statement has | ||||
| 9404 | ** been run. A single "run" for the purposes of this counter is one | ||||
| 9405 | ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()]. | ||||
| 9406 | ** The counter is incremented on the first [sqlite3_step()] call of each | ||||
| 9407 | ** cycle.</dd> | ||||
| 9408 | ** | ||||
| 9409 | ** [[SQLITE_STMTSTATUS_FILTER_MISS]] | ||||
| 9410 | ** [[SQLITE_STMTSTATUS_FILTER HIT]] | ||||
| 9411 | ** <dt>SQLITE_STMTSTATUS_FILTER_HIT<br> | ||||
| 9412 | ** SQLITE_STMTSTATUS_FILTER_MISS</dt> | ||||
| 9413 | ** <dd>^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join | ||||
| 9414 | ** step was bypassed because a Bloom filter returned not-found. The | ||||
| 9415 | ** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of | ||||
| 9416 | ** times that the Bloom filter returned a find, and thus the join step | ||||
| 9417 | ** had to be processed as normal.</dd> | ||||
| 9418 | ** | ||||
| 9419 | ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt> | ||||
| 9420 | ** <dd>^This is the approximate number of bytes of heap memory | ||||
| 9421 | ** used to store the prepared statement. ^This value is not actually | ||||
| 9422 | ** a counter, and so the resetFlg parameter to sqlite3_stmt_status() | ||||
| 9423 | ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED. | ||||
| 9424 | ** </dd> | ||||
| 9425 | ** </dl> | ||||
| 9426 | */ | ||||
| 9427 | #define SQLITE_STMTSTATUS_FULLSCAN_STEP1 1 | ||||
| 9428 | #define SQLITE_STMTSTATUS_SORT2 2 | ||||
| 9429 | #define SQLITE_STMTSTATUS_AUTOINDEX3 3 | ||||
| 9430 | #define SQLITE_STMTSTATUS_VM_STEP4 4 | ||||
| 9431 | #define SQLITE_STMTSTATUS_REPREPARE5 5 | ||||
| 9432 | #define SQLITE_STMTSTATUS_RUN6 6 | ||||
| 9433 | #define SQLITE_STMTSTATUS_FILTER_MISS7 7 | ||||
| 9434 | #define SQLITE_STMTSTATUS_FILTER_HIT8 8 | ||||
| 9435 | #define SQLITE_STMTSTATUS_MEMUSED99 99 | ||||
| 9436 | |||||
| 9437 | /* | ||||
| 9438 | ** CAPI3REF: Custom Page Cache Object | ||||
| 9439 | ** | ||||
| 9440 | ** The sqlite3_pcache type is opaque. It is implemented by | ||||
| 9441 | ** the pluggable module. The SQLite core has no knowledge of | ||||
| 9442 | ** its size or internal structure and never deals with the | ||||
| 9443 | ** sqlite3_pcache object except by holding and passing pointers | ||||
| 9444 | ** to the object. | ||||
| 9445 | ** | ||||
| 9446 | ** See [sqlite3_pcache_methods2] for additional information. | ||||
| 9447 | */ | ||||
| 9448 | typedef struct sqlite3_pcache sqlite3_pcache; | ||||
| 9449 | |||||
| 9450 | /* | ||||
| 9451 | ** CAPI3REF: Custom Page Cache Object | ||||
| 9452 | ** | ||||
| 9453 | ** The sqlite3_pcache_page object represents a single page in the | ||||
| 9454 | ** page cache. The page cache will allocate instances of this | ||||
| 9455 | ** object. Various methods of the page cache use pointers to instances | ||||
| 9456 | ** of this object as parameters or as their return value. | ||||
| 9457 | ** | ||||
| 9458 | ** See [sqlite3_pcache_methods2] for additional information. | ||||
| 9459 | */ | ||||
| 9460 | typedef struct sqlite3_pcache_page sqlite3_pcache_page; | ||||
| 9461 | struct sqlite3_pcache_page { | ||||
| 9462 | void *pBuf; /* The content of the page */ | ||||
| 9463 | void *pExtra; /* Extra information associated with the page */ | ||||
| 9464 | }; | ||||
| 9465 | |||||
| 9466 | /* | ||||
| 9467 | ** CAPI3REF: Application Defined Page Cache. | ||||
| 9468 | ** KEYWORDS: {page cache} | ||||
| 9469 | ** | ||||
| 9470 | ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can | ||||
| 9471 | ** register an alternative page cache implementation by passing in an | ||||
| 9472 | ** instance of the sqlite3_pcache_methods2 structure.)^ | ||||
| 9473 | ** In many applications, most of the heap memory allocated by | ||||
| 9474 | ** SQLite is used for the page cache. | ||||
| 9475 | ** By implementing a | ||||
| 9476 | ** custom page cache using this API, an application can better control | ||||
| 9477 | ** the amount of memory consumed by SQLite, the way in which | ||||
| 9478 | ** that memory is allocated and released, and the policies used to | ||||
| 9479 | ** determine exactly which parts of a database file are cached and for | ||||
| 9480 | ** how long. | ||||
| 9481 | ** | ||||
| 9482 | ** The alternative page cache mechanism is an | ||||
| 9483 | ** extreme measure that is only needed by the most demanding applications. | ||||
| 9484 | ** The built-in page cache is recommended for most uses. | ||||
| 9485 | ** | ||||
| 9486 | ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an | ||||
| 9487 | ** internal buffer by SQLite within the call to [sqlite3_config]. Hence | ||||
| 9488 | ** the application may discard the parameter after the call to | ||||
| 9489 | ** [sqlite3_config()] returns.)^ | ||||
| 9490 | ** | ||||
| 9491 | ** [[the xInit() page cache method]] | ||||
| 9492 | ** ^(The xInit() method is called once for each effective | ||||
| 9493 | ** call to [sqlite3_initialize()])^ | ||||
| 9494 | ** (usually only once during the lifetime of the process). ^(The xInit() | ||||
| 9495 | ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ | ||||
| 9496 | ** The intent of the xInit() method is to set up global data structures | ||||
| 9497 | ** required by the custom page cache implementation. | ||||
| 9498 | ** ^(If the xInit() method is NULL, then the | ||||
| 9499 | ** built-in default page cache is used instead of the application defined | ||||
| 9500 | ** page cache.)^ | ||||
| 9501 | ** | ||||
| 9502 | ** [[the xShutdown() page cache method]] | ||||
| 9503 | ** ^The xShutdown() method is called by [sqlite3_shutdown()]. | ||||
| 9504 | ** It can be used to clean up | ||||
| 9505 | ** any outstanding resources before process shutdown, if required. | ||||
| 9506 | ** ^The xShutdown() method may be NULL. | ||||
| 9507 | ** | ||||
| 9508 | ** ^SQLite automatically serializes calls to the xInit method, | ||||
| 9509 | ** so the xInit method need not be threadsafe. ^The | ||||
| 9510 | ** xShutdown method is only called from [sqlite3_shutdown()] so it does | ||||
| 9511 | ** not need to be threadsafe either. All other methods must be threadsafe | ||||
| 9512 | ** in multithreaded applications. | ||||
| 9513 | ** | ||||
| 9514 | ** ^SQLite will never invoke xInit() more than once without an intervening | ||||
| 9515 | ** call to xShutdown(). | ||||
| 9516 | ** | ||||
| 9517 | ** [[the xCreate() page cache methods]] | ||||
| 9518 | ** ^SQLite invokes the xCreate() method to construct a new cache instance. | ||||
| 9519 | ** SQLite will typically create one cache instance for each open database file, | ||||
| 9520 | ** though this is not guaranteed. ^The | ||||
| 9521 | ** first parameter, szPage, is the size in bytes of the pages that must | ||||
| 9522 | ** be allocated by the cache. ^szPage will always be a power of two. ^The | ||||
| 9523 | ** second parameter szExtra is a number of bytes of extra storage | ||||
| 9524 | ** associated with each page cache entry. ^The szExtra parameter will be | ||||
| 9525 | ** a number less than 250. SQLite will use the | ||||
| 9526 | ** extra szExtra bytes on each page to store metadata about the underlying | ||||
| 9527 | ** database page on disk. The value passed into szExtra depends | ||||
| 9528 | ** on the SQLite version, the target platform, and how SQLite was compiled. | ||||
| 9529 | ** ^The third argument to xCreate(), bPurgeable, is true if the cache being | ||||
| 9530 | ** created will be used to cache database pages of a file stored on disk, or | ||||
| 9531 | ** false if it is used for an in-memory database. The cache implementation | ||||
| 9532 | ** does not have to do anything special based upon the value of bPurgeable; | ||||
| 9533 | ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will | ||||
| 9534 | ** never invoke xUnpin() except to deliberately delete a page. | ||||
| 9535 | ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to | ||||
| 9536 | ** false will always have the "discard" flag set to true. | ||||
| 9537 | ** ^Hence, a cache created with bPurgeable set to false will | ||||
| 9538 | ** never contain any unpinned pages. | ||||
| 9539 | ** | ||||
| 9540 | ** [[the xCachesize() page cache method]] | ||||
| 9541 | ** ^(The xCachesize() method may be called at any time by SQLite to set the | ||||
| 9542 | ** suggested maximum cache-size (number of pages stored) for the cache | ||||
| 9543 | ** instance passed as the first argument. This is the value configured using | ||||
| 9544 | ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable | ||||
| 9545 | ** parameter, the implementation is not required to do anything with this | ||||
| 9546 | ** value; it is advisory only. | ||||
| 9547 | ** | ||||
| 9548 | ** [[the xPagecount() page cache methods]] | ||||
| 9549 | ** The xPagecount() method must return the number of pages currently | ||||
| 9550 | ** stored in the cache, both pinned and unpinned. | ||||
| 9551 | ** | ||||
| 9552 | ** [[the xFetch() page cache methods]] | ||||
| 9553 | ** The xFetch() method locates a page in the cache and returns a pointer to | ||||
| 9554 | ** an sqlite3_pcache_page object associated with that page, or a NULL pointer. | ||||
| 9555 | ** The pBuf element of the returned sqlite3_pcache_page object will be a | ||||
| 9556 | ** pointer to a buffer of szPage bytes used to store the content of a | ||||
| 9557 | ** single database page. The pExtra element of sqlite3_pcache_page will be | ||||
| 9558 | ** a pointer to the szExtra bytes of extra storage that SQLite has requested | ||||
| 9559 | ** for each entry in the page cache. | ||||
| 9560 | ** | ||||
| 9561 | ** The page to be fetched is determined by the key. ^The minimum key value | ||||
| 9562 | ** is 1. After it has been retrieved using xFetch, the page is considered | ||||
| 9563 | ** to be "pinned". | ||||
| 9564 | ** | ||||
| 9565 | ** If the requested page is already in the page cache, then the page cache | ||||
| 9566 | ** implementation must return a pointer to the page buffer with its content | ||||
| 9567 | ** intact. If the requested page is not already in the cache, then the | ||||
| 9568 | ** cache implementation should use the value of the createFlag | ||||
| 9569 | ** parameter to help it determine what action to take: | ||||
| 9570 | ** | ||||
| 9571 | ** <table border=1 width=85% align=center> | ||||
| 9572 | ** <tr><th> createFlag <th> Behavior when page is not already in cache | ||||
| 9573 | ** <tr><td> 0 <td> Do not allocate a new page. Return NULL. | ||||
| 9574 | ** <tr><td> 1 <td> Allocate a new page if it is easy and convenient to do so. | ||||
| 9575 | ** Otherwise return NULL. | ||||
| 9576 | ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return | ||||
| 9577 | ** NULL if allocating a new page is effectively impossible. | ||||
| 9578 | ** </table> | ||||
| 9579 | ** | ||||
| 9580 | ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite | ||||
| 9581 | ** will only use a createFlag of 2 after a prior call with a createFlag of 1 | ||||
| 9582 | ** failed.)^ In between the xFetch() calls, SQLite may | ||||
| 9583 | ** attempt to unpin one or more cache pages by spilling the content of | ||||
| 9584 | ** pinned pages to disk and synching the operating system disk cache. | ||||
| 9585 | ** | ||||
| 9586 | ** [[the xUnpin() page cache method]] | ||||
| 9587 | ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page | ||||
| 9588 | ** as its second argument. If the third parameter, discard, is non-zero, | ||||
| 9589 | ** then the page must be evicted from the cache. | ||||
| 9590 | ** ^If the discard parameter is | ||||
| 9591 | ** zero, then the page may be discarded or retained at the discretion of the | ||||
| 9592 | ** page cache implementation. ^The page cache implementation | ||||
| 9593 | ** may choose to evict unpinned pages at any time. | ||||
| 9594 | ** | ||||
| 9595 | ** The cache must not perform any reference counting. A single | ||||
| 9596 | ** call to xUnpin() unpins the page regardless of the number of prior calls | ||||
| 9597 | ** to xFetch(). | ||||
| 9598 | ** | ||||
| 9599 | ** [[the xRekey() page cache methods]] | ||||
| 9600 | ** The xRekey() method is used to change the key value associated with the | ||||
| 9601 | ** page passed as the second argument. If the cache | ||||
| 9602 | ** previously contains an entry associated with newKey, it must be | ||||
| 9603 | ** discarded. ^Any prior cache entry associated with newKey is guaranteed not | ||||
| 9604 | ** to be pinned. | ||||
| 9605 | ** | ||||
| 9606 | ** When SQLite calls the xTruncate() method, the cache must discard all | ||||
| 9607 | ** existing cache entries with page numbers (keys) greater than or equal | ||||
| 9608 | ** to the value of the iLimit parameter passed to xTruncate(). If any | ||||
| 9609 | ** of these pages are pinned, they become implicitly unpinned, meaning that | ||||
| 9610 | ** they can be safely discarded. | ||||
| 9611 | ** | ||||
| 9612 | ** [[the xDestroy() page cache method]] | ||||
| 9613 | ** ^The xDestroy() method is used to delete a cache allocated by xCreate(). | ||||
| 9614 | ** All resources associated with the specified cache should be freed. ^After | ||||
| 9615 | ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] | ||||
| 9616 | ** handle invalid, and will not use it with any other sqlite3_pcache_methods2 | ||||
| 9617 | ** functions. | ||||
| 9618 | ** | ||||
| 9619 | ** [[the xShrink() page cache method]] | ||||
| 9620 | ** ^SQLite invokes the xShrink() method when it wants the page cache to | ||||
| 9621 | ** free up as much of heap memory as possible. The page cache implementation | ||||
| 9622 | ** is not obligated to free any memory, but well-behaved implementations should | ||||
| 9623 | ** do their best. | ||||
| 9624 | */ | ||||
| 9625 | typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; | ||||
| 9626 | struct sqlite3_pcache_methods2 { | ||||
| 9627 | int iVersion; | ||||
| 9628 | void *pArg; | ||||
| 9629 | int (*xInit)(void*); | ||||
| 9630 | void (*xShutdown)(void*); | ||||
| 9631 | sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); | ||||
| 9632 | void (*xCachesize)(sqlite3_pcache*, int nCachesize); | ||||
| 9633 | int (*xPagecount)(sqlite3_pcache*); | ||||
| 9634 | sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); | ||||
| 9635 | void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); | ||||
| 9636 | void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, | ||||
| 9637 | unsigned oldKey, unsigned newKey); | ||||
| 9638 | void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); | ||||
| 9639 | void (*xDestroy)(sqlite3_pcache*); | ||||
| 9640 | void (*xShrink)(sqlite3_pcache*); | ||||
| 9641 | }; | ||||
| 9642 | |||||
| 9643 | /* | ||||
| 9644 | ** This is the obsolete pcache_methods object that has now been replaced | ||||
| 9645 | ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is | ||||
| 9646 | ** retained in the header file for backwards compatibility only. | ||||
| 9647 | */ | ||||
| 9648 | typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; | ||||
| 9649 | struct sqlite3_pcache_methods { | ||||
| 9650 | void *pArg; | ||||
| 9651 | int (*xInit)(void*); | ||||
| 9652 | void (*xShutdown)(void*); | ||||
| 9653 | sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); | ||||
| 9654 | void (*xCachesize)(sqlite3_pcache*, int nCachesize); | ||||
| 9655 | int (*xPagecount)(sqlite3_pcache*); | ||||
| 9656 | void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); | ||||
| 9657 | void (*xUnpin)(sqlite3_pcache*, void*, int discard); | ||||
| 9658 | void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); | ||||
| 9659 | void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); | ||||
| 9660 | void (*xDestroy)(sqlite3_pcache*); | ||||
| 9661 | }; | ||||
| 9662 | |||||
| 9663 | |||||
| 9664 | /* | ||||
| 9665 | ** CAPI3REF: Online Backup Object | ||||
| 9666 | ** | ||||
| 9667 | ** The sqlite3_backup object records state information about an ongoing | ||||
| 9668 | ** online backup operation. ^The sqlite3_backup object is created by | ||||
| 9669 | ** a call to [sqlite3_backup_init()] and is destroyed by a call to | ||||
| 9670 | ** [sqlite3_backup_finish()]. | ||||
| 9671 | ** | ||||
| 9672 | ** See Also: [Using the SQLite Online Backup API] | ||||
| 9673 | */ | ||||
| 9674 | typedef struct sqlite3_backup sqlite3_backup; | ||||
| 9675 | |||||
| 9676 | /* | ||||
| 9677 | ** CAPI3REF: Online Backup API. | ||||
| 9678 | ** | ||||
| 9679 | ** The backup API copies the content of one database into another. | ||||
| 9680 | ** It is useful either for creating backups of databases or | ||||
| 9681 | ** for copying in-memory databases to or from persistent files. | ||||
| 9682 | ** | ||||
| 9683 | ** See Also: [Using the SQLite Online Backup API] | ||||
| 9684 | ** | ||||
| 9685 | ** ^SQLite holds a write transaction open on the destination database file | ||||
| 9686 | ** for the duration of the backup operation. | ||||
| 9687 | ** ^The source database is read-locked only while it is being read; | ||||
| 9688 | ** it is not locked continuously for the entire backup operation. | ||||
| 9689 | ** ^Thus, the backup may be performed on a live source database without | ||||
| 9690 | ** preventing other database connections from | ||||
| 9691 | ** reading or writing to the source database while the backup is underway. | ||||
| 9692 | ** | ||||
| 9693 | ** ^(To perform a backup operation: | ||||
| 9694 | ** <ol> | ||||
| 9695 | ** <li><b>sqlite3_backup_init()</b> is called once to initialize the | ||||
| 9696 | ** backup, | ||||
| 9697 | ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer | ||||
| 9698 | ** the data between the two databases, and finally | ||||
| 9699 | ** <li><b>sqlite3_backup_finish()</b> is called to release all resources | ||||
| 9700 | ** associated with the backup operation. | ||||
| 9701 | ** </ol>)^ | ||||
| 9702 | ** There should be exactly one call to sqlite3_backup_finish() for each | ||||
| 9703 | ** successful call to sqlite3_backup_init(). | ||||
| 9704 | ** | ||||
| 9705 | ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b> | ||||
| 9706 | ** | ||||
| 9707 | ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the | ||||
| 9708 | ** [database connection] associated with the destination database | ||||
| 9709 | ** and the database name, respectively. | ||||
| 9710 | ** ^The database name is "main" for the main database, "temp" for the | ||||
| 9711 | ** temporary database, or the name specified after the AS keyword in | ||||
| 9712 | ** an [ATTACH] statement for an attached database. | ||||
| 9713 | ** ^The S and M arguments passed to | ||||
| 9714 | ** sqlite3_backup_init(D,N,S,M) identify the [database connection] | ||||
| 9715 | ** and database name of the source database, respectively. | ||||
| 9716 | ** ^The source and destination [database connections] (parameters S and D) | ||||
| 9717 | ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with | ||||
| 9718 | ** an error. | ||||
| 9719 | ** | ||||
| 9720 | ** ^A call to sqlite3_backup_init() will fail, returning NULL, if | ||||
| 9721 | ** there is already a read or read-write transaction open on the | ||||
| 9722 | ** destination database. | ||||
| 9723 | ** | ||||
| 9724 | ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is | ||||
| 9725 | ** returned and an error code and error message are stored in the | ||||
| 9726 | ** destination [database connection] D. | ||||
| 9727 | ** ^The error code and message for the failed call to sqlite3_backup_init() | ||||
| 9728 | ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or | ||||
| 9729 | ** [sqlite3_errmsg16()] functions. | ||||
| 9730 | ** ^A successful call to sqlite3_backup_init() returns a pointer to an | ||||
| 9731 | ** [sqlite3_backup] object. | ||||
| 9732 | ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and | ||||
| 9733 | ** sqlite3_backup_finish() functions to perform the specified backup | ||||
| 9734 | ** operation. | ||||
| 9735 | ** | ||||
| 9736 | ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b> | ||||
| 9737 | ** | ||||
| 9738 | ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between | ||||
| 9739 | ** the source and destination databases specified by [sqlite3_backup] object B. | ||||
| 9740 | ** ^If N is negative, all remaining source pages are copied. | ||||
| 9741 | ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there | ||||
| 9742 | ** are still more pages to be copied, then the function returns [SQLITE_OK]. | ||||
| 9743 | ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages | ||||
| 9744 | ** from source to destination, then it returns [SQLITE_DONE]. | ||||
| 9745 | ** ^If an error occurs while running sqlite3_backup_step(B,N), | ||||
| 9746 | ** then an [error code] is returned. ^As well as [SQLITE_OK] and | ||||
| 9747 | ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], | ||||
| 9748 | ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an | ||||
| 9749 | ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. | ||||
| 9750 | ** | ||||
| 9751 | ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if | ||||
| 9752 | ** <ol> | ||||
| 9753 | ** <li> the destination database was opened read-only, or | ||||
| 9754 | ** <li> the destination database is using write-ahead-log journaling | ||||
| 9755 | ** and the destination and source page sizes differ, or | ||||
| 9756 | ** <li> the destination database is an in-memory database and the | ||||
| 9757 | ** destination and source page sizes differ. | ||||
| 9758 | ** </ol>)^ | ||||
| 9759 | ** | ||||
| 9760 | ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then | ||||
| 9761 | ** the [sqlite3_busy_handler | busy-handler function] | ||||
| 9762 | ** is invoked (if one is specified). ^If the | ||||
| 9763 | ** busy-handler returns non-zero before the lock is available, then | ||||
| 9764 | ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to | ||||
| 9765 | ** sqlite3_backup_step() can be retried later. ^If the source | ||||
| 9766 | ** [database connection] | ||||
| 9767 | ** is being used to write to the source database when sqlite3_backup_step() | ||||
| 9768 | ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this | ||||
| 9769 | ** case the call to sqlite3_backup_step() can be retried later on. ^(If | ||||
| 9770 | ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or | ||||
| 9771 | ** [SQLITE_READONLY] is returned, then | ||||
| 9772 | ** there is no point in retrying the call to sqlite3_backup_step(). These | ||||
| 9773 | ** errors are considered fatal.)^ The application must accept | ||||
| 9774 | ** that the backup operation has failed and pass the backup operation handle | ||||
| 9775 | ** to the sqlite3_backup_finish() to release associated resources. | ||||
| 9776 | ** | ||||
| 9777 | ** ^The first call to sqlite3_backup_step() obtains an exclusive lock | ||||
| 9778 | ** on the destination file. ^The exclusive lock is not released until either | ||||
| 9779 | ** sqlite3_backup_finish() is called or the backup operation is complete | ||||
| 9780 | ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to | ||||
| 9781 | ** sqlite3_backup_step() obtains a [shared lock] on the source database that | ||||
| 9782 | ** lasts for the duration of the sqlite3_backup_step() call. | ||||
| 9783 | ** ^Because the source database is not locked between calls to | ||||
| 9784 | ** sqlite3_backup_step(), the source database may be modified mid-way | ||||
| 9785 | ** through the backup process. ^If the source database is modified by an | ||||
| 9786 | ** external process or via a database connection other than the one being | ||||
| 9787 | ** used by the backup operation, then the backup will be automatically | ||||
| 9788 | ** restarted by the next call to sqlite3_backup_step(). ^If the source | ||||
| 9789 | ** database is modified by using the same database connection as is used | ||||
| 9790 | ** by the backup operation, then the backup database is automatically | ||||
| 9791 | ** updated at the same time. | ||||
| 9792 | ** | ||||
| 9793 | ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b> | ||||
| 9794 | ** | ||||
| 9795 | ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the | ||||
| 9796 | ** application wishes to abandon the backup operation, the application | ||||
| 9797 | ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). | ||||
| 9798 | ** ^The sqlite3_backup_finish() interfaces releases all | ||||
| 9799 | ** resources associated with the [sqlite3_backup] object. | ||||
| 9800 | ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any | ||||
| 9801 | ** active write-transaction on the destination database is rolled back. | ||||
| 9802 | ** The [sqlite3_backup] object is invalid | ||||
| 9803 | ** and may not be used following a call to sqlite3_backup_finish(). | ||||
| 9804 | ** | ||||
| 9805 | ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no | ||||
| 9806 | ** sqlite3_backup_step() errors occurred, regardless of whether or not | ||||
| 9807 | ** sqlite3_backup_step() completed. | ||||
| 9808 | ** ^If an out-of-memory condition or IO error occurred during any prior | ||||
| 9809 | ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then | ||||
| 9810 | ** sqlite3_backup_finish() returns the corresponding [error code]. | ||||
| 9811 | ** | ||||
| 9812 | ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() | ||||
| 9813 | ** is not a permanent error and does not affect the return value of | ||||
| 9814 | ** sqlite3_backup_finish(). | ||||
| 9815 | ** | ||||
| 9816 | ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] | ||||
| 9817 | ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b> | ||||
| 9818 | ** | ||||
| 9819 | ** ^The sqlite3_backup_remaining() routine returns the number of pages still | ||||
| 9820 | ** to be backed up at the conclusion of the most recent sqlite3_backup_step(). | ||||
| 9821 | ** ^The sqlite3_backup_pagecount() routine returns the total number of pages | ||||
| 9822 | ** in the source database at the conclusion of the most recent | ||||
| 9823 | ** sqlite3_backup_step(). | ||||
| 9824 | ** ^(The values returned by these functions are only updated by | ||||
| 9825 | ** sqlite3_backup_step(). If the source database is modified in a way that | ||||
| 9826 | ** changes the size of the source database or the number of pages remaining, | ||||
| 9827 | ** those changes are not reflected in the output of sqlite3_backup_pagecount() | ||||
| 9828 | ** and sqlite3_backup_remaining() until after the next | ||||
| 9829 | ** sqlite3_backup_step().)^ | ||||
| 9830 | ** | ||||
| 9831 | ** <b>Concurrent Usage of Database Handles</b> | ||||
| 9832 | ** | ||||
| 9833 | ** ^The source [database connection] may be used by the application for other | ||||
| 9834 | ** purposes while a backup operation is underway or being initialized. | ||||
| 9835 | ** ^If SQLite is compiled and configured to support threadsafe database | ||||
| 9836 | ** connections, then the source database connection may be used concurrently | ||||
| 9837 | ** from within other threads. | ||||
| 9838 | ** | ||||
| 9839 | ** However, the application must guarantee that the destination | ||||
| 9840 | ** [database connection] is not passed to any other API (by any thread) after | ||||
| 9841 | ** sqlite3_backup_init() is called and before the corresponding call to | ||||
| 9842 | ** sqlite3_backup_finish(). SQLite does not currently check to see | ||||
| 9843 | ** if the application incorrectly accesses the destination [database connection] | ||||
| 9844 | ** and so no error code is reported, but the operations may malfunction | ||||
| 9845 | ** nevertheless. Use of the destination database connection while a | ||||
| 9846 | ** backup is in progress might also cause a mutex deadlock. | ||||
| 9847 | ** | ||||
| 9848 | ** If running in [shared cache mode], the application must | ||||
| 9849 | ** guarantee that the shared cache used by the destination database | ||||
| 9850 | ** is not accessed while the backup is running. In practice this means | ||||
| 9851 | ** that the application must guarantee that the disk file being | ||||
| 9852 | ** backed up to is not accessed by any connection within the process, | ||||
| 9853 | ** not just the specific connection that was passed to sqlite3_backup_init(). | ||||
| 9854 | ** | ||||
| 9855 | ** The [sqlite3_backup] object itself is partially threadsafe. Multiple | ||||
| 9856 | ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). | ||||
| 9857 | ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() | ||||
| 9858 | ** APIs are not strictly speaking threadsafe. If they are invoked at the | ||||
| 9859 | ** same time as another thread is invoking sqlite3_backup_step() it is | ||||
| 9860 | ** possible that they return invalid values. | ||||
| 9861 | ** | ||||
| 9862 | ** <b>Alternatives To Using The Backup API</b> | ||||
| 9863 | ** | ||||
| 9864 | ** Other techniques for safely creating a consistent backup of an SQLite | ||||
| 9865 | ** database include: | ||||
| 9866 | ** | ||||
| 9867 | ** <ul> | ||||
| 9868 | ** <li> The [VACUUM INTO] command. | ||||
| 9869 | ** <li> The [sqlite3_rsync] utility program. | ||||
| 9870 | ** </ul> | ||||
| 9871 | */ | ||||
| 9872 | SQLITE_API sqlite3_backup *sqlite3_backup_init( | ||||
| 9873 | sqlite3 *pDest, /* Destination database handle */ | ||||
| 9874 | const char *zDestName, /* Destination database name */ | ||||
| 9875 | sqlite3 *pSource, /* Source database handle */ | ||||
| 9876 | const char *zSourceName /* Source database name */ | ||||
| 9877 | ); | ||||
| 9878 | SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); | ||||
| 9879 | SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); | ||||
| 9880 | SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); | ||||
| 9881 | SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); | ||||
| 9882 | |||||
| 9883 | /* | ||||
| 9884 | ** CAPI3REF: Unlock Notification | ||||
| 9885 | ** METHOD: sqlite3 | ||||
| 9886 | ** | ||||
| 9887 | ** ^When running in shared-cache mode, a database operation may fail with | ||||
| 9888 | ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or | ||||
| 9889 | ** individual tables within the shared-cache cannot be obtained. See | ||||
| 9890 | ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. | ||||
| 9891 | ** ^This API may be used to register a callback that SQLite will invoke | ||||
| 9892 | ** when the connection currently holding the required lock relinquishes it. | ||||
| 9893 | ** ^This API is only available if the library was compiled with the | ||||
| 9894 | ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. | ||||
| 9895 | ** | ||||
| 9896 | ** See Also: [Using the SQLite Unlock Notification Feature]. | ||||
| 9897 | ** | ||||
| 9898 | ** ^Shared-cache locks are released when a database connection concludes | ||||
| 9899 | ** its current transaction, either by committing it or rolling it back. | ||||
| 9900 | ** | ||||
| 9901 | ** ^When a connection (known as the blocked connection) fails to obtain a | ||||
| 9902 | ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the | ||||
| 9903 | ** identity of the database connection (the blocking connection) that | ||||
| 9904 | ** has locked the required resource is stored internally. ^After an | ||||
| 9905 | ** application receives an SQLITE_LOCKED error, it may call the | ||||
| 9906 | ** sqlite3_unlock_notify() method with the blocked connection handle as | ||||
| 9907 | ** the first argument to register for a callback that will be invoked | ||||
| 9908 | ** when the blocking connection's current transaction is concluded. ^The | ||||
| 9909 | ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] | ||||
| 9910 | ** call that concludes the blocking connection's transaction. | ||||
| 9911 | ** | ||||
| 9912 | ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, | ||||
| 9913 | ** there is a chance that the blocking connection will have already | ||||
| 9914 | ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. | ||||
| 9915 | ** If this happens, then the specified callback is invoked immediately, | ||||
| 9916 | ** from within the call to sqlite3_unlock_notify().)^ | ||||
| 9917 | ** | ||||
| 9918 | ** ^If the blocked connection is attempting to obtain a write-lock on a | ||||
| 9919 | ** shared-cache table, and more than one other connection currently holds | ||||
| 9920 | ** a read-lock on the same table, then SQLite arbitrarily selects one of | ||||
| 9921 | ** the other connections to use as the blocking connection. | ||||
| 9922 | ** | ||||
| 9923 | ** ^(There may be at most one unlock-notify callback registered by a | ||||
| 9924 | ** blocked connection. If sqlite3_unlock_notify() is called when the | ||||
| 9925 | ** blocked connection already has a registered unlock-notify callback, | ||||
| 9926 | ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is | ||||
| 9927 | ** called with a NULL pointer as its second argument, then any existing | ||||
| 9928 | ** unlock-notify callback is canceled. ^The blocked connection's | ||||
| 9929 | ** unlock-notify callback may also be canceled by closing the blocked | ||||
| 9930 | ** connection using [sqlite3_close()]. | ||||
| 9931 | ** | ||||
| 9932 | ** The unlock-notify callback is not reentrant. If an application invokes | ||||
| 9933 | ** any sqlite3_xxx API functions from within an unlock-notify callback, a | ||||
| 9934 | ** crash or deadlock may be the result. | ||||
| 9935 | ** | ||||
| 9936 | ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always | ||||
| 9937 | ** returns SQLITE_OK. | ||||
| 9938 | ** | ||||
| 9939 | ** <b>Callback Invocation Details</b> | ||||
| 9940 | ** | ||||
| 9941 | ** When an unlock-notify callback is registered, the application provides a | ||||
| 9942 | ** single void* pointer that is passed to the callback when it is invoked. | ||||
| 9943 | ** However, the signature of the callback function allows SQLite to pass | ||||
| 9944 | ** it an array of void* context pointers. The first argument passed to | ||||
| 9945 | ** an unlock-notify callback is a pointer to an array of void* pointers, | ||||
| 9946 | ** and the second is the number of entries in the array. | ||||
| 9947 | ** | ||||
| 9948 | ** When a blocking connection's transaction is concluded, there may be | ||||
| 9949 | ** more than one blocked connection that has registered for an unlock-notify | ||||
| 9950 | ** callback. ^If two or more such blocked connections have specified the | ||||
| 9951 | ** same callback function, then instead of invoking the callback function | ||||
| 9952 | ** multiple times, it is invoked once with the set of void* context pointers | ||||
| 9953 | ** specified by the blocked connections bundled together into an array. | ||||
| 9954 | ** This gives the application an opportunity to prioritize any actions | ||||
| 9955 | ** related to the set of unblocked database connections. | ||||
| 9956 | ** | ||||
| 9957 | ** <b>Deadlock Detection</b> | ||||
| 9958 | ** | ||||
| 9959 | ** Assuming that after registering for an unlock-notify callback a | ||||
| 9960 | ** database waits for the callback to be issued before taking any further | ||||
| 9961 | ** action (a reasonable assumption), then using this API may cause the | ||||
| 9962 | ** application to deadlock. For example, if connection X is waiting for | ||||
| 9963 | ** connection Y's transaction to be concluded, and similarly connection | ||||
| 9964 | ** Y is waiting on connection X's transaction, then neither connection | ||||
| 9965 | ** will proceed and the system may remain deadlocked indefinitely. | ||||
| 9966 | ** | ||||
| 9967 | ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock | ||||
| 9968 | ** detection. ^If a given call to sqlite3_unlock_notify() would put the | ||||
| 9969 | ** system in a deadlocked state, then SQLITE_LOCKED is returned and no | ||||
| 9970 | ** unlock-notify callback is registered. The system is said to be in | ||||
| 9971 | ** a deadlocked state if connection A has registered for an unlock-notify | ||||
| 9972 | ** callback on the conclusion of connection B's transaction, and connection | ||||
| 9973 | ** B has itself registered for an unlock-notify callback when connection | ||||
| 9974 | ** A's transaction is concluded. ^Indirect deadlock is also detected, so | ||||
| 9975 | ** the system is also considered to be deadlocked if connection B has | ||||
| 9976 | ** registered for an unlock-notify callback on the conclusion of connection | ||||
| 9977 | ** C's transaction, where connection C is waiting on connection A. ^Any | ||||
| 9978 | ** number of levels of indirection are allowed. | ||||
| 9979 | ** | ||||
| 9980 | ** <b>The "DROP TABLE" Exception</b> | ||||
| 9981 | ** | ||||
| 9982 | ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost | ||||
| 9983 | ** always appropriate to call sqlite3_unlock_notify(). There is however, | ||||
| 9984 | ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, | ||||
| 9985 | ** SQLite checks if there are any currently executing SELECT statements | ||||
| 9986 | ** that belong to the same connection. If there are, SQLITE_LOCKED is | ||||
| 9987 | ** returned. In this case there is no "blocking connection", so invoking | ||||
| 9988 | ** sqlite3_unlock_notify() results in the unlock-notify callback being | ||||
| 9989 | ** invoked immediately. If the application then re-attempts the "DROP TABLE" | ||||
| 9990 | ** or "DROP INDEX" query, an infinite loop might be the result. | ||||
| 9991 | ** | ||||
| 9992 | ** One way around this problem is to check the extended error code returned | ||||
| 9993 | ** by an sqlite3_step() call. ^(If there is a blocking connection, then the | ||||
| 9994 | ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in | ||||
| 9995 | ** the special "DROP TABLE/INDEX" case, the extended error code is just | ||||
| 9996 | ** SQLITE_LOCKED.)^ | ||||
| 9997 | */ | ||||
| 9998 | SQLITE_API int sqlite3_unlock_notify( | ||||
| 9999 | sqlite3 *pBlocked, /* Waiting connection */ | ||||
| 10000 | void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ | ||||
| 10001 | void *pNotifyArg /* Argument to pass to xNotify */ | ||||
| 10002 | ); | ||||
| 10003 | |||||
| 10004 | |||||
| 10005 | /* | ||||
| 10006 | ** CAPI3REF: String Comparison | ||||
| 10007 | ** | ||||
| 10008 | ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications | ||||
| 10009 | ** and extensions to compare the contents of two buffers containing UTF-8 | ||||
| 10010 | ** strings in a case-independent fashion, using the same definition of "case | ||||
| 10011 | ** independence" that SQLite uses internally when comparing identifiers. | ||||
| 10012 | */ | ||||
| 10013 | SQLITE_API int sqlite3_stricmp(const char *, const char *); | ||||
| 10014 | SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); | ||||
| 10015 | |||||
| 10016 | /* | ||||
| 10017 | ** CAPI3REF: String Globbing | ||||
| 10018 | * | ||||
| 10019 | ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if | ||||
| 10020 | ** string X matches the [GLOB] pattern P. | ||||
| 10021 | ** ^The definition of [GLOB] pattern matching used in | ||||
| 10022 | ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the | ||||
| 10023 | ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function | ||||
| 10024 | ** is case sensitive. | ||||
| 10025 | ** | ||||
| 10026 | ** Note that this routine returns zero on a match and non-zero if the strings | ||||
| 10027 | ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. | ||||
| 10028 | ** | ||||
| 10029 | ** See also: [sqlite3_strlike()]. | ||||
| 10030 | */ | ||||
| 10031 | SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); | ||||
| 10032 | |||||
| 10033 | /* | ||||
| 10034 | ** CAPI3REF: String LIKE Matching | ||||
| 10035 | * | ||||
| 10036 | ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if | ||||
| 10037 | ** string X matches the [LIKE] pattern P with escape character E. | ||||
| 10038 | ** ^The definition of [LIKE] pattern matching used in | ||||
| 10039 | ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" | ||||
| 10040 | ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without | ||||
| 10041 | ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. | ||||
| 10042 | ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case | ||||
| 10043 | ** insensitive - equivalent upper and lower case ASCII characters match | ||||
| 10044 | ** one another. | ||||
| 10045 | ** | ||||
| 10046 | ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though | ||||
| 10047 | ** only ASCII characters are case folded. | ||||
| 10048 | ** | ||||
| 10049 | ** Note that this routine returns zero on a match and non-zero if the strings | ||||
| 10050 | ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. | ||||
| 10051 | ** | ||||
| 10052 | ** See also: [sqlite3_strglob()]. | ||||
| 10053 | */ | ||||
| 10054 | SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); | ||||
| 10055 | |||||
| 10056 | /* | ||||
| 10057 | ** CAPI3REF: Error Logging Interface | ||||
| 10058 | ** | ||||
| 10059 | ** ^The [sqlite3_log()] interface writes a message into the [error log] | ||||
| 10060 | ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. | ||||
| 10061 | ** ^If logging is enabled, the zFormat string and subsequent arguments are | ||||
| 10062 | ** used with [sqlite3_snprintf()] to generate the final output string. | ||||
| 10063 | ** | ||||
| 10064 | ** The sqlite3_log() interface is intended for use by extensions such as | ||||
| 10065 | ** virtual tables, collating functions, and SQL functions. While there is | ||||
| 10066 | ** nothing to prevent an application from calling sqlite3_log(), doing so | ||||
| 10067 | ** is considered bad form. | ||||
| 10068 | ** | ||||
| 10069 | ** The zFormat string must not be NULL. | ||||
| 10070 | ** | ||||
| 10071 | ** To avoid deadlocks and other threading problems, the sqlite3_log() routine | ||||
| 10072 | ** will not use dynamically allocated memory. The log message is stored in | ||||
| 10073 | ** a fixed-length buffer on the stack. If the log message is longer than | ||||
| 10074 | ** a few hundred characters, it will be truncated to the length of the | ||||
| 10075 | ** buffer. | ||||
| 10076 | */ | ||||
| 10077 | SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); | ||||
| 10078 | |||||
| 10079 | /* | ||||
| 10080 | ** CAPI3REF: Write-Ahead Log Commit Hook | ||||
| 10081 | ** METHOD: sqlite3 | ||||
| 10082 | ** | ||||
| 10083 | ** ^The [sqlite3_wal_hook()] function is used to register a callback that | ||||
| 10084 | ** is invoked each time data is committed to a database in wal mode. | ||||
| 10085 | ** | ||||
| 10086 | ** ^(The callback is invoked by SQLite after the commit has taken place and | ||||
| 10087 | ** the associated write-lock on the database released)^, so the implementation | ||||
| 10088 | ** may read, write or [checkpoint] the database as required. | ||||
| 10089 | ** | ||||
| 10090 | ** ^The first parameter passed to the callback function when it is invoked | ||||
| 10091 | ** is a copy of the third parameter passed to sqlite3_wal_hook() when | ||||
| 10092 | ** registering the callback. ^The second is a copy of the database handle. | ||||
| 10093 | ** ^The third parameter is the name of the database that was written to - | ||||
| 10094 | ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter | ||||
| 10095 | ** is the number of pages currently in the write-ahead log file, | ||||
| 10096 | ** including those that were just committed. | ||||
| 10097 | ** | ||||
| 10098 | ** The callback function should normally return [SQLITE_OK]. ^If an error | ||||
| 10099 | ** code is returned, that error will propagate back up through the | ||||
| 10100 | ** SQLite code base to cause the statement that provoked the callback | ||||
| 10101 | ** to report an error, though the commit will have still occurred. If the | ||||
| 10102 | ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value | ||||
| 10103 | ** that does not correspond to any valid SQLite error code, the results | ||||
| 10104 | ** are undefined. | ||||
| 10105 | ** | ||||
| 10106 | ** A single database handle may have at most a single write-ahead log callback | ||||
| 10107 | ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any | ||||
| 10108 | ** previously registered write-ahead log callback. ^The return value is | ||||
| 10109 | ** a copy of the third parameter from the previous call, if any, or 0. | ||||
| 10110 | ** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the | ||||
| 10111 | ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will | ||||
| 10112 | ** overwrite any prior [sqlite3_wal_hook()] settings. | ||||
| 10113 | */ | ||||
| 10114 | SQLITE_API void *sqlite3_wal_hook( | ||||
| 10115 | sqlite3*, | ||||
| 10116 | int(*)(void *,sqlite3*,const char*,int), | ||||
| 10117 | void* | ||||
| 10118 | ); | ||||
| 10119 | |||||
| 10120 | /* | ||||
| 10121 | ** CAPI3REF: Configure an auto-checkpoint | ||||
| 10122 | ** METHOD: sqlite3 | ||||
| 10123 | ** | ||||
| 10124 | ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around | ||||
| 10125 | ** [sqlite3_wal_hook()] that causes any database on [database connection] D | ||||
| 10126 | ** to automatically [checkpoint] | ||||
| 10127 | ** after committing a transaction if there are N or | ||||
| 10128 | ** more frames in the [write-ahead log] file. ^Passing zero or | ||||
| 10129 | ** a negative value as the nFrame parameter disables automatic | ||||
| 10130 | ** checkpoints entirely. | ||||
| 10131 | ** | ||||
| 10132 | ** ^The callback registered by this function replaces any existing callback | ||||
| 10133 | ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback | ||||
| 10134 | ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism | ||||
| 10135 | ** configured by this function. | ||||
| 10136 | ** | ||||
| 10137 | ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface | ||||
| 10138 | ** from SQL. | ||||
| 10139 | ** | ||||
| 10140 | ** ^Checkpoints initiated by this mechanism are | ||||
| 10141 | ** [sqlite3_wal_checkpoint_v2|PASSIVE]. | ||||
| 10142 | ** | ||||
| 10143 | ** ^Every new [database connection] defaults to having the auto-checkpoint | ||||
| 10144 | ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] | ||||
| 10145 | ** pages. The use of this interface | ||||
| 10146 | ** is only necessary if the default setting is found to be suboptimal | ||||
| 10147 | ** for a particular application. | ||||
| 10148 | */ | ||||
| 10149 | SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); | ||||
| 10150 | |||||
| 10151 | /* | ||||
| 10152 | ** CAPI3REF: Checkpoint a database | ||||
| 10153 | ** METHOD: sqlite3 | ||||
| 10154 | ** | ||||
| 10155 | ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to | ||||
| 10156 | ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ | ||||
| 10157 | ** | ||||
| 10158 | ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the | ||||
| 10159 | ** [write-ahead log] for database X on [database connection] D to be | ||||
| 10160 | ** transferred into the database file and for the write-ahead log to | ||||
| 10161 | ** be reset. See the [checkpointing] documentation for addition | ||||
| 10162 | ** information. | ||||
| 10163 | ** | ||||
| 10164 | ** This interface used to be the only way to cause a checkpoint to | ||||
| 10165 | ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] | ||||
| 10166 | ** interface was added. This interface is retained for backwards | ||||
| 10167 | ** compatibility and as a convenience for applications that need to manually | ||||
| 10168 | ** start a callback but which do not need the full power (and corresponding | ||||
| 10169 | ** complication) of [sqlite3_wal_checkpoint_v2()]. | ||||
| 10170 | */ | ||||
| 10171 | SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); | ||||
| 10172 | |||||
| 10173 | /* | ||||
| 10174 | ** CAPI3REF: Checkpoint a database | ||||
| 10175 | ** METHOD: sqlite3 | ||||
| 10176 | ** | ||||
| 10177 | ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint | ||||
| 10178 | ** operation on database X of [database connection] D in mode M. Status | ||||
| 10179 | ** information is written back into integers pointed to by L and C.)^ | ||||
| 10180 | ** ^(The M parameter must be a valid [checkpoint mode]:)^ | ||||
| 10181 | ** | ||||
| 10182 | ** <dl> | ||||
| 10183 | ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd> | ||||
| 10184 | ** ^Checkpoint as many frames as possible without waiting for any database | ||||
| 10185 | ** readers or writers to finish, then sync the database file if all frames | ||||
| 10186 | ** in the log were checkpointed. ^The [busy-handler callback] | ||||
| 10187 | ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode. | ||||
| 10188 | ** ^On the other hand, passive mode might leave the checkpoint unfinished | ||||
| 10189 | ** if there are concurrent readers or writers. | ||||
| 10190 | ** | ||||
| 10191 | ** <dt>SQLITE_CHECKPOINT_FULL<dd> | ||||
| 10192 | ** ^This mode blocks (it invokes the | ||||
| 10193 | ** [sqlite3_busy_handler|busy-handler callback]) until there is no | ||||
| 10194 | ** database writer and all readers are reading from the most recent database | ||||
| 10195 | ** snapshot. ^It then checkpoints all frames in the log file and syncs the | ||||
| 10196 | ** database file. ^This mode blocks new database writers while it is pending, | ||||
| 10197 | ** but new database readers are allowed to continue unimpeded. | ||||
| 10198 | ** | ||||
| 10199 | ** <dt>SQLITE_CHECKPOINT_RESTART<dd> | ||||
| 10200 | ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition | ||||
| 10201 | ** that after checkpointing the log file it blocks (calls the | ||||
| 10202 | ** [busy-handler callback]) | ||||
| 10203 | ** until all readers are reading from the database file only. ^This ensures | ||||
| 10204 | ** that the next writer will restart the log file from the beginning. | ||||
| 10205 | ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new | ||||
| 10206 | ** database writer attempts while it is pending, but does not impede readers. | ||||
| 10207 | ** | ||||
| 10208 | ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd> | ||||
| 10209 | ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the | ||||
| 10210 | ** addition that it also truncates the log file to zero bytes just prior | ||||
| 10211 | ** to a successful return. | ||||
| 10212 | ** </dl> | ||||
| 10213 | ** | ||||
| 10214 | ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in | ||||
| 10215 | ** the log file or to -1 if the checkpoint could not run because | ||||
| 10216 | ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not | ||||
| 10217 | ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the | ||||
| 10218 | ** log file (including any that were already checkpointed before the function | ||||
| 10219 | ** was called) or to -1 if the checkpoint could not run due to an error or | ||||
| 10220 | ** because the database is not in WAL mode. ^Note that upon successful | ||||
| 10221 | ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been | ||||
| 10222 | ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. | ||||
| 10223 | ** | ||||
| 10224 | ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If | ||||
| 10225 | ** any other process is running a checkpoint operation at the same time, the | ||||
| 10226 | ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a | ||||
| 10227 | ** busy-handler configured, it will not be invoked in this case. | ||||
| 10228 | ** | ||||
| 10229 | ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the | ||||
| 10230 | ** exclusive "writer" lock on the database file. ^If the writer lock cannot be | ||||
| 10231 | ** obtained immediately, and a busy-handler is configured, it is invoked and | ||||
| 10232 | ** the writer lock retried until either the busy-handler returns 0 or the lock | ||||
| 10233 | ** is successfully obtained. ^The busy-handler is also invoked while waiting for | ||||
| 10234 | ** database readers as described above. ^If the busy-handler returns 0 before | ||||
| 10235 | ** the writer lock is obtained or while waiting for database readers, the | ||||
| 10236 | ** checkpoint operation proceeds from that point in the same way as | ||||
| 10237 | ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible | ||||
| 10238 | ** without blocking any further. ^SQLITE_BUSY is returned in this case. | ||||
| 10239 | ** | ||||
| 10240 | ** ^If parameter zDb is NULL or points to a zero length string, then the | ||||
| 10241 | ** specified operation is attempted on all WAL databases [attached] to | ||||
| 10242 | ** [database connection] db. In this case the | ||||
| 10243 | ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If | ||||
| 10244 | ** an SQLITE_BUSY error is encountered when processing one or more of the | ||||
| 10245 | ** attached WAL databases, the operation is still attempted on any remaining | ||||
| 10246 | ** attached databases and SQLITE_BUSY is returned at the end. ^If any other | ||||
| 10247 | ** error occurs while processing an attached database, processing is abandoned | ||||
| 10248 | ** and the error code is returned to the caller immediately. ^If no error | ||||
| 10249 | ** (SQLITE_BUSY or otherwise) is encountered while processing the attached | ||||
| 10250 | ** databases, SQLITE_OK is returned. | ||||
| 10251 | ** | ||||
| 10252 | ** ^If database zDb is the name of an attached database that is not in WAL | ||||
| 10253 | ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If | ||||
| 10254 | ** zDb is not NULL (or a zero length string) and is not the name of any | ||||
| 10255 | ** attached database, SQLITE_ERROR is returned to the caller. | ||||
| 10256 | ** | ||||
| 10257 | ** ^Unless it returns SQLITE_MISUSE, | ||||
| 10258 | ** the sqlite3_wal_checkpoint_v2() interface | ||||
| 10259 | ** sets the error information that is queried by | ||||
| 10260 | ** [sqlite3_errcode()] and [sqlite3_errmsg()]. | ||||
| 10261 | ** | ||||
| 10262 | ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface | ||||
| 10263 | ** from SQL. | ||||
| 10264 | */ | ||||
| 10265 | SQLITE_API int sqlite3_wal_checkpoint_v2( | ||||
| 10266 | sqlite3 *db, /* Database handle */ | ||||
| 10267 | const char *zDb, /* Name of attached database (or NULL) */ | ||||
| 10268 | int eMode, /* SQLITE_CHECKPOINT_* value */ | ||||
| 10269 | int *pnLog, /* OUT: Size of WAL log in frames */ | ||||
| 10270 | int *pnCkpt /* OUT: Total number of frames checkpointed */ | ||||
| 10271 | ); | ||||
| 10272 | |||||
| 10273 | /* | ||||
| 10274 | ** CAPI3REF: Checkpoint Mode Values | ||||
| 10275 | ** KEYWORDS: {checkpoint mode} | ||||
| 10276 | ** | ||||
| 10277 | ** These constants define all valid values for the "checkpoint mode" passed | ||||
| 10278 | ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. | ||||
| 10279 | ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the | ||||
| 10280 | ** meaning of each of these checkpoint modes. | ||||
| 10281 | */ | ||||
| 10282 | #define SQLITE_CHECKPOINT_PASSIVE0 0 /* Do as much as possible w/o blocking */ | ||||
| 10283 | #define SQLITE_CHECKPOINT_FULL1 1 /* Wait for writers, then checkpoint */ | ||||
| 10284 | #define SQLITE_CHECKPOINT_RESTART2 2 /* Like FULL but wait for readers */ | ||||
| 10285 | #define SQLITE_CHECKPOINT_TRUNCATE3 3 /* Like RESTART but also truncate WAL */ | ||||
| 10286 | |||||
| 10287 | /* | ||||
| 10288 | ** CAPI3REF: Virtual Table Interface Configuration | ||||
| 10289 | ** | ||||
| 10290 | ** This function may be called by either the [xConnect] or [xCreate] method | ||||
| 10291 | ** of a [virtual table] implementation to configure | ||||
| 10292 | ** various facets of the virtual table interface. | ||||
| 10293 | ** | ||||
| 10294 | ** If this interface is invoked outside the context of an xConnect or | ||||
| 10295 | ** xCreate virtual table method then the behavior is undefined. | ||||
| 10296 | ** | ||||
| 10297 | ** In the call sqlite3_vtab_config(D,C,...) the D parameter is the | ||||
| 10298 | ** [database connection] in which the virtual table is being created and | ||||
| 10299 | ** which is passed in as the first argument to the [xConnect] or [xCreate] | ||||
| 10300 | ** method that is invoking sqlite3_vtab_config(). The C parameter is one | ||||
| 10301 | ** of the [virtual table configuration options]. The presence and meaning | ||||
| 10302 | ** of parameters after C depend on which [virtual table configuration option] | ||||
| 10303 | ** is used. | ||||
| 10304 | */ | ||||
| 10305 | SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); | ||||
| 10306 | |||||
| 10307 | /* | ||||
| 10308 | ** CAPI3REF: Virtual Table Configuration Options | ||||
| 10309 | ** KEYWORDS: {virtual table configuration options} | ||||
| 10310 | ** KEYWORDS: {virtual table configuration option} | ||||
| 10311 | ** | ||||
| 10312 | ** These macros define the various options to the | ||||
| 10313 | ** [sqlite3_vtab_config()] interface that [virtual table] implementations | ||||
| 10314 | ** can use to customize and optimize their behavior. | ||||
| 10315 | ** | ||||
| 10316 | ** <dl> | ||||
| 10317 | ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]] | ||||
| 10318 | ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt> | ||||
| 10319 | ** <dd>Calls of the form | ||||
| 10320 | ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, | ||||
| 10321 | ** where X is an integer. If X is zero, then the [virtual table] whose | ||||
| 10322 | ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not | ||||
| 10323 | ** support constraints. In this configuration (which is the default) if | ||||
| 10324 | ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire | ||||
| 10325 | ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been | ||||
| 10326 | ** specified as part of the user's SQL statement, regardless of the actual | ||||
| 10327 | ** ON CONFLICT mode specified. | ||||
| 10328 | ** | ||||
| 10329 | ** If X is non-zero, then the virtual table implementation guarantees | ||||
| 10330 | ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before | ||||
| 10331 | ** any modifications to internal or persistent data structures have been made. | ||||
| 10332 | ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite | ||||
| 10333 | ** is able to roll back a statement or database transaction, and abandon | ||||
| 10334 | ** or continue processing the current SQL statement as appropriate. | ||||
| 10335 | ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns | ||||
| 10336 | ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode | ||||
| 10337 | ** had been ABORT. | ||||
| 10338 | ** | ||||
| 10339 | ** Virtual table implementations that are required to handle OR REPLACE | ||||
| 10340 | ** must do so within the [xUpdate] method. If a call to the | ||||
| 10341 | ** [sqlite3_vtab_on_conflict()] function indicates that the current ON | ||||
| 10342 | ** CONFLICT policy is REPLACE, the virtual table implementation should | ||||
| 10343 | ** silently replace the appropriate rows within the xUpdate callback and | ||||
| 10344 | ** return SQLITE_OK. Or, if this is not possible, it may return | ||||
| 10345 | ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT | ||||
| 10346 | ** constraint handling. | ||||
| 10347 | ** </dd> | ||||
| 10348 | ** | ||||
| 10349 | ** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt> | ||||
| 10350 | ** <dd>Calls of the form | ||||
| 10351 | ** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the | ||||
| 10352 | ** the [xConnect] or [xCreate] methods of a [virtual table] implementation | ||||
| 10353 | ** prohibits that virtual table from being used from within triggers and | ||||
| 10354 | ** views. | ||||
| 10355 | ** </dd> | ||||
| 10356 | ** | ||||
| 10357 | ** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt> | ||||
| 10358 | ** <dd>Calls of the form | ||||
| 10359 | ** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the | ||||
| 10360 | ** [xConnect] or [xCreate] methods of a [virtual table] implementation | ||||
| 10361 | ** identify that virtual table as being safe to use from within triggers | ||||
| 10362 | ** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the | ||||
| 10363 | ** virtual table can do no serious harm even if it is controlled by a | ||||
| 10364 | ** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS | ||||
| 10365 | ** flag unless absolutely necessary. | ||||
| 10366 | ** </dd> | ||||
| 10367 | ** | ||||
| 10368 | ** [[SQLITE_VTAB_USES_ALL_SCHEMAS]]<dt>SQLITE_VTAB_USES_ALL_SCHEMAS</dt> | ||||
| 10369 | ** <dd>Calls of the form | ||||
| 10370 | ** [sqlite3_vtab_config](db,SQLITE_VTAB_USES_ALL_SCHEMA) from within the | ||||
| 10371 | ** the [xConnect] or [xCreate] methods of a [virtual table] implementation | ||||
| 10372 | ** instruct the query planner to begin at least a read transaction on | ||||
| 10373 | ** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the | ||||
| 10374 | ** virtual table is used. | ||||
| 10375 | ** </dd> | ||||
| 10376 | ** </dl> | ||||
| 10377 | */ | ||||
| 10378 | #define SQLITE_VTAB_CONSTRAINT_SUPPORT1 1 | ||||
| 10379 | #define SQLITE_VTAB_INNOCUOUS2 2 | ||||
| 10380 | #define SQLITE_VTAB_DIRECTONLY3 3 | ||||
| 10381 | #define SQLITE_VTAB_USES_ALL_SCHEMAS4 4 | ||||
| 10382 | |||||
| 10383 | /* | ||||
| 10384 | ** CAPI3REF: Determine The Virtual Table Conflict Policy | ||||
| 10385 | ** | ||||
| 10386 | ** This function may only be called from within a call to the [xUpdate] method | ||||
| 10387 | ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The | ||||
| 10388 | ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], | ||||
| 10389 | ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode | ||||
| 10390 | ** of the SQL statement that triggered the call to the [xUpdate] method of the | ||||
| 10391 | ** [virtual table]. | ||||
| 10392 | */ | ||||
| 10393 | SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); | ||||
| 10394 | |||||
| 10395 | /* | ||||
| 10396 | ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE | ||||
| 10397 | ** | ||||
| 10398 | ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn] | ||||
| 10399 | ** method of a [virtual table], then it might return true if the | ||||
| 10400 | ** column is being fetched as part of an UPDATE operation during which the | ||||
| 10401 | ** column value will not change. The virtual table implementation can use | ||||
| 10402 | ** this hint as permission to substitute a return value that is less | ||||
| 10403 | ** expensive to compute and that the corresponding | ||||
| 10404 | ** [xUpdate] method understands as a "no-change" value. | ||||
| 10405 | ** | ||||
| 10406 | ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that | ||||
| 10407 | ** the column is not changed by the UPDATE statement, then the xColumn | ||||
| 10408 | ** method can optionally return without setting a result, without calling | ||||
| 10409 | ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces]. | ||||
| 10410 | ** In that case, [sqlite3_value_nochange(X)] will return true for the | ||||
| 10411 | ** same column in the [xUpdate] method. | ||||
| 10412 | ** | ||||
| 10413 | ** The sqlite3_vtab_nochange() routine is an optimization. Virtual table | ||||
| 10414 | ** implementations should continue to give a correct answer even if the | ||||
| 10415 | ** sqlite3_vtab_nochange() interface were to always return false. In the | ||||
| 10416 | ** current implementation, the sqlite3_vtab_nochange() interface does always | ||||
| 10417 | ** returns false for the enhanced [UPDATE FROM] statement. | ||||
| 10418 | */ | ||||
| 10419 | SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*); | ||||
| 10420 | |||||
| 10421 | /* | ||||
| 10422 | ** CAPI3REF: Determine The Collation For a Virtual Table Constraint | ||||
| 10423 | ** METHOD: sqlite3_index_info | ||||
| 10424 | ** | ||||
| 10425 | ** This function may only be called from within a call to the [xBestIndex] | ||||
| 10426 | ** method of a [virtual table]. This function returns a pointer to a string | ||||
| 10427 | ** that is the name of the appropriate collation sequence to use for text | ||||
| 10428 | ** comparisons on the constraint identified by its arguments. | ||||
| 10429 | ** | ||||
| 10430 | ** The first argument must be the pointer to the [sqlite3_index_info] object | ||||
| 10431 | ** that is the first parameter to the xBestIndex() method. The second argument | ||||
| 10432 | ** must be an index into the aConstraint[] array belonging to the | ||||
| 10433 | ** sqlite3_index_info structure passed to xBestIndex. | ||||
| 10434 | ** | ||||
| 10435 | ** Important: | ||||
| 10436 | ** The first parameter must be the same pointer that is passed into the | ||||
| 10437 | ** xBestMethod() method. The first parameter may not be a pointer to a | ||||
| 10438 | ** different [sqlite3_index_info] object, even an exact copy. | ||||
| 10439 | ** | ||||
| 10440 | ** The return value is computed as follows: | ||||
| 10441 | ** | ||||
| 10442 | ** <ol> | ||||
| 10443 | ** <li><p> If the constraint comes from a WHERE clause expression that contains | ||||
| 10444 | ** a [COLLATE operator], then the name of the collation specified by | ||||
| 10445 | ** that COLLATE operator is returned. | ||||
| 10446 | ** <li><p> If there is no COLLATE operator, but the column that is the subject | ||||
| 10447 | ** of the constraint specifies an alternative collating sequence via | ||||
| 10448 | ** a [COLLATE clause] on the column definition within the CREATE TABLE | ||||
| 10449 | ** statement that was passed into [sqlite3_declare_vtab()], then the | ||||
| 10450 | ** name of that alternative collating sequence is returned. | ||||
| 10451 | ** <li><p> Otherwise, "BINARY" is returned. | ||||
| 10452 | ** </ol> | ||||
| 10453 | */ | ||||
| 10454 | SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); | ||||
| 10455 | |||||
| 10456 | /* | ||||
| 10457 | ** CAPI3REF: Determine if a virtual table query is DISTINCT | ||||
| 10458 | ** METHOD: sqlite3_index_info | ||||
| 10459 | ** | ||||
| 10460 | ** This API may only be used from within an [xBestIndex|xBestIndex method] | ||||
| 10461 | ** of a [virtual table] implementation. The result of calling this | ||||
| 10462 | ** interface from outside of xBestIndex() is undefined and probably harmful. | ||||
| 10463 | ** | ||||
| 10464 | ** ^The sqlite3_vtab_distinct() interface returns an integer between 0 and | ||||
| 10465 | ** 3. The integer returned by sqlite3_vtab_distinct() | ||||
| 10466 | ** gives the virtual table additional information about how the query | ||||
| 10467 | ** planner wants the output to be ordered. As long as the virtual table | ||||
| 10468 | ** can meet the ordering requirements of the query planner, it may set | ||||
| 10469 | ** the "orderByConsumed" flag. | ||||
| 10470 | ** | ||||
| 10471 | ** <ol><li value="0"><p> | ||||
| 10472 | ** ^If the sqlite3_vtab_distinct() interface returns 0, that means | ||||
| 10473 | ** that the query planner needs the virtual table to return all rows in the | ||||
| 10474 | ** sort order defined by the "nOrderBy" and "aOrderBy" fields of the | ||||
| 10475 | ** [sqlite3_index_info] object. This is the default expectation. If the | ||||
| 10476 | ** virtual table outputs all rows in sorted order, then it is always safe for | ||||
| 10477 | ** the xBestIndex method to set the "orderByConsumed" flag, regardless of | ||||
| 10478 | ** the return value from sqlite3_vtab_distinct(). | ||||
| 10479 | ** <li value="1"><p> | ||||
| 10480 | ** ^(If the sqlite3_vtab_distinct() interface returns 1, that means | ||||
| 10481 | ** that the query planner does not need the rows to be returned in sorted order | ||||
| 10482 | ** as long as all rows with the same values in all columns identified by the | ||||
| 10483 | ** "aOrderBy" field are adjacent.)^ This mode is used when the query planner | ||||
| 10484 | ** is doing a GROUP BY. | ||||
| 10485 | ** <li value="2"><p> | ||||
| 10486 | ** ^(If the sqlite3_vtab_distinct() interface returns 2, that means | ||||
| 10487 | ** that the query planner does not need the rows returned in any particular | ||||
| 10488 | ** order, as long as rows with the same values in all columns identified | ||||
| 10489 | ** by "aOrderBy" are adjacent.)^ ^(Furthermore, when two or more rows | ||||
| 10490 | ** contain the same values for all columns identified by "colUsed", all but | ||||
| 10491 | ** one such row may optionally be omitted from the result.)^ | ||||
| 10492 | ** The virtual table is not required to omit rows that are duplicates | ||||
| 10493 | ** over the "colUsed" columns, but if the virtual table can do that without | ||||
| 10494 | ** too much extra effort, it could potentially help the query to run faster. | ||||
| 10495 | ** This mode is used for a DISTINCT query. | ||||
| 10496 | ** <li value="3"><p> | ||||
| 10497 | ** ^(If the sqlite3_vtab_distinct() interface returns 3, that means the | ||||
| 10498 | ** virtual table must return rows in the order defined by "aOrderBy" as | ||||
| 10499 | ** if the sqlite3_vtab_distinct() interface had returned 0. However if | ||||
| 10500 | ** two or more rows in the result have the same values for all columns | ||||
| 10501 | ** identified by "colUsed", then all but one such row may optionally be | ||||
| 10502 | ** omitted.)^ Like when the return value is 2, the virtual table | ||||
| 10503 | ** is not required to omit rows that are duplicates over the "colUsed" | ||||
| 10504 | ** columns, but if the virtual table can do that without | ||||
| 10505 | ** too much extra effort, it could potentially help the query to run faster. | ||||
| 10506 | ** This mode is used for queries | ||||
| 10507 | ** that have both DISTINCT and ORDER BY clauses. | ||||
| 10508 | ** </ol> | ||||
| 10509 | ** | ||||
| 10510 | ** <p>The following table summarizes the conditions under which the | ||||
| 10511 | ** virtual table is allowed to set the "orderByConsumed" flag based on | ||||
| 10512 | ** the value returned by sqlite3_vtab_distinct(). This table is a | ||||
| 10513 | ** restatement of the previous four paragraphs: | ||||
| 10514 | ** | ||||
| 10515 | ** <table border=1 cellspacing=0 cellpadding=10 width="90%"> | ||||
| 10516 | ** <tr> | ||||
| 10517 | ** <td valign="top">sqlite3_vtab_distinct() return value | ||||
| 10518 | ** <td valign="top">Rows are returned in aOrderBy order | ||||
| 10519 | ** <td valign="top">Rows with the same value in all aOrderBy columns are adjacent | ||||
| 10520 | ** <td valign="top">Duplicates over all colUsed columns may be omitted | ||||
| 10521 | ** <tr><td>0<td>yes<td>yes<td>no | ||||
| 10522 | ** <tr><td>1<td>no<td>yes<td>no | ||||
| 10523 | ** <tr><td>2<td>no<td>yes<td>yes | ||||
| 10524 | ** <tr><td>3<td>yes<td>yes<td>yes | ||||
| 10525 | ** </table> | ||||
| 10526 | ** | ||||
| 10527 | ** ^For the purposes of comparing virtual table output values to see if the | ||||
| 10528 | ** values are the same value for sorting purposes, two NULL values are considered | ||||
| 10529 | ** to be the same. In other words, the comparison operator is "IS" | ||||
| 10530 | ** (or "IS NOT DISTINCT FROM") and not "==". | ||||
| 10531 | ** | ||||
| 10532 | ** If a virtual table implementation is unable to meet the requirements | ||||
| 10533 | ** specified above, then it must not set the "orderByConsumed" flag in the | ||||
| 10534 | ** [sqlite3_index_info] object or an incorrect answer may result. | ||||
| 10535 | ** | ||||
| 10536 | ** ^A virtual table implementation is always free to return rows in any order | ||||
| 10537 | ** it wants, as long as the "orderByConsumed" flag is not set. ^When the | ||||
| 10538 | ** "orderByConsumed" flag is unset, the query planner will add extra | ||||
| 10539 | ** [bytecode] to ensure that the final results returned by the SQL query are | ||||
| 10540 | ** ordered correctly. The use of the "orderByConsumed" flag and the | ||||
| 10541 | ** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful | ||||
| 10542 | ** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed" | ||||
| 10543 | ** flag might help queries against a virtual table to run faster. Being | ||||
| 10544 | ** overly aggressive and setting the "orderByConsumed" flag when it is not | ||||
| 10545 | ** valid to do so, on the other hand, might cause SQLite to return incorrect | ||||
| 10546 | ** results. | ||||
| 10547 | */ | ||||
| 10548 | SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*); | ||||
| 10549 | |||||
| 10550 | /* | ||||
| 10551 | ** CAPI3REF: Identify and handle IN constraints in xBestIndex | ||||
| 10552 | ** | ||||
| 10553 | ** This interface may only be used from within an | ||||
| 10554 | ** [xBestIndex|xBestIndex() method] of a [virtual table] implementation. | ||||
| 10555 | ** The result of invoking this interface from any other context is | ||||
| 10556 | ** undefined and probably harmful. | ||||
| 10557 | ** | ||||
| 10558 | ** ^(A constraint on a virtual table of the form | ||||
| 10559 | ** "[IN operator|column IN (...)]" is | ||||
| 10560 | ** communicated to the xBestIndex method as a | ||||
| 10561 | ** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^ If xBestIndex wants to use | ||||
| 10562 | ** this constraint, it must set the corresponding | ||||
| 10563 | ** aConstraintUsage[].argvIndex to a positive integer. ^(Then, under | ||||
| 10564 | ** the usual mode of handling IN operators, SQLite generates [bytecode] | ||||
| 10565 | ** that invokes the [xFilter|xFilter() method] once for each value | ||||
| 10566 | ** on the right-hand side of the IN operator.)^ Thus the virtual table | ||||
| 10567 | ** only sees a single value from the right-hand side of the IN operator | ||||
| 10568 | ** at a time. | ||||
| 10569 | ** | ||||
| 10570 | ** In some cases, however, it would be advantageous for the virtual | ||||
| 10571 | ** table to see all values on the right-hand of the IN operator all at | ||||
| 10572 | ** once. The sqlite3_vtab_in() interfaces facilitates this in two ways: | ||||
| 10573 | ** | ||||
| 10574 | ** <ol> | ||||
| 10575 | ** <li><p> | ||||
| 10576 | ** ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero) | ||||
| 10577 | ** if and only if the [sqlite3_index_info|P->aConstraint][N] constraint | ||||
| 10578 | ** is an [IN operator] that can be processed all at once. ^In other words, | ||||
| 10579 | ** sqlite3_vtab_in() with -1 in the third argument is a mechanism | ||||
| 10580 | ** by which the virtual table can ask SQLite if all-at-once processing | ||||
| 10581 | ** of the IN operator is even possible. | ||||
| 10582 | ** | ||||
| 10583 | ** <li><p> | ||||
| 10584 | ** ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates | ||||
| 10585 | ** to SQLite that the virtual table does or does not want to process | ||||
| 10586 | ** the IN operator all-at-once, respectively. ^Thus when the third | ||||
| 10587 | ** parameter (F) is non-negative, this interface is the mechanism by | ||||
| 10588 | ** which the virtual table tells SQLite how it wants to process the | ||||
| 10589 | ** IN operator. | ||||
| 10590 | ** </ol> | ||||
| 10591 | ** | ||||
| 10592 | ** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times | ||||
| 10593 | ** within the same xBestIndex method call. ^For any given P,N pair, | ||||
| 10594 | ** the return value from sqlite3_vtab_in(P,N,F) will always be the same | ||||
| 10595 | ** within the same xBestIndex call. ^If the interface returns true | ||||
| 10596 | ** (non-zero), that means that the constraint is an IN operator | ||||
| 10597 | ** that can be processed all-at-once. ^If the constraint is not an IN | ||||
| 10598 | ** operator or cannot be processed all-at-once, then the interface returns | ||||
| 10599 | ** false. | ||||
| 10600 | ** | ||||
| 10601 | ** ^(All-at-once processing of the IN operator is selected if both of the | ||||
| 10602 | ** following conditions are met: | ||||
| 10603 | ** | ||||
| 10604 | ** <ol> | ||||
| 10605 | ** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive | ||||
| 10606 | ** integer. This is how the virtual table tells SQLite that it wants to | ||||
| 10607 | ** use the N-th constraint. | ||||
| 10608 | ** | ||||
| 10609 | ** <li><p> The last call to sqlite3_vtab_in(P,N,F) for which F was | ||||
| 10610 | ** non-negative had F>=1. | ||||
| 10611 | ** </ol>)^ | ||||
| 10612 | ** | ||||
| 10613 | ** ^If either or both of the conditions above are false, then SQLite uses | ||||
| 10614 | ** the traditional one-at-a-time processing strategy for the IN constraint. | ||||
| 10615 | ** ^If both conditions are true, then the argvIndex-th parameter to the | ||||
| 10616 | ** xFilter method will be an [sqlite3_value] that appears to be NULL, | ||||
| 10617 | ** but which can be passed to [sqlite3_vtab_in_first()] and | ||||
| 10618 | ** [sqlite3_vtab_in_next()] to find all values on the right-hand side | ||||
| 10619 | ** of the IN constraint. | ||||
| 10620 | */ | ||||
| 10621 | SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle); | ||||
| 10622 | |||||
| 10623 | /* | ||||
| 10624 | ** CAPI3REF: Find all elements on the right-hand side of an IN constraint. | ||||
| 10625 | ** | ||||
| 10626 | ** These interfaces are only useful from within the | ||||
| 10627 | ** [xFilter|xFilter() method] of a [virtual table] implementation. | ||||
| 10628 | ** The result of invoking these interfaces from any other context | ||||
| 10629 | ** is undefined and probably harmful. | ||||
| 10630 | ** | ||||
| 10631 | ** The X parameter in a call to sqlite3_vtab_in_first(X,P) or | ||||
| 10632 | ** sqlite3_vtab_in_next(X,P) should be one of the parameters to the | ||||
| 10633 | ** xFilter method which invokes these routines, and specifically | ||||
| 10634 | ** a parameter that was previously selected for all-at-once IN constraint | ||||
| 10635 | ** processing using the [sqlite3_vtab_in()] interface in the | ||||
| 10636 | ** [xBestIndex|xBestIndex method]. ^(If the X parameter is not | ||||
| 10637 | ** an xFilter argument that was selected for all-at-once IN constraint | ||||
| 10638 | ** processing, then these routines return [SQLITE_ERROR].)^ | ||||
| 10639 | ** | ||||
| 10640 | ** ^(Use these routines to access all values on the right-hand side | ||||
| 10641 | ** of the IN constraint using code like the following: | ||||
| 10642 | ** | ||||
| 10643 | ** <blockquote><pre> | ||||
| 10644 | ** for(rc=sqlite3_vtab_in_first(pList, &pVal); | ||||
| 10645 | ** rc==SQLITE_OK && pVal; | ||||
| 10646 | ** rc=sqlite3_vtab_in_next(pList, &pVal) | ||||
| 10647 | ** ){ | ||||
| 10648 | ** // do something with pVal | ||||
| 10649 | ** } | ||||
| 10650 | ** if( rc!=SQLITE_OK ){ | ||||
| 10651 | ** // an error has occurred | ||||
| 10652 | ** } | ||||
| 10653 | ** </pre></blockquote>)^ | ||||
| 10654 | ** | ||||
| 10655 | ** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P) | ||||
| 10656 | ** routines return SQLITE_OK and set *P to point to the first or next value | ||||
| 10657 | ** on the RHS of the IN constraint. ^If there are no more values on the | ||||
| 10658 | ** right hand side of the IN constraint, then *P is set to NULL and these | ||||
| 10659 | ** routines return [SQLITE_DONE]. ^The return value might be | ||||
| 10660 | ** some other value, such as SQLITE_NOMEM, in the event of a malfunction. | ||||
| 10661 | ** | ||||
| 10662 | ** The *ppOut values returned by these routines are only valid until the | ||||
| 10663 | ** next call to either of these routines or until the end of the xFilter | ||||
| 10664 | ** method from which these routines were called. If the virtual table | ||||
| 10665 | ** implementation needs to retain the *ppOut values for longer, it must make | ||||
| 10666 | ** copies. The *ppOut values are [protected sqlite3_value|protected]. | ||||
| 10667 | */ | ||||
| 10668 | SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut); | ||||
| 10669 | SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut); | ||||
| 10670 | |||||
| 10671 | /* | ||||
| 10672 | ** CAPI3REF: Constraint values in xBestIndex() | ||||
| 10673 | ** METHOD: sqlite3_index_info | ||||
| 10674 | ** | ||||
| 10675 | ** This API may only be used from within the [xBestIndex|xBestIndex method] | ||||
| 10676 | ** of a [virtual table] implementation. The result of calling this interface | ||||
| 10677 | ** from outside of an xBestIndex method are undefined and probably harmful. | ||||
| 10678 | ** | ||||
| 10679 | ** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within | ||||
| 10680 | ** the [xBestIndex] method of a [virtual table] implementation, with P being | ||||
| 10681 | ** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and | ||||
| 10682 | ** J being a 0-based index into P->aConstraint[], then this routine | ||||
| 10683 | ** attempts to set *V to the value of the right-hand operand of | ||||
| 10684 | ** that constraint if the right-hand operand is known. ^If the | ||||
| 10685 | ** right-hand operand is not known, then *V is set to a NULL pointer. | ||||
| 10686 | ** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if | ||||
| 10687 | ** and only if *V is set to a value. ^The sqlite3_vtab_rhs_value(P,J,V) | ||||
| 10688 | ** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th | ||||
| 10689 | ** constraint is not available. ^The sqlite3_vtab_rhs_value() interface | ||||
| 10690 | ** can return a result code other than SQLITE_OK or SQLITE_NOTFOUND if | ||||
| 10691 | ** something goes wrong. | ||||
| 10692 | ** | ||||
| 10693 | ** The sqlite3_vtab_rhs_value() interface is usually only successful if | ||||
| 10694 | ** the right-hand operand of a constraint is a literal value in the original | ||||
| 10695 | ** SQL statement. If the right-hand operand is an expression or a reference | ||||
| 10696 | ** to some other column or a [host parameter], then sqlite3_vtab_rhs_value() | ||||
| 10697 | ** will probably return [SQLITE_NOTFOUND]. | ||||
| 10698 | ** | ||||
| 10699 | ** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and | ||||
| 10700 | ** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand. For such | ||||
| 10701 | ** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^ | ||||
| 10702 | ** | ||||
| 10703 | ** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value | ||||
| 10704 | ** and remains valid for the duration of the xBestIndex method call. | ||||
| 10705 | ** ^When xBestIndex returns, the sqlite3_value object returned by | ||||
| 10706 | ** sqlite3_vtab_rhs_value() is automatically deallocated. | ||||
| 10707 | ** | ||||
| 10708 | ** The "_rhs_" in the name of this routine is an abbreviation for | ||||
| 10709 | ** "Right-Hand Side". | ||||
| 10710 | */ | ||||
| 10711 | SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal); | ||||
| 10712 | |||||
| 10713 | /* | ||||
| 10714 | ** CAPI3REF: Conflict resolution modes | ||||
| 10715 | ** KEYWORDS: {conflict resolution mode} | ||||
| 10716 | ** | ||||
| 10717 | ** These constants are returned by [sqlite3_vtab_on_conflict()] to | ||||
| 10718 | ** inform a [virtual table] implementation of the [ON CONFLICT] mode | ||||
| 10719 | ** for the SQL statement being evaluated. | ||||
| 10720 | ** | ||||
| 10721 | ** Note that the [SQLITE_IGNORE] constant is also used as a potential | ||||
| 10722 | ** return value from the [sqlite3_set_authorizer()] callback and that | ||||
| 10723 | ** [SQLITE_ABORT] is also a [result code]. | ||||
| 10724 | */ | ||||
| 10725 | #define SQLITE_ROLLBACK1 1 | ||||
| 10726 | /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ | ||||
| 10727 | #define SQLITE_FAIL3 3 | ||||
| 10728 | /* #define SQLITE_ABORT 4 // Also an error code */ | ||||
| 10729 | #define SQLITE_REPLACE5 5 | ||||
| 10730 | |||||
| 10731 | /* | ||||
| 10732 | ** CAPI3REF: Prepared Statement Scan Status Opcodes | ||||
| 10733 | ** KEYWORDS: {scanstatus options} | ||||
| 10734 | ** | ||||
| 10735 | ** The following constants can be used for the T parameter to the | ||||
| 10736 | ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a | ||||
| 10737 | ** different metric for sqlite3_stmt_scanstatus() to return. | ||||
| 10738 | ** | ||||
| 10739 | ** When the value returned to V is a string, space to hold that string is | ||||
| 10740 | ** managed by the prepared statement S and will be automatically freed when | ||||
| 10741 | ** S is finalized. | ||||
| 10742 | ** | ||||
| 10743 | ** Not all values are available for all query elements. When a value is | ||||
| 10744 | ** not available, the output variable is set to -1 if the value is numeric, | ||||
| 10745 | ** or to NULL if it is a string (SQLITE_SCANSTAT_NAME). | ||||
| 10746 | ** | ||||
| 10747 | ** <dl> | ||||
| 10748 | ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt> | ||||
| 10749 | ** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be | ||||
| 10750 | ** set to the total number of times that the X-th loop has run.</dd> | ||||
| 10751 | ** | ||||
| 10752 | ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt> | ||||
| 10753 | ** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set | ||||
| 10754 | ** to the total number of rows examined by all iterations of the X-th loop.</dd> | ||||
| 10755 | ** | ||||
| 10756 | ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt> | ||||
| 10757 | ** <dd>^The "double" variable pointed to by the V parameter will be set to the | ||||
| 10758 | ** query planner's estimate for the average number of rows output from each | ||||
| 10759 | ** iteration of the X-th loop. If the query planner's estimate was accurate, | ||||
| 10760 | ** then this value will approximate the quotient NVISIT/NLOOP and the | ||||
| 10761 | ** product of this value for all prior loops with the same SELECTID will | ||||
| 10762 | ** be the NLOOP value for the current loop.</dd> | ||||
| 10763 | ** | ||||
| 10764 | ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt> | ||||
| 10765 | ** <dd>^The "const char *" variable pointed to by the V parameter will be set | ||||
| 10766 | ** to a zero-terminated UTF-8 string containing the name of the index or table | ||||
| 10767 | ** used for the X-th loop.</dd> | ||||
| 10768 | ** | ||||
| 10769 | ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt> | ||||
| 10770 | ** <dd>^The "const char *" variable pointed to by the V parameter will be set | ||||
| 10771 | ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] | ||||
| 10772 | ** description for the X-th loop.</dd> | ||||
| 10773 | ** | ||||
| 10774 | ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt> | ||||
| 10775 | ** <dd>^The "int" variable pointed to by the V parameter will be set to the | ||||
| 10776 | ** id for the X-th query plan element. The id value is unique within the | ||||
| 10777 | ** statement. The select-id is the same value as is output in the first | ||||
| 10778 | ** column of an [EXPLAIN QUERY PLAN] query.</dd> | ||||
| 10779 | ** | ||||
| 10780 | ** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt> | ||||
| 10781 | ** <dd>The "int" variable pointed to by the V parameter will be set to the | ||||
| 10782 | ** id of the parent of the current query element, if applicable, or | ||||
| 10783 | ** to zero if the query element has no parent. This is the same value as | ||||
| 10784 | ** returned in the second column of an [EXPLAIN QUERY PLAN] query.</dd> | ||||
| 10785 | ** | ||||
| 10786 | ** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt> | ||||
| 10787 | ** <dd>The sqlite3_int64 output value is set to the number of cycles, | ||||
| 10788 | ** according to the processor time-stamp counter, that elapsed while the | ||||
| 10789 | ** query element was being processed. This value is not available for | ||||
| 10790 | ** all query elements - if it is unavailable the output variable is | ||||
| 10791 | ** set to -1.</dd> | ||||
| 10792 | ** </dl> | ||||
| 10793 | */ | ||||
| 10794 | #define SQLITE_SCANSTAT_NLOOP0 0 | ||||
| 10795 | #define SQLITE_SCANSTAT_NVISIT1 1 | ||||
| 10796 | #define SQLITE_SCANSTAT_EST2 2 | ||||
| 10797 | #define SQLITE_SCANSTAT_NAME3 3 | ||||
| 10798 | #define SQLITE_SCANSTAT_EXPLAIN4 4 | ||||
| 10799 | #define SQLITE_SCANSTAT_SELECTID5 5 | ||||
| 10800 | #define SQLITE_SCANSTAT_PARENTID6 6 | ||||
| 10801 | #define SQLITE_SCANSTAT_NCYCLE7 7 | ||||
| 10802 | |||||
| 10803 | /* | ||||
| 10804 | ** CAPI3REF: Prepared Statement Scan Status | ||||
| 10805 | ** METHOD: sqlite3_stmt | ||||
| 10806 | ** | ||||
| 10807 | ** These interfaces return information about the predicted and measured | ||||
| 10808 | ** performance for pStmt. Advanced applications can use this | ||||
| 10809 | ** interface to compare the predicted and the measured performance and | ||||
| 10810 | ** issue warnings and/or rerun [ANALYZE] if discrepancies are found. | ||||
| 10811 | ** | ||||
| 10812 | ** Since this interface is expected to be rarely used, it is only | ||||
| 10813 | ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS] | ||||
| 10814 | ** compile-time option. | ||||
| 10815 | ** | ||||
| 10816 | ** The "iScanStatusOp" parameter determines which status information to return. | ||||
| 10817 | ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior | ||||
| 10818 | ** of this interface is undefined. ^The requested measurement is written into | ||||
| 10819 | ** a variable pointed to by the "pOut" parameter. | ||||
| 10820 | ** | ||||
| 10821 | ** The "flags" parameter must be passed a mask of flags. At present only | ||||
| 10822 | ** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX | ||||
| 10823 | ** is specified, then status information is available for all elements | ||||
| 10824 | ** of a query plan that are reported by "EXPLAIN QUERY PLAN" output. If | ||||
| 10825 | ** SQLITE_SCANSTAT_COMPLEX is not specified, then only query plan elements | ||||
| 10826 | ** that correspond to query loops (the "SCAN..." and "SEARCH..." elements of | ||||
| 10827 | ** the EXPLAIN QUERY PLAN output) are available. Invoking API | ||||
| 10828 | ** sqlite3_stmt_scanstatus() is equivalent to calling | ||||
| 10829 | ** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter. | ||||
| 10830 | ** | ||||
| 10831 | ** Parameter "idx" identifies the specific query element to retrieve statistics | ||||
| 10832 | ** for. Query elements are numbered starting from zero. A value of -1 may | ||||
| 10833 | ** retrieve statistics for the entire query. ^If idx is out of range | ||||
| 10834 | ** - less than -1 or greater than or equal to the total number of query | ||||
| 10835 | ** elements used to implement the statement - a non-zero value is returned and | ||||
| 10836 | ** the variable that pOut points to is unchanged. | ||||
| 10837 | ** | ||||
| 10838 | ** See also: [sqlite3_stmt_scanstatus_reset()] | ||||
| 10839 | */ | ||||
| 10840 | SQLITE_API int sqlite3_stmt_scanstatus( | ||||
| 10841 | sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ | ||||
| 10842 | int idx, /* Index of loop to report on */ | ||||
| 10843 | int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ | ||||
| 10844 | void *pOut /* Result written here */ | ||||
| 10845 | ); | ||||
| 10846 | SQLITE_API int sqlite3_stmt_scanstatus_v2( | ||||
| 10847 | sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ | ||||
| 10848 | int idx, /* Index of loop to report on */ | ||||
| 10849 | int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ | ||||
| 10850 | int flags, /* Mask of flags defined below */ | ||||
| 10851 | void *pOut /* Result written here */ | ||||
| 10852 | ); | ||||
| 10853 | |||||
| 10854 | /* | ||||
| 10855 | ** CAPI3REF: Prepared Statement Scan Status | ||||
| 10856 | ** KEYWORDS: {scan status flags} | ||||
| 10857 | */ | ||||
| 10858 | #define SQLITE_SCANSTAT_COMPLEX0x0001 0x0001 | ||||
| 10859 | |||||
| 10860 | /* | ||||
| 10861 | ** CAPI3REF: Zero Scan-Status Counters | ||||
| 10862 | ** METHOD: sqlite3_stmt | ||||
| 10863 | ** | ||||
| 10864 | ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. | ||||
| 10865 | ** | ||||
| 10866 | ** This API is only available if the library is built with pre-processor | ||||
| 10867 | ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. | ||||
| 10868 | */ | ||||
| 10869 | SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); | ||||
| 10870 | |||||
| 10871 | /* | ||||
| 10872 | ** CAPI3REF: Flush caches to disk mid-transaction | ||||
| 10873 | ** METHOD: sqlite3 | ||||
| 10874 | ** | ||||
| 10875 | ** ^If a write-transaction is open on [database connection] D when the | ||||
| 10876 | ** [sqlite3_db_cacheflush(D)] interface is invoked, any dirty | ||||
| 10877 | ** pages in the pager-cache that are not currently in use are written out | ||||
| 10878 | ** to disk. A dirty page may be in use if a database cursor created by an | ||||
| 10879 | ** active SQL statement is reading from it, or if it is page 1 of a database | ||||
| 10880 | ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] | ||||
| 10881 | ** interface flushes caches for all schemas - "main", "temp", and | ||||
| 10882 | ** any [attached] databases. | ||||
| 10883 | ** | ||||
| 10884 | ** ^If this function needs to obtain extra database locks before dirty pages | ||||
| 10885 | ** can be flushed to disk, it does so. ^If those locks cannot be obtained | ||||
| 10886 | ** immediately and there is a busy-handler callback configured, it is invoked | ||||
| 10887 | ** in the usual manner. ^If the required lock still cannot be obtained, then | ||||
| 10888 | ** the database is skipped and an attempt made to flush any dirty pages | ||||
| 10889 | ** belonging to the next (if any) database. ^If any databases are skipped | ||||
| 10890 | ** because locks cannot be obtained, but no other error occurs, this | ||||
| 10891 | ** function returns SQLITE_BUSY. | ||||
| 10892 | ** | ||||
| 10893 | ** ^If any other error occurs while flushing dirty pages to disk (for | ||||
| 10894 | ** example an IO error or out-of-memory condition), then processing is | ||||
| 10895 | ** abandoned and an SQLite [error code] is returned to the caller immediately. | ||||
| 10896 | ** | ||||
| 10897 | ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. | ||||
| 10898 | ** | ||||
| 10899 | ** ^This function does not set the database handle error code or message | ||||
| 10900 | ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. | ||||
| 10901 | */ | ||||
| 10902 | SQLITE_API int sqlite3_db_cacheflush(sqlite3*); | ||||
| 10903 | |||||
| 10904 | /* | ||||
| 10905 | ** CAPI3REF: The pre-update hook. | ||||
| 10906 | ** METHOD: sqlite3 | ||||
| 10907 | ** | ||||
| 10908 | ** ^These interfaces are only available if SQLite is compiled using the | ||||
| 10909 | ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. | ||||
| 10910 | ** | ||||
| 10911 | ** ^The [sqlite3_preupdate_hook()] interface registers a callback function | ||||
| 10912 | ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation | ||||
| 10913 | ** on a database table. | ||||
| 10914 | ** ^At most one preupdate hook may be registered at a time on a single | ||||
| 10915 | ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides | ||||
| 10916 | ** the previous setting. | ||||
| 10917 | ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] | ||||
| 10918 | ** with a NULL pointer as the second parameter. | ||||
| 10919 | ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as | ||||
| 10920 | ** the first parameter to callbacks. | ||||
| 10921 | ** | ||||
| 10922 | ** ^The preupdate hook only fires for changes to real database tables; the | ||||
| 10923 | ** preupdate hook is not invoked for changes to [virtual tables] or to | ||||
| 10924 | ** system tables like sqlite_sequence or sqlite_stat1. | ||||
| 10925 | ** | ||||
| 10926 | ** ^The second parameter to the preupdate callback is a pointer to | ||||
| 10927 | ** the [database connection] that registered the preupdate hook. | ||||
| 10928 | ** ^The third parameter to the preupdate callback is one of the constants | ||||
| 10929 | ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the | ||||
| 10930 | ** kind of update operation that is about to occur. | ||||
| 10931 | ** ^(The fourth parameter to the preupdate callback is the name of the | ||||
| 10932 | ** database within the database connection that is being modified. This | ||||
| 10933 | ** will be "main" for the main database or "temp" for TEMP tables or | ||||
| 10934 | ** the name given after the AS keyword in the [ATTACH] statement for attached | ||||
| 10935 | ** databases.)^ | ||||
| 10936 | ** ^The fifth parameter to the preupdate callback is the name of the | ||||
| 10937 | ** table that is being modified. | ||||
| 10938 | ** | ||||
| 10939 | ** For an UPDATE or DELETE operation on a [rowid table], the sixth | ||||
| 10940 | ** parameter passed to the preupdate callback is the initial [rowid] of the | ||||
| 10941 | ** row being modified or deleted. For an INSERT operation on a rowid table, | ||||
| 10942 | ** or any operation on a WITHOUT ROWID table, the value of the sixth | ||||
| 10943 | ** parameter is undefined. For an INSERT or UPDATE on a rowid table the | ||||
| 10944 | ** seventh parameter is the final rowid value of the row being inserted | ||||
| 10945 | ** or updated. The value of the seventh parameter passed to the callback | ||||
| 10946 | ** function is not defined for operations on WITHOUT ROWID tables, or for | ||||
| 10947 | ** DELETE operations on rowid tables. | ||||
| 10948 | ** | ||||
| 10949 | ** ^The sqlite3_preupdate_hook(D,C,P) function returns the P argument from | ||||
| 10950 | ** the previous call on the same [database connection] D, or NULL for | ||||
| 10951 | ** the first call on D. | ||||
| 10952 | ** | ||||
| 10953 | ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], | ||||
| 10954 | ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces | ||||
| 10955 | ** provide additional information about a preupdate event. These routines | ||||
| 10956 | ** may only be called from within a preupdate callback. Invoking any of | ||||
| 10957 | ** these routines from outside of a preupdate callback or with a | ||||
| 10958 | ** [database connection] pointer that is different from the one supplied | ||||
| 10959 | ** to the preupdate callback results in undefined and probably undesirable | ||||
| 10960 | ** behavior. | ||||
| 10961 | ** | ||||
| 10962 | ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns | ||||
| 10963 | ** in the row that is being inserted, updated, or deleted. | ||||
| 10964 | ** | ||||
| 10965 | ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to | ||||
| 10966 | ** a [protected sqlite3_value] that contains the value of the Nth column of | ||||
| 10967 | ** the table row before it is updated. The N parameter must be between 0 | ||||
| 10968 | ** and one less than the number of columns or the behavior will be | ||||
| 10969 | ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE | ||||
| 10970 | ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the | ||||
| 10971 | ** behavior is undefined. The [sqlite3_value] that P points to | ||||
| 10972 | ** will be destroyed when the preupdate callback returns. | ||||
| 10973 | ** | ||||
| 10974 | ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to | ||||
| 10975 | ** a [protected sqlite3_value] that contains the value of the Nth column of | ||||
| 10976 | ** the table row after it is updated. The N parameter must be between 0 | ||||
| 10977 | ** and one less than the number of columns or the behavior will be | ||||
| 10978 | ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE | ||||
| 10979 | ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the | ||||
| 10980 | ** behavior is undefined. The [sqlite3_value] that P points to | ||||
| 10981 | ** will be destroyed when the preupdate callback returns. | ||||
| 10982 | ** | ||||
| 10983 | ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate | ||||
| 10984 | ** callback was invoked as a result of a direct insert, update, or delete | ||||
| 10985 | ** operation; or 1 for inserts, updates, or deletes invoked by top-level | ||||
| 10986 | ** triggers; or 2 for changes resulting from triggers called by top-level | ||||
| 10987 | ** triggers; and so forth. | ||||
| 10988 | ** | ||||
| 10989 | ** When the [sqlite3_blob_write()] API is used to update a blob column, | ||||
| 10990 | ** the pre-update hook is invoked with SQLITE_DELETE, because | ||||
| 10991 | ** the new values are not yet available. In this case, when a | ||||
| 10992 | ** callback made with op==SQLITE_DELETE is actually a write using the | ||||
| 10993 | ** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns | ||||
| 10994 | ** the index of the column being written. In other cases, where the | ||||
| 10995 | ** pre-update hook is being invoked for some other reason, including a | ||||
| 10996 | ** regular DELETE, sqlite3_preupdate_blobwrite() returns -1. | ||||
| 10997 | ** | ||||
| 10998 | ** See also: [sqlite3_update_hook()] | ||||
| 10999 | */ | ||||
| 11000 | #if defined(SQLITE_ENABLE_PREUPDATE_HOOK1) | ||||
| 11001 | SQLITE_API void *sqlite3_preupdate_hook( | ||||
| 11002 | sqlite3 *db, | ||||
| 11003 | void(*xPreUpdate)( | ||||
| 11004 | void *pCtx, /* Copy of third arg to preupdate_hook() */ | ||||
| 11005 | sqlite3 *db, /* Database handle */ | ||||
| 11006 | int op, /* SQLITE_UPDATE, DELETE or INSERT */ | ||||
| 11007 | char const *zDb, /* Database name */ | ||||
| 11008 | char const *zName, /* Table name */ | ||||
| 11009 | sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ | ||||
| 11010 | sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ | ||||
| 11011 | ), | ||||
| 11012 | void* | ||||
| 11013 | ); | ||||
| 11014 | SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); | ||||
| 11015 | SQLITE_API int sqlite3_preupdate_count(sqlite3 *); | ||||
| 11016 | SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); | ||||
| 11017 | SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); | ||||
| 11018 | SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *); | ||||
| 11019 | #endif | ||||
| 11020 | |||||
| 11021 | /* | ||||
| 11022 | ** CAPI3REF: Low-level system error code | ||||
| 11023 | ** METHOD: sqlite3 | ||||
| 11024 | ** | ||||
| 11025 | ** ^Attempt to return the underlying operating system error code or error | ||||
| 11026 | ** number that caused the most recent I/O error or failure to open a file. | ||||
| 11027 | ** The return value is OS-dependent. For example, on unix systems, after | ||||
| 11028 | ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be | ||||
| 11029 | ** called to get back the underlying "errno" that caused the problem, such | ||||
| 11030 | ** as ENOSPC, EAUTH, EISDIR, and so forth. | ||||
| 11031 | */ | ||||
| 11032 | SQLITE_API int sqlite3_system_errno(sqlite3*); | ||||
| 11033 | |||||
| 11034 | /* | ||||
| 11035 | ** CAPI3REF: Database Snapshot | ||||
| 11036 | ** KEYWORDS: {snapshot} {sqlite3_snapshot} | ||||
| 11037 | ** | ||||
| 11038 | ** An instance of the snapshot object records the state of a [WAL mode] | ||||
| 11039 | ** database for some specific point in history. | ||||
| 11040 | ** | ||||
| 11041 | ** In [WAL mode], multiple [database connections] that are open on the | ||||
| 11042 | ** same database file can each be reading a different historical version | ||||
| 11043 | ** of the database file. When a [database connection] begins a read | ||||
| 11044 | ** transaction, that connection sees an unchanging copy of the database | ||||
| 11045 | ** as it existed for the point in time when the transaction first started. | ||||
| 11046 | ** Subsequent changes to the database from other connections are not seen | ||||
| 11047 | ** by the reader until a new read transaction is started. | ||||
| 11048 | ** | ||||
| 11049 | ** The sqlite3_snapshot object records state information about an historical | ||||
| 11050 | ** version of the database file so that it is possible to later open a new read | ||||
| 11051 | ** transaction that sees that historical version of the database rather than | ||||
| 11052 | ** the most recent version. | ||||
| 11053 | */ | ||||
| 11054 | typedef struct sqlite3_snapshot { | ||||
| 11055 | unsigned char hidden[48]; | ||||
| 11056 | } sqlite3_snapshot; | ||||
| 11057 | |||||
| 11058 | /* | ||||
| 11059 | ** CAPI3REF: Record A Database Snapshot | ||||
| 11060 | ** CONSTRUCTOR: sqlite3_snapshot | ||||
| 11061 | ** | ||||
| 11062 | ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a | ||||
| 11063 | ** new [sqlite3_snapshot] object that records the current state of | ||||
| 11064 | ** schema S in database connection D. ^On success, the | ||||
| 11065 | ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly | ||||
| 11066 | ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK. | ||||
| 11067 | ** If there is not already a read-transaction open on schema S when | ||||
| 11068 | ** this function is called, one is opened automatically. | ||||
| 11069 | ** | ||||
| 11070 | ** If a read-transaction is opened by this function, then it is guaranteed | ||||
| 11071 | ** that the returned snapshot object may not be invalidated by a database | ||||
| 11072 | ** writer or checkpointer until after the read-transaction is closed. This | ||||
| 11073 | ** is not guaranteed if a read-transaction is already open when this | ||||
| 11074 | ** function is called. In that case, any subsequent write or checkpoint | ||||
| 11075 | ** operation on the database may invalidate the returned snapshot handle, | ||||
| 11076 | ** even while the read-transaction remains open. | ||||
| 11077 | ** | ||||
| 11078 | ** The following must be true for this function to succeed. If any of | ||||
| 11079 | ** the following statements are false when sqlite3_snapshot_get() is | ||||
| 11080 | ** called, SQLITE_ERROR is returned. The final value of *P is undefined | ||||
| 11081 | ** in this case. | ||||
| 11082 | ** | ||||
| 11083 | ** <ul> | ||||
| 11084 | ** <li> The database handle must not be in [autocommit mode]. | ||||
| 11085 | ** | ||||
| 11086 | ** <li> Schema S of [database connection] D must be a [WAL mode] database. | ||||
| 11087 | ** | ||||
| 11088 | ** <li> There must not be a write transaction open on schema S of database | ||||
| 11089 | ** connection D. | ||||
| 11090 | ** | ||||
| 11091 | ** <li> One or more transactions must have been written to the current wal | ||||
| 11092 | ** file since it was created on disk (by any connection). This means | ||||
| 11093 | ** that a snapshot cannot be taken on a wal mode database with no wal | ||||
| 11094 | ** file immediately after it is first opened. At least one transaction | ||||
| 11095 | ** must be written to it first. | ||||
| 11096 | ** </ul> | ||||
| 11097 | ** | ||||
| 11098 | ** This function may also return SQLITE_NOMEM. If it is called with the | ||||
| 11099 | ** database handle in autocommit mode but fails for some other reason, | ||||
| 11100 | ** whether or not a read transaction is opened on schema S is undefined. | ||||
| 11101 | ** | ||||
| 11102 | ** The [sqlite3_snapshot] object returned from a successful call to | ||||
| 11103 | ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()] | ||||
| 11104 | ** to avoid a memory leak. | ||||
| 11105 | ** | ||||
| 11106 | ** The [sqlite3_snapshot_get()] interface is only available when the | ||||
| 11107 | ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. | ||||
| 11108 | */ | ||||
| 11109 | SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( | ||||
| 11110 | sqlite3 *db, | ||||
| 11111 | const char *zSchema, | ||||
| 11112 | sqlite3_snapshot **ppSnapshot | ||||
| 11113 | ); | ||||
| 11114 | |||||
| 11115 | /* | ||||
| 11116 | ** CAPI3REF: Start a read transaction on an historical snapshot | ||||
| 11117 | ** METHOD: sqlite3_snapshot | ||||
| 11118 | ** | ||||
| 11119 | ** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read | ||||
| 11120 | ** transaction or upgrades an existing one for schema S of | ||||
| 11121 | ** [database connection] D such that the read transaction refers to | ||||
| 11122 | ** historical [snapshot] P, rather than the most recent change to the | ||||
| 11123 | ** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK | ||||
| 11124 | ** on success or an appropriate [error code] if it fails. | ||||
| 11125 | ** | ||||
| 11126 | ** ^In order to succeed, the database connection must not be in | ||||
| 11127 | ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there | ||||
| 11128 | ** is already a read transaction open on schema S, then the database handle | ||||
| 11129 | ** must have no active statements (SELECT statements that have been passed | ||||
| 11130 | ** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). | ||||
| 11131 | ** SQLITE_ERROR is returned if either of these conditions is violated, or | ||||
| 11132 | ** if schema S does not exist, or if the snapshot object is invalid. | ||||
| 11133 | ** | ||||
| 11134 | ** ^A call to sqlite3_snapshot_open() will fail to open if the specified | ||||
| 11135 | ** snapshot has been overwritten by a [checkpoint]. In this case | ||||
| 11136 | ** SQLITE_ERROR_SNAPSHOT is returned. | ||||
| 11137 | ** | ||||
| 11138 | ** If there is already a read transaction open when this function is | ||||
| 11139 | ** invoked, then the same read transaction remains open (on the same | ||||
| 11140 | ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT | ||||
| 11141 | ** is returned. If another error code - for example SQLITE_PROTOCOL or an | ||||
| 11142 | ** SQLITE_IOERR error code - is returned, then the final state of the | ||||
| 11143 | ** read transaction is undefined. If SQLITE_OK is returned, then the | ||||
| 11144 | ** read transaction is now open on database snapshot P. | ||||
| 11145 | ** | ||||
| 11146 | ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the | ||||
| 11147 | ** database connection D does not know that the database file for | ||||
| 11148 | ** schema S is in [WAL mode]. A database connection might not know | ||||
| 11149 | ** that the database file is in [WAL mode] if there has been no prior | ||||
| 11150 | ** I/O on that database connection, or if the database entered [WAL mode] | ||||
| 11151 | ** after the most recent I/O on the database connection.)^ | ||||
| 11152 | ** (Hint: Run "[PRAGMA application_id]" against a newly opened | ||||
| 11153 | ** database connection in order to make it ready to use snapshots.) | ||||
| 11154 | ** | ||||
| 11155 | ** The [sqlite3_snapshot_open()] interface is only available when the | ||||
| 11156 | ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. | ||||
| 11157 | */ | ||||
| 11158 | SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( | ||||
| 11159 | sqlite3 *db, | ||||
| 11160 | const char *zSchema, | ||||
| 11161 | sqlite3_snapshot *pSnapshot | ||||
| 11162 | ); | ||||
| 11163 | |||||
| 11164 | /* | ||||
| 11165 | ** CAPI3REF: Destroy a snapshot | ||||
| 11166 | ** DESTRUCTOR: sqlite3_snapshot | ||||
| 11167 | ** | ||||
| 11168 | ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P. | ||||
| 11169 | ** The application must eventually free every [sqlite3_snapshot] object | ||||
| 11170 | ** using this routine to avoid a memory leak. | ||||
| 11171 | ** | ||||
| 11172 | ** The [sqlite3_snapshot_free()] interface is only available when the | ||||
| 11173 | ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. | ||||
| 11174 | */ | ||||
| 11175 | SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); | ||||
| 11176 | |||||
| 11177 | /* | ||||
| 11178 | ** CAPI3REF: Compare the ages of two snapshot handles. | ||||
| 11179 | ** METHOD: sqlite3_snapshot | ||||
| 11180 | ** | ||||
| 11181 | ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages | ||||
| 11182 | ** of two valid snapshot handles. | ||||
| 11183 | ** | ||||
| 11184 | ** If the two snapshot handles are not associated with the same database | ||||
| 11185 | ** file, the result of the comparison is undefined. | ||||
| 11186 | ** | ||||
| 11187 | ** Additionally, the result of the comparison is only valid if both of the | ||||
| 11188 | ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the | ||||
| 11189 | ** last time the wal file was deleted. The wal file is deleted when the | ||||
| 11190 | ** database is changed back to rollback mode or when the number of database | ||||
| 11191 | ** clients drops to zero. If either snapshot handle was obtained before the | ||||
| 11192 | ** wal file was last deleted, the value returned by this function | ||||
| 11193 | ** is undefined. | ||||
| 11194 | ** | ||||
| 11195 | ** Otherwise, this API returns a negative value if P1 refers to an older | ||||
| 11196 | ** snapshot than P2, zero if the two handles refer to the same database | ||||
| 11197 | ** snapshot, and a positive value if P1 is a newer snapshot than P2. | ||||
| 11198 | ** | ||||
| 11199 | ** This interface is only available if SQLite is compiled with the | ||||
| 11200 | ** [SQLITE_ENABLE_SNAPSHOT] option. | ||||
| 11201 | */ | ||||
| 11202 | SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( | ||||
| 11203 | sqlite3_snapshot *p1, | ||||
| 11204 | sqlite3_snapshot *p2 | ||||
| 11205 | ); | ||||
| 11206 | |||||
| 11207 | /* | ||||
| 11208 | ** CAPI3REF: Recover snapshots from a wal file | ||||
| 11209 | ** METHOD: sqlite3_snapshot | ||||
| 11210 | ** | ||||
| 11211 | ** If a [WAL file] remains on disk after all database connections close | ||||
| 11212 | ** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control] | ||||
| 11213 | ** or because the last process to have the database opened exited without | ||||
| 11214 | ** calling [sqlite3_close()]) and a new connection is subsequently opened | ||||
| 11215 | ** on that database and [WAL file], the [sqlite3_snapshot_open()] interface | ||||
| 11216 | ** will only be able to open the last transaction added to the WAL file | ||||
| 11217 | ** even though the WAL file contains other valid transactions. | ||||
| 11218 | ** | ||||
| 11219 | ** This function attempts to scan the WAL file associated with database zDb | ||||
| 11220 | ** of database handle db and make all valid snapshots available to | ||||
| 11221 | ** sqlite3_snapshot_open(). It is an error if there is already a read | ||||
| 11222 | ** transaction open on the database, or if the database is not a WAL mode | ||||
| 11223 | ** database. | ||||
| 11224 | ** | ||||
| 11225 | ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. | ||||
| 11226 | ** | ||||
| 11227 | ** This interface is only available if SQLite is compiled with the | ||||
| 11228 | ** [SQLITE_ENABLE_SNAPSHOT] option. | ||||
| 11229 | */ | ||||
| 11230 | SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); | ||||
| 11231 | |||||
| 11232 | /* | ||||
| 11233 | ** CAPI3REF: Serialize a database | ||||
| 11234 | ** | ||||
| 11235 | ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to | ||||
| 11236 | ** memory that is a serialization of the S database on | ||||
| 11237 | ** [database connection] D. If S is a NULL pointer, the main database is used. | ||||
| 11238 | ** If P is not a NULL pointer, then the size of the database in bytes | ||||
| 11239 | ** is written into *P. | ||||
| 11240 | ** | ||||
| 11241 | ** For an ordinary on-disk database file, the serialization is just a | ||||
| 11242 | ** copy of the disk file. For an in-memory database or a "TEMP" database, | ||||
| 11243 | ** the serialization is the same sequence of bytes which would be written | ||||
| 11244 | ** to disk if that database were backed up to disk. | ||||
| 11245 | ** | ||||
| 11246 | ** The usual case is that sqlite3_serialize() copies the serialization of | ||||
| 11247 | ** the database into memory obtained from [sqlite3_malloc64()] and returns | ||||
| 11248 | ** a pointer to that memory. The caller is responsible for freeing the | ||||
| 11249 | ** returned value to avoid a memory leak. However, if the F argument | ||||
| 11250 | ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations | ||||
| 11251 | ** are made, and the sqlite3_serialize() function will return a pointer | ||||
| 11252 | ** to the contiguous memory representation of the database that SQLite | ||||
| 11253 | ** is currently using for that database, or NULL if no such contiguous | ||||
| 11254 | ** memory representation of the database exists. A contiguous memory | ||||
| 11255 | ** representation of the database will usually only exist if there has | ||||
| 11256 | ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same | ||||
| 11257 | ** values of D and S. | ||||
| 11258 | ** The size of the database is written into *P even if the | ||||
| 11259 | ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy | ||||
| 11260 | ** of the database exists. | ||||
| 11261 | ** | ||||
| 11262 | ** After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set, | ||||
| 11263 | ** the returned buffer content will remain accessible and unchanged | ||||
| 11264 | ** until either the next write operation on the connection or when | ||||
| 11265 | ** the connection is closed, and applications must not modify the | ||||
| 11266 | ** buffer. If the bit had been clear, the returned buffer will not | ||||
| 11267 | ** be accessed by SQLite after the call. | ||||
| 11268 | ** | ||||
| 11269 | ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the | ||||
| 11270 | ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory | ||||
| 11271 | ** allocation error occurs. | ||||
| 11272 | ** | ||||
| 11273 | ** This interface is omitted if SQLite is compiled with the | ||||
| 11274 | ** [SQLITE_OMIT_DESERIALIZE] option. | ||||
| 11275 | */ | ||||
| 11276 | SQLITE_API unsigned char *sqlite3_serialize( | ||||
| 11277 | sqlite3 *db, /* The database connection */ | ||||
| 11278 | const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */ | ||||
| 11279 | sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */ | ||||
| 11280 | unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */ | ||||
| 11281 | ); | ||||
| 11282 | |||||
| 11283 | /* | ||||
| 11284 | ** CAPI3REF: Flags for sqlite3_serialize | ||||
| 11285 | ** | ||||
| 11286 | ** Zero or more of the following constants can be OR-ed together for | ||||
| 11287 | ** the F argument to [sqlite3_serialize(D,S,P,F)]. | ||||
| 11288 | ** | ||||
| 11289 | ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return | ||||
| 11290 | ** a pointer to contiguous in-memory database that it is currently using, | ||||
| 11291 | ** without making a copy of the database. If SQLite is not currently using | ||||
| 11292 | ** a contiguous in-memory database, then this option causes | ||||
| 11293 | ** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be | ||||
| 11294 | ** using a contiguous in-memory database if it has been initialized by a | ||||
| 11295 | ** prior call to [sqlite3_deserialize()]. | ||||
| 11296 | */ | ||||
| 11297 | #define SQLITE_SERIALIZE_NOCOPY0x001 0x001 /* Do no memory allocations */ | ||||
| 11298 | |||||
| 11299 | /* | ||||
| 11300 | ** CAPI3REF: Deserialize a database | ||||
| 11301 | ** | ||||
| 11302 | ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the | ||||
| 11303 | ** [database connection] D to disconnect from database S and then | ||||
| 11304 | ** reopen S as an in-memory database based on the serialization contained | ||||
| 11305 | ** in P. The serialized database P is N bytes in size. M is the size of | ||||
| 11306 | ** the buffer P, which might be larger than N. If M is larger than N, and | ||||
| 11307 | ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is | ||||
| 11308 | ** permitted to add content to the in-memory database as long as the total | ||||
| 11309 | ** size does not exceed M bytes. | ||||
| 11310 | ** | ||||
| 11311 | ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will | ||||
| 11312 | ** invoke sqlite3_free() on the serialization buffer when the database | ||||
| 11313 | ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then | ||||
| 11314 | ** SQLite will try to increase the buffer size using sqlite3_realloc64() | ||||
| 11315 | ** if writes on the database cause it to grow larger than M bytes. | ||||
| 11316 | ** | ||||
| 11317 | ** Applications must not modify the buffer P or invalidate it before | ||||
| 11318 | ** the database connection D is closed. | ||||
| 11319 | ** | ||||
| 11320 | ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the | ||||
| 11321 | ** database is currently in a read transaction or is involved in a backup | ||||
| 11322 | ** operation. | ||||
| 11323 | ** | ||||
| 11324 | ** It is not possible to deserialize into the TEMP database. If the | ||||
| 11325 | ** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the | ||||
| 11326 | ** function returns SQLITE_ERROR. | ||||
| 11327 | ** | ||||
| 11328 | ** The deserialized database should not be in [WAL mode]. If the database | ||||
| 11329 | ** is in WAL mode, then any attempt to use the database file will result | ||||
| 11330 | ** in an [SQLITE_CANTOPEN] error. The application can set the | ||||
| 11331 | ** [file format version numbers] (bytes 18 and 19) of the input database P | ||||
| 11332 | ** to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the | ||||
| 11333 | ** database file into rollback mode and work around this limitation. | ||||
| 11334 | ** | ||||
| 11335 | ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the | ||||
| 11336 | ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then | ||||
| 11337 | ** [sqlite3_free()] is invoked on argument P prior to returning. | ||||
| 11338 | ** | ||||
| 11339 | ** This interface is omitted if SQLite is compiled with the | ||||
| 11340 | ** [SQLITE_OMIT_DESERIALIZE] option. | ||||
| 11341 | */ | ||||
| 11342 | SQLITE_API int sqlite3_deserialize( | ||||
| 11343 | sqlite3 *db, /* The database connection */ | ||||
| 11344 | const char *zSchema, /* Which DB to reopen with the deserialization */ | ||||
| 11345 | unsigned char *pData, /* The serialized database content */ | ||||
| 11346 | sqlite3_int64 szDb, /* Number of bytes in the deserialization */ | ||||
| 11347 | sqlite3_int64 szBuf, /* Total size of buffer pData[] */ | ||||
| 11348 | unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ | ||||
| 11349 | ); | ||||
| 11350 | |||||
| 11351 | /* | ||||
| 11352 | ** CAPI3REF: Flags for sqlite3_deserialize() | ||||
| 11353 | ** | ||||
| 11354 | ** The following are allowed values for the 6th argument (the F argument) to | ||||
| 11355 | ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface. | ||||
| 11356 | ** | ||||
| 11357 | ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization | ||||
| 11358 | ** in the P argument is held in memory obtained from [sqlite3_malloc64()] | ||||
| 11359 | ** and that SQLite should take ownership of this memory and automatically | ||||
| 11360 | ** free it when it has finished using it. Without this flag, the caller | ||||
| 11361 | ** is responsible for freeing any dynamically allocated memory. | ||||
| 11362 | ** | ||||
| 11363 | ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to | ||||
| 11364 | ** grow the size of the database using calls to [sqlite3_realloc64()]. This | ||||
| 11365 | ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used. | ||||
| 11366 | ** Without this flag, the deserialized database cannot increase in size beyond | ||||
| 11367 | ** the number of bytes specified by the M parameter. | ||||
| 11368 | ** | ||||
| 11369 | ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database | ||||
| 11370 | ** should be treated as read-only. | ||||
| 11371 | */ | ||||
| 11372 | #define SQLITE_DESERIALIZE_FREEONCLOSE1 1 /* Call sqlite3_free() on close */ | ||||
| 11373 | #define SQLITE_DESERIALIZE_RESIZEABLE2 2 /* Resize using sqlite3_realloc64() */ | ||||
| 11374 | #define SQLITE_DESERIALIZE_READONLY4 4 /* Database is read-only */ | ||||
| 11375 | |||||
| 11376 | /* | ||||
| 11377 | ** Undo the hack that converts floating point types to integer for | ||||
| 11378 | ** builds on processors without floating point support. | ||||
| 11379 | */ | ||||
| 11380 | #ifdef SQLITE_OMIT_FLOATING_POINT | ||||
| 11381 | # undef double | ||||
| 11382 | #endif | ||||
| 11383 | |||||
| 11384 | #if defined(__wasi__) | ||||
| 11385 | # undef SQLITE_WASI | ||||
| 11386 | # define SQLITE_WASI 1 | ||||
| 11387 | # ifndef SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 11388 | # define SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 11389 | # endif | ||||
| 11390 | # ifndef SQLITE_THREADSAFE2 | ||||
| 11391 | # define SQLITE_THREADSAFE2 0 | ||||
| 11392 | # endif | ||||
| 11393 | #endif | ||||
| 11394 | |||||
| 11395 | #if 0 | ||||
| 11396 | } /* End of the 'extern "C"' block */ | ||||
| 11397 | #endif | ||||
| 11398 | /* #endif for SQLITE3_H will be added by mksqlite3.tcl */ | ||||
| 11399 | |||||
| 11400 | /******** Begin file sqlite3rtree.h *********/ | ||||
| 11401 | /* | ||||
| 11402 | ** 2010 August 30 | ||||
| 11403 | ** | ||||
| 11404 | ** The author disclaims copyright to this source code. In place of | ||||
| 11405 | ** a legal notice, here is a blessing: | ||||
| 11406 | ** | ||||
| 11407 | ** May you do good and not evil. | ||||
| 11408 | ** May you find forgiveness for yourself and forgive others. | ||||
| 11409 | ** May you share freely, never taking more than you give. | ||||
| 11410 | ** | ||||
| 11411 | ************************************************************************* | ||||
| 11412 | */ | ||||
| 11413 | |||||
| 11414 | #ifndef _SQLITE3RTREE_H_ | ||||
| 11415 | #define _SQLITE3RTREE_H_ | ||||
| 11416 | |||||
| 11417 | |||||
| 11418 | #if 0 | ||||
| 11419 | extern "C" { | ||||
| 11420 | #endif | ||||
| 11421 | |||||
| 11422 | typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; | ||||
| 11423 | typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info; | ||||
| 11424 | |||||
| 11425 | /* The double-precision datatype used by RTree depends on the | ||||
| 11426 | ** SQLITE_RTREE_INT_ONLY compile-time option. | ||||
| 11427 | */ | ||||
| 11428 | #ifdef SQLITE_RTREE_INT_ONLY | ||||
| 11429 | typedef sqlite3_int64 sqlite3_rtree_dbl; | ||||
| 11430 | #else | ||||
| 11431 | typedef double sqlite3_rtree_dbl; | ||||
| 11432 | #endif | ||||
| 11433 | |||||
| 11434 | /* | ||||
| 11435 | ** Register a geometry callback named zGeom that can be used as part of an | ||||
| 11436 | ** R-Tree geometry query as follows: | ||||
| 11437 | ** | ||||
| 11438 | ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...) | ||||
| 11439 | */ | ||||
| 11440 | SQLITE_API int sqlite3_rtree_geometry_callback( | ||||
| 11441 | sqlite3 *db, | ||||
| 11442 | const char *zGeom, | ||||
| 11443 | int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*), | ||||
| 11444 | void *pContext | ||||
| 11445 | ); | ||||
| 11446 | |||||
| 11447 | |||||
| 11448 | /* | ||||
| 11449 | ** A pointer to a structure of the following type is passed as the first | ||||
| 11450 | ** argument to callbacks registered using rtree_geometry_callback(). | ||||
| 11451 | */ | ||||
| 11452 | struct sqlite3_rtree_geometry { | ||||
| 11453 | void *pContext; /* Copy of pContext passed to s_r_g_c() */ | ||||
| 11454 | int nParam; /* Size of array aParam[] */ | ||||
| 11455 | sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */ | ||||
| 11456 | void *pUser; /* Callback implementation user data */ | ||||
| 11457 | void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ | ||||
| 11458 | }; | ||||
| 11459 | |||||
| 11460 | /* | ||||
| 11461 | ** Register a 2nd-generation geometry callback named zScore that can be | ||||
| 11462 | ** used as part of an R-Tree geometry query as follows: | ||||
| 11463 | ** | ||||
| 11464 | ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...) | ||||
| 11465 | */ | ||||
| 11466 | SQLITE_API int sqlite3_rtree_query_callback( | ||||
| 11467 | sqlite3 *db, | ||||
| 11468 | const char *zQueryFunc, | ||||
| 11469 | int (*xQueryFunc)(sqlite3_rtree_query_info*), | ||||
| 11470 | void *pContext, | ||||
| 11471 | void (*xDestructor)(void*) | ||||
| 11472 | ); | ||||
| 11473 | |||||
| 11474 | |||||
| 11475 | /* | ||||
| 11476 | ** A pointer to a structure of the following type is passed as the | ||||
| 11477 | ** argument to scored geometry callback registered using | ||||
| 11478 | ** sqlite3_rtree_query_callback(). | ||||
| 11479 | ** | ||||
| 11480 | ** Note that the first 5 fields of this structure are identical to | ||||
| 11481 | ** sqlite3_rtree_geometry. This structure is a subclass of | ||||
| 11482 | ** sqlite3_rtree_geometry. | ||||
| 11483 | */ | ||||
| 11484 | struct sqlite3_rtree_query_info { | ||||
| 11485 | void *pContext; /* pContext from when function registered */ | ||||
| 11486 | int nParam; /* Number of function parameters */ | ||||
| 11487 | sqlite3_rtree_dbl *aParam; /* value of function parameters */ | ||||
| 11488 | void *pUser; /* callback can use this, if desired */ | ||||
| 11489 | void (*xDelUser)(void*); /* function to free pUser */ | ||||
| 11490 | sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */ | ||||
| 11491 | unsigned int *anQueue; /* Number of pending entries in the queue */ | ||||
| 11492 | int nCoord; /* Number of coordinates */ | ||||
| 11493 | int iLevel; /* Level of current node or entry */ | ||||
| 11494 | int mxLevel; /* The largest iLevel value in the tree */ | ||||
| 11495 | sqlite3_int64 iRowid; /* Rowid for current entry */ | ||||
| 11496 | sqlite3_rtree_dbl rParentScore; /* Score of parent node */ | ||||
| 11497 | int eParentWithin; /* Visibility of parent node */ | ||||
| 11498 | int eWithin; /* OUT: Visibility */ | ||||
| 11499 | sqlite3_rtree_dbl rScore; /* OUT: Write the score here */ | ||||
| 11500 | /* The following fields are only available in 3.8.11 and later */ | ||||
| 11501 | sqlite3_value **apSqlParam; /* Original SQL values of parameters */ | ||||
| 11502 | }; | ||||
| 11503 | |||||
| 11504 | /* | ||||
| 11505 | ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin. | ||||
| 11506 | */ | ||||
| 11507 | #define NOT_WITHIN0 0 /* Object completely outside of query region */ | ||||
| 11508 | #define PARTLY_WITHIN1 1 /* Object partially overlaps query region */ | ||||
| 11509 | #define FULLY_WITHIN2 2 /* Object fully contained within query region */ | ||||
| 11510 | |||||
| 11511 | |||||
| 11512 | #if 0 | ||||
| 11513 | } /* end of the 'extern "C"' block */ | ||||
| 11514 | #endif | ||||
| 11515 | |||||
| 11516 | #endif /* ifndef _SQLITE3RTREE_H_ */ | ||||
| 11517 | |||||
| 11518 | /******** End of sqlite3rtree.h *********/ | ||||
| 11519 | /******** Begin file sqlite3session.h *********/ | ||||
| 11520 | |||||
| 11521 | #if !defined(__SQLITESESSION_H_1) && defined(SQLITE_ENABLE_SESSION1) | ||||
| 11522 | #define __SQLITESESSION_H_1 1 | ||||
| 11523 | |||||
| 11524 | /* | ||||
| 11525 | ** Make sure we can call this stuff from C++. | ||||
| 11526 | */ | ||||
| 11527 | #if 0 | ||||
| 11528 | extern "C" { | ||||
| 11529 | #endif | ||||
| 11530 | |||||
| 11531 | |||||
| 11532 | /* | ||||
| 11533 | ** CAPI3REF: Session Object Handle | ||||
| 11534 | ** | ||||
| 11535 | ** An instance of this object is a [session] that can be used to | ||||
| 11536 | ** record changes to a database. | ||||
| 11537 | */ | ||||
| 11538 | typedef struct sqlite3_session sqlite3_session; | ||||
| 11539 | |||||
| 11540 | /* | ||||
| 11541 | ** CAPI3REF: Changeset Iterator Handle | ||||
| 11542 | ** | ||||
| 11543 | ** An instance of this object acts as a cursor for iterating | ||||
| 11544 | ** over the elements of a [changeset] or [patchset]. | ||||
| 11545 | */ | ||||
| 11546 | typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; | ||||
| 11547 | |||||
| 11548 | /* | ||||
| 11549 | ** CAPI3REF: Create A New Session Object | ||||
| 11550 | ** CONSTRUCTOR: sqlite3_session | ||||
| 11551 | ** | ||||
| 11552 | ** Create a new session object attached to database handle db. If successful, | ||||
| 11553 | ** a pointer to the new object is written to *ppSession and SQLITE_OK is | ||||
| 11554 | ** returned. If an error occurs, *ppSession is set to NULL and an SQLite | ||||
| 11555 | ** error code (e.g. SQLITE_NOMEM) is returned. | ||||
| 11556 | ** | ||||
| 11557 | ** It is possible to create multiple session objects attached to a single | ||||
| 11558 | ** database handle. | ||||
| 11559 | ** | ||||
| 11560 | ** Session objects created using this function should be deleted using the | ||||
| 11561 | ** [sqlite3session_delete()] function before the database handle that they | ||||
| 11562 | ** are attached to is itself closed. If the database handle is closed before | ||||
| 11563 | ** the session object is deleted, then the results of calling any session | ||||
| 11564 | ** module function, including [sqlite3session_delete()] on the session object | ||||
| 11565 | ** are undefined. | ||||
| 11566 | ** | ||||
| 11567 | ** Because the session module uses the [sqlite3_preupdate_hook()] API, it | ||||
| 11568 | ** is not possible for an application to register a pre-update hook on a | ||||
| 11569 | ** database handle that has one or more session objects attached. Nor is | ||||
| 11570 | ** it possible to create a session object attached to a database handle for | ||||
| 11571 | ** which a pre-update hook is already defined. The results of attempting | ||||
| 11572 | ** either of these things are undefined. | ||||
| 11573 | ** | ||||
| 11574 | ** The session object will be used to create changesets for tables in | ||||
| 11575 | ** database zDb, where zDb is either "main", or "temp", or the name of an | ||||
| 11576 | ** attached database. It is not an error if database zDb is not attached | ||||
| 11577 | ** to the database when the session object is created. | ||||
| 11578 | */ | ||||
| 11579 | SQLITE_API int sqlite3session_create( | ||||
| 11580 | sqlite3 *db, /* Database handle */ | ||||
| 11581 | const char *zDb, /* Name of db (e.g. "main") */ | ||||
| 11582 | sqlite3_session **ppSession /* OUT: New session object */ | ||||
| 11583 | ); | ||||
| 11584 | |||||
| 11585 | /* | ||||
| 11586 | ** CAPI3REF: Delete A Session Object | ||||
| 11587 | ** DESTRUCTOR: sqlite3_session | ||||
| 11588 | ** | ||||
| 11589 | ** Delete a session object previously allocated using | ||||
| 11590 | ** [sqlite3session_create()]. Once a session object has been deleted, the | ||||
| 11591 | ** results of attempting to use pSession with any other session module | ||||
| 11592 | ** function are undefined. | ||||
| 11593 | ** | ||||
| 11594 | ** Session objects must be deleted before the database handle to which they | ||||
| 11595 | ** are attached is closed. Refer to the documentation for | ||||
| 11596 | ** [sqlite3session_create()] for details. | ||||
| 11597 | */ | ||||
| 11598 | SQLITE_API void sqlite3session_delete(sqlite3_session *pSession); | ||||
| 11599 | |||||
| 11600 | /* | ||||
| 11601 | ** CAPI3REF: Configure a Session Object | ||||
| 11602 | ** METHOD: sqlite3_session | ||||
| 11603 | ** | ||||
| 11604 | ** This method is used to configure a session object after it has been | ||||
| 11605 | ** created. At present the only valid values for the second parameter are | ||||
| 11606 | ** [SQLITE_SESSION_OBJCONFIG_SIZE] and [SQLITE_SESSION_OBJCONFIG_ROWID]. | ||||
| 11607 | ** | ||||
| 11608 | */ | ||||
| 11609 | SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg); | ||||
| 11610 | |||||
| 11611 | /* | ||||
| 11612 | ** CAPI3REF: Options for sqlite3session_object_config | ||||
| 11613 | ** | ||||
| 11614 | ** The following values may passed as the the 2nd parameter to | ||||
| 11615 | ** sqlite3session_object_config(). | ||||
| 11616 | ** | ||||
| 11617 | ** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd> | ||||
| 11618 | ** This option is used to set, clear or query the flag that enables | ||||
| 11619 | ** the [sqlite3session_changeset_size()] API. Because it imposes some | ||||
| 11620 | ** computational overhead, this API is disabled by default. Argument | ||||
| 11621 | ** pArg must point to a value of type (int). If the value is initially | ||||
| 11622 | ** 0, then the sqlite3session_changeset_size() API is disabled. If it | ||||
| 11623 | ** is greater than 0, then the same API is enabled. Or, if the initial | ||||
| 11624 | ** value is less than zero, no change is made. In all cases the (int) | ||||
| 11625 | ** variable is set to 1 if the sqlite3session_changeset_size() API is | ||||
| 11626 | ** enabled following the current call, or 0 otherwise. | ||||
| 11627 | ** | ||||
| 11628 | ** It is an error (SQLITE_MISUSE) to attempt to modify this setting after | ||||
| 11629 | ** the first table has been attached to the session object. | ||||
| 11630 | ** | ||||
| 11631 | ** <dt>SQLITE_SESSION_OBJCONFIG_ROWID <dd> | ||||
| 11632 | ** This option is used to set, clear or query the flag that enables | ||||
| 11633 | ** collection of data for tables with no explicit PRIMARY KEY. | ||||
| 11634 | ** | ||||
| 11635 | ** Normally, tables with no explicit PRIMARY KEY are simply ignored | ||||
| 11636 | ** by the sessions module. However, if this flag is set, it behaves | ||||
| 11637 | ** as if such tables have a column "_rowid_ INTEGER PRIMARY KEY" inserted | ||||
| 11638 | ** as their leftmost columns. | ||||
| 11639 | ** | ||||
| 11640 | ** It is an error (SQLITE_MISUSE) to attempt to modify this setting after | ||||
| 11641 | ** the first table has been attached to the session object. | ||||
| 11642 | */ | ||||
| 11643 | #define SQLITE_SESSION_OBJCONFIG_SIZE1 1 | ||||
| 11644 | #define SQLITE_SESSION_OBJCONFIG_ROWID2 2 | ||||
| 11645 | |||||
| 11646 | /* | ||||
| 11647 | ** CAPI3REF: Enable Or Disable A Session Object | ||||
| 11648 | ** METHOD: sqlite3_session | ||||
| 11649 | ** | ||||
| 11650 | ** Enable or disable the recording of changes by a session object. When | ||||
| 11651 | ** enabled, a session object records changes made to the database. When | ||||
| 11652 | ** disabled - it does not. A newly created session object is enabled. | ||||
| 11653 | ** Refer to the documentation for [sqlite3session_changeset()] for further | ||||
| 11654 | ** details regarding how enabling and disabling a session object affects | ||||
| 11655 | ** the eventual changesets. | ||||
| 11656 | ** | ||||
| 11657 | ** Passing zero to this function disables the session. Passing a value | ||||
| 11658 | ** greater than zero enables it. Passing a value less than zero is a | ||||
| 11659 | ** no-op, and may be used to query the current state of the session. | ||||
| 11660 | ** | ||||
| 11661 | ** The return value indicates the final state of the session object: 0 if | ||||
| 11662 | ** the session is disabled, or 1 if it is enabled. | ||||
| 11663 | */ | ||||
| 11664 | SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable); | ||||
| 11665 | |||||
| 11666 | /* | ||||
| 11667 | ** CAPI3REF: Set Or Clear the Indirect Change Flag | ||||
| 11668 | ** METHOD: sqlite3_session | ||||
| 11669 | ** | ||||
| 11670 | ** Each change recorded by a session object is marked as either direct or | ||||
| 11671 | ** indirect. A change is marked as indirect if either: | ||||
| 11672 | ** | ||||
| 11673 | ** <ul> | ||||
| 11674 | ** <li> The session object "indirect" flag is set when the change is | ||||
| 11675 | ** made, or | ||||
| 11676 | ** <li> The change is made by an SQL trigger or foreign key action | ||||
| 11677 | ** instead of directly as a result of a users SQL statement. | ||||
| 11678 | ** </ul> | ||||
| 11679 | ** | ||||
| 11680 | ** If a single row is affected by more than one operation within a session, | ||||
| 11681 | ** then the change is considered indirect if all operations meet the criteria | ||||
| 11682 | ** for an indirect change above, or direct otherwise. | ||||
| 11683 | ** | ||||
| 11684 | ** This function is used to set, clear or query the session object indirect | ||||
| 11685 | ** flag. If the second argument passed to this function is zero, then the | ||||
| 11686 | ** indirect flag is cleared. If it is greater than zero, the indirect flag | ||||
| 11687 | ** is set. Passing a value less than zero does not modify the current value | ||||
| 11688 | ** of the indirect flag, and may be used to query the current state of the | ||||
| 11689 | ** indirect flag for the specified session object. | ||||
| 11690 | ** | ||||
| 11691 | ** The return value indicates the final state of the indirect flag: 0 if | ||||
| 11692 | ** it is clear, or 1 if it is set. | ||||
| 11693 | */ | ||||
| 11694 | SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect); | ||||
| 11695 | |||||
| 11696 | /* | ||||
| 11697 | ** CAPI3REF: Attach A Table To A Session Object | ||||
| 11698 | ** METHOD: sqlite3_session | ||||
| 11699 | ** | ||||
| 11700 | ** If argument zTab is not NULL, then it is the name of a table to attach | ||||
| 11701 | ** to the session object passed as the first argument. All subsequent changes | ||||
| 11702 | ** made to the table while the session object is enabled will be recorded. See | ||||
| 11703 | ** documentation for [sqlite3session_changeset()] for further details. | ||||
| 11704 | ** | ||||
| 11705 | ** Or, if argument zTab is NULL, then changes are recorded for all tables | ||||
| 11706 | ** in the database. If additional tables are added to the database (by | ||||
| 11707 | ** executing "CREATE TABLE" statements) after this call is made, changes for | ||||
| 11708 | ** the new tables are also recorded. | ||||
| 11709 | ** | ||||
| 11710 | ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly | ||||
| 11711 | ** defined as part of their CREATE TABLE statement. It does not matter if the | ||||
| 11712 | ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY | ||||
| 11713 | ** KEY may consist of a single column, or may be a composite key. | ||||
| 11714 | ** | ||||
| 11715 | ** It is not an error if the named table does not exist in the database. Nor | ||||
| 11716 | ** is it an error if the named table does not have a PRIMARY KEY. However, | ||||
| 11717 | ** no changes will be recorded in either of these scenarios. | ||||
| 11718 | ** | ||||
| 11719 | ** Changes are not recorded for individual rows that have NULL values stored | ||||
| 11720 | ** in one or more of their PRIMARY KEY columns. | ||||
| 11721 | ** | ||||
| 11722 | ** SQLITE_OK is returned if the call completes without error. Or, if an error | ||||
| 11723 | ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned. | ||||
| 11724 | ** | ||||
| 11725 | ** <h3>Special sqlite_stat1 Handling</h3> | ||||
| 11726 | ** | ||||
| 11727 | ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to | ||||
| 11728 | ** some of the rules above. In SQLite, the schema of sqlite_stat1 is: | ||||
| 11729 | ** <pre> | ||||
| 11730 | ** CREATE TABLE sqlite_stat1(tbl,idx,stat) | ||||
| 11731 | ** </pre> | ||||
| 11732 | ** | ||||
| 11733 | ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are | ||||
| 11734 | ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes | ||||
| 11735 | ** are recorded for rows for which (idx IS NULL) is true. However, for such | ||||
| 11736 | ** rows a zero-length blob (SQL value X'') is stored in the changeset or | ||||
| 11737 | ** patchset instead of a NULL value. This allows such changesets to be | ||||
| 11738 | ** manipulated by legacy implementations of sqlite3changeset_invert(), | ||||
| 11739 | ** concat() and similar. | ||||
| 11740 | ** | ||||
| 11741 | ** The sqlite3changeset_apply() function automatically converts the | ||||
| 11742 | ** zero-length blob back to a NULL value when updating the sqlite_stat1 | ||||
| 11743 | ** table. However, if the application calls sqlite3changeset_new(), | ||||
| 11744 | ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset | ||||
| 11745 | ** iterator directly (including on a changeset iterator passed to a | ||||
| 11746 | ** conflict-handler callback) then the X'' value is returned. The application | ||||
| 11747 | ** must translate X'' to NULL itself if required. | ||||
| 11748 | ** | ||||
| 11749 | ** Legacy (older than 3.22.0) versions of the sessions module cannot capture | ||||
| 11750 | ** changes made to the sqlite_stat1 table. Legacy versions of the | ||||
| 11751 | ** sqlite3changeset_apply() function silently ignore any modifications to the | ||||
| 11752 | ** sqlite_stat1 table that are part of a changeset or patchset. | ||||
| 11753 | */ | ||||
| 11754 | SQLITE_API int sqlite3session_attach( | ||||
| 11755 | sqlite3_session *pSession, /* Session object */ | ||||
| 11756 | const char *zTab /* Table name */ | ||||
| 11757 | ); | ||||
| 11758 | |||||
| 11759 | /* | ||||
| 11760 | ** CAPI3REF: Set a table filter on a Session Object. | ||||
| 11761 | ** METHOD: sqlite3_session | ||||
| 11762 | ** | ||||
| 11763 | ** The second argument (xFilter) is the "filter callback". For changes to rows | ||||
| 11764 | ** in tables that are not attached to the Session object, the filter is called | ||||
| 11765 | ** to determine whether changes to the table's rows should be tracked or not. | ||||
| 11766 | ** If xFilter returns 0, changes are not tracked. Note that once a table is | ||||
| 11767 | ** attached, xFilter will not be called again. | ||||
| 11768 | */ | ||||
| 11769 | SQLITE_API void sqlite3session_table_filter( | ||||
| 11770 | sqlite3_session *pSession, /* Session object */ | ||||
| 11771 | int(*xFilter)( | ||||
| 11772 | void *pCtx, /* Copy of third arg to _filter_table() */ | ||||
| 11773 | const char *zTab /* Table name */ | ||||
| 11774 | ), | ||||
| 11775 | void *pCtx /* First argument passed to xFilter */ | ||||
| 11776 | ); | ||||
| 11777 | |||||
| 11778 | /* | ||||
| 11779 | ** CAPI3REF: Generate A Changeset From A Session Object | ||||
| 11780 | ** METHOD: sqlite3_session | ||||
| 11781 | ** | ||||
| 11782 | ** Obtain a changeset containing changes to the tables attached to the | ||||
| 11783 | ** session object passed as the first argument. If successful, | ||||
| 11784 | ** set *ppChangeset to point to a buffer containing the changeset | ||||
| 11785 | ** and *pnChangeset to the size of the changeset in bytes before returning | ||||
| 11786 | ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to | ||||
| 11787 | ** zero and return an SQLite error code. | ||||
| 11788 | ** | ||||
| 11789 | ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes, | ||||
| 11790 | ** each representing a change to a single row of an attached table. An INSERT | ||||
| 11791 | ** change contains the values of each field of a new database row. A DELETE | ||||
| 11792 | ** contains the original values of each field of a deleted database row. An | ||||
| 11793 | ** UPDATE change contains the original values of each field of an updated | ||||
| 11794 | ** database row along with the updated values for each updated non-primary-key | ||||
| 11795 | ** column. It is not possible for an UPDATE change to represent a change that | ||||
| 11796 | ** modifies the values of primary key columns. If such a change is made, it | ||||
| 11797 | ** is represented in a changeset as a DELETE followed by an INSERT. | ||||
| 11798 | ** | ||||
| 11799 | ** Changes are not recorded for rows that have NULL values stored in one or | ||||
| 11800 | ** more of their PRIMARY KEY columns. If such a row is inserted or deleted, | ||||
| 11801 | ** no corresponding change is present in the changesets returned by this | ||||
| 11802 | ** function. If an existing row with one or more NULL values stored in | ||||
| 11803 | ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL, | ||||
| 11804 | ** only an INSERT is appears in the changeset. Similarly, if an existing row | ||||
| 11805 | ** with non-NULL PRIMARY KEY values is updated so that one or more of its | ||||
| 11806 | ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a | ||||
| 11807 | ** DELETE change only. | ||||
| 11808 | ** | ||||
| 11809 | ** The contents of a changeset may be traversed using an iterator created | ||||
| 11810 | ** using the [sqlite3changeset_start()] API. A changeset may be applied to | ||||
| 11811 | ** a database with a compatible schema using the [sqlite3changeset_apply()] | ||||
| 11812 | ** API. | ||||
| 11813 | ** | ||||
| 11814 | ** Within a changeset generated by this function, all changes related to a | ||||
| 11815 | ** single table are grouped together. In other words, when iterating through | ||||
| 11816 | ** a changeset or when applying a changeset to a database, all changes related | ||||
| 11817 | ** to a single table are processed before moving on to the next table. Tables | ||||
| 11818 | ** are sorted in the same order in which they were attached (or auto-attached) | ||||
| 11819 | ** to the sqlite3_session object. The order in which the changes related to | ||||
| 11820 | ** a single table are stored is undefined. | ||||
| 11821 | ** | ||||
| 11822 | ** Following a successful call to this function, it is the responsibility of | ||||
| 11823 | ** the caller to eventually free the buffer that *ppChangeset points to using | ||||
| 11824 | ** [sqlite3_free()]. | ||||
| 11825 | ** | ||||
| 11826 | ** <h3>Changeset Generation</h3> | ||||
| 11827 | ** | ||||
| 11828 | ** Once a table has been attached to a session object, the session object | ||||
| 11829 | ** records the primary key values of all new rows inserted into the table. | ||||
| 11830 | ** It also records the original primary key and other column values of any | ||||
| 11831 | ** deleted or updated rows. For each unique primary key value, data is only | ||||
| 11832 | ** recorded once - the first time a row with said primary key is inserted, | ||||
| 11833 | ** updated or deleted in the lifetime of the session. | ||||
| 11834 | ** | ||||
| 11835 | ** There is one exception to the previous paragraph: when a row is inserted, | ||||
| 11836 | ** updated or deleted, if one or more of its primary key columns contain a | ||||
| 11837 | ** NULL value, no record of the change is made. | ||||
| 11838 | ** | ||||
| 11839 | ** The session object therefore accumulates two types of records - those | ||||
| 11840 | ** that consist of primary key values only (created when the user inserts | ||||
| 11841 | ** a new record) and those that consist of the primary key values and the | ||||
| 11842 | ** original values of other table columns (created when the users deletes | ||||
| 11843 | ** or updates a record). | ||||
| 11844 | ** | ||||
| 11845 | ** When this function is called, the requested changeset is created using | ||||
| 11846 | ** both the accumulated records and the current contents of the database | ||||
| 11847 | ** file. Specifically: | ||||
| 11848 | ** | ||||
| 11849 | ** <ul> | ||||
| 11850 | ** <li> For each record generated by an insert, the database is queried | ||||
| 11851 | ** for a row with a matching primary key. If one is found, an INSERT | ||||
| 11852 | ** change is added to the changeset. If no such row is found, no change | ||||
| 11853 | ** is added to the changeset. | ||||
| 11854 | ** | ||||
| 11855 | ** <li> For each record generated by an update or delete, the database is | ||||
| 11856 | ** queried for a row with a matching primary key. If such a row is | ||||
| 11857 | ** found and one or more of the non-primary key fields have been | ||||
| 11858 | ** modified from their original values, an UPDATE change is added to | ||||
| 11859 | ** the changeset. Or, if no such row is found in the table, a DELETE | ||||
| 11860 | ** change is added to the changeset. If there is a row with a matching | ||||
| 11861 | ** primary key in the database, but all fields contain their original | ||||
| 11862 | ** values, no change is added to the changeset. | ||||
| 11863 | ** </ul> | ||||
| 11864 | ** | ||||
| 11865 | ** This means, amongst other things, that if a row is inserted and then later | ||||
| 11866 | ** deleted while a session object is active, neither the insert nor the delete | ||||
| 11867 | ** will be present in the changeset. Or if a row is deleted and then later a | ||||
| 11868 | ** row with the same primary key values inserted while a session object is | ||||
| 11869 | ** active, the resulting changeset will contain an UPDATE change instead of | ||||
| 11870 | ** a DELETE and an INSERT. | ||||
| 11871 | ** | ||||
| 11872 | ** When a session object is disabled (see the [sqlite3session_enable()] API), | ||||
| 11873 | ** it does not accumulate records when rows are inserted, updated or deleted. | ||||
| 11874 | ** This may appear to have some counter-intuitive effects if a single row | ||||
| 11875 | ** is written to more than once during a session. For example, if a row | ||||
| 11876 | ** is inserted while a session object is enabled, then later deleted while | ||||
| 11877 | ** the same session object is disabled, no INSERT record will appear in the | ||||
| 11878 | ** changeset, even though the delete took place while the session was disabled. | ||||
| 11879 | ** Or, if one field of a row is updated while a session is enabled, and | ||||
| 11880 | ** then another field of the same row is updated while the session is disabled, | ||||
| 11881 | ** the resulting changeset will contain an UPDATE change that updates both | ||||
| 11882 | ** fields. | ||||
| 11883 | */ | ||||
| 11884 | SQLITE_API int sqlite3session_changeset( | ||||
| 11885 | sqlite3_session *pSession, /* Session object */ | ||||
| 11886 | int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */ | ||||
| 11887 | void **ppChangeset /* OUT: Buffer containing changeset */ | ||||
| 11888 | ); | ||||
| 11889 | |||||
| 11890 | /* | ||||
| 11891 | ** CAPI3REF: Return An Upper-limit For The Size Of The Changeset | ||||
| 11892 | ** METHOD: sqlite3_session | ||||
| 11893 | ** | ||||
| 11894 | ** By default, this function always returns 0. For it to return | ||||
| 11895 | ** a useful result, the sqlite3_session object must have been configured | ||||
| 11896 | ** to enable this API using sqlite3session_object_config() with the | ||||
| 11897 | ** SQLITE_SESSION_OBJCONFIG_SIZE verb. | ||||
| 11898 | ** | ||||
| 11899 | ** When enabled, this function returns an upper limit, in bytes, for the size | ||||
| 11900 | ** of the changeset that might be produced if sqlite3session_changeset() were | ||||
| 11901 | ** called. The final changeset size might be equal to or smaller than the | ||||
| 11902 | ** size in bytes returned by this function. | ||||
| 11903 | */ | ||||
| 11904 | SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession); | ||||
| 11905 | |||||
| 11906 | /* | ||||
| 11907 | ** CAPI3REF: Load The Difference Between Tables Into A Session | ||||
| 11908 | ** METHOD: sqlite3_session | ||||
| 11909 | ** | ||||
| 11910 | ** If it is not already attached to the session object passed as the first | ||||
| 11911 | ** argument, this function attaches table zTbl in the same manner as the | ||||
| 11912 | ** [sqlite3session_attach()] function. If zTbl does not exist, or if it | ||||
| 11913 | ** does not have a primary key, this function is a no-op (but does not return | ||||
| 11914 | ** an error). | ||||
| 11915 | ** | ||||
| 11916 | ** Argument zFromDb must be the name of a database ("main", "temp" etc.) | ||||
| 11917 | ** attached to the same database handle as the session object that contains | ||||
| 11918 | ** a table compatible with the table attached to the session by this function. | ||||
| 11919 | ** A table is considered compatible if it: | ||||
| 11920 | ** | ||||
| 11921 | ** <ul> | ||||
| 11922 | ** <li> Has the same name, | ||||
| 11923 | ** <li> Has the same set of columns declared in the same order, and | ||||
| 11924 | ** <li> Has the same PRIMARY KEY definition. | ||||
| 11925 | ** </ul> | ||||
| 11926 | ** | ||||
| 11927 | ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables | ||||
| 11928 | ** are compatible but do not have any PRIMARY KEY columns, it is not an error | ||||
| 11929 | ** but no changes are added to the session object. As with other session | ||||
| 11930 | ** APIs, tables without PRIMARY KEYs are simply ignored. | ||||
| 11931 | ** | ||||
| 11932 | ** This function adds a set of changes to the session object that could be | ||||
| 11933 | ** used to update the table in database zFrom (call this the "from-table") | ||||
| 11934 | ** so that its content is the same as the table attached to the session | ||||
| 11935 | ** object (call this the "to-table"). Specifically: | ||||
| 11936 | ** | ||||
| 11937 | ** <ul> | ||||
| 11938 | ** <li> For each row (primary key) that exists in the to-table but not in | ||||
| 11939 | ** the from-table, an INSERT record is added to the session object. | ||||
| 11940 | ** | ||||
| 11941 | ** <li> For each row (primary key) that exists in the to-table but not in | ||||
| 11942 | ** the from-table, a DELETE record is added to the session object. | ||||
| 11943 | ** | ||||
| 11944 | ** <li> For each row (primary key) that exists in both tables, but features | ||||
| 11945 | ** different non-PK values in each, an UPDATE record is added to the | ||||
| 11946 | ** session. | ||||
| 11947 | ** </ul> | ||||
| 11948 | ** | ||||
| 11949 | ** To clarify, if this function is called and then a changeset constructed | ||||
| 11950 | ** using [sqlite3session_changeset()], then after applying that changeset to | ||||
| 11951 | ** database zFrom the contents of the two compatible tables would be | ||||
| 11952 | ** identical. | ||||
| 11953 | ** | ||||
| 11954 | ** Unless the call to this function is a no-op as described above, it is an | ||||
| 11955 | ** error if database zFrom does not exist or does not contain the required | ||||
| 11956 | ** compatible table. | ||||
| 11957 | ** | ||||
| 11958 | ** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite | ||||
| 11959 | ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg | ||||
| 11960 | ** may be set to point to a buffer containing an English language error | ||||
| 11961 | ** message. It is the responsibility of the caller to free this buffer using | ||||
| 11962 | ** sqlite3_free(). | ||||
| 11963 | */ | ||||
| 11964 | SQLITE_API int sqlite3session_diff( | ||||
| 11965 | sqlite3_session *pSession, | ||||
| 11966 | const char *zFromDb, | ||||
| 11967 | const char *zTbl, | ||||
| 11968 | char **pzErrMsg | ||||
| 11969 | ); | ||||
| 11970 | |||||
| 11971 | |||||
| 11972 | /* | ||||
| 11973 | ** CAPI3REF: Generate A Patchset From A Session Object | ||||
| 11974 | ** METHOD: sqlite3_session | ||||
| 11975 | ** | ||||
| 11976 | ** The differences between a patchset and a changeset are that: | ||||
| 11977 | ** | ||||
| 11978 | ** <ul> | ||||
| 11979 | ** <li> DELETE records consist of the primary key fields only. The | ||||
| 11980 | ** original values of other fields are omitted. | ||||
| 11981 | ** <li> The original values of any modified fields are omitted from | ||||
| 11982 | ** UPDATE records. | ||||
| 11983 | ** </ul> | ||||
| 11984 | ** | ||||
| 11985 | ** A patchset blob may be used with up to date versions of all | ||||
| 11986 | ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), | ||||
| 11987 | ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly, | ||||
| 11988 | ** attempting to use a patchset blob with old versions of the | ||||
| 11989 | ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. | ||||
| 11990 | ** | ||||
| 11991 | ** Because the non-primary key "old.*" fields are omitted, no | ||||
| 11992 | ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset | ||||
| 11993 | ** is passed to the sqlite3changeset_apply() API. Other conflict types work | ||||
| 11994 | ** in the same way as for changesets. | ||||
| 11995 | ** | ||||
| 11996 | ** Changes within a patchset are ordered in the same way as for changesets | ||||
| 11997 | ** generated by the sqlite3session_changeset() function (i.e. all changes for | ||||
| 11998 | ** a single table are grouped together, tables appear in the order in which | ||||
| 11999 | ** they were attached to the session object). | ||||
| 12000 | */ | ||||
| 12001 | SQLITE_API int sqlite3session_patchset( | ||||
| 12002 | sqlite3_session *pSession, /* Session object */ | ||||
| 12003 | int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */ | ||||
| 12004 | void **ppPatchset /* OUT: Buffer containing patchset */ | ||||
| 12005 | ); | ||||
| 12006 | |||||
| 12007 | /* | ||||
| 12008 | ** CAPI3REF: Test if a changeset has recorded any changes. | ||||
| 12009 | ** | ||||
| 12010 | ** Return non-zero if no changes to attached tables have been recorded by | ||||
| 12011 | ** the session object passed as the first argument. Otherwise, if one or | ||||
| 12012 | ** more changes have been recorded, return zero. | ||||
| 12013 | ** | ||||
| 12014 | ** Even if this function returns zero, it is possible that calling | ||||
| 12015 | ** [sqlite3session_changeset()] on the session handle may still return a | ||||
| 12016 | ** changeset that contains no changes. This can happen when a row in | ||||
| 12017 | ** an attached table is modified and then later on the original values | ||||
| 12018 | ** are restored. However, if this function returns non-zero, then it is | ||||
| 12019 | ** guaranteed that a call to sqlite3session_changeset() will return a | ||||
| 12020 | ** changeset containing zero changes. | ||||
| 12021 | */ | ||||
| 12022 | SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession); | ||||
| 12023 | |||||
| 12024 | /* | ||||
| 12025 | ** CAPI3REF: Query for the amount of heap memory used by a session object. | ||||
| 12026 | ** | ||||
| 12027 | ** This API returns the total amount of heap memory in bytes currently | ||||
| 12028 | ** used by the session object passed as the only argument. | ||||
| 12029 | */ | ||||
| 12030 | SQLITE_API sqlite3_int64 sqlite3session_memory_used(sqlite3_session *pSession); | ||||
| 12031 | |||||
| 12032 | /* | ||||
| 12033 | ** CAPI3REF: Create An Iterator To Traverse A Changeset | ||||
| 12034 | ** CONSTRUCTOR: sqlite3_changeset_iter | ||||
| 12035 | ** | ||||
| 12036 | ** Create an iterator used to iterate through the contents of a changeset. | ||||
| 12037 | ** If successful, *pp is set to point to the iterator handle and SQLITE_OK | ||||
| 12038 | ** is returned. Otherwise, if an error occurs, *pp is set to zero and an | ||||
| 12039 | ** SQLite error code is returned. | ||||
| 12040 | ** | ||||
| 12041 | ** The following functions can be used to advance and query a changeset | ||||
| 12042 | ** iterator created by this function: | ||||
| 12043 | ** | ||||
| 12044 | ** <ul> | ||||
| 12045 | ** <li> [sqlite3changeset_next()] | ||||
| 12046 | ** <li> [sqlite3changeset_op()] | ||||
| 12047 | ** <li> [sqlite3changeset_new()] | ||||
| 12048 | ** <li> [sqlite3changeset_old()] | ||||
| 12049 | ** </ul> | ||||
| 12050 | ** | ||||
| 12051 | ** It is the responsibility of the caller to eventually destroy the iterator | ||||
| 12052 | ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the | ||||
| 12053 | ** changeset (pChangeset) must remain valid until after the iterator is | ||||
| 12054 | ** destroyed. | ||||
| 12055 | ** | ||||
| 12056 | ** Assuming the changeset blob was created by one of the | ||||
| 12057 | ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or | ||||
| 12058 | ** [sqlite3changeset_invert()] functions, all changes within the changeset | ||||
| 12059 | ** that apply to a single table are grouped together. This means that when | ||||
| 12060 | ** an application iterates through a changeset using an iterator created by | ||||
| 12061 | ** this function, all changes that relate to a single table are visited | ||||
| 12062 | ** consecutively. There is no chance that the iterator will visit a change | ||||
| 12063 | ** the applies to table X, then one for table Y, and then later on visit | ||||
| 12064 | ** another change for table X. | ||||
| 12065 | ** | ||||
| 12066 | ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent | ||||
| 12067 | ** may be modified by passing a combination of | ||||
| 12068 | ** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter. | ||||
| 12069 | ** | ||||
| 12070 | ** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b> | ||||
| 12071 | ** and therefore subject to change. | ||||
| 12072 | */ | ||||
| 12073 | SQLITE_API int sqlite3changeset_start( | ||||
| 12074 | sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ | ||||
| 12075 | int nChangeset, /* Size of changeset blob in bytes */ | ||||
| 12076 | void *pChangeset /* Pointer to blob containing changeset */ | ||||
| 12077 | ); | ||||
| 12078 | SQLITE_API int sqlite3changeset_start_v2( | ||||
| 12079 | sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */ | ||||
| 12080 | int nChangeset, /* Size of changeset blob in bytes */ | ||||
| 12081 | void *pChangeset, /* Pointer to blob containing changeset */ | ||||
| 12082 | int flags /* SESSION_CHANGESETSTART_* flags */ | ||||
| 12083 | ); | ||||
| 12084 | |||||
| 12085 | /* | ||||
| 12086 | ** CAPI3REF: Flags for sqlite3changeset_start_v2 | ||||
| 12087 | ** | ||||
| 12088 | ** The following flags may passed via the 4th parameter to | ||||
| 12089 | ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]: | ||||
| 12090 | ** | ||||
| 12091 | ** <dt>SQLITE_CHANGESETSTART_INVERT <dd> | ||||
| 12092 | ** Invert the changeset while iterating through it. This is equivalent to | ||||
| 12093 | ** inverting a changeset using sqlite3changeset_invert() before applying it. | ||||
| 12094 | ** It is an error to specify this flag with a patchset. | ||||
| 12095 | */ | ||||
| 12096 | #define SQLITE_CHANGESETSTART_INVERT0x0002 0x0002 | ||||
| 12097 | |||||
| 12098 | |||||
| 12099 | /* | ||||
| 12100 | ** CAPI3REF: Advance A Changeset Iterator | ||||
| 12101 | ** METHOD: sqlite3_changeset_iter | ||||
| 12102 | ** | ||||
| 12103 | ** This function may only be used with iterators created by the function | ||||
| 12104 | ** [sqlite3changeset_start()]. If it is called on an iterator passed to | ||||
| 12105 | ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE | ||||
| 12106 | ** is returned and the call has no effect. | ||||
| 12107 | ** | ||||
| 12108 | ** Immediately after an iterator is created by sqlite3changeset_start(), it | ||||
| 12109 | ** does not point to any change in the changeset. Assuming the changeset | ||||
| 12110 | ** is not empty, the first call to this function advances the iterator to | ||||
| 12111 | ** point to the first change in the changeset. Each subsequent call advances | ||||
| 12112 | ** the iterator to point to the next change in the changeset (if any). If | ||||
| 12113 | ** no error occurs and the iterator points to a valid change after a call | ||||
| 12114 | ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. | ||||
| 12115 | ** Otherwise, if all changes in the changeset have already been visited, | ||||
| 12116 | ** SQLITE_DONE is returned. | ||||
| 12117 | ** | ||||
| 12118 | ** If an error occurs, an SQLite error code is returned. Possible error | ||||
| 12119 | ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or | ||||
| 12120 | ** SQLITE_NOMEM. | ||||
| 12121 | */ | ||||
| 12122 | SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter); | ||||
| 12123 | |||||
| 12124 | /* | ||||
| 12125 | ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator | ||||
| 12126 | ** METHOD: sqlite3_changeset_iter | ||||
| 12127 | ** | ||||
| 12128 | ** The pIter argument passed to this function may either be an iterator | ||||
| 12129 | ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator | ||||
| 12130 | ** created by [sqlite3changeset_start()]. In the latter case, the most recent | ||||
| 12131 | ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this | ||||
| 12132 | ** is not the case, this function returns [SQLITE_MISUSE]. | ||||
| 12133 | ** | ||||
| 12134 | ** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three | ||||
| 12135 | ** outputs are set through these pointers: | ||||
| 12136 | ** | ||||
| 12137 | ** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], | ||||
| 12138 | ** depending on the type of change that the iterator currently points to; | ||||
| 12139 | ** | ||||
| 12140 | ** *pnCol is set to the number of columns in the table affected by the change; and | ||||
| 12141 | ** | ||||
| 12142 | ** *pzTab is set to point to a nul-terminated utf-8 encoded string containing | ||||
| 12143 | ** the name of the table affected by the current change. The buffer remains | ||||
| 12144 | ** valid until either sqlite3changeset_next() is called on the iterator | ||||
| 12145 | ** or until the conflict-handler function returns. | ||||
| 12146 | ** | ||||
| 12147 | ** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change | ||||
| 12148 | ** is an indirect change, or false (0) otherwise. See the documentation for | ||||
| 12149 | ** [sqlite3session_indirect()] for a description of direct and indirect | ||||
| 12150 | ** changes. | ||||
| 12151 | ** | ||||
| 12152 | ** If no error occurs, SQLITE_OK is returned. If an error does occur, an | ||||
| 12153 | ** SQLite error code is returned. The values of the output variables may not | ||||
| 12154 | ** be trusted in this case. | ||||
| 12155 | */ | ||||
| 12156 | SQLITE_API int sqlite3changeset_op( | ||||
| 12157 | sqlite3_changeset_iter *pIter, /* Iterator object */ | ||||
| 12158 | const char **pzTab, /* OUT: Pointer to table name */ | ||||
| 12159 | int *pnCol, /* OUT: Number of columns in table */ | ||||
| 12160 | int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */ | ||||
| 12161 | int *pbIndirect /* OUT: True for an 'indirect' change */ | ||||
| 12162 | ); | ||||
| 12163 | |||||
| 12164 | /* | ||||
| 12165 | ** CAPI3REF: Obtain The Primary Key Definition Of A Table | ||||
| 12166 | ** METHOD: sqlite3_changeset_iter | ||||
| 12167 | ** | ||||
| 12168 | ** For each modified table, a changeset includes the following: | ||||
| 12169 | ** | ||||
| 12170 | ** <ul> | ||||
| 12171 | ** <li> The number of columns in the table, and | ||||
| 12172 | ** <li> Which of those columns make up the tables PRIMARY KEY. | ||||
| 12173 | ** </ul> | ||||
| 12174 | ** | ||||
| 12175 | ** This function is used to find which columns comprise the PRIMARY KEY of | ||||
| 12176 | ** the table modified by the change that iterator pIter currently points to. | ||||
| 12177 | ** If successful, *pabPK is set to point to an array of nCol entries, where | ||||
| 12178 | ** nCol is the number of columns in the table. Elements of *pabPK are set to | ||||
| 12179 | ** 0x01 if the corresponding column is part of the tables primary key, or | ||||
| 12180 | ** 0x00 if it is not. | ||||
| 12181 | ** | ||||
| 12182 | ** If argument pnCol is not NULL, then *pnCol is set to the number of columns | ||||
| 12183 | ** in the table. | ||||
| 12184 | ** | ||||
| 12185 | ** If this function is called when the iterator does not point to a valid | ||||
| 12186 | ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise, | ||||
| 12187 | ** SQLITE_OK is returned and the output variables populated as described | ||||
| 12188 | ** above. | ||||
| 12189 | */ | ||||
| 12190 | SQLITE_API int sqlite3changeset_pk( | ||||
| 12191 | sqlite3_changeset_iter *pIter, /* Iterator object */ | ||||
| 12192 | unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */ | ||||
| 12193 | int *pnCol /* OUT: Number of entries in output array */ | ||||
| 12194 | ); | ||||
| 12195 | |||||
| 12196 | /* | ||||
| 12197 | ** CAPI3REF: Obtain old.* Values From A Changeset Iterator | ||||
| 12198 | ** METHOD: sqlite3_changeset_iter | ||||
| 12199 | ** | ||||
| 12200 | ** The pIter argument passed to this function may either be an iterator | ||||
| 12201 | ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator | ||||
| 12202 | ** created by [sqlite3changeset_start()]. In the latter case, the most recent | ||||
| 12203 | ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. | ||||
| 12204 | ** Furthermore, it may only be called if the type of change that the iterator | ||||
| 12205 | ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise, | ||||
| 12206 | ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. | ||||
| 12207 | ** | ||||
| 12208 | ** Argument iVal must be greater than or equal to 0, and less than the number | ||||
| 12209 | ** of columns in the table affected by the current change. Otherwise, | ||||
| 12210 | ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. | ||||
| 12211 | ** | ||||
| 12212 | ** If successful, this function sets *ppValue to point to a protected | ||||
| 12213 | ** sqlite3_value object containing the iVal'th value from the vector of | ||||
| 12214 | ** original row values stored as part of the UPDATE or DELETE change and | ||||
| 12215 | ** returns SQLITE_OK. The name of the function comes from the fact that this | ||||
| 12216 | ** is similar to the "old.*" columns available to update or delete triggers. | ||||
| 12217 | ** | ||||
| 12218 | ** If some other error occurs (e.g. an OOM condition), an SQLite error code | ||||
| 12219 | ** is returned and *ppValue is set to NULL. | ||||
| 12220 | */ | ||||
| 12221 | SQLITE_API int sqlite3changeset_old( | ||||
| 12222 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ | ||||
| 12223 | int iVal, /* Column number */ | ||||
| 12224 | sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */ | ||||
| 12225 | ); | ||||
| 12226 | |||||
| 12227 | /* | ||||
| 12228 | ** CAPI3REF: Obtain new.* Values From A Changeset Iterator | ||||
| 12229 | ** METHOD: sqlite3_changeset_iter | ||||
| 12230 | ** | ||||
| 12231 | ** The pIter argument passed to this function may either be an iterator | ||||
| 12232 | ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator | ||||
| 12233 | ** created by [sqlite3changeset_start()]. In the latter case, the most recent | ||||
| 12234 | ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. | ||||
| 12235 | ** Furthermore, it may only be called if the type of change that the iterator | ||||
| 12236 | ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise, | ||||
| 12237 | ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL. | ||||
| 12238 | ** | ||||
| 12239 | ** Argument iVal must be greater than or equal to 0, and less than the number | ||||
| 12240 | ** of columns in the table affected by the current change. Otherwise, | ||||
| 12241 | ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. | ||||
| 12242 | ** | ||||
| 12243 | ** If successful, this function sets *ppValue to point to a protected | ||||
| 12244 | ** sqlite3_value object containing the iVal'th value from the vector of | ||||
| 12245 | ** new row values stored as part of the UPDATE or INSERT change and | ||||
| 12246 | ** returns SQLITE_OK. If the change is an UPDATE and does not include | ||||
| 12247 | ** a new value for the requested column, *ppValue is set to NULL and | ||||
| 12248 | ** SQLITE_OK returned. The name of the function comes from the fact that | ||||
| 12249 | ** this is similar to the "new.*" columns available to update or delete | ||||
| 12250 | ** triggers. | ||||
| 12251 | ** | ||||
| 12252 | ** If some other error occurs (e.g. an OOM condition), an SQLite error code | ||||
| 12253 | ** is returned and *ppValue is set to NULL. | ||||
| 12254 | */ | ||||
| 12255 | SQLITE_API int sqlite3changeset_new( | ||||
| 12256 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ | ||||
| 12257 | int iVal, /* Column number */ | ||||
| 12258 | sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */ | ||||
| 12259 | ); | ||||
| 12260 | |||||
| 12261 | /* | ||||
| 12262 | ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator | ||||
| 12263 | ** METHOD: sqlite3_changeset_iter | ||||
| 12264 | ** | ||||
| 12265 | ** This function should only be used with iterator objects passed to a | ||||
| 12266 | ** conflict-handler callback by [sqlite3changeset_apply()] with either | ||||
| 12267 | ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function | ||||
| 12268 | ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue | ||||
| 12269 | ** is set to NULL. | ||||
| 12270 | ** | ||||
| 12271 | ** Argument iVal must be greater than or equal to 0, and less than the number | ||||
| 12272 | ** of columns in the table affected by the current change. Otherwise, | ||||
| 12273 | ** [SQLITE_RANGE] is returned and *ppValue is set to NULL. | ||||
| 12274 | ** | ||||
| 12275 | ** If successful, this function sets *ppValue to point to a protected | ||||
| 12276 | ** sqlite3_value object containing the iVal'th value from the | ||||
| 12277 | ** "conflicting row" associated with the current conflict-handler callback | ||||
| 12278 | ** and returns SQLITE_OK. | ||||
| 12279 | ** | ||||
| 12280 | ** If some other error occurs (e.g. an OOM condition), an SQLite error code | ||||
| 12281 | ** is returned and *ppValue is set to NULL. | ||||
| 12282 | */ | ||||
| 12283 | SQLITE_API int sqlite3changeset_conflict( | ||||
| 12284 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ | ||||
| 12285 | int iVal, /* Column number */ | ||||
| 12286 | sqlite3_value **ppValue /* OUT: Value from conflicting row */ | ||||
| 12287 | ); | ||||
| 12288 | |||||
| 12289 | /* | ||||
| 12290 | ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations | ||||
| 12291 | ** METHOD: sqlite3_changeset_iter | ||||
| 12292 | ** | ||||
| 12293 | ** This function may only be called with an iterator passed to an | ||||
| 12294 | ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case | ||||
| 12295 | ** it sets the output variable to the total number of known foreign key | ||||
| 12296 | ** violations in the destination database and returns SQLITE_OK. | ||||
| 12297 | ** | ||||
| 12298 | ** In all other cases this function returns SQLITE_MISUSE. | ||||
| 12299 | */ | ||||
| 12300 | SQLITE_API int sqlite3changeset_fk_conflicts( | ||||
| 12301 | sqlite3_changeset_iter *pIter, /* Changeset iterator */ | ||||
| 12302 | int *pnOut /* OUT: Number of FK violations */ | ||||
| 12303 | ); | ||||
| 12304 | |||||
| 12305 | |||||
| 12306 | /* | ||||
| 12307 | ** CAPI3REF: Finalize A Changeset Iterator | ||||
| 12308 | ** METHOD: sqlite3_changeset_iter | ||||
| 12309 | ** | ||||
| 12310 | ** This function is used to finalize an iterator allocated with | ||||
| 12311 | ** [sqlite3changeset_start()]. | ||||
| 12312 | ** | ||||
| 12313 | ** This function should only be called on iterators created using the | ||||
| 12314 | ** [sqlite3changeset_start()] function. If an application calls this | ||||
| 12315 | ** function with an iterator passed to a conflict-handler by | ||||
| 12316 | ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the | ||||
| 12317 | ** call has no effect. | ||||
| 12318 | ** | ||||
| 12319 | ** If an error was encountered within a call to an sqlite3changeset_xxx() | ||||
| 12320 | ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an | ||||
| 12321 | ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding | ||||
| 12322 | ** to that error is returned by this function. Otherwise, SQLITE_OK is | ||||
| 12323 | ** returned. This is to allow the following pattern (pseudo-code): | ||||
| 12324 | ** | ||||
| 12325 | ** <pre> | ||||
| 12326 | ** sqlite3changeset_start(); | ||||
| 12327 | ** while( SQLITE_ROW==sqlite3changeset_next() ){ | ||||
| 12328 | ** // Do something with change. | ||||
| 12329 | ** } | ||||
| 12330 | ** rc = sqlite3changeset_finalize(); | ||||
| 12331 | ** if( rc!=SQLITE_OK ){ | ||||
| 12332 | ** // An error has occurred | ||||
| 12333 | ** } | ||||
| 12334 | ** </pre> | ||||
| 12335 | */ | ||||
| 12336 | SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter); | ||||
| 12337 | |||||
| 12338 | /* | ||||
| 12339 | ** CAPI3REF: Invert A Changeset | ||||
| 12340 | ** | ||||
| 12341 | ** This function is used to "invert" a changeset object. Applying an inverted | ||||
| 12342 | ** changeset to a database reverses the effects of applying the uninverted | ||||
| 12343 | ** changeset. Specifically: | ||||
| 12344 | ** | ||||
| 12345 | ** <ul> | ||||
| 12346 | ** <li> Each DELETE change is changed to an INSERT, and | ||||
| 12347 | ** <li> Each INSERT change is changed to a DELETE, and | ||||
| 12348 | ** <li> For each UPDATE change, the old.* and new.* values are exchanged. | ||||
| 12349 | ** </ul> | ||||
| 12350 | ** | ||||
| 12351 | ** This function does not change the order in which changes appear within | ||||
| 12352 | ** the changeset. It merely reverses the sense of each individual change. | ||||
| 12353 | ** | ||||
| 12354 | ** If successful, a pointer to a buffer containing the inverted changeset | ||||
| 12355 | ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and | ||||
| 12356 | ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are | ||||
| 12357 | ** zeroed and an SQLite error code returned. | ||||
| 12358 | ** | ||||
| 12359 | ** It is the responsibility of the caller to eventually call sqlite3_free() | ||||
| 12360 | ** on the *ppOut pointer to free the buffer allocation following a successful | ||||
| 12361 | ** call to this function. | ||||
| 12362 | ** | ||||
| 12363 | ** WARNING/TODO: This function currently assumes that the input is a valid | ||||
| 12364 | ** changeset. If it is not, the results are undefined. | ||||
| 12365 | */ | ||||
| 12366 | SQLITE_API int sqlite3changeset_invert( | ||||
| 12367 | int nIn, const void *pIn, /* Input changeset */ | ||||
| 12368 | int *pnOut, void **ppOut /* OUT: Inverse of input */ | ||||
| 12369 | ); | ||||
| 12370 | |||||
| 12371 | /* | ||||
| 12372 | ** CAPI3REF: Concatenate Two Changeset Objects | ||||
| 12373 | ** | ||||
| 12374 | ** This function is used to concatenate two changesets, A and B, into a | ||||
| 12375 | ** single changeset. The result is a changeset equivalent to applying | ||||
| 12376 | ** changeset A followed by changeset B. | ||||
| 12377 | ** | ||||
| 12378 | ** This function combines the two input changesets using an | ||||
| 12379 | ** sqlite3_changegroup object. Calling it produces similar results as the | ||||
| 12380 | ** following code fragment: | ||||
| 12381 | ** | ||||
| 12382 | ** <pre> | ||||
| 12383 | ** sqlite3_changegroup *pGrp; | ||||
| 12384 | ** rc = sqlite3_changegroup_new(&pGrp); | ||||
| 12385 | ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA); | ||||
| 12386 | ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB); | ||||
| 12387 | ** if( rc==SQLITE_OK ){ | ||||
| 12388 | ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut); | ||||
| 12389 | ** }else{ | ||||
| 12390 | ** *ppOut = 0; | ||||
| 12391 | ** *pnOut = 0; | ||||
| 12392 | ** } | ||||
| 12393 | ** </pre> | ||||
| 12394 | ** | ||||
| 12395 | ** Refer to the sqlite3_changegroup documentation below for details. | ||||
| 12396 | */ | ||||
| 12397 | SQLITE_API int sqlite3changeset_concat( | ||||
| 12398 | int nA, /* Number of bytes in buffer pA */ | ||||
| 12399 | void *pA, /* Pointer to buffer containing changeset A */ | ||||
| 12400 | int nB, /* Number of bytes in buffer pB */ | ||||
| 12401 | void *pB, /* Pointer to buffer containing changeset B */ | ||||
| 12402 | int *pnOut, /* OUT: Number of bytes in output changeset */ | ||||
| 12403 | void **ppOut /* OUT: Buffer containing output changeset */ | ||||
| 12404 | ); | ||||
| 12405 | |||||
| 12406 | /* | ||||
| 12407 | ** CAPI3REF: Changegroup Handle | ||||
| 12408 | ** | ||||
| 12409 | ** A changegroup is an object used to combine two or more | ||||
| 12410 | ** [changesets] or [patchsets] | ||||
| 12411 | */ | ||||
| 12412 | typedef struct sqlite3_changegroup sqlite3_changegroup; | ||||
| 12413 | |||||
| 12414 | /* | ||||
| 12415 | ** CAPI3REF: Create A New Changegroup Object | ||||
| 12416 | ** CONSTRUCTOR: sqlite3_changegroup | ||||
| 12417 | ** | ||||
| 12418 | ** An sqlite3_changegroup object is used to combine two or more changesets | ||||
| 12419 | ** (or patchsets) into a single changeset (or patchset). A single changegroup | ||||
| 12420 | ** object may combine changesets or patchsets, but not both. The output is | ||||
| 12421 | ** always in the same format as the input. | ||||
| 12422 | ** | ||||
| 12423 | ** If successful, this function returns SQLITE_OK and populates (*pp) with | ||||
| 12424 | ** a pointer to a new sqlite3_changegroup object before returning. The caller | ||||
| 12425 | ** should eventually free the returned object using a call to | ||||
| 12426 | ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code | ||||
| 12427 | ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL. | ||||
| 12428 | ** | ||||
| 12429 | ** The usual usage pattern for an sqlite3_changegroup object is as follows: | ||||
| 12430 | ** | ||||
| 12431 | ** <ul> | ||||
| 12432 | ** <li> It is created using a call to sqlite3changegroup_new(). | ||||
| 12433 | ** | ||||
| 12434 | ** <li> Zero or more changesets (or patchsets) are added to the object | ||||
| 12435 | ** by calling sqlite3changegroup_add(). | ||||
| 12436 | ** | ||||
| 12437 | ** <li> The result of combining all input changesets together is obtained | ||||
| 12438 | ** by the application via a call to sqlite3changegroup_output(). | ||||
| 12439 | ** | ||||
| 12440 | ** <li> The object is deleted using a call to sqlite3changegroup_delete(). | ||||
| 12441 | ** </ul> | ||||
| 12442 | ** | ||||
| 12443 | ** Any number of calls to add() and output() may be made between the calls to | ||||
| 12444 | ** new() and delete(), and in any order. | ||||
| 12445 | ** | ||||
| 12446 | ** As well as the regular sqlite3changegroup_add() and | ||||
| 12447 | ** sqlite3changegroup_output() functions, also available are the streaming | ||||
| 12448 | ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm(). | ||||
| 12449 | */ | ||||
| 12450 | SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp); | ||||
| 12451 | |||||
| 12452 | /* | ||||
| 12453 | ** CAPI3REF: Add a Schema to a Changegroup | ||||
| 12454 | ** METHOD: sqlite3_changegroup_schema | ||||
| 12455 | ** | ||||
| 12456 | ** This method may be used to optionally enforce the rule that the changesets | ||||
| 12457 | ** added to the changegroup handle must match the schema of database zDb | ||||
| 12458 | ** ("main", "temp", or the name of an attached database). If | ||||
| 12459 | ** sqlite3changegroup_add() is called to add a changeset that is not compatible | ||||
| 12460 | ** with the configured schema, SQLITE_SCHEMA is returned and the changegroup | ||||
| 12461 | ** object is left in an undefined state. | ||||
| 12462 | ** | ||||
| 12463 | ** A changeset schema is considered compatible with the database schema in | ||||
| 12464 | ** the same way as for sqlite3changeset_apply(). Specifically, for each | ||||
| 12465 | ** table in the changeset, there exists a database table with: | ||||
| 12466 | ** | ||||
| 12467 | ** <ul> | ||||
| 12468 | ** <li> The name identified by the changeset, and | ||||
| 12469 | ** <li> at least as many columns as recorded in the changeset, and | ||||
| 12470 | ** <li> the primary key columns in the same position as recorded in | ||||
| 12471 | ** the changeset. | ||||
| 12472 | ** </ul> | ||||
| 12473 | ** | ||||
| 12474 | ** The output of the changegroup object always has the same schema as the | ||||
| 12475 | ** database nominated using this function. In cases where changesets passed | ||||
| 12476 | ** to sqlite3changegroup_add() have fewer columns than the corresponding table | ||||
| 12477 | ** in the database schema, these are filled in using the default column | ||||
| 12478 | ** values from the database schema. This makes it possible to combined | ||||
| 12479 | ** changesets that have different numbers of columns for a single table | ||||
| 12480 | ** within a changegroup, provided that they are otherwise compatible. | ||||
| 12481 | */ | ||||
| 12482 | SQLITE_API int sqlite3changegroup_schema(sqlite3_changegroup*, sqlite3*, const char *zDb); | ||||
| 12483 | |||||
| 12484 | /* | ||||
| 12485 | ** CAPI3REF: Add A Changeset To A Changegroup | ||||
| 12486 | ** METHOD: sqlite3_changegroup | ||||
| 12487 | ** | ||||
| 12488 | ** Add all changes within the changeset (or patchset) in buffer pData (size | ||||
| 12489 | ** nData bytes) to the changegroup. | ||||
| 12490 | ** | ||||
| 12491 | ** If the buffer contains a patchset, then all prior calls to this function | ||||
| 12492 | ** on the same changegroup object must also have specified patchsets. Or, if | ||||
| 12493 | ** the buffer contains a changeset, so must have the earlier calls to this | ||||
| 12494 | ** function. Otherwise, SQLITE_ERROR is returned and no changes are added | ||||
| 12495 | ** to the changegroup. | ||||
| 12496 | ** | ||||
| 12497 | ** Rows within the changeset and changegroup are identified by the values in | ||||
| 12498 | ** their PRIMARY KEY columns. A change in the changeset is considered to | ||||
| 12499 | ** apply to the same row as a change already present in the changegroup if | ||||
| 12500 | ** the two rows have the same primary key. | ||||
| 12501 | ** | ||||
| 12502 | ** Changes to rows that do not already appear in the changegroup are | ||||
| 12503 | ** simply copied into it. Or, if both the new changeset and the changegroup | ||||
| 12504 | ** contain changes that apply to a single row, the final contents of the | ||||
| 12505 | ** changegroup depends on the type of each change, as follows: | ||||
| 12506 | ** | ||||
| 12507 | ** <table border=1 style="margin-left:8ex;margin-right:8ex"> | ||||
| 12508 | ** <tr><th style="white-space:pre">Existing Change </th> | ||||
| 12509 | ** <th style="white-space:pre">New Change </th> | ||||
| 12510 | ** <th>Output Change | ||||
| 12511 | ** <tr><td>INSERT <td>INSERT <td> | ||||
| 12512 | ** The new change is ignored. This case does not occur if the new | ||||
| 12513 | ** changeset was recorded immediately after the changesets already | ||||
| 12514 | ** added to the changegroup. | ||||
| 12515 | ** <tr><td>INSERT <td>UPDATE <td> | ||||
| 12516 | ** The INSERT change remains in the changegroup. The values in the | ||||
| 12517 | ** INSERT change are modified as if the row was inserted by the | ||||
| 12518 | ** existing change and then updated according to the new change. | ||||
| 12519 | ** <tr><td>INSERT <td>DELETE <td> | ||||
| 12520 | ** The existing INSERT is removed from the changegroup. The DELETE is | ||||
| 12521 | ** not added. | ||||
| 12522 | ** <tr><td>UPDATE <td>INSERT <td> | ||||
| 12523 | ** The new change is ignored. This case does not occur if the new | ||||
| 12524 | ** changeset was recorded immediately after the changesets already | ||||
| 12525 | ** added to the changegroup. | ||||
| 12526 | ** <tr><td>UPDATE <td>UPDATE <td> | ||||
| 12527 | ** The existing UPDATE remains within the changegroup. It is amended | ||||
| 12528 | ** so that the accompanying values are as if the row was updated once | ||||
| 12529 | ** by the existing change and then again by the new change. | ||||
| 12530 | ** <tr><td>UPDATE <td>DELETE <td> | ||||
| 12531 | ** The existing UPDATE is replaced by the new DELETE within the | ||||
| 12532 | ** changegroup. | ||||
| 12533 | ** <tr><td>DELETE <td>INSERT <td> | ||||
| 12534 | ** If one or more of the column values in the row inserted by the | ||||
| 12535 | ** new change differ from those in the row deleted by the existing | ||||
| 12536 | ** change, the existing DELETE is replaced by an UPDATE within the | ||||
| 12537 | ** changegroup. Otherwise, if the inserted row is exactly the same | ||||
| 12538 | ** as the deleted row, the existing DELETE is simply discarded. | ||||
| 12539 | ** <tr><td>DELETE <td>UPDATE <td> | ||||
| 12540 | ** The new change is ignored. This case does not occur if the new | ||||
| 12541 | ** changeset was recorded immediately after the changesets already | ||||
| 12542 | ** added to the changegroup. | ||||
| 12543 | ** <tr><td>DELETE <td>DELETE <td> | ||||
| 12544 | ** The new change is ignored. This case does not occur if the new | ||||
| 12545 | ** changeset was recorded immediately after the changesets already | ||||
| 12546 | ** added to the changegroup. | ||||
| 12547 | ** </table> | ||||
| 12548 | ** | ||||
| 12549 | ** If the new changeset contains changes to a table that is already present | ||||
| 12550 | ** in the changegroup, then the number of columns and the position of the | ||||
| 12551 | ** primary key columns for the table must be consistent. If this is not the | ||||
| 12552 | ** case, this function fails with SQLITE_SCHEMA. Except, if the changegroup | ||||
| 12553 | ** object has been configured with a database schema using the | ||||
| 12554 | ** sqlite3changegroup_schema() API, then it is possible to combine changesets | ||||
| 12555 | ** with different numbers of columns for a single table, provided that | ||||
| 12556 | ** they are otherwise compatible. | ||||
| 12557 | ** | ||||
| 12558 | ** If the input changeset appears to be corrupt and the corruption is | ||||
| 12559 | ** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition | ||||
| 12560 | ** occurs during processing, this function returns SQLITE_NOMEM. | ||||
| 12561 | ** | ||||
| 12562 | ** In all cases, if an error occurs the state of the final contents of the | ||||
| 12563 | ** changegroup is undefined. If no error occurs, SQLITE_OK is returned. | ||||
| 12564 | */ | ||||
| 12565 | SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); | ||||
| 12566 | |||||
| 12567 | /* | ||||
| 12568 | ** CAPI3REF: Add A Single Change To A Changegroup | ||||
| 12569 | ** METHOD: sqlite3_changegroup | ||||
| 12570 | ** | ||||
| 12571 | ** This function adds the single change currently indicated by the iterator | ||||
| 12572 | ** passed as the second argument to the changegroup object. The rules for | ||||
| 12573 | ** adding the change are just as described for [sqlite3changegroup_add()]. | ||||
| 12574 | ** | ||||
| 12575 | ** If the change is successfully added to the changegroup, SQLITE_OK is | ||||
| 12576 | ** returned. Otherwise, an SQLite error code is returned. | ||||
| 12577 | ** | ||||
| 12578 | ** The iterator must point to a valid entry when this function is called. | ||||
| 12579 | ** If it does not, SQLITE_ERROR is returned and no change is added to the | ||||
| 12580 | ** changegroup. Additionally, the iterator must not have been opened with | ||||
| 12581 | ** the SQLITE_CHANGESETAPPLY_INVERT flag. In this case SQLITE_ERROR is also | ||||
| 12582 | ** returned. | ||||
| 12583 | */ | ||||
| 12584 | SQLITE_API int sqlite3changegroup_add_change( | ||||
| 12585 | sqlite3_changegroup*, | ||||
| 12586 | sqlite3_changeset_iter* | ||||
| 12587 | ); | ||||
| 12588 | |||||
| 12589 | |||||
| 12590 | |||||
| 12591 | /* | ||||
| 12592 | ** CAPI3REF: Obtain A Composite Changeset From A Changegroup | ||||
| 12593 | ** METHOD: sqlite3_changegroup | ||||
| 12594 | ** | ||||
| 12595 | ** Obtain a buffer containing a changeset (or patchset) representing the | ||||
| 12596 | ** current contents of the changegroup. If the inputs to the changegroup | ||||
| 12597 | ** were themselves changesets, the output is a changeset. Or, if the | ||||
| 12598 | ** inputs were patchsets, the output is also a patchset. | ||||
| 12599 | ** | ||||
| 12600 | ** As with the output of the sqlite3session_changeset() and | ||||
| 12601 | ** sqlite3session_patchset() functions, all changes related to a single | ||||
| 12602 | ** table are grouped together in the output of this function. Tables appear | ||||
| 12603 | ** in the same order as for the very first changeset added to the changegroup. | ||||
| 12604 | ** If the second or subsequent changesets added to the changegroup contain | ||||
| 12605 | ** changes for tables that do not appear in the first changeset, they are | ||||
| 12606 | ** appended onto the end of the output changeset, again in the order in | ||||
| 12607 | ** which they are first encountered. | ||||
| 12608 | ** | ||||
| 12609 | ** If an error occurs, an SQLite error code is returned and the output | ||||
| 12610 | ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK | ||||
| 12611 | ** is returned and the output variables are set to the size of and a | ||||
| 12612 | ** pointer to the output buffer, respectively. In this case it is the | ||||
| 12613 | ** responsibility of the caller to eventually free the buffer using a | ||||
| 12614 | ** call to sqlite3_free(). | ||||
| 12615 | */ | ||||
| 12616 | SQLITE_API int sqlite3changegroup_output( | ||||
| 12617 | sqlite3_changegroup*, | ||||
| 12618 | int *pnData, /* OUT: Size of output buffer in bytes */ | ||||
| 12619 | void **ppData /* OUT: Pointer to output buffer */ | ||||
| 12620 | ); | ||||
| 12621 | |||||
| 12622 | /* | ||||
| 12623 | ** CAPI3REF: Delete A Changegroup Object | ||||
| 12624 | ** DESTRUCTOR: sqlite3_changegroup | ||||
| 12625 | */ | ||||
| 12626 | SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); | ||||
| 12627 | |||||
| 12628 | /* | ||||
| 12629 | ** CAPI3REF: Apply A Changeset To A Database | ||||
| 12630 | ** | ||||
| 12631 | ** Apply a changeset or patchset to a database. These functions attempt to | ||||
| 12632 | ** update the "main" database attached to handle db with the changes found in | ||||
| 12633 | ** the changeset passed via the second and third arguments. | ||||
| 12634 | ** | ||||
| 12635 | ** The fourth argument (xFilter) passed to these functions is the "filter | ||||
| 12636 | ** callback". If it is not NULL, then for each table affected by at least one | ||||
| 12637 | ** change in the changeset, the filter callback is invoked with | ||||
| 12638 | ** the table name as the second argument, and a copy of the context pointer | ||||
| 12639 | ** passed as the sixth argument as the first. If the "filter callback" | ||||
| 12640 | ** returns zero, then no attempt is made to apply any changes to the table. | ||||
| 12641 | ** Otherwise, if the return value is non-zero or the xFilter argument to | ||||
| 12642 | ** is NULL, all changes related to the table are attempted. | ||||
| 12643 | ** | ||||
| 12644 | ** For each table that is not excluded by the filter callback, this function | ||||
| 12645 | ** tests that the target database contains a compatible table. A table is | ||||
| 12646 | ** considered compatible if all of the following are true: | ||||
| 12647 | ** | ||||
| 12648 | ** <ul> | ||||
| 12649 | ** <li> The table has the same name as the name recorded in the | ||||
| 12650 | ** changeset, and | ||||
| 12651 | ** <li> The table has at least as many columns as recorded in the | ||||
| 12652 | ** changeset, and | ||||
| 12653 | ** <li> The table has primary key columns in the same position as | ||||
| 12654 | ** recorded in the changeset. | ||||
| 12655 | ** </ul> | ||||
| 12656 | ** | ||||
| 12657 | ** If there is no compatible table, it is not an error, but none of the | ||||
| 12658 | ** changes associated with the table are applied. A warning message is issued | ||||
| 12659 | ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most | ||||
| 12660 | ** one such warning is issued for each table in the changeset. | ||||
| 12661 | ** | ||||
| 12662 | ** For each change for which there is a compatible table, an attempt is made | ||||
| 12663 | ** to modify the table contents according to the UPDATE, INSERT or DELETE | ||||
| 12664 | ** change. If a change cannot be applied cleanly, the conflict handler | ||||
| 12665 | ** function passed as the fifth argument to sqlite3changeset_apply() may be | ||||
| 12666 | ** invoked. A description of exactly when the conflict handler is invoked for | ||||
| 12667 | ** each type of change is below. | ||||
| 12668 | ** | ||||
| 12669 | ** Unlike the xFilter argument, xConflict may not be passed NULL. The results | ||||
| 12670 | ** of passing anything other than a valid function pointer as the xConflict | ||||
| 12671 | ** argument are undefined. | ||||
| 12672 | ** | ||||
| 12673 | ** Each time the conflict handler function is invoked, it must return one | ||||
| 12674 | ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or | ||||
| 12675 | ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned | ||||
| 12676 | ** if the second argument passed to the conflict handler is either | ||||
| 12677 | ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler | ||||
| 12678 | ** returns an illegal value, any changes already made are rolled back and | ||||
| 12679 | ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different | ||||
| 12680 | ** actions are taken by sqlite3changeset_apply() depending on the value | ||||
| 12681 | ** returned by each invocation of the conflict-handler function. Refer to | ||||
| 12682 | ** the documentation for the three | ||||
| 12683 | ** [SQLITE_CHANGESET_OMIT|available return values] for details. | ||||
| 12684 | ** | ||||
| 12685 | ** <dl> | ||||
| 12686 | ** <dt>DELETE Changes<dd> | ||||
| 12687 | ** For each DELETE change, the function checks if the target database | ||||
| 12688 | ** contains a row with the same primary key value (or values) as the | ||||
| 12689 | ** original row values stored in the changeset. If it does, and the values | ||||
| 12690 | ** stored in all non-primary key columns also match the values stored in | ||||
| 12691 | ** the changeset the row is deleted from the target database. | ||||
| 12692 | ** | ||||
| 12693 | ** If a row with matching primary key values is found, but one or more of | ||||
| 12694 | ** the non-primary key fields contains a value different from the original | ||||
| 12695 | ** row value stored in the changeset, the conflict-handler function is | ||||
| 12696 | ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the | ||||
| 12697 | ** database table has more columns than are recorded in the changeset, | ||||
| 12698 | ** only the values of those non-primary key fields are compared against | ||||
| 12699 | ** the current database contents - any trailing database table columns | ||||
| 12700 | ** are ignored. | ||||
| 12701 | ** | ||||
| 12702 | ** If no row with matching primary key values is found in the database, | ||||
| 12703 | ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] | ||||
| 12704 | ** passed as the second argument. | ||||
| 12705 | ** | ||||
| 12706 | ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT | ||||
| 12707 | ** (which can only happen if a foreign key constraint is violated), the | ||||
| 12708 | ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT] | ||||
| 12709 | ** passed as the second argument. This includes the case where the DELETE | ||||
| 12710 | ** operation is attempted because an earlier call to the conflict handler | ||||
| 12711 | ** function returned [SQLITE_CHANGESET_REPLACE]. | ||||
| 12712 | ** | ||||
| 12713 | ** <dt>INSERT Changes<dd> | ||||
| 12714 | ** For each INSERT change, an attempt is made to insert the new row into | ||||
| 12715 | ** the database. If the changeset row contains fewer fields than the | ||||
| 12716 | ** database table, the trailing fields are populated with their default | ||||
| 12717 | ** values. | ||||
| 12718 | ** | ||||
| 12719 | ** If the attempt to insert the row fails because the database already | ||||
| 12720 | ** contains a row with the same primary key values, the conflict handler | ||||
| 12721 | ** function is invoked with the second argument set to | ||||
| 12722 | ** [SQLITE_CHANGESET_CONFLICT]. | ||||
| 12723 | ** | ||||
| 12724 | ** If the attempt to insert the row fails because of some other constraint | ||||
| 12725 | ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is | ||||
| 12726 | ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT]. | ||||
| 12727 | ** This includes the case where the INSERT operation is re-attempted because | ||||
| 12728 | ** an earlier call to the conflict handler function returned | ||||
| 12729 | ** [SQLITE_CHANGESET_REPLACE]. | ||||
| 12730 | ** | ||||
| 12731 | ** <dt>UPDATE Changes<dd> | ||||
| 12732 | ** For each UPDATE change, the function checks if the target database | ||||
| 12733 | ** contains a row with the same primary key value (or values) as the | ||||
| 12734 | ** original row values stored in the changeset. If it does, and the values | ||||
| 12735 | ** stored in all modified non-primary key columns also match the values | ||||
| 12736 | ** stored in the changeset the row is updated within the target database. | ||||
| 12737 | ** | ||||
| 12738 | ** If a row with matching primary key values is found, but one or more of | ||||
| 12739 | ** the modified non-primary key fields contains a value different from an | ||||
| 12740 | ** original row value stored in the changeset, the conflict-handler function | ||||
| 12741 | ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since | ||||
| 12742 | ** UPDATE changes only contain values for non-primary key fields that are | ||||
| 12743 | ** to be modified, only those fields need to match the original values to | ||||
| 12744 | ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. | ||||
| 12745 | ** | ||||
| 12746 | ** If no row with matching primary key values is found in the database, | ||||
| 12747 | ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] | ||||
| 12748 | ** passed as the second argument. | ||||
| 12749 | ** | ||||
| 12750 | ** If the UPDATE operation is attempted, but SQLite returns | ||||
| 12751 | ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with | ||||
| 12752 | ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument. | ||||
| 12753 | ** This includes the case where the UPDATE operation is attempted after | ||||
| 12754 | ** an earlier call to the conflict handler function returned | ||||
| 12755 | ** [SQLITE_CHANGESET_REPLACE]. | ||||
| 12756 | ** </dl> | ||||
| 12757 | ** | ||||
| 12758 | ** It is safe to execute SQL statements, including those that write to the | ||||
| 12759 | ** table that the callback related to, from within the xConflict callback. | ||||
| 12760 | ** This can be used to further customize the application's conflict | ||||
| 12761 | ** resolution strategy. | ||||
| 12762 | ** | ||||
| 12763 | ** All changes made by these functions are enclosed in a savepoint transaction. | ||||
| 12764 | ** If any other error (aside from a constraint failure when attempting to | ||||
| 12765 | ** write to the target database) occurs, then the savepoint transaction is | ||||
| 12766 | ** rolled back, restoring the target database to its original state, and an | ||||
| 12767 | ** SQLite error code returned. | ||||
| 12768 | ** | ||||
| 12769 | ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and | ||||
| 12770 | ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2() | ||||
| 12771 | ** may set (*ppRebase) to point to a "rebase" that may be used with the | ||||
| 12772 | ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase) | ||||
| 12773 | ** is set to the size of the buffer in bytes. It is the responsibility of the | ||||
| 12774 | ** caller to eventually free any such buffer using sqlite3_free(). The buffer | ||||
| 12775 | ** is only allocated and populated if one or more conflicts were encountered | ||||
| 12776 | ** while applying the patchset. See comments surrounding the sqlite3_rebaser | ||||
| 12777 | ** APIs for further details. | ||||
| 12778 | ** | ||||
| 12779 | ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent | ||||
| 12780 | ** may be modified by passing a combination of | ||||
| 12781 | ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter. | ||||
| 12782 | ** | ||||
| 12783 | ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b> | ||||
| 12784 | ** and therefore subject to change. | ||||
| 12785 | */ | ||||
| 12786 | SQLITE_API int sqlite3changeset_apply( | ||||
| 12787 | sqlite3 *db, /* Apply change to "main" db of this handle */ | ||||
| 12788 | int nChangeset, /* Size of changeset in bytes */ | ||||
| 12789 | void *pChangeset, /* Changeset blob */ | ||||
| 12790 | int(*xFilter)( | ||||
| 12791 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 12792 | const char *zTab /* Table name */ | ||||
| 12793 | ), | ||||
| 12794 | int(*xConflict)( | ||||
| 12795 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 12796 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ | ||||
| 12797 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ | ||||
| 12798 | ), | ||||
| 12799 | void *pCtx /* First argument passed to xConflict */ | ||||
| 12800 | ); | ||||
| 12801 | SQLITE_API int sqlite3changeset_apply_v2( | ||||
| 12802 | sqlite3 *db, /* Apply change to "main" db of this handle */ | ||||
| 12803 | int nChangeset, /* Size of changeset in bytes */ | ||||
| 12804 | void *pChangeset, /* Changeset blob */ | ||||
| 12805 | int(*xFilter)( | ||||
| 12806 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 12807 | const char *zTab /* Table name */ | ||||
| 12808 | ), | ||||
| 12809 | int(*xConflict)( | ||||
| 12810 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 12811 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ | ||||
| 12812 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ | ||||
| 12813 | ), | ||||
| 12814 | void *pCtx, /* First argument passed to xConflict */ | ||||
| 12815 | void **ppRebase, int *pnRebase, /* OUT: Rebase data */ | ||||
| 12816 | int flags /* SESSION_CHANGESETAPPLY_* flags */ | ||||
| 12817 | ); | ||||
| 12818 | |||||
| 12819 | /* | ||||
| 12820 | ** CAPI3REF: Flags for sqlite3changeset_apply_v2 | ||||
| 12821 | ** | ||||
| 12822 | ** The following flags may passed via the 9th parameter to | ||||
| 12823 | ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]: | ||||
| 12824 | ** | ||||
| 12825 | ** <dl> | ||||
| 12826 | ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd> | ||||
| 12827 | ** Usually, the sessions module encloses all operations performed by | ||||
| 12828 | ** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The | ||||
| 12829 | ** SAVEPOINT is committed if the changeset or patchset is successfully | ||||
| 12830 | ** applied, or rolled back if an error occurs. Specifying this flag | ||||
| 12831 | ** causes the sessions module to omit this savepoint. In this case, if the | ||||
| 12832 | ** caller has an open transaction or savepoint when apply_v2() is called, | ||||
| 12833 | ** it may revert the partially applied changeset by rolling it back. | ||||
| 12834 | ** | ||||
| 12835 | ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> | ||||
| 12836 | ** Invert the changeset before applying it. This is equivalent to inverting | ||||
| 12837 | ** a changeset using sqlite3changeset_invert() before applying it. It is | ||||
| 12838 | ** an error to specify this flag with a patchset. | ||||
| 12839 | ** | ||||
| 12840 | ** <dt>SQLITE_CHANGESETAPPLY_IGNORENOOP <dd> | ||||
| 12841 | ** Do not invoke the conflict handler callback for any changes that | ||||
| 12842 | ** would not actually modify the database even if they were applied. | ||||
| 12843 | ** Specifically, this means that the conflict handler is not invoked | ||||
| 12844 | ** for: | ||||
| 12845 | ** <ul> | ||||
| 12846 | ** <li>a delete change if the row being deleted cannot be found, | ||||
| 12847 | ** <li>an update change if the modified fields are already set to | ||||
| 12848 | ** their new values in the conflicting row, or | ||||
| 12849 | ** <li>an insert change if all fields of the conflicting row match | ||||
| 12850 | ** the row being inserted. | ||||
| 12851 | ** </ul> | ||||
| 12852 | ** | ||||
| 12853 | ** <dt>SQLITE_CHANGESETAPPLY_FKNOACTION <dd> | ||||
| 12854 | ** If this flag it set, then all foreign key constraints in the target | ||||
| 12855 | ** database behave as if they were declared with "ON UPDATE NO ACTION ON | ||||
| 12856 | ** DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL | ||||
| 12857 | ** or SET DEFAULT. | ||||
| 12858 | */ | ||||
| 12859 | #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT0x0001 0x0001 | ||||
| 12860 | #define SQLITE_CHANGESETAPPLY_INVERT0x0002 0x0002 | ||||
| 12861 | #define SQLITE_CHANGESETAPPLY_IGNORENOOP0x0004 0x0004 | ||||
| 12862 | #define SQLITE_CHANGESETAPPLY_FKNOACTION0x0008 0x0008 | ||||
| 12863 | |||||
| 12864 | /* | ||||
| 12865 | ** CAPI3REF: Constants Passed To The Conflict Handler | ||||
| 12866 | ** | ||||
| 12867 | ** Values that may be passed as the second argument to a conflict-handler. | ||||
| 12868 | ** | ||||
| 12869 | ** <dl> | ||||
| 12870 | ** <dt>SQLITE_CHANGESET_DATA<dd> | ||||
| 12871 | ** The conflict handler is invoked with CHANGESET_DATA as the second argument | ||||
| 12872 | ** when processing a DELETE or UPDATE change if a row with the required | ||||
| 12873 | ** PRIMARY KEY fields is present in the database, but one or more other | ||||
| 12874 | ** (non primary-key) fields modified by the update do not contain the | ||||
| 12875 | ** expected "before" values. | ||||
| 12876 | ** | ||||
| 12877 | ** The conflicting row, in this case, is the database row with the matching | ||||
| 12878 | ** primary key. | ||||
| 12879 | ** | ||||
| 12880 | ** <dt>SQLITE_CHANGESET_NOTFOUND<dd> | ||||
| 12881 | ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second | ||||
| 12882 | ** argument when processing a DELETE or UPDATE change if a row with the | ||||
| 12883 | ** required PRIMARY KEY fields is not present in the database. | ||||
| 12884 | ** | ||||
| 12885 | ** There is no conflicting row in this case. The results of invoking the | ||||
| 12886 | ** sqlite3changeset_conflict() API are undefined. | ||||
| 12887 | ** | ||||
| 12888 | ** <dt>SQLITE_CHANGESET_CONFLICT<dd> | ||||
| 12889 | ** CHANGESET_CONFLICT is passed as the second argument to the conflict | ||||
| 12890 | ** handler while processing an INSERT change if the operation would result | ||||
| 12891 | ** in duplicate primary key values. | ||||
| 12892 | ** | ||||
| 12893 | ** The conflicting row in this case is the database row with the matching | ||||
| 12894 | ** primary key. | ||||
| 12895 | ** | ||||
| 12896 | ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd> | ||||
| 12897 | ** If foreign key handling is enabled, and applying a changeset leaves the | ||||
| 12898 | ** database in a state containing foreign key violations, the conflict | ||||
| 12899 | ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument | ||||
| 12900 | ** exactly once before the changeset is committed. If the conflict handler | ||||
| 12901 | ** returns CHANGESET_OMIT, the changes, including those that caused the | ||||
| 12902 | ** foreign key constraint violation, are committed. Or, if it returns | ||||
| 12903 | ** CHANGESET_ABORT, the changeset is rolled back. | ||||
| 12904 | ** | ||||
| 12905 | ** No current or conflicting row information is provided. The only function | ||||
| 12906 | ** it is possible to call on the supplied sqlite3_changeset_iter handle | ||||
| 12907 | ** is sqlite3changeset_fk_conflicts(). | ||||
| 12908 | ** | ||||
| 12909 | ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd> | ||||
| 12910 | ** If any other constraint violation occurs while applying a change (i.e. | ||||
| 12911 | ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is | ||||
| 12912 | ** invoked with CHANGESET_CONSTRAINT as the second argument. | ||||
| 12913 | ** | ||||
| 12914 | ** There is no conflicting row in this case. The results of invoking the | ||||
| 12915 | ** sqlite3changeset_conflict() API are undefined. | ||||
| 12916 | ** | ||||
| 12917 | ** </dl> | ||||
| 12918 | */ | ||||
| 12919 | #define SQLITE_CHANGESET_DATA1 1 | ||||
| 12920 | #define SQLITE_CHANGESET_NOTFOUND2 2 | ||||
| 12921 | #define SQLITE_CHANGESET_CONFLICT3 3 | ||||
| 12922 | #define SQLITE_CHANGESET_CONSTRAINT4 4 | ||||
| 12923 | #define SQLITE_CHANGESET_FOREIGN_KEY5 5 | ||||
| 12924 | |||||
| 12925 | /* | ||||
| 12926 | ** CAPI3REF: Constants Returned By The Conflict Handler | ||||
| 12927 | ** | ||||
| 12928 | ** A conflict handler callback must return one of the following three values. | ||||
| 12929 | ** | ||||
| 12930 | ** <dl> | ||||
| 12931 | ** <dt>SQLITE_CHANGESET_OMIT<dd> | ||||
| 12932 | ** If a conflict handler returns this value no special action is taken. The | ||||
| 12933 | ** change that caused the conflict is not applied. The session module | ||||
| 12934 | ** continues to the next change in the changeset. | ||||
| 12935 | ** | ||||
| 12936 | ** <dt>SQLITE_CHANGESET_REPLACE<dd> | ||||
| 12937 | ** This value may only be returned if the second argument to the conflict | ||||
| 12938 | ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this | ||||
| 12939 | ** is not the case, any changes applied so far are rolled back and the | ||||
| 12940 | ** call to sqlite3changeset_apply() returns SQLITE_MISUSE. | ||||
| 12941 | ** | ||||
| 12942 | ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict | ||||
| 12943 | ** handler, then the conflicting row is either updated or deleted, depending | ||||
| 12944 | ** on the type of change. | ||||
| 12945 | ** | ||||
| 12946 | ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict | ||||
| 12947 | ** handler, then the conflicting row is removed from the database and a | ||||
| 12948 | ** second attempt to apply the change is made. If this second attempt fails, | ||||
| 12949 | ** the original row is restored to the database before continuing. | ||||
| 12950 | ** | ||||
| 12951 | ** <dt>SQLITE_CHANGESET_ABORT<dd> | ||||
| 12952 | ** If this value is returned, any changes applied so far are rolled back | ||||
| 12953 | ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT. | ||||
| 12954 | ** </dl> | ||||
| 12955 | */ | ||||
| 12956 | #define SQLITE_CHANGESET_OMIT0 0 | ||||
| 12957 | #define SQLITE_CHANGESET_REPLACE1 1 | ||||
| 12958 | #define SQLITE_CHANGESET_ABORT2 2 | ||||
| 12959 | |||||
| 12960 | /* | ||||
| 12961 | ** CAPI3REF: Rebasing changesets | ||||
| 12962 | ** EXPERIMENTAL | ||||
| 12963 | ** | ||||
| 12964 | ** Suppose there is a site hosting a database in state S0. And that | ||||
| 12965 | ** modifications are made that move that database to state S1 and a | ||||
| 12966 | ** changeset recorded (the "local" changeset). Then, a changeset based | ||||
| 12967 | ** on S0 is received from another site (the "remote" changeset) and | ||||
| 12968 | ** applied to the database. The database is then in state | ||||
| 12969 | ** (S1+"remote"), where the exact state depends on any conflict | ||||
| 12970 | ** resolution decisions (OMIT or REPLACE) made while applying "remote". | ||||
| 12971 | ** Rebasing a changeset is to update it to take those conflict | ||||
| 12972 | ** resolution decisions into account, so that the same conflicts | ||||
| 12973 | ** do not have to be resolved elsewhere in the network. | ||||
| 12974 | ** | ||||
| 12975 | ** For example, if both the local and remote changesets contain an | ||||
| 12976 | ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)": | ||||
| 12977 | ** | ||||
| 12978 | ** local: INSERT INTO t1 VALUES(1, 'v1'); | ||||
| 12979 | ** remote: INSERT INTO t1 VALUES(1, 'v2'); | ||||
| 12980 | ** | ||||
| 12981 | ** and the conflict resolution is REPLACE, then the INSERT change is | ||||
| 12982 | ** removed from the local changeset (it was overridden). Or, if the | ||||
| 12983 | ** conflict resolution was "OMIT", then the local changeset is modified | ||||
| 12984 | ** to instead contain: | ||||
| 12985 | ** | ||||
| 12986 | ** UPDATE t1 SET b = 'v2' WHERE a=1; | ||||
| 12987 | ** | ||||
| 12988 | ** Changes within the local changeset are rebased as follows: | ||||
| 12989 | ** | ||||
| 12990 | ** <dl> | ||||
| 12991 | ** <dt>Local INSERT<dd> | ||||
| 12992 | ** This may only conflict with a remote INSERT. If the conflict | ||||
| 12993 | ** resolution was OMIT, then add an UPDATE change to the rebased | ||||
| 12994 | ** changeset. Or, if the conflict resolution was REPLACE, add | ||||
| 12995 | ** nothing to the rebased changeset. | ||||
| 12996 | ** | ||||
| 12997 | ** <dt>Local DELETE<dd> | ||||
| 12998 | ** This may conflict with a remote UPDATE or DELETE. In both cases the | ||||
| 12999 | ** only possible resolution is OMIT. If the remote operation was a | ||||
| 13000 | ** DELETE, then add no change to the rebased changeset. If the remote | ||||
| 13001 | ** operation was an UPDATE, then the old.* fields of change are updated | ||||
| 13002 | ** to reflect the new.* values in the UPDATE. | ||||
| 13003 | ** | ||||
| 13004 | ** <dt>Local UPDATE<dd> | ||||
| 13005 | ** This may conflict with a remote UPDATE or DELETE. If it conflicts | ||||
| 13006 | ** with a DELETE, and the conflict resolution was OMIT, then the update | ||||
| 13007 | ** is changed into an INSERT. Any undefined values in the new.* record | ||||
| 13008 | ** from the update change are filled in using the old.* values from | ||||
| 13009 | ** the conflicting DELETE. Or, if the conflict resolution was REPLACE, | ||||
| 13010 | ** the UPDATE change is simply omitted from the rebased changeset. | ||||
| 13011 | ** | ||||
| 13012 | ** If conflict is with a remote UPDATE and the resolution is OMIT, then | ||||
| 13013 | ** the old.* values are rebased using the new.* values in the remote | ||||
| 13014 | ** change. Or, if the resolution is REPLACE, then the change is copied | ||||
| 13015 | ** into the rebased changeset with updates to columns also updated by | ||||
| 13016 | ** the conflicting remote UPDATE removed. If this means no columns would | ||||
| 13017 | ** be updated, the change is omitted. | ||||
| 13018 | ** </dl> | ||||
| 13019 | ** | ||||
| 13020 | ** A local change may be rebased against multiple remote changes | ||||
| 13021 | ** simultaneously. If a single key is modified by multiple remote | ||||
| 13022 | ** changesets, they are combined as follows before the local changeset | ||||
| 13023 | ** is rebased: | ||||
| 13024 | ** | ||||
| 13025 | ** <ul> | ||||
| 13026 | ** <li> If there has been one or more REPLACE resolutions on a | ||||
| 13027 | ** key, it is rebased according to a REPLACE. | ||||
| 13028 | ** | ||||
| 13029 | ** <li> If there have been no REPLACE resolutions on a key, then | ||||
| 13030 | ** the local changeset is rebased according to the most recent | ||||
| 13031 | ** of the OMIT resolutions. | ||||
| 13032 | ** </ul> | ||||
| 13033 | ** | ||||
| 13034 | ** Note that conflict resolutions from multiple remote changesets are | ||||
| 13035 | ** combined on a per-field basis, not per-row. This means that in the | ||||
| 13036 | ** case of multiple remote UPDATE operations, some fields of a single | ||||
| 13037 | ** local change may be rebased for REPLACE while others are rebased for | ||||
| 13038 | ** OMIT. | ||||
| 13039 | ** | ||||
| 13040 | ** In order to rebase a local changeset, the remote changeset must first | ||||
| 13041 | ** be applied to the local database using sqlite3changeset_apply_v2() and | ||||
| 13042 | ** the buffer of rebase information captured. Then: | ||||
| 13043 | ** | ||||
| 13044 | ** <ol> | ||||
| 13045 | ** <li> An sqlite3_rebaser object is created by calling | ||||
| 13046 | ** sqlite3rebaser_create(). | ||||
| 13047 | ** <li> The new object is configured with the rebase buffer obtained from | ||||
| 13048 | ** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure(). | ||||
| 13049 | ** If the local changeset is to be rebased against multiple remote | ||||
| 13050 | ** changesets, then sqlite3rebaser_configure() should be called | ||||
| 13051 | ** multiple times, in the same order that the multiple | ||||
| 13052 | ** sqlite3changeset_apply_v2() calls were made. | ||||
| 13053 | ** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase(). | ||||
| 13054 | ** <li> The sqlite3_rebaser object is deleted by calling | ||||
| 13055 | ** sqlite3rebaser_delete(). | ||||
| 13056 | ** </ol> | ||||
| 13057 | */ | ||||
| 13058 | typedef struct sqlite3_rebaser sqlite3_rebaser; | ||||
| 13059 | |||||
| 13060 | /* | ||||
| 13061 | ** CAPI3REF: Create a changeset rebaser object. | ||||
| 13062 | ** EXPERIMENTAL | ||||
| 13063 | ** | ||||
| 13064 | ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to | ||||
| 13065 | ** point to the new object and return SQLITE_OK. Otherwise, if an error | ||||
| 13066 | ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) | ||||
| 13067 | ** to NULL. | ||||
| 13068 | */ | ||||
| 13069 | SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew); | ||||
| 13070 | |||||
| 13071 | /* | ||||
| 13072 | ** CAPI3REF: Configure a changeset rebaser object. | ||||
| 13073 | ** EXPERIMENTAL | ||||
| 13074 | ** | ||||
| 13075 | ** Configure the changeset rebaser object to rebase changesets according | ||||
| 13076 | ** to the conflict resolutions described by buffer pRebase (size nRebase | ||||
| 13077 | ** bytes), which must have been obtained from a previous call to | ||||
| 13078 | ** sqlite3changeset_apply_v2(). | ||||
| 13079 | */ | ||||
| 13080 | SQLITE_API int sqlite3rebaser_configure( | ||||
| 13081 | sqlite3_rebaser*, | ||||
| 13082 | int nRebase, const void *pRebase | ||||
| 13083 | ); | ||||
| 13084 | |||||
| 13085 | /* | ||||
| 13086 | ** CAPI3REF: Rebase a changeset | ||||
| 13087 | ** EXPERIMENTAL | ||||
| 13088 | ** | ||||
| 13089 | ** Argument pIn must point to a buffer containing a changeset nIn bytes | ||||
| 13090 | ** in size. This function allocates and populates a buffer with a copy | ||||
| 13091 | ** of the changeset rebased according to the configuration of the | ||||
| 13092 | ** rebaser object passed as the first argument. If successful, (*ppOut) | ||||
| 13093 | ** is set to point to the new buffer containing the rebased changeset and | ||||
| 13094 | ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the | ||||
| 13095 | ** responsibility of the caller to eventually free the new buffer using | ||||
| 13096 | ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut) | ||||
| 13097 | ** are set to zero and an SQLite error code returned. | ||||
| 13098 | */ | ||||
| 13099 | SQLITE_API int sqlite3rebaser_rebase( | ||||
| 13100 | sqlite3_rebaser*, | ||||
| 13101 | int nIn, const void *pIn, | ||||
| 13102 | int *pnOut, void **ppOut | ||||
| 13103 | ); | ||||
| 13104 | |||||
| 13105 | /* | ||||
| 13106 | ** CAPI3REF: Delete a changeset rebaser object. | ||||
| 13107 | ** EXPERIMENTAL | ||||
| 13108 | ** | ||||
| 13109 | ** Delete the changeset rebaser object and all associated resources. There | ||||
| 13110 | ** should be one call to this function for each successful invocation | ||||
| 13111 | ** of sqlite3rebaser_create(). | ||||
| 13112 | */ | ||||
| 13113 | SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p); | ||||
| 13114 | |||||
| 13115 | /* | ||||
| 13116 | ** CAPI3REF: Streaming Versions of API functions. | ||||
| 13117 | ** | ||||
| 13118 | ** The six streaming API xxx_strm() functions serve similar purposes to the | ||||
| 13119 | ** corresponding non-streaming API functions: | ||||
| 13120 | ** | ||||
| 13121 | ** <table border=1 style="margin-left:8ex;margin-right:8ex"> | ||||
| 13122 | ** <tr><th>Streaming function<th>Non-streaming equivalent</th> | ||||
| 13123 | ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] | ||||
| 13124 | ** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2] | ||||
| 13125 | ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] | ||||
| 13126 | ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] | ||||
| 13127 | ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] | ||||
| 13128 | ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] | ||||
| 13129 | ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] | ||||
| 13130 | ** </table> | ||||
| 13131 | ** | ||||
| 13132 | ** Non-streaming functions that accept changesets (or patchsets) as input | ||||
| 13133 | ** require that the entire changeset be stored in a single buffer in memory. | ||||
| 13134 | ** Similarly, those that return a changeset or patchset do so by returning | ||||
| 13135 | ** a pointer to a single large buffer allocated using sqlite3_malloc(). | ||||
| 13136 | ** Normally this is convenient. However, if an application running in a | ||||
| 13137 | ** low-memory environment is required to handle very large changesets, the | ||||
| 13138 | ** large contiguous memory allocations required can become onerous. | ||||
| 13139 | ** | ||||
| 13140 | ** In order to avoid this problem, instead of a single large buffer, input | ||||
| 13141 | ** is passed to a streaming API functions by way of a callback function that | ||||
| 13142 | ** the sessions module invokes to incrementally request input data as it is | ||||
| 13143 | ** required. In all cases, a pair of API function parameters such as | ||||
| 13144 | ** | ||||
| 13145 | ** <pre> | ||||
| 13146 | ** int nChangeset, | ||||
| 13147 | ** void *pChangeset, | ||||
| 13148 | ** </pre> | ||||
| 13149 | ** | ||||
| 13150 | ** Is replaced by: | ||||
| 13151 | ** | ||||
| 13152 | ** <pre> | ||||
| 13153 | ** int (*xInput)(void *pIn, void *pData, int *pnData), | ||||
| 13154 | ** void *pIn, | ||||
| 13155 | ** </pre> | ||||
| 13156 | ** | ||||
| 13157 | ** Each time the xInput callback is invoked by the sessions module, the first | ||||
| 13158 | ** argument passed is a copy of the supplied pIn context pointer. The second | ||||
| 13159 | ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no | ||||
| 13160 | ** error occurs the xInput method should copy up to (*pnData) bytes of data | ||||
| 13161 | ** into the buffer and set (*pnData) to the actual number of bytes copied | ||||
| 13162 | ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) | ||||
| 13163 | ** should be set to zero to indicate this. Or, if an error occurs, an SQLite | ||||
| 13164 | ** error code should be returned. In all cases, if an xInput callback returns | ||||
| 13165 | ** an error, all processing is abandoned and the streaming API function | ||||
| 13166 | ** returns a copy of the error code to the caller. | ||||
| 13167 | ** | ||||
| 13168 | ** In the case of sqlite3changeset_start_strm(), the xInput callback may be | ||||
| 13169 | ** invoked by the sessions module at any point during the lifetime of the | ||||
| 13170 | ** iterator. If such an xInput callback returns an error, the iterator enters | ||||
| 13171 | ** an error state, whereby all subsequent calls to iterator functions | ||||
| 13172 | ** immediately fail with the same error code as returned by xInput. | ||||
| 13173 | ** | ||||
| 13174 | ** Similarly, streaming API functions that return changesets (or patchsets) | ||||
| 13175 | ** return them in chunks by way of a callback function instead of via a | ||||
| 13176 | ** pointer to a single large buffer. In this case, a pair of parameters such | ||||
| 13177 | ** as: | ||||
| 13178 | ** | ||||
| 13179 | ** <pre> | ||||
| 13180 | ** int *pnChangeset, | ||||
| 13181 | ** void **ppChangeset, | ||||
| 13182 | ** </pre> | ||||
| 13183 | ** | ||||
| 13184 | ** Is replaced by: | ||||
| 13185 | ** | ||||
| 13186 | ** <pre> | ||||
| 13187 | ** int (*xOutput)(void *pOut, const void *pData, int nData), | ||||
| 13188 | ** void *pOut | ||||
| 13189 | ** </pre> | ||||
| 13190 | ** | ||||
| 13191 | ** The xOutput callback is invoked zero or more times to return data to | ||||
| 13192 | ** the application. The first parameter passed to each call is a copy of the | ||||
| 13193 | ** pOut pointer supplied by the application. The second parameter, pData, | ||||
| 13194 | ** points to a buffer nData bytes in size containing the chunk of output | ||||
| 13195 | ** data being returned. If the xOutput callback successfully processes the | ||||
| 13196 | ** supplied data, it should return SQLITE_OK to indicate success. Otherwise, | ||||
| 13197 | ** it should return some other SQLite error code. In this case processing | ||||
| 13198 | ** is immediately abandoned and the streaming API function returns a copy | ||||
| 13199 | ** of the xOutput error code to the application. | ||||
| 13200 | ** | ||||
| 13201 | ** The sessions module never invokes an xOutput callback with the third | ||||
| 13202 | ** parameter set to a value less than or equal to zero. Other than this, | ||||
| 13203 | ** no guarantees are made as to the size of the chunks of data returned. | ||||
| 13204 | */ | ||||
| 13205 | SQLITE_API int sqlite3changeset_apply_strm( | ||||
| 13206 | sqlite3 *db, /* Apply change to "main" db of this handle */ | ||||
| 13207 | int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ | ||||
| 13208 | void *pIn, /* First arg for xInput */ | ||||
| 13209 | int(*xFilter)( | ||||
| 13210 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 13211 | const char *zTab /* Table name */ | ||||
| 13212 | ), | ||||
| 13213 | int(*xConflict)( | ||||
| 13214 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 13215 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ | ||||
| 13216 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ | ||||
| 13217 | ), | ||||
| 13218 | void *pCtx /* First argument passed to xConflict */ | ||||
| 13219 | ); | ||||
| 13220 | SQLITE_API int sqlite3changeset_apply_v2_strm( | ||||
| 13221 | sqlite3 *db, /* Apply change to "main" db of this handle */ | ||||
| 13222 | int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ | ||||
| 13223 | void *pIn, /* First arg for xInput */ | ||||
| 13224 | int(*xFilter)( | ||||
| 13225 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 13226 | const char *zTab /* Table name */ | ||||
| 13227 | ), | ||||
| 13228 | int(*xConflict)( | ||||
| 13229 | void *pCtx, /* Copy of sixth arg to _apply() */ | ||||
| 13230 | int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ | ||||
| 13231 | sqlite3_changeset_iter *p /* Handle describing change and conflict */ | ||||
| 13232 | ), | ||||
| 13233 | void *pCtx, /* First argument passed to xConflict */ | ||||
| 13234 | void **ppRebase, int *pnRebase, | ||||
| 13235 | int flags | ||||
| 13236 | ); | ||||
| 13237 | SQLITE_API int sqlite3changeset_concat_strm( | ||||
| 13238 | int (*xInputA)(void *pIn, void *pData, int *pnData), | ||||
| 13239 | void *pInA, | ||||
| 13240 | int (*xInputB)(void *pIn, void *pData, int *pnData), | ||||
| 13241 | void *pInB, | ||||
| 13242 | int (*xOutput)(void *pOut, const void *pData, int nData), | ||||
| 13243 | void *pOut | ||||
| 13244 | ); | ||||
| 13245 | SQLITE_API int sqlite3changeset_invert_strm( | ||||
| 13246 | int (*xInput)(void *pIn, void *pData, int *pnData), | ||||
| 13247 | void *pIn, | ||||
| 13248 | int (*xOutput)(void *pOut, const void *pData, int nData), | ||||
| 13249 | void *pOut | ||||
| 13250 | ); | ||||
| 13251 | SQLITE_API int sqlite3changeset_start_strm( | ||||
| 13252 | sqlite3_changeset_iter **pp, | ||||
| 13253 | int (*xInput)(void *pIn, void *pData, int *pnData), | ||||
| 13254 | void *pIn | ||||
| 13255 | ); | ||||
| 13256 | SQLITE_API int sqlite3changeset_start_v2_strm( | ||||
| 13257 | sqlite3_changeset_iter **pp, | ||||
| 13258 | int (*xInput)(void *pIn, void *pData, int *pnData), | ||||
| 13259 | void *pIn, | ||||
| 13260 | int flags | ||||
| 13261 | ); | ||||
| 13262 | SQLITE_API int sqlite3session_changeset_strm( | ||||
| 13263 | sqlite3_session *pSession, | ||||
| 13264 | int (*xOutput)(void *pOut, const void *pData, int nData), | ||||
| 13265 | void *pOut | ||||
| 13266 | ); | ||||
| 13267 | SQLITE_API int sqlite3session_patchset_strm( | ||||
| 13268 | sqlite3_session *pSession, | ||||
| 13269 | int (*xOutput)(void *pOut, const void *pData, int nData), | ||||
| 13270 | void *pOut | ||||
| 13271 | ); | ||||
| 13272 | SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, | ||||
| 13273 | int (*xInput)(void *pIn, void *pData, int *pnData), | ||||
| 13274 | void *pIn | ||||
| 13275 | ); | ||||
| 13276 | SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*, | ||||
| 13277 | int (*xOutput)(void *pOut, const void *pData, int nData), | ||||
| 13278 | void *pOut | ||||
| 13279 | ); | ||||
| 13280 | SQLITE_API int sqlite3rebaser_rebase_strm( | ||||
| 13281 | sqlite3_rebaser *pRebaser, | ||||
| 13282 | int (*xInput)(void *pIn, void *pData, int *pnData), | ||||
| 13283 | void *pIn, | ||||
| 13284 | int (*xOutput)(void *pOut, const void *pData, int nData), | ||||
| 13285 | void *pOut | ||||
| 13286 | ); | ||||
| 13287 | |||||
| 13288 | /* | ||||
| 13289 | ** CAPI3REF: Configure global parameters | ||||
| 13290 | ** | ||||
| 13291 | ** The sqlite3session_config() interface is used to make global configuration | ||||
| 13292 | ** changes to the sessions module in order to tune it to the specific needs | ||||
| 13293 | ** of the application. | ||||
| 13294 | ** | ||||
| 13295 | ** The sqlite3session_config() interface is not threadsafe. If it is invoked | ||||
| 13296 | ** while any other thread is inside any other sessions method then the | ||||
| 13297 | ** results are undefined. Furthermore, if it is invoked after any sessions | ||||
| 13298 | ** related objects have been created, the results are also undefined. | ||||
| 13299 | ** | ||||
| 13300 | ** The first argument to the sqlite3session_config() function must be one | ||||
| 13301 | ** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The | ||||
| 13302 | ** interpretation of the (void*) value passed as the second parameter and | ||||
| 13303 | ** the effect of calling this function depends on the value of the first | ||||
| 13304 | ** parameter. | ||||
| 13305 | ** | ||||
| 13306 | ** <dl> | ||||
| 13307 | ** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd> | ||||
| 13308 | ** By default, the sessions module streaming interfaces attempt to input | ||||
| 13309 | ** and output data in approximately 1 KiB chunks. This operand may be used | ||||
| 13310 | ** to set and query the value of this configuration setting. The pointer | ||||
| 13311 | ** passed as the second argument must point to a value of type (int). | ||||
| 13312 | ** If this value is greater than 0, it is used as the new streaming data | ||||
| 13313 | ** chunk size for both input and output. Before returning, the (int) value | ||||
| 13314 | ** pointed to by pArg is set to the final value of the streaming interface | ||||
| 13315 | ** chunk size. | ||||
| 13316 | ** </dl> | ||||
| 13317 | ** | ||||
| 13318 | ** This function returns SQLITE_OK if successful, or an SQLite error code | ||||
| 13319 | ** otherwise. | ||||
| 13320 | */ | ||||
| 13321 | SQLITE_API int sqlite3session_config(int op, void *pArg); | ||||
| 13322 | |||||
| 13323 | /* | ||||
| 13324 | ** CAPI3REF: Values for sqlite3session_config(). | ||||
| 13325 | */ | ||||
| 13326 | #define SQLITE_SESSION_CONFIG_STRMSIZE1 1 | ||||
| 13327 | |||||
| 13328 | /* | ||||
| 13329 | ** Make sure we can call this stuff from C++. | ||||
| 13330 | */ | ||||
| 13331 | #if 0 | ||||
| 13332 | } | ||||
| 13333 | #endif | ||||
| 13334 | |||||
| 13335 | #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */ | ||||
| 13336 | |||||
| 13337 | /******** End of sqlite3session.h *********/ | ||||
| 13338 | /******** Begin file fts5.h *********/ | ||||
| 13339 | /* | ||||
| 13340 | ** 2014 May 31 | ||||
| 13341 | ** | ||||
| 13342 | ** The author disclaims copyright to this source code. In place of | ||||
| 13343 | ** a legal notice, here is a blessing: | ||||
| 13344 | ** | ||||
| 13345 | ** May you do good and not evil. | ||||
| 13346 | ** May you find forgiveness for yourself and forgive others. | ||||
| 13347 | ** May you share freely, never taking more than you give. | ||||
| 13348 | ** | ||||
| 13349 | ****************************************************************************** | ||||
| 13350 | ** | ||||
| 13351 | ** Interfaces to extend FTS5. Using the interfaces defined in this file, | ||||
| 13352 | ** FTS5 may be extended with: | ||||
| 13353 | ** | ||||
| 13354 | ** * custom tokenizers, and | ||||
| 13355 | ** * custom auxiliary functions. | ||||
| 13356 | */ | ||||
| 13357 | |||||
| 13358 | |||||
| 13359 | #ifndef _FTS5_H | ||||
| 13360 | #define _FTS5_H | ||||
| 13361 | |||||
| 13362 | |||||
| 13363 | #if 0 | ||||
| 13364 | extern "C" { | ||||
| 13365 | #endif | ||||
| 13366 | |||||
| 13367 | /************************************************************************* | ||||
| 13368 | ** CUSTOM AUXILIARY FUNCTIONS | ||||
| 13369 | ** | ||||
| 13370 | ** Virtual table implementations may overload SQL functions by implementing | ||||
| 13371 | ** the sqlite3_module.xFindFunction() method. | ||||
| 13372 | */ | ||||
| 13373 | |||||
| 13374 | typedef struct Fts5ExtensionApi Fts5ExtensionApi; | ||||
| 13375 | typedef struct Fts5Context Fts5Context; | ||||
| 13376 | typedef struct Fts5PhraseIter Fts5PhraseIter; | ||||
| 13377 | |||||
| 13378 | typedef void (*fts5_extension_function)( | ||||
| 13379 | const Fts5ExtensionApi *pApi, /* API offered by current FTS version */ | ||||
| 13380 | Fts5Context *pFts, /* First arg to pass to pApi functions */ | ||||
| 13381 | sqlite3_context *pCtx, /* Context for returning result/error */ | ||||
| 13382 | int nVal, /* Number of values in apVal[] array */ | ||||
| 13383 | sqlite3_value **apVal /* Array of trailing arguments */ | ||||
| 13384 | ); | ||||
| 13385 | |||||
| 13386 | struct Fts5PhraseIter { | ||||
| 13387 | const unsigned char *a; | ||||
| 13388 | const unsigned char *b; | ||||
| 13389 | }; | ||||
| 13390 | |||||
| 13391 | /* | ||||
| 13392 | ** EXTENSION API FUNCTIONS | ||||
| 13393 | ** | ||||
| 13394 | ** xUserData(pFts): | ||||
| 13395 | ** Return a copy of the pUserData pointer passed to the xCreateFunction() | ||||
| 13396 | ** API when the extension function was registered. | ||||
| 13397 | ** | ||||
| 13398 | ** xColumnTotalSize(pFts, iCol, pnToken): | ||||
| 13399 | ** If parameter iCol is less than zero, set output variable *pnToken | ||||
| 13400 | ** to the total number of tokens in the FTS5 table. Or, if iCol is | ||||
| 13401 | ** non-negative but less than the number of columns in the table, return | ||||
| 13402 | ** the total number of tokens in column iCol, considering all rows in | ||||
| 13403 | ** the FTS5 table. | ||||
| 13404 | ** | ||||
| 13405 | ** If parameter iCol is greater than or equal to the number of columns | ||||
| 13406 | ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. | ||||
| 13407 | ** an OOM condition or IO error), an appropriate SQLite error code is | ||||
| 13408 | ** returned. | ||||
| 13409 | ** | ||||
| 13410 | ** xColumnCount(pFts): | ||||
| 13411 | ** Return the number of columns in the table. | ||||
| 13412 | ** | ||||
| 13413 | ** xColumnSize(pFts, iCol, pnToken): | ||||
| 13414 | ** If parameter iCol is less than zero, set output variable *pnToken | ||||
| 13415 | ** to the total number of tokens in the current row. Or, if iCol is | ||||
| 13416 | ** non-negative but less than the number of columns in the table, set | ||||
| 13417 | ** *pnToken to the number of tokens in column iCol of the current row. | ||||
| 13418 | ** | ||||
| 13419 | ** If parameter iCol is greater than or equal to the number of columns | ||||
| 13420 | ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g. | ||||
| 13421 | ** an OOM condition or IO error), an appropriate SQLite error code is | ||||
| 13422 | ** returned. | ||||
| 13423 | ** | ||||
| 13424 | ** This function may be quite inefficient if used with an FTS5 table | ||||
| 13425 | ** created with the "columnsize=0" option. | ||||
| 13426 | ** | ||||
| 13427 | ** xColumnText: | ||||
| 13428 | ** If parameter iCol is less than zero, or greater than or equal to the | ||||
| 13429 | ** number of columns in the table, SQLITE_RANGE is returned. | ||||
| 13430 | ** | ||||
| 13431 | ** Otherwise, this function attempts to retrieve the text of column iCol of | ||||
| 13432 | ** the current document. If successful, (*pz) is set to point to a buffer | ||||
| 13433 | ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes | ||||
| 13434 | ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise, | ||||
| 13435 | ** if an error occurs, an SQLite error code is returned and the final values | ||||
| 13436 | ** of (*pz) and (*pn) are undefined. | ||||
| 13437 | ** | ||||
| 13438 | ** xPhraseCount: | ||||
| 13439 | ** Returns the number of phrases in the current query expression. | ||||
| 13440 | ** | ||||
| 13441 | ** xPhraseSize: | ||||
| 13442 | ** If parameter iCol is less than zero, or greater than or equal to the | ||||
| 13443 | ** number of phrases in the current query, as returned by xPhraseCount, | ||||
| 13444 | ** 0 is returned. Otherwise, this function returns the number of tokens in | ||||
| 13445 | ** phrase iPhrase of the query. Phrases are numbered starting from zero. | ||||
| 13446 | ** | ||||
| 13447 | ** xInstCount: | ||||
| 13448 | ** Set *pnInst to the total number of occurrences of all phrases within | ||||
| 13449 | ** the query within the current row. Return SQLITE_OK if successful, or | ||||
| 13450 | ** an error code (i.e. SQLITE_NOMEM) if an error occurs. | ||||
| 13451 | ** | ||||
| 13452 | ** This API can be quite slow if used with an FTS5 table created with the | ||||
| 13453 | ** "detail=none" or "detail=column" option. If the FTS5 table is created | ||||
| 13454 | ** with either "detail=none" or "detail=column" and "content=" option | ||||
| 13455 | ** (i.e. if it is a contentless table), then this API always returns 0. | ||||
| 13456 | ** | ||||
| 13457 | ** xInst: | ||||
| 13458 | ** Query for the details of phrase match iIdx within the current row. | ||||
| 13459 | ** Phrase matches are numbered starting from zero, so the iIdx argument | ||||
| 13460 | ** should be greater than or equal to zero and smaller than the value | ||||
| 13461 | ** output by xInstCount(). If iIdx is less than zero or greater than | ||||
| 13462 | ** or equal to the value returned by xInstCount(), SQLITE_RANGE is returned. | ||||
| 13463 | ** | ||||
| 13464 | ** Otherwise, output parameter *piPhrase is set to the phrase number, *piCol | ||||
| 13465 | ** to the column in which it occurs and *piOff the token offset of the | ||||
| 13466 | ** first token of the phrase. SQLITE_OK is returned if successful, or an | ||||
| 13467 | ** error code (i.e. SQLITE_NOMEM) if an error occurs. | ||||
| 13468 | ** | ||||
| 13469 | ** This API can be quite slow if used with an FTS5 table created with the | ||||
| 13470 | ** "detail=none" or "detail=column" option. | ||||
| 13471 | ** | ||||
| 13472 | ** xRowid: | ||||
| 13473 | ** Returns the rowid of the current row. | ||||
| 13474 | ** | ||||
| 13475 | ** xTokenize: | ||||
| 13476 | ** Tokenize text using the tokenizer belonging to the FTS5 table. | ||||
| 13477 | ** | ||||
| 13478 | ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): | ||||
| 13479 | ** This API function is used to query the FTS table for phrase iPhrase | ||||
| 13480 | ** of the current query. Specifically, a query equivalent to: | ||||
| 13481 | ** | ||||
| 13482 | ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid | ||||
| 13483 | ** | ||||
| 13484 | ** with $p set to a phrase equivalent to the phrase iPhrase of the | ||||
| 13485 | ** current query is executed. Any column filter that applies to | ||||
| 13486 | ** phrase iPhrase of the current query is included in $p. For each | ||||
| 13487 | ** row visited, the callback function passed as the fourth argument | ||||
| 13488 | ** is invoked. The context and API objects passed to the callback | ||||
| 13489 | ** function may be used to access the properties of each matched row. | ||||
| 13490 | ** Invoking Api.xUserData() returns a copy of the pointer passed as | ||||
| 13491 | ** the third argument to pUserData. | ||||
| 13492 | ** | ||||
| 13493 | ** If parameter iPhrase is less than zero, or greater than or equal to | ||||
| 13494 | ** the number of phrases in the query, as returned by xPhraseCount(), | ||||
| 13495 | ** this function returns SQLITE_RANGE. | ||||
| 13496 | ** | ||||
| 13497 | ** If the callback function returns any value other than SQLITE_OK, the | ||||
| 13498 | ** query is abandoned and the xQueryPhrase function returns immediately. | ||||
| 13499 | ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. | ||||
| 13500 | ** Otherwise, the error code is propagated upwards. | ||||
| 13501 | ** | ||||
| 13502 | ** If the query runs to completion without incident, SQLITE_OK is returned. | ||||
| 13503 | ** Or, if some error occurs before the query completes or is aborted by | ||||
| 13504 | ** the callback, an SQLite error code is returned. | ||||
| 13505 | ** | ||||
| 13506 | ** | ||||
| 13507 | ** xSetAuxdata(pFts5, pAux, xDelete) | ||||
| 13508 | ** | ||||
| 13509 | ** Save the pointer passed as the second argument as the extension function's | ||||
| 13510 | ** "auxiliary data". The pointer may then be retrieved by the current or any | ||||
| 13511 | ** future invocation of the same fts5 extension function made as part of | ||||
| 13512 | ** the same MATCH query using the xGetAuxdata() API. | ||||
| 13513 | ** | ||||
| 13514 | ** Each extension function is allocated a single auxiliary data slot for | ||||
| 13515 | ** each FTS query (MATCH expression). If the extension function is invoked | ||||
| 13516 | ** more than once for a single FTS query, then all invocations share a | ||||
| 13517 | ** single auxiliary data context. | ||||
| 13518 | ** | ||||
| 13519 | ** If there is already an auxiliary data pointer when this function is | ||||
| 13520 | ** invoked, then it is replaced by the new pointer. If an xDelete callback | ||||
| 13521 | ** was specified along with the original pointer, it is invoked at this | ||||
| 13522 | ** point. | ||||
| 13523 | ** | ||||
| 13524 | ** The xDelete callback, if one is specified, is also invoked on the | ||||
| 13525 | ** auxiliary data pointer after the FTS5 query has finished. | ||||
| 13526 | ** | ||||
| 13527 | ** If an error (e.g. an OOM condition) occurs within this function, | ||||
| 13528 | ** the auxiliary data is set to NULL and an error code returned. If the | ||||
| 13529 | ** xDelete parameter was not NULL, it is invoked on the auxiliary data | ||||
| 13530 | ** pointer before returning. | ||||
| 13531 | ** | ||||
| 13532 | ** | ||||
| 13533 | ** xGetAuxdata(pFts5, bClear) | ||||
| 13534 | ** | ||||
| 13535 | ** Returns the current auxiliary data pointer for the fts5 extension | ||||
| 13536 | ** function. See the xSetAuxdata() method for details. | ||||
| 13537 | ** | ||||
| 13538 | ** If the bClear argument is non-zero, then the auxiliary data is cleared | ||||
| 13539 | ** (set to NULL) before this function returns. In this case the xDelete, | ||||
| 13540 | ** if any, is not invoked. | ||||
| 13541 | ** | ||||
| 13542 | ** | ||||
| 13543 | ** xRowCount(pFts5, pnRow) | ||||
| 13544 | ** | ||||
| 13545 | ** This function is used to retrieve the total number of rows in the table. | ||||
| 13546 | ** In other words, the same value that would be returned by: | ||||
| 13547 | ** | ||||
| 13548 | ** SELECT count(*) FROM ftstable; | ||||
| 13549 | ** | ||||
| 13550 | ** xPhraseFirst() | ||||
| 13551 | ** This function is used, along with type Fts5PhraseIter and the xPhraseNext | ||||
| 13552 | ** method, to iterate through all instances of a single query phrase within | ||||
| 13553 | ** the current row. This is the same information as is accessible via the | ||||
| 13554 | ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient | ||||
| 13555 | ** to use, this API may be faster under some circumstances. To iterate | ||||
| 13556 | ** through instances of phrase iPhrase, use the following code: | ||||
| 13557 | ** | ||||
| 13558 | ** Fts5PhraseIter iter; | ||||
| 13559 | ** int iCol, iOff; | ||||
| 13560 | ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff); | ||||
| 13561 | ** iCol>=0; | ||||
| 13562 | ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff) | ||||
| 13563 | ** ){ | ||||
| 13564 | ** // An instance of phrase iPhrase at offset iOff of column iCol | ||||
| 13565 | ** } | ||||
| 13566 | ** | ||||
| 13567 | ** The Fts5PhraseIter structure is defined above. Applications should not | ||||
| 13568 | ** modify this structure directly - it should only be used as shown above | ||||
| 13569 | ** with the xPhraseFirst() and xPhraseNext() API methods (and by | ||||
| 13570 | ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below). | ||||
| 13571 | ** | ||||
| 13572 | ** This API can be quite slow if used with an FTS5 table created with the | ||||
| 13573 | ** "detail=none" or "detail=column" option. If the FTS5 table is created | ||||
| 13574 | ** with either "detail=none" or "detail=column" and "content=" option | ||||
| 13575 | ** (i.e. if it is a contentless table), then this API always iterates | ||||
| 13576 | ** through an empty set (all calls to xPhraseFirst() set iCol to -1). | ||||
| 13577 | ** | ||||
| 13578 | ** In all cases, matches are visited in (column ASC, offset ASC) order. | ||||
| 13579 | ** i.e. all those in column 0, sorted by offset, followed by those in | ||||
| 13580 | ** column 1, etc. | ||||
| 13581 | ** | ||||
| 13582 | ** xPhraseNext() | ||||
| 13583 | ** See xPhraseFirst above. | ||||
| 13584 | ** | ||||
| 13585 | ** xPhraseFirstColumn() | ||||
| 13586 | ** This function and xPhraseNextColumn() are similar to the xPhraseFirst() | ||||
| 13587 | ** and xPhraseNext() APIs described above. The difference is that instead | ||||
| 13588 | ** of iterating through all instances of a phrase in the current row, these | ||||
| 13589 | ** APIs are used to iterate through the set of columns in the current row | ||||
| 13590 | ** that contain one or more instances of a specified phrase. For example: | ||||
| 13591 | ** | ||||
| 13592 | ** Fts5PhraseIter iter; | ||||
| 13593 | ** int iCol; | ||||
| 13594 | ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol); | ||||
| 13595 | ** iCol>=0; | ||||
| 13596 | ** pApi->xPhraseNextColumn(pFts, &iter, &iCol) | ||||
| 13597 | ** ){ | ||||
| 13598 | ** // Column iCol contains at least one instance of phrase iPhrase | ||||
| 13599 | ** } | ||||
| 13600 | ** | ||||
| 13601 | ** This API can be quite slow if used with an FTS5 table created with the | ||||
| 13602 | ** "detail=none" option. If the FTS5 table is created with either | ||||
| 13603 | ** "detail=none" "content=" option (i.e. if it is a contentless table), | ||||
| 13604 | ** then this API always iterates through an empty set (all calls to | ||||
| 13605 | ** xPhraseFirstColumn() set iCol to -1). | ||||
| 13606 | ** | ||||
| 13607 | ** The information accessed using this API and its companion | ||||
| 13608 | ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext | ||||
| 13609 | ** (or xInst/xInstCount). The chief advantage of this API is that it is | ||||
| 13610 | ** significantly more efficient than those alternatives when used with | ||||
| 13611 | ** "detail=column" tables. | ||||
| 13612 | ** | ||||
| 13613 | ** xPhraseNextColumn() | ||||
| 13614 | ** See xPhraseFirstColumn above. | ||||
| 13615 | ** | ||||
| 13616 | ** xQueryToken(pFts5, iPhrase, iToken, ppToken, pnToken) | ||||
| 13617 | ** This is used to access token iToken of phrase iPhrase of the current | ||||
| 13618 | ** query. Before returning, output parameter *ppToken is set to point | ||||
| 13619 | ** to a buffer containing the requested token, and *pnToken to the | ||||
| 13620 | ** size of this buffer in bytes. | ||||
| 13621 | ** | ||||
| 13622 | ** If iPhrase or iToken are less than zero, or if iPhrase is greater than | ||||
| 13623 | ** or equal to the number of phrases in the query as reported by | ||||
| 13624 | ** xPhraseCount(), or if iToken is equal to or greater than the number of | ||||
| 13625 | ** tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken | ||||
| 13626 | are both zeroed. | ||||
| 13627 | ** | ||||
| 13628 | ** The output text is not a copy of the query text that specified the | ||||
| 13629 | ** token. It is the output of the tokenizer module. For tokendata=1 | ||||
| 13630 | ** tables, this includes any embedded 0x00 and trailing data. | ||||
| 13631 | ** | ||||
| 13632 | ** xInstToken(pFts5, iIdx, iToken, ppToken, pnToken) | ||||
| 13633 | ** This is used to access token iToken of phrase hit iIdx within the | ||||
| 13634 | ** current row. If iIdx is less than zero or greater than or equal to the | ||||
| 13635 | ** value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise, | ||||
| 13636 | ** output variable (*ppToken) is set to point to a buffer containing the | ||||
| 13637 | ** matching document token, and (*pnToken) to the size of that buffer in | ||||
| 13638 | ** bytes. | ||||
| 13639 | ** | ||||
| 13640 | ** The output text is not a copy of the document text that was tokenized. | ||||
| 13641 | ** It is the output of the tokenizer module. For tokendata=1 tables, this | ||||
| 13642 | ** includes any embedded 0x00 and trailing data. | ||||
| 13643 | ** | ||||
| 13644 | ** This API may be slow in some cases if the token identified by parameters | ||||
| 13645 | ** iIdx and iToken matched a prefix token in the query. In most cases, the | ||||
| 13646 | ** first call to this API for each prefix token in the query is forced | ||||
| 13647 | ** to scan the portion of the full-text index that matches the prefix | ||||
| 13648 | ** token to collect the extra data required by this API. If the prefix | ||||
| 13649 | ** token matches a large number of token instances in the document set, | ||||
| 13650 | ** this may be a performance problem. | ||||
| 13651 | ** | ||||
| 13652 | ** If the user knows in advance that a query may use this API for a | ||||
| 13653 | ** prefix token, FTS5 may be configured to collect all required data as part | ||||
| 13654 | ** of the initial querying of the full-text index, avoiding the second scan | ||||
| 13655 | ** entirely. This also causes prefix queries that do not use this API to | ||||
| 13656 | ** run more slowly and use more memory. FTS5 may be configured in this way | ||||
| 13657 | ** either on a per-table basis using the [FTS5 insttoken | 'insttoken'] | ||||
| 13658 | ** option, or on a per-query basis using the | ||||
| 13659 | ** [fts5_insttoken | fts5_insttoken()] user function. | ||||
| 13660 | ** | ||||
| 13661 | ** This API can be quite slow if used with an FTS5 table created with the | ||||
| 13662 | ** "detail=none" or "detail=column" option. | ||||
| 13663 | ** | ||||
| 13664 | ** xColumnLocale(pFts5, iIdx, pzLocale, pnLocale) | ||||
| 13665 | ** If parameter iCol is less than zero, or greater than or equal to the | ||||
| 13666 | ** number of columns in the table, SQLITE_RANGE is returned. | ||||
| 13667 | ** | ||||
| 13668 | ** Otherwise, this function attempts to retrieve the locale associated | ||||
| 13669 | ** with column iCol of the current row. Usually, there is no associated | ||||
| 13670 | ** locale, and output parameters (*pzLocale) and (*pnLocale) are set | ||||
| 13671 | ** to NULL and 0, respectively. However, if the fts5_locale() function | ||||
| 13672 | ** was used to associate a locale with the value when it was inserted | ||||
| 13673 | ** into the fts5 table, then (*pzLocale) is set to point to a nul-terminated | ||||
| 13674 | ** buffer containing the name of the locale in utf-8 encoding. (*pnLocale) | ||||
| 13675 | ** is set to the size in bytes of the buffer, not including the | ||||
| 13676 | ** nul-terminator. | ||||
| 13677 | ** | ||||
| 13678 | ** If successful, SQLITE_OK is returned. Or, if an error occurs, an | ||||
| 13679 | ** SQLite error code is returned. The final value of the output parameters | ||||
| 13680 | ** is undefined in this case. | ||||
| 13681 | ** | ||||
| 13682 | ** xTokenize_v2: | ||||
| 13683 | ** Tokenize text using the tokenizer belonging to the FTS5 table. This | ||||
| 13684 | ** API is the same as the xTokenize() API, except that it allows a tokenizer | ||||
| 13685 | ** locale to be specified. | ||||
| 13686 | */ | ||||
| 13687 | struct Fts5ExtensionApi { | ||||
| 13688 | int iVersion; /* Currently always set to 4 */ | ||||
| 13689 | |||||
| 13690 | void *(*xUserData)(Fts5Context*); | ||||
| 13691 | |||||
| 13692 | int (*xColumnCount)(Fts5Context*); | ||||
| 13693 | int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow); | ||||
| 13694 | int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken); | ||||
| 13695 | |||||
| 13696 | int (*xTokenize)(Fts5Context*, | ||||
| 13697 | const char *pText, int nText, /* Text to tokenize */ | ||||
| 13698 | void *pCtx, /* Context passed to xToken() */ | ||||
| 13699 | int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ | ||||
| 13700 | ); | ||||
| 13701 | |||||
| 13702 | int (*xPhraseCount)(Fts5Context*); | ||||
| 13703 | int (*xPhraseSize)(Fts5Context*, int iPhrase); | ||||
| 13704 | |||||
| 13705 | int (*xInstCount)(Fts5Context*, int *pnInst); | ||||
| 13706 | int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff); | ||||
| 13707 | |||||
| 13708 | sqlite3_int64 (*xRowid)(Fts5Context*); | ||||
| 13709 | int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn); | ||||
| 13710 | int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken); | ||||
| 13711 | |||||
| 13712 | int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData, | ||||
| 13713 | int(*)(const Fts5ExtensionApi*,Fts5Context*,void*) | ||||
| 13714 | ); | ||||
| 13715 | int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*)); | ||||
| 13716 | void *(*xGetAuxdata)(Fts5Context*, int bClear); | ||||
| 13717 | |||||
| 13718 | int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*); | ||||
| 13719 | void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff); | ||||
| 13720 | |||||
| 13721 | int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*); | ||||
| 13722 | void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol); | ||||
| 13723 | |||||
| 13724 | /* Below this point are iVersion>=3 only */ | ||||
| 13725 | int (*xQueryToken)(Fts5Context*, | ||||
| 13726 | int iPhrase, int iToken, | ||||
| 13727 | const char **ppToken, int *pnToken | ||||
| 13728 | ); | ||||
| 13729 | int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*); | ||||
| 13730 | |||||
| 13731 | /* Below this point are iVersion>=4 only */ | ||||
| 13732 | int (*xColumnLocale)(Fts5Context*, int iCol, const char **pz, int *pn); | ||||
| 13733 | int (*xTokenize_v2)(Fts5Context*, | ||||
| 13734 | const char *pText, int nText, /* Text to tokenize */ | ||||
| 13735 | const char *pLocale, int nLocale, /* Locale to pass to tokenizer */ | ||||
| 13736 | void *pCtx, /* Context passed to xToken() */ | ||||
| 13737 | int (*xToken)(void*, int, const char*, int, int, int) /* Callback */ | ||||
| 13738 | ); | ||||
| 13739 | }; | ||||
| 13740 | |||||
| 13741 | /* | ||||
| 13742 | ** CUSTOM AUXILIARY FUNCTIONS | ||||
| 13743 | *************************************************************************/ | ||||
| 13744 | |||||
| 13745 | /************************************************************************* | ||||
| 13746 | ** CUSTOM TOKENIZERS | ||||
| 13747 | ** | ||||
| 13748 | ** Applications may also register custom tokenizer types. A tokenizer | ||||
| 13749 | ** is registered by providing fts5 with a populated instance of the | ||||
| 13750 | ** following structure. All structure methods must be defined, setting | ||||
| 13751 | ** any member of the fts5_tokenizer struct to NULL leads to undefined | ||||
| 13752 | ** behaviour. The structure methods are expected to function as follows: | ||||
| 13753 | ** | ||||
| 13754 | ** xCreate: | ||||
| 13755 | ** This function is used to allocate and initialize a tokenizer instance. | ||||
| 13756 | ** A tokenizer instance is required to actually tokenize text. | ||||
| 13757 | ** | ||||
| 13758 | ** The first argument passed to this function is a copy of the (void*) | ||||
| 13759 | ** pointer provided by the application when the fts5_tokenizer_v2 object | ||||
| 13760 | ** was registered with FTS5 (the third argument to xCreateTokenizer()). | ||||
| 13761 | ** The second and third arguments are an array of nul-terminated strings | ||||
| 13762 | ** containing the tokenizer arguments, if any, specified following the | ||||
| 13763 | ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used | ||||
| 13764 | ** to create the FTS5 table. | ||||
| 13765 | ** | ||||
| 13766 | ** The final argument is an output variable. If successful, (*ppOut) | ||||
| 13767 | ** should be set to point to the new tokenizer handle and SQLITE_OK | ||||
| 13768 | ** returned. If an error occurs, some value other than SQLITE_OK should | ||||
| 13769 | ** be returned. In this case, fts5 assumes that the final value of *ppOut | ||||
| 13770 | ** is undefined. | ||||
| 13771 | ** | ||||
| 13772 | ** xDelete: | ||||
| 13773 | ** This function is invoked to delete a tokenizer handle previously | ||||
| 13774 | ** allocated using xCreate(). Fts5 guarantees that this function will | ||||
| 13775 | ** be invoked exactly once for each successful call to xCreate(). | ||||
| 13776 | ** | ||||
| 13777 | ** xTokenize: | ||||
| 13778 | ** This function is expected to tokenize the nText byte string indicated | ||||
| 13779 | ** by argument pText. pText may or may not be nul-terminated. The first | ||||
| 13780 | ** argument passed to this function is a pointer to an Fts5Tokenizer object | ||||
| 13781 | ** returned by an earlier call to xCreate(). | ||||
| 13782 | ** | ||||
| 13783 | ** The third argument indicates the reason that FTS5 is requesting | ||||
| 13784 | ** tokenization of the supplied text. This is always one of the following | ||||
| 13785 | ** four values: | ||||
| 13786 | ** | ||||
| 13787 | ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into | ||||
| 13788 | ** or removed from the FTS table. The tokenizer is being invoked to | ||||
| 13789 | ** determine the set of tokens to add to (or delete from) the | ||||
| 13790 | ** FTS index. | ||||
| 13791 | ** | ||||
| 13792 | ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed | ||||
| 13793 | ** against the FTS index. The tokenizer is being called to tokenize | ||||
| 13794 | ** a bareword or quoted string specified as part of the query. | ||||
| 13795 | ** | ||||
| 13796 | ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as | ||||
| 13797 | ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is | ||||
| 13798 | ** followed by a "*" character, indicating that the last token | ||||
| 13799 | ** returned by the tokenizer will be treated as a token prefix. | ||||
| 13800 | ** | ||||
| 13801 | ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to | ||||
| 13802 | ** satisfy an fts5_api.xTokenize() request made by an auxiliary | ||||
| 13803 | ** function. Or an fts5_api.xColumnSize() request made by the same | ||||
| 13804 | ** on a columnsize=0 database. | ||||
| 13805 | ** </ul> | ||||
| 13806 | ** | ||||
| 13807 | ** The sixth and seventh arguments passed to xTokenize() - pLocale and | ||||
| 13808 | ** nLocale - are a pointer to a buffer containing the locale to use for | ||||
| 13809 | ** tokenization (e.g. "en_US") and its size in bytes, respectively. The | ||||
| 13810 | ** pLocale buffer is not nul-terminated. pLocale may be passed NULL (in | ||||
| 13811 | ** which case nLocale is always 0) to indicate that the tokenizer should | ||||
| 13812 | ** use its default locale. | ||||
| 13813 | ** | ||||
| 13814 | ** For each token in the input string, the supplied callback xToken() must | ||||
| 13815 | ** be invoked. The first argument to it should be a copy of the pointer | ||||
| 13816 | ** passed as the second argument to xTokenize(). The third and fourth | ||||
| 13817 | ** arguments are a pointer to a buffer containing the token text, and the | ||||
| 13818 | ** size of the token in bytes. The 4th and 5th arguments are the byte offsets | ||||
| 13819 | ** of the first byte of and first byte immediately following the text from | ||||
| 13820 | ** which the token is derived within the input. | ||||
| 13821 | ** | ||||
| 13822 | ** The second argument passed to the xToken() callback ("tflags") should | ||||
| 13823 | ** normally be set to 0. The exception is if the tokenizer supports | ||||
| 13824 | ** synonyms. In this case see the discussion below for details. | ||||
| 13825 | ** | ||||
| 13826 | ** FTS5 assumes the xToken() callback is invoked for each token in the | ||||
| 13827 | ** order that they occur within the input text. | ||||
| 13828 | ** | ||||
| 13829 | ** If an xToken() callback returns any value other than SQLITE_OK, then | ||||
| 13830 | ** the tokenization should be abandoned and the xTokenize() method should | ||||
| 13831 | ** immediately return a copy of the xToken() return value. Or, if the | ||||
| 13832 | ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally, | ||||
| 13833 | ** if an error occurs with the xTokenize() implementation itself, it | ||||
| 13834 | ** may abandon the tokenization and return any error code other than | ||||
| 13835 | ** SQLITE_OK or SQLITE_DONE. | ||||
| 13836 | ** | ||||
| 13837 | ** If the tokenizer is registered using an fts5_tokenizer_v2 object, | ||||
| 13838 | ** then the xTokenize() method has two additional arguments - pLocale | ||||
| 13839 | ** and nLocale. These specify the locale that the tokenizer should use | ||||
| 13840 | ** for the current request. If pLocale and nLocale are both 0, then the | ||||
| 13841 | ** tokenizer should use its default locale. Otherwise, pLocale points to | ||||
| 13842 | ** an nLocale byte buffer containing the name of the locale to use as utf-8 | ||||
| 13843 | ** text. pLocale is not nul-terminated. | ||||
| 13844 | ** | ||||
| 13845 | ** FTS5_TOKENIZER | ||||
| 13846 | ** | ||||
| 13847 | ** There is also an fts5_tokenizer object. This is an older, deprecated, | ||||
| 13848 | ** version of fts5_tokenizer_v2. It is similar except that: | ||||
| 13849 | ** | ||||
| 13850 | ** <ul> | ||||
| 13851 | ** <li> There is no "iVersion" field, and | ||||
| 13852 | ** <li> The xTokenize() method does not take a locale argument. | ||||
| 13853 | ** </ul> | ||||
| 13854 | ** | ||||
| 13855 | ** Legacy fts5_tokenizer tokenizers must be registered using the | ||||
| 13856 | ** legacy xCreateTokenizer() function, instead of xCreateTokenizer_v2(). | ||||
| 13857 | ** | ||||
| 13858 | ** Tokenizer implementations registered using either API may be retrieved | ||||
| 13859 | ** using both xFindTokenizer() and xFindTokenizer_v2(). | ||||
| 13860 | ** | ||||
| 13861 | ** SYNONYM SUPPORT | ||||
| 13862 | ** | ||||
| 13863 | ** Custom tokenizers may also support synonyms. Consider a case in which a | ||||
| 13864 | ** user wishes to query for a phrase such as "first place". Using the | ||||
| 13865 | ** built-in tokenizers, the FTS5 query 'first + place' will match instances | ||||
| 13866 | ** of "first place" within the document set, but not alternative forms | ||||
| 13867 | ** such as "1st place". In some applications, it would be better to match | ||||
| 13868 | ** all instances of "first place" or "1st place" regardless of which form | ||||
| 13869 | ** the user specified in the MATCH query text. | ||||
| 13870 | ** | ||||
| 13871 | ** There are several ways to approach this in FTS5: | ||||
| 13872 | ** | ||||
| 13873 | ** <ol><li> By mapping all synonyms to a single token. In this case, using | ||||
| 13874 | ** the above example, this means that the tokenizer returns the | ||||
| 13875 | ** same token for inputs "first" and "1st". Say that token is in | ||||
| 13876 | ** fact "first", so that when the user inserts the document "I won | ||||
| 13877 | ** 1st place" entries are added to the index for tokens "i", "won", | ||||
| 13878 | ** "first" and "place". If the user then queries for '1st + place', | ||||
| 13879 | ** the tokenizer substitutes "first" for "1st" and the query works | ||||
| 13880 | ** as expected. | ||||
| 13881 | ** | ||||
| 13882 | ** <li> By querying the index for all synonyms of each query term | ||||
| 13883 | ** separately. In this case, when tokenizing query text, the | ||||
| 13884 | ** tokenizer may provide multiple synonyms for a single term | ||||
| 13885 | ** within the document. FTS5 then queries the index for each | ||||
| 13886 | ** synonym individually. For example, faced with the query: | ||||
| 13887 | ** | ||||
| 13888 | ** <codeblock> | ||||
| 13889 | ** ... MATCH 'first place'</codeblock> | ||||
| 13890 | ** | ||||
| 13891 | ** the tokenizer offers both "1st" and "first" as synonyms for the | ||||
| 13892 | ** first token in the MATCH query and FTS5 effectively runs a query | ||||
| 13893 | ** similar to: | ||||
| 13894 | ** | ||||
| 13895 | ** <codeblock> | ||||
| 13896 | ** ... MATCH '(first OR 1st) place'</codeblock> | ||||
| 13897 | ** | ||||
| 13898 | ** except that, for the purposes of auxiliary functions, the query | ||||
| 13899 | ** still appears to contain just two phrases - "(first OR 1st)" | ||||
| 13900 | ** being treated as a single phrase. | ||||
| 13901 | ** | ||||
| 13902 | ** <li> By adding multiple synonyms for a single term to the FTS index. | ||||
| 13903 | ** Using this method, when tokenizing document text, the tokenizer | ||||
| 13904 | ** provides multiple synonyms for each token. So that when a | ||||
| 13905 | ** document such as "I won first place" is tokenized, entries are | ||||
| 13906 | ** added to the FTS index for "i", "won", "first", "1st" and | ||||
| 13907 | ** "place". | ||||
| 13908 | ** | ||||
| 13909 | ** This way, even if the tokenizer does not provide synonyms | ||||
| 13910 | ** when tokenizing query text (it should not - to do so would be | ||||
| 13911 | ** inefficient), it doesn't matter if the user queries for | ||||
| 13912 | ** 'first + place' or '1st + place', as there are entries in the | ||||
| 13913 | ** FTS index corresponding to both forms of the first token. | ||||
| 13914 | ** </ol> | ||||
| 13915 | ** | ||||
| 13916 | ** Whether it is parsing document or query text, any call to xToken that | ||||
| 13917 | ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit | ||||
| 13918 | ** is considered to supply a synonym for the previous token. For example, | ||||
| 13919 | ** when parsing the document "I won first place", a tokenizer that supports | ||||
| 13920 | ** synonyms would call xToken() 5 times, as follows: | ||||
| 13921 | ** | ||||
| 13922 | ** <codeblock> | ||||
| 13923 | ** xToken(pCtx, 0, "i", 1, 0, 1); | ||||
| 13924 | ** xToken(pCtx, 0, "won", 3, 2, 5); | ||||
| 13925 | ** xToken(pCtx, 0, "first", 5, 6, 11); | ||||
| 13926 | ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11); | ||||
| 13927 | ** xToken(pCtx, 0, "place", 5, 12, 17); | ||||
| 13928 | **</codeblock> | ||||
| 13929 | ** | ||||
| 13930 | ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time | ||||
| 13931 | ** xToken() is called. Multiple synonyms may be specified for a single token | ||||
| 13932 | ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. | ||||
| 13933 | ** There is no limit to the number of synonyms that may be provided for a | ||||
| 13934 | ** single token. | ||||
| 13935 | ** | ||||
| 13936 | ** In many cases, method (1) above is the best approach. It does not add | ||||
| 13937 | ** extra data to the FTS index or require FTS5 to query for multiple terms, | ||||
| 13938 | ** so it is efficient in terms of disk space and query speed. However, it | ||||
| 13939 | ** does not support prefix queries very well. If, as suggested above, the | ||||
| 13940 | ** token "first" is substituted for "1st" by the tokenizer, then the query: | ||||
| 13941 | ** | ||||
| 13942 | ** <codeblock> | ||||
| 13943 | ** ... MATCH '1s*'</codeblock> | ||||
| 13944 | ** | ||||
| 13945 | ** will not match documents that contain the token "1st" (as the tokenizer | ||||
| 13946 | ** will probably not map "1s" to any prefix of "first"). | ||||
| 13947 | ** | ||||
| 13948 | ** For full prefix support, method (3) may be preferred. In this case, | ||||
| 13949 | ** because the index contains entries for both "first" and "1st", prefix | ||||
| 13950 | ** queries such as 'fi*' or '1s*' will match correctly. However, because | ||||
| 13951 | ** extra entries are added to the FTS index, this method uses more space | ||||
| 13952 | ** within the database. | ||||
| 13953 | ** | ||||
| 13954 | ** Method (2) offers a midpoint between (1) and (3). Using this method, | ||||
| 13955 | ** a query such as '1s*' will match documents that contain the literal | ||||
| 13956 | ** token "1st", but not "first" (assuming the tokenizer is not able to | ||||
| 13957 | ** provide synonyms for prefixes). However, a non-prefix query like '1st' | ||||
| 13958 | ** will match against "1st" and "first". This method does not require | ||||
| 13959 | ** extra disk space, as no extra entries are added to the FTS index. | ||||
| 13960 | ** On the other hand, it may require more CPU cycles to run MATCH queries, | ||||
| 13961 | ** as separate queries of the FTS index are required for each synonym. | ||||
| 13962 | ** | ||||
| 13963 | ** When using methods (2) or (3), it is important that the tokenizer only | ||||
| 13964 | ** provide synonyms when tokenizing document text (method (3)) or query | ||||
| 13965 | ** text (method (2)), not both. Doing so will not cause any errors, but is | ||||
| 13966 | ** inefficient. | ||||
| 13967 | */ | ||||
| 13968 | typedef struct Fts5Tokenizer Fts5Tokenizer; | ||||
| 13969 | typedef struct fts5_tokenizer_v2 fts5_tokenizer_v2; | ||||
| 13970 | struct fts5_tokenizer_v2 { | ||||
| 13971 | int iVersion; /* Currently always 2 */ | ||||
| 13972 | |||||
| 13973 | int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); | ||||
| 13974 | void (*xDelete)(Fts5Tokenizer*); | ||||
| 13975 | int (*xTokenize)(Fts5Tokenizer*, | ||||
| 13976 | void *pCtx, | ||||
| 13977 | int flags, /* Mask of FTS5_TOKENIZE_* flags */ | ||||
| 13978 | const char *pText, int nText, | ||||
| 13979 | const char *pLocale, int nLocale, | ||||
| 13980 | int (*xToken)( | ||||
| 13981 | void *pCtx, /* Copy of 2nd argument to xTokenize() */ | ||||
| 13982 | int tflags, /* Mask of FTS5_TOKEN_* flags */ | ||||
| 13983 | const char *pToken, /* Pointer to buffer containing token */ | ||||
| 13984 | int nToken, /* Size of token in bytes */ | ||||
| 13985 | int iStart, /* Byte offset of token within input text */ | ||||
| 13986 | int iEnd /* Byte offset of end of token within input text */ | ||||
| 13987 | ) | ||||
| 13988 | ); | ||||
| 13989 | }; | ||||
| 13990 | |||||
| 13991 | /* | ||||
| 13992 | ** New code should use the fts5_tokenizer_v2 type to define tokenizer | ||||
| 13993 | ** implementations. The following type is included for legacy applications | ||||
| 13994 | ** that still use it. | ||||
| 13995 | */ | ||||
| 13996 | typedef struct fts5_tokenizer fts5_tokenizer; | ||||
| 13997 | struct fts5_tokenizer { | ||||
| 13998 | int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); | ||||
| 13999 | void (*xDelete)(Fts5Tokenizer*); | ||||
| 14000 | int (*xTokenize)(Fts5Tokenizer*, | ||||
| 14001 | void *pCtx, | ||||
| 14002 | int flags, /* Mask of FTS5_TOKENIZE_* flags */ | ||||
| 14003 | const char *pText, int nText, | ||||
| 14004 | int (*xToken)( | ||||
| 14005 | void *pCtx, /* Copy of 2nd argument to xTokenize() */ | ||||
| 14006 | int tflags, /* Mask of FTS5_TOKEN_* flags */ | ||||
| 14007 | const char *pToken, /* Pointer to buffer containing token */ | ||||
| 14008 | int nToken, /* Size of token in bytes */ | ||||
| 14009 | int iStart, /* Byte offset of token within input text */ | ||||
| 14010 | int iEnd /* Byte offset of end of token within input text */ | ||||
| 14011 | ) | ||||
| 14012 | ); | ||||
| 14013 | }; | ||||
| 14014 | |||||
| 14015 | |||||
| 14016 | /* Flags that may be passed as the third argument to xTokenize() */ | ||||
| 14017 | #define FTS5_TOKENIZE_QUERY0x0001 0x0001 | ||||
| 14018 | #define FTS5_TOKENIZE_PREFIX0x0002 0x0002 | ||||
| 14019 | #define FTS5_TOKENIZE_DOCUMENT0x0004 0x0004 | ||||
| 14020 | #define FTS5_TOKENIZE_AUX0x0008 0x0008 | ||||
| 14021 | |||||
| 14022 | /* Flags that may be passed by the tokenizer implementation back to FTS5 | ||||
| 14023 | ** as the third argument to the supplied xToken callback. */ | ||||
| 14024 | #define FTS5_TOKEN_COLOCATED0x0001 0x0001 /* Same position as prev. token */ | ||||
| 14025 | |||||
| 14026 | /* | ||||
| 14027 | ** END OF CUSTOM TOKENIZERS | ||||
| 14028 | *************************************************************************/ | ||||
| 14029 | |||||
| 14030 | /************************************************************************* | ||||
| 14031 | ** FTS5 EXTENSION REGISTRATION API | ||||
| 14032 | */ | ||||
| 14033 | typedef struct fts5_api fts5_api; | ||||
| 14034 | struct fts5_api { | ||||
| 14035 | int iVersion; /* Currently always set to 3 */ | ||||
| 14036 | |||||
| 14037 | /* Create a new tokenizer */ | ||||
| 14038 | int (*xCreateTokenizer)( | ||||
| 14039 | fts5_api *pApi, | ||||
| 14040 | const char *zName, | ||||
| 14041 | void *pUserData, | ||||
| 14042 | fts5_tokenizer *pTokenizer, | ||||
| 14043 | void (*xDestroy)(void*) | ||||
| 14044 | ); | ||||
| 14045 | |||||
| 14046 | /* Find an existing tokenizer */ | ||||
| 14047 | int (*xFindTokenizer)( | ||||
| 14048 | fts5_api *pApi, | ||||
| 14049 | const char *zName, | ||||
| 14050 | void **ppUserData, | ||||
| 14051 | fts5_tokenizer *pTokenizer | ||||
| 14052 | ); | ||||
| 14053 | |||||
| 14054 | /* Create a new auxiliary function */ | ||||
| 14055 | int (*xCreateFunction)( | ||||
| 14056 | fts5_api *pApi, | ||||
| 14057 | const char *zName, | ||||
| 14058 | void *pUserData, | ||||
| 14059 | fts5_extension_function xFunction, | ||||
| 14060 | void (*xDestroy)(void*) | ||||
| 14061 | ); | ||||
| 14062 | |||||
| 14063 | /* APIs below this point are only available if iVersion>=3 */ | ||||
| 14064 | |||||
| 14065 | /* Create a new tokenizer */ | ||||
| 14066 | int (*xCreateTokenizer_v2)( | ||||
| 14067 | fts5_api *pApi, | ||||
| 14068 | const char *zName, | ||||
| 14069 | void *pUserData, | ||||
| 14070 | fts5_tokenizer_v2 *pTokenizer, | ||||
| 14071 | void (*xDestroy)(void*) | ||||
| 14072 | ); | ||||
| 14073 | |||||
| 14074 | /* Find an existing tokenizer */ | ||||
| 14075 | int (*xFindTokenizer_v2)( | ||||
| 14076 | fts5_api *pApi, | ||||
| 14077 | const char *zName, | ||||
| 14078 | void **ppUserData, | ||||
| 14079 | fts5_tokenizer_v2 **ppTokenizer | ||||
| 14080 | ); | ||||
| 14081 | }; | ||||
| 14082 | |||||
| 14083 | /* | ||||
| 14084 | ** END OF REGISTRATION API | ||||
| 14085 | *************************************************************************/ | ||||
| 14086 | |||||
| 14087 | #if 0 | ||||
| 14088 | } /* end of the 'extern "C"' block */ | ||||
| 14089 | #endif | ||||
| 14090 | |||||
| 14091 | #endif /* _FTS5_H */ | ||||
| 14092 | |||||
| 14093 | /******** End of fts5.h *********/ | ||||
| 14094 | #endif /* SQLITE3_H */ | ||||
| 14095 | |||||
| 14096 | /************** End of sqlite3.h *********************************************/ | ||||
| 14097 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 14098 | |||||
| 14099 | /* | ||||
| 14100 | ** Reuse the STATIC_LRU for mutex access to sqlite3_temp_directory. | ||||
| 14101 | */ | ||||
| 14102 | #define SQLITE_MUTEX_STATIC_TEMPDIR11 SQLITE_MUTEX_STATIC_VFS111 | ||||
| 14103 | |||||
| 14104 | /* | ||||
| 14105 | ** Include the configuration header output by 'configure' if we're using the | ||||
| 14106 | ** autoconf-based build | ||||
| 14107 | */ | ||||
| 14108 | #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) | ||||
| 14109 | #include "sqlite_cfg.h" | ||||
| 14110 | #define SQLITECONFIG_H 1 | ||||
| 14111 | #endif | ||||
| 14112 | |||||
| 14113 | /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ | ||||
| 14114 | /************** Begin file sqliteLimit.h *************************************/ | ||||
| 14115 | /* | ||||
| 14116 | ** 2007 May 7 | ||||
| 14117 | ** | ||||
| 14118 | ** The author disclaims copyright to this source code. In place of | ||||
| 14119 | ** a legal notice, here is a blessing: | ||||
| 14120 | ** | ||||
| 14121 | ** May you do good and not evil. | ||||
| 14122 | ** May you find forgiveness for yourself and forgive others. | ||||
| 14123 | ** May you share freely, never taking more than you give. | ||||
| 14124 | ** | ||||
| 14125 | ************************************************************************* | ||||
| 14126 | ** | ||||
| 14127 | ** This file defines various limits of what SQLite can process. | ||||
| 14128 | */ | ||||
| 14129 | |||||
| 14130 | /* | ||||
| 14131 | ** The maximum length of a TEXT or BLOB in bytes. This also | ||||
| 14132 | ** limits the size of a row in a table or index. | ||||
| 14133 | ** | ||||
| 14134 | ** The hard limit is the ability of a 32-bit signed integer | ||||
| 14135 | ** to count the size: 2^31-1 or 2147483647. | ||||
| 14136 | */ | ||||
| 14137 | #ifndef SQLITE_MAX_LENGTH2147483645 | ||||
| 14138 | # define SQLITE_MAX_LENGTH2147483645 1000000000 | ||||
| 14139 | #endif | ||||
| 14140 | #define SQLITE_MIN_LENGTH30 30 /* Minimum value for the length limit */ | ||||
| 14141 | |||||
| 14142 | /* | ||||
| 14143 | ** This is the maximum number of | ||||
| 14144 | ** | ||||
| 14145 | ** * Columns in a table | ||||
| 14146 | ** * Columns in an index | ||||
| 14147 | ** * Columns in a view | ||||
| 14148 | ** * Terms in the SET clause of an UPDATE statement | ||||
| 14149 | ** * Terms in the result set of a SELECT statement | ||||
| 14150 | ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. | ||||
| 14151 | ** * Terms in the VALUES clause of an INSERT statement | ||||
| 14152 | ** | ||||
| 14153 | ** The hard upper limit here is 32767. Most database people will | ||||
| 14154 | ** tell you that in a well-normalized database, you usually should | ||||
| 14155 | ** not have more than a dozen or so columns in any table. And if | ||||
| 14156 | ** that is the case, there is no point in having more than a few | ||||
| 14157 | ** dozen values in any of the other situations described above. | ||||
| 14158 | ** | ||||
| 14159 | ** An index can only have SQLITE_MAX_COLUMN columns from the user | ||||
| 14160 | ** point of view, but the underlying b-tree that implements the index | ||||
| 14161 | ** might have up to twice as many columns in a WITHOUT ROWID table, | ||||
| 14162 | ** since must also store the primary key at the end. Hence the | ||||
| 14163 | ** column count for Index is u16 instead of i16. | ||||
| 14164 | */ | ||||
| 14165 | #if !defined(SQLITE_MAX_COLUMN2000) | ||||
| 14166 | # define SQLITE_MAX_COLUMN2000 2000 | ||||
| 14167 | #elif SQLITE_MAX_COLUMN2000>32767 | ||||
| 14168 | # error SQLITE_MAX_COLUMN2000 may not exceed 32767 | ||||
| 14169 | #endif | ||||
| 14170 | |||||
| 14171 | /* | ||||
| 14172 | ** The maximum length of a single SQL statement in bytes. | ||||
| 14173 | ** | ||||
| 14174 | ** It used to be the case that setting this value to zero would | ||||
| 14175 | ** turn the limit off. That is no longer true. It is not possible | ||||
| 14176 | ** to turn this limit off. | ||||
| 14177 | */ | ||||
| 14178 | #ifndef SQLITE_MAX_SQL_LENGTH1000000000 | ||||
| 14179 | # define SQLITE_MAX_SQL_LENGTH1000000000 1000000000 | ||||
| 14180 | #endif | ||||
| 14181 | |||||
| 14182 | /* | ||||
| 14183 | ** The maximum depth of an expression tree. This is limited to | ||||
| 14184 | ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might | ||||
| 14185 | ** want to place more severe limits on the complexity of an | ||||
| 14186 | ** expression. A value of 0 means that there is no limit. | ||||
| 14187 | */ | ||||
| 14188 | #ifndef SQLITE_MAX_EXPR_DEPTH1000 | ||||
| 14189 | # define SQLITE_MAX_EXPR_DEPTH1000 1000 | ||||
| 14190 | #endif | ||||
| 14191 | |||||
| 14192 | /* | ||||
| 14193 | ** The maximum number of terms in a compound SELECT statement. | ||||
| 14194 | ** The code generator for compound SELECT statements does one | ||||
| 14195 | ** level of recursion for each term. A stack overflow can result | ||||
| 14196 | ** if the number of terms is too large. In practice, most SQL | ||||
| 14197 | ** never has more than 3 or 4 terms. Use a value of 0 to disable | ||||
| 14198 | ** any limit on the number of terms in a compound SELECT. | ||||
| 14199 | */ | ||||
| 14200 | #ifndef SQLITE_MAX_COMPOUND_SELECT500 | ||||
| 14201 | # define SQLITE_MAX_COMPOUND_SELECT500 500 | ||||
| 14202 | #endif | ||||
| 14203 | |||||
| 14204 | /* | ||||
| 14205 | ** The maximum number of opcodes in a VDBE program. | ||||
| 14206 | ** Not currently enforced. | ||||
| 14207 | */ | ||||
| 14208 | #ifndef SQLITE_MAX_VDBE_OP250000000 | ||||
| 14209 | # define SQLITE_MAX_VDBE_OP250000000 250000000 | ||||
| 14210 | #endif | ||||
| 14211 | |||||
| 14212 | /* | ||||
| 14213 | ** The maximum number of arguments to an SQL function. | ||||
| 14214 | ** | ||||
| 14215 | ** This value has a hard upper limit of 32767 due to storage | ||||
| 14216 | ** constraints (it needs to fit inside a i16). We keep it | ||||
| 14217 | ** lower than that to prevent abuse. | ||||
| 14218 | */ | ||||
| 14219 | #ifndef SQLITE_MAX_FUNCTION_ARG1000 | ||||
| 14220 | # define SQLITE_MAX_FUNCTION_ARG1000 1000 | ||||
| 14221 | #endif | ||||
| 14222 | |||||
| 14223 | /* | ||||
| 14224 | ** The suggested maximum number of in-memory pages to use for | ||||
| 14225 | ** the main database table and for temporary tables. | ||||
| 14226 | ** | ||||
| 14227 | ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000, | ||||
| 14228 | ** which means the cache size is limited to 2048000 bytes of memory. | ||||
| 14229 | ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be | ||||
| 14230 | ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options. | ||||
| 14231 | */ | ||||
| 14232 | #ifndef SQLITE_DEFAULT_CACHE_SIZE128 | ||||
| 14233 | # define SQLITE_DEFAULT_CACHE_SIZE128 -2000 | ||||
| 14234 | #endif | ||||
| 14235 | |||||
| 14236 | /* | ||||
| 14237 | ** The default number of frames to accumulate in the log file before | ||||
| 14238 | ** checkpointing the database in WAL mode. | ||||
| 14239 | */ | ||||
| 14240 | #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT1000 | ||||
| 14241 | # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT1000 1000 | ||||
| 14242 | #endif | ||||
| 14243 | |||||
| 14244 | /* | ||||
| 14245 | ** The maximum number of attached databases. This must be between 0 | ||||
| 14246 | ** and 125. The upper bound of 125 is because the attached databases are | ||||
| 14247 | ** counted using a signed 8-bit integer which has a maximum value of 127 | ||||
| 14248 | ** and we have to allow 2 extra counts for the "main" and "temp" databases. | ||||
| 14249 | */ | ||||
| 14250 | #ifndef SQLITE_MAX_ATTACHED10 | ||||
| 14251 | # define SQLITE_MAX_ATTACHED10 10 | ||||
| 14252 | #endif | ||||
| 14253 | |||||
| 14254 | |||||
| 14255 | /* | ||||
| 14256 | ** The maximum value of a ?nnn wildcard that the parser will accept. | ||||
| 14257 | ** If the value exceeds 32767 then extra space is required for the Expr | ||||
| 14258 | ** structure. But otherwise, we believe that the number can be as large | ||||
| 14259 | ** as a signed 32-bit integer can hold. | ||||
| 14260 | */ | ||||
| 14261 | #ifndef SQLITE_MAX_VARIABLE_NUMBER500000 | ||||
| 14262 | # define SQLITE_MAX_VARIABLE_NUMBER500000 32766 | ||||
| 14263 | #endif | ||||
| 14264 | |||||
| 14265 | /* Maximum page size. The upper bound on this value is 65536. This a limit | ||||
| 14266 | ** imposed by the use of 16-bit offsets within each page. | ||||
| 14267 | ** | ||||
| 14268 | ** Earlier versions of SQLite allowed the user to change this value at | ||||
| 14269 | ** compile time. This is no longer permitted, on the grounds that it creates | ||||
| 14270 | ** a library that is technically incompatible with an SQLite library | ||||
| 14271 | ** compiled with a different limit. If a process operating on a database | ||||
| 14272 | ** with a page-size of 65536 bytes crashes, then an instance of SQLite | ||||
| 14273 | ** compiled with the default page-size limit will not be able to rollback | ||||
| 14274 | ** the aborted transaction. This could lead to database corruption. | ||||
| 14275 | */ | ||||
| 14276 | #ifdef SQLITE_MAX_PAGE_SIZE65536 | ||||
| 14277 | # undef SQLITE_MAX_PAGE_SIZE65536 | ||||
| 14278 | #endif | ||||
| 14279 | #define SQLITE_MAX_PAGE_SIZE65536 65536 | ||||
| 14280 | |||||
| 14281 | |||||
| 14282 | /* | ||||
| 14283 | ** The default size of a database page. | ||||
| 14284 | */ | ||||
| 14285 | #ifndef SQLITE_DEFAULT_PAGE_SIZE4096 | ||||
| 14286 | # define SQLITE_DEFAULT_PAGE_SIZE4096 4096 | ||||
| 14287 | #endif | ||||
| 14288 | #if SQLITE_DEFAULT_PAGE_SIZE4096>SQLITE_MAX_PAGE_SIZE65536 | ||||
| 14289 | # undef SQLITE_DEFAULT_PAGE_SIZE4096 | ||||
| 14290 | # define SQLITE_DEFAULT_PAGE_SIZE4096 SQLITE_MAX_PAGE_SIZE65536 | ||||
| 14291 | #endif | ||||
| 14292 | |||||
| 14293 | /* | ||||
| 14294 | ** Ordinarily, if no value is explicitly provided, SQLite creates databases | ||||
| 14295 | ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain | ||||
| 14296 | ** device characteristics (sector-size and atomic write() support), | ||||
| 14297 | ** SQLite may choose a larger value. This constant is the maximum value | ||||
| 14298 | ** SQLite will choose on its own. | ||||
| 14299 | */ | ||||
| 14300 | #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE8192 | ||||
| 14301 | # define SQLITE_MAX_DEFAULT_PAGE_SIZE8192 8192 | ||||
| 14302 | #endif | ||||
| 14303 | #if SQLITE_MAX_DEFAULT_PAGE_SIZE8192>SQLITE_MAX_PAGE_SIZE65536 | ||||
| 14304 | # undef SQLITE_MAX_DEFAULT_PAGE_SIZE8192 | ||||
| 14305 | # define SQLITE_MAX_DEFAULT_PAGE_SIZE8192 SQLITE_MAX_PAGE_SIZE65536 | ||||
| 14306 | #endif | ||||
| 14307 | |||||
| 14308 | |||||
| 14309 | /* | ||||
| 14310 | ** Maximum number of pages in one database file. | ||||
| 14311 | ** | ||||
| 14312 | ** This is really just the default value for the max_page_count pragma. | ||||
| 14313 | ** This value can be lowered (or raised) at run-time using that the | ||||
| 14314 | ** max_page_count macro. | ||||
| 14315 | */ | ||||
| 14316 | #ifndef SQLITE_MAX_PAGE_COUNT0xfffffffe | ||||
| 14317 | # define SQLITE_MAX_PAGE_COUNT0xfffffffe 0xfffffffe /* 4294967294 */ | ||||
| 14318 | #endif | ||||
| 14319 | |||||
| 14320 | /* | ||||
| 14321 | ** Maximum length (in bytes) of the pattern in a LIKE or GLOB | ||||
| 14322 | ** operator. | ||||
| 14323 | */ | ||||
| 14324 | #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH50000 | ||||
| 14325 | # define SQLITE_MAX_LIKE_PATTERN_LENGTH50000 50000 | ||||
| 14326 | #endif | ||||
| 14327 | |||||
| 14328 | /* | ||||
| 14329 | ** Maximum depth of recursion for triggers. | ||||
| 14330 | ** | ||||
| 14331 | ** A value of 1 means that a trigger program will not be able to itself | ||||
| 14332 | ** fire any triggers. A value of 0 means that no trigger programs at all | ||||
| 14333 | ** may be executed. | ||||
| 14334 | */ | ||||
| 14335 | #ifndef SQLITE_MAX_TRIGGER_DEPTH1000 | ||||
| 14336 | # define SQLITE_MAX_TRIGGER_DEPTH1000 1000 | ||||
| 14337 | #endif | ||||
| 14338 | |||||
| 14339 | /************** End of sqliteLimit.h *****************************************/ | ||||
| 14340 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 14341 | |||||
| 14342 | /* Disable nuisance warnings on Borland compilers */ | ||||
| 14343 | #if defined(__BORLANDC__) | ||||
| 14344 | #pragma warn -rch /* unreachable code */ | ||||
| 14345 | #pragma warn -ccc /* Condition is always true or false */ | ||||
| 14346 | #pragma warn -aus /* Assigned value is never used */ | ||||
| 14347 | #pragma warn -csu /* Comparing signed and unsigned */ | ||||
| 14348 | #pragma warn -spa /* Suspicious pointer arithmetic */ | ||||
| 14349 | #endif | ||||
| 14350 | |||||
| 14351 | /* | ||||
| 14352 | ** A few places in the code require atomic load/store of aligned | ||||
| 14353 | ** integer values. | ||||
| 14354 | */ | ||||
| 14355 | #ifndef __has_extension | ||||
| 14356 | # define0 __has_extension(x)0 0 /* compatibility with non-clang compilers */ | ||||
| 14357 | #endif | ||||
| 14358 | #if GCC_VERSION(4*1000000+2*1000+1)>=4007000 || __has_extension(c_atomic)1 | ||||
| 14359 | # define SQLITE_ATOMIC_INTRINSICS1 1 | ||||
| 14360 | # define AtomicLoad(PTR)__atomic_load_n((PTR),0) __atomic_load_n((PTR),__ATOMIC_RELAXED0) | ||||
| 14361 | # define AtomicStore(PTR,VAL)__atomic_store_n((PTR),(VAL),0) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED0) | ||||
| 14362 | #else | ||||
| 14363 | # define SQLITE_ATOMIC_INTRINSICS1 0 | ||||
| 14364 | # define AtomicLoad(PTR)__atomic_load_n((PTR),0) (*(PTR)) | ||||
| 14365 | # define AtomicStore(PTR,VAL)__atomic_store_n((PTR),(VAL),0) (*(PTR) = (VAL)) | ||||
| 14366 | #endif | ||||
| 14367 | |||||
| 14368 | /* | ||||
| 14369 | ** Include standard header files as necessary | ||||
| 14370 | */ | ||||
| 14371 | #ifdef HAVE_STDINT_H | ||||
| 14372 | #include <stdint.h> | ||||
| 14373 | #endif | ||||
| 14374 | #ifdef HAVE_INTTYPES_H | ||||
| 14375 | #include <inttypes.h> | ||||
| 14376 | #endif | ||||
| 14377 | |||||
| 14378 | /* | ||||
| 14379 | ** The following macros are used to cast pointers to integers and | ||||
| 14380 | ** integers to pointers. The way you do this varies from one compiler | ||||
| 14381 | ** to the next, so we have developed the following set of #if statements | ||||
| 14382 | ** to generate appropriate macros for a wide range of compilers. | ||||
| 14383 | ** | ||||
| 14384 | ** The correct "ANSI" way to do this is to use the intptr_t type. | ||||
| 14385 | ** Unfortunately, that typedef is not available on all compilers, or | ||||
| 14386 | ** if it is available, it requires an #include of specific headers | ||||
| 14387 | ** that vary from one machine to the next. | ||||
| 14388 | ** | ||||
| 14389 | ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on | ||||
| 14390 | ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). | ||||
| 14391 | ** So we have to define the macros in different ways depending on the | ||||
| 14392 | ** compiler. | ||||
| 14393 | */ | ||||
| 14394 | #if defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ | ||||
| 14395 | # define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)(intptr_t)(X)) | ||||
| 14396 | # define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(intptr_t)(X)) | ||||
| 14397 | #elif defined(__PTRDIFF_TYPE__long int) /* This case should work for GCC */ | ||||
| 14398 | # define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)(__PTRDIFF_TYPE__long int)(X)) | ||||
| 14399 | # define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(__PTRDIFF_TYPE__long int)(X)) | ||||
| 14400 | #elif !defined(__GNUC__4) /* Works for compilers other than LLVM */ | ||||
| 14401 | # define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)&((char*)0)[X]) | ||||
| 14402 | # define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(((char*)X)-(char*)0)) | ||||
| 14403 | #else /* Generates a warning - but it always works */ | ||||
| 14404 | # define SQLITE_INT_TO_PTR(X)((void*)(long int)(X)) ((void*)(X)) | ||||
| 14405 | # define SQLITE_PTR_TO_INT(X)((int)(long int)(X)) ((int)(X)) | ||||
| 14406 | #endif | ||||
| 14407 | |||||
| 14408 | /* | ||||
| 14409 | ** Macros to hint to the compiler that a function should or should not be | ||||
| 14410 | ** inlined. | ||||
| 14411 | */ | ||||
| 14412 | #if defined(__GNUC__4) | ||||
| 14413 | # define SQLITE_NOINLINE__attribute__((noinline)) __attribute__((noinline)) | ||||
| 14414 | # define SQLITE_INLINE__attribute__((always_inline)) inline __attribute__((always_inline)) inline | ||||
| 14415 | #elif defined(_MSC_VER) && _MSC_VER>=1310 | ||||
| 14416 | # define SQLITE_NOINLINE__attribute__((noinline)) __declspec(noinline) | ||||
| 14417 | # define SQLITE_INLINE__attribute__((always_inline)) inline __forceinline | ||||
| 14418 | #else | ||||
| 14419 | # define SQLITE_NOINLINE__attribute__((noinline)) | ||||
| 14420 | # define SQLITE_INLINE__attribute__((always_inline)) inline | ||||
| 14421 | #endif | ||||
| 14422 | #if defined(SQLITE_COVERAGE_TEST) || defined(__STRICT_ANSI__) | ||||
| 14423 | # undef SQLITE_INLINE__attribute__((always_inline)) inline | ||||
| 14424 | # define SQLITE_INLINE__attribute__((always_inline)) inline | ||||
| 14425 | #endif | ||||
| 14426 | |||||
| 14427 | /* | ||||
| 14428 | ** Make sure that the compiler intrinsics we desire are enabled when | ||||
| 14429 | ** compiling with an appropriate version of MSVC unless prevented by | ||||
| 14430 | ** the SQLITE_DISABLE_INTRINSIC define. | ||||
| 14431 | */ | ||||
| 14432 | #if !defined(SQLITE_DISABLE_INTRINSIC) | ||||
| 14433 | # if defined(_MSC_VER) && _MSC_VER>=1400 | ||||
| 14434 | # if !defined(_WIN32_WCE) | ||||
| 14435 | # include <intrin.h> | ||||
| 14436 | # pragma intrinsic(_byteswap_ushort) | ||||
| 14437 | # pragma intrinsic(_byteswap_ulong) | ||||
| 14438 | # pragma intrinsic(_byteswap_uint64) | ||||
| 14439 | # pragma intrinsic(_ReadWriteBarrier) | ||||
| 14440 | # else | ||||
| 14441 | # include <cmnintrin.h> | ||||
| 14442 | # endif | ||||
| 14443 | # endif | ||||
| 14444 | #endif | ||||
| 14445 | |||||
| 14446 | /* | ||||
| 14447 | ** Enable SQLITE_USE_SEH by default on MSVC builds. Only omit | ||||
| 14448 | ** SEH support if the -DSQLITE_OMIT_SEH option is given. | ||||
| 14449 | */ | ||||
| 14450 | #if defined(_MSC_VER) && !defined(SQLITE_OMIT_SEH) | ||||
| 14451 | # define SQLITE_USE_SEH 1 | ||||
| 14452 | #else | ||||
| 14453 | # undef SQLITE_USE_SEH | ||||
| 14454 | #endif | ||||
| 14455 | |||||
| 14456 | /* | ||||
| 14457 | ** Enable SQLITE_DIRECT_OVERFLOW_READ, unless the build explicitly | ||||
| 14458 | ** disables it using -DSQLITE_DIRECT_OVERFLOW_READ=0 | ||||
| 14459 | */ | ||||
| 14460 | #if defined(SQLITE_DIRECT_OVERFLOW_READ1) && SQLITE_DIRECT_OVERFLOW_READ1+1==1 | ||||
| 14461 | /* Disable if -DSQLITE_DIRECT_OVERFLOW_READ=0 */ | ||||
| 14462 | # undef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 14463 | #else | ||||
| 14464 | /* In all other cases, enable */ | ||||
| 14465 | # define SQLITE_DIRECT_OVERFLOW_READ1 1 | ||||
| 14466 | #endif | ||||
| 14467 | |||||
| 14468 | |||||
| 14469 | /* | ||||
| 14470 | ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. | ||||
| 14471 | ** 0 means mutexes are permanently disable and the library is never | ||||
| 14472 | ** threadsafe. 1 means the library is serialized which is the highest | ||||
| 14473 | ** level of threadsafety. 2 means the library is multithreaded - multiple | ||||
| 14474 | ** threads can use SQLite as long as no two threads try to use the same | ||||
| 14475 | ** database connection at the same time. | ||||
| 14476 | ** | ||||
| 14477 | ** Older versions of SQLite used an optional THREADSAFE macro. | ||||
| 14478 | ** We support that for legacy. | ||||
| 14479 | ** | ||||
| 14480 | ** To ensure that the correct value of "THREADSAFE" is reported when querying | ||||
| 14481 | ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this | ||||
| 14482 | ** logic is partially replicated in ctime.c. If it is updated here, it should | ||||
| 14483 | ** also be updated there. | ||||
| 14484 | */ | ||||
| 14485 | #if !defined(SQLITE_THREADSAFE2) | ||||
| 14486 | # if defined(THREADSAFE) | ||||
| 14487 | # define SQLITE_THREADSAFE2 THREADSAFE | ||||
| 14488 | # else | ||||
| 14489 | # define SQLITE_THREADSAFE2 1 /* IMP: R-07272-22309 */ | ||||
| 14490 | # endif | ||||
| 14491 | #endif | ||||
| 14492 | |||||
| 14493 | /* | ||||
| 14494 | ** Powersafe overwrite is on by default. But can be turned off using | ||||
| 14495 | ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. | ||||
| 14496 | */ | ||||
| 14497 | #ifndef SQLITE_POWERSAFE_OVERWRITE1 | ||||
| 14498 | # define SQLITE_POWERSAFE_OVERWRITE1 1 | ||||
| 14499 | #endif | ||||
| 14500 | |||||
| 14501 | /* | ||||
| 14502 | ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by | ||||
| 14503 | ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in | ||||
| 14504 | ** which case memory allocation statistics are disabled by default. | ||||
| 14505 | */ | ||||
| 14506 | #if !defined(SQLITE_DEFAULT_MEMSTATUS1) | ||||
| 14507 | # define SQLITE_DEFAULT_MEMSTATUS1 1 | ||||
| 14508 | #endif | ||||
| 14509 | |||||
| 14510 | /* | ||||
| 14511 | ** Exactly one of the following macros must be defined in order to | ||||
| 14512 | ** specify which memory allocation subsystem to use. | ||||
| 14513 | ** | ||||
| 14514 | ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() | ||||
| 14515 | ** SQLITE_WIN32_MALLOC // Use Win32 native heap API | ||||
| 14516 | ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails | ||||
| 14517 | ** SQLITE_MEMDEBUG // Debugging version of system malloc() | ||||
| 14518 | ** | ||||
| 14519 | ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the | ||||
| 14520 | ** assert() macro is enabled, each call into the Win32 native heap subsystem | ||||
| 14521 | ** will cause HeapValidate to be called. If heap validation should fail, an | ||||
| 14522 | ** assertion will be triggered. | ||||
| 14523 | ** | ||||
| 14524 | ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as | ||||
| 14525 | ** the default. | ||||
| 14526 | */ | ||||
| 14527 | #if defined(SQLITE_SYSTEM_MALLOC1) \ | ||||
| 14528 | + defined(SQLITE_WIN32_MALLOC) \ | ||||
| 14529 | + defined(SQLITE_ZERO_MALLOC) \ | ||||
| 14530 | + defined(SQLITE_MEMDEBUG)>1 | ||||
| 14531 | # error "Two or more of the following compile-time configuration options\ | ||||
| 14532 | are defined but at most one is allowed:\ | ||||
| 14533 | SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ | ||||
| 14534 | SQLITE_ZERO_MALLOC" | ||||
| 14535 | #endif | ||||
| 14536 | #if defined(SQLITE_SYSTEM_MALLOC1) \ | ||||
| 14537 | + defined(SQLITE_WIN32_MALLOC) \ | ||||
| 14538 | + defined(SQLITE_ZERO_MALLOC) \ | ||||
| 14539 | + defined(SQLITE_MEMDEBUG)==0 | ||||
| 14540 | # define SQLITE_SYSTEM_MALLOC1 1 | ||||
| 14541 | #endif | ||||
| 14542 | |||||
| 14543 | /* | ||||
| 14544 | ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the | ||||
| 14545 | ** sizes of memory allocations below this value where possible. | ||||
| 14546 | */ | ||||
| 14547 | #if !defined(SQLITE_MALLOC_SOFT_LIMIT1024) | ||||
| 14548 | # define SQLITE_MALLOC_SOFT_LIMIT1024 1024 | ||||
| 14549 | #endif | ||||
| 14550 | |||||
| 14551 | /* | ||||
| 14552 | ** We need to define _XOPEN_SOURCE as follows in order to enable | ||||
| 14553 | ** recursive mutexes on most Unix systems and fchmod() on OpenBSD. | ||||
| 14554 | ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit | ||||
| 14555 | ** it. | ||||
| 14556 | */ | ||||
| 14557 | #if !defined(_XOPEN_SOURCE700) && !defined(__DARWIN__) && !defined(__APPLE__) | ||||
| 14558 | # define _XOPEN_SOURCE700 600 | ||||
| 14559 | #endif | ||||
| 14560 | |||||
| 14561 | /* | ||||
| 14562 | ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that | ||||
| 14563 | ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, | ||||
| 14564 | ** make it true by defining or undefining NDEBUG. | ||||
| 14565 | ** | ||||
| 14566 | ** Setting NDEBUG makes the code smaller and faster by disabling the | ||||
| 14567 | ** assert() statements in the code. So we want the default action | ||||
| 14568 | ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG | ||||
| 14569 | ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out | ||||
| 14570 | ** feature. | ||||
| 14571 | */ | ||||
| 14572 | #if !defined(NDEBUG1) && !defined(SQLITE_DEBUG) | ||||
| 14573 | # define NDEBUG1 1 | ||||
| 14574 | #endif | ||||
| 14575 | #if defined(NDEBUG1) && defined(SQLITE_DEBUG) | ||||
| 14576 | # undef NDEBUG1 | ||||
| 14577 | #endif | ||||
| 14578 | |||||
| 14579 | /* | ||||
| 14580 | ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on. | ||||
| 14581 | */ | ||||
| 14582 | #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG) | ||||
| 14583 | # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1 | ||||
| 14584 | #endif | ||||
| 14585 | |||||
| 14586 | /* | ||||
| 14587 | ** The testcase() macro is used to aid in coverage testing. When | ||||
| 14588 | ** doing coverage testing, the condition inside the argument to | ||||
| 14589 | ** testcase() must be evaluated both true and false in order to | ||||
| 14590 | ** get full branch coverage. The testcase() macro is inserted | ||||
| 14591 | ** to help ensure adequate test coverage in places where simple | ||||
| 14592 | ** condition/decision coverage is inadequate. For example, testcase() | ||||
| 14593 | ** can be used to make sure boundary values are tested. For | ||||
| 14594 | ** bitmask tests, testcase() can be used to make sure each bit | ||||
| 14595 | ** is significant and used at least once. On switch statements | ||||
| 14596 | ** where multiple cases go to the same block of code, testcase() | ||||
| 14597 | ** can insure that all cases are evaluated. | ||||
| 14598 | */ | ||||
| 14599 | #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG) | ||||
| 14600 | # ifndef SQLITE_AMALGAMATION1 | ||||
| 14601 | extern unsigned int sqlite3CoverageCounter; | ||||
| 14602 | # endif | ||||
| 14603 | # define testcase(X) if( X ){ sqlite3CoverageCounter += (unsigned)__LINE__14603; } | ||||
| 14604 | #else | ||||
| 14605 | # define testcase(X) | ||||
| 14606 | #endif | ||||
| 14607 | |||||
| 14608 | /* | ||||
| 14609 | ** The TESTONLY macro is used to enclose variable declarations or | ||||
| 14610 | ** other bits of code that are needed to support the arguments | ||||
| 14611 | ** within testcase() and assert() macros. | ||||
| 14612 | */ | ||||
| 14613 | #if !defined(NDEBUG1) || defined(SQLITE_COVERAGE_TEST) | ||||
| 14614 | # define TESTONLY(X) X | ||||
| 14615 | #else | ||||
| 14616 | # define TESTONLY(X) | ||||
| 14617 | #endif | ||||
| 14618 | |||||
| 14619 | /* | ||||
| 14620 | ** Sometimes we need a small amount of code such as a variable initialization | ||||
| 14621 | ** to setup for a later assert() statement. We do not want this code to | ||||
| 14622 | ** appear when assert() is disabled. The following macro is therefore | ||||
| 14623 | ** used to contain that setup code. The "VVA" acronym stands for | ||||
| 14624 | ** "Verification, Validation, and Accreditation". In other words, the | ||||
| 14625 | ** code within VVA_ONLY() will only run during verification processes. | ||||
| 14626 | */ | ||||
| 14627 | #ifndef NDEBUG1 | ||||
| 14628 | # define VVA_ONLY(X) X | ||||
| 14629 | #else | ||||
| 14630 | # define VVA_ONLY(X) | ||||
| 14631 | #endif | ||||
| 14632 | |||||
| 14633 | /* | ||||
| 14634 | ** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage | ||||
| 14635 | ** and mutation testing | ||||
| 14636 | */ | ||||
| 14637 | #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) | ||||
| 14638 | # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1 | ||||
| 14639 | #endif | ||||
| 14640 | |||||
| 14641 | /* | ||||
| 14642 | ** The ALWAYS and NEVER macros surround boolean expressions which | ||||
| 14643 | ** are intended to always be true or false, respectively. Such | ||||
| 14644 | ** expressions could be omitted from the code completely. But they | ||||
| 14645 | ** are included in a few cases in order to enhance the resilience | ||||
| 14646 | ** of SQLite to unexpected behavior - to make the code "self-healing" | ||||
| 14647 | ** or "ductile" rather than being "brittle" and crashing at the first | ||||
| 14648 | ** hint of unplanned behavior. | ||||
| 14649 | ** | ||||
| 14650 | ** In other words, ALWAYS and NEVER are added for defensive code. | ||||
| 14651 | ** | ||||
| 14652 | ** When doing coverage testing ALWAYS and NEVER are hard-coded to | ||||
| 14653 | ** be true and false so that the unreachable code they specify will | ||||
| 14654 | ** not be counted as untested code. | ||||
| 14655 | */ | ||||
| 14656 | #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS) | ||||
| 14657 | # define ALWAYS(X)(X) (1) | ||||
| 14658 | # define NEVER(X)(X) (0) | ||||
| 14659 | #elif !defined(NDEBUG1) | ||||
| 14660 | # define ALWAYS(X)(X) ((X)?1:(assert(0)((void) (0)),0)) | ||||
| 14661 | # define NEVER(X)(X) ((X)?(assert(0)((void) (0)),1):0) | ||||
| 14662 | #else | ||||
| 14663 | # define ALWAYS(X)(X) (X) | ||||
| 14664 | # define NEVER(X)(X) (X) | ||||
| 14665 | #endif | ||||
| 14666 | |||||
| 14667 | /* | ||||
| 14668 | ** Some conditionals are optimizations only. In other words, if the | ||||
| 14669 | ** conditionals are replaced with a constant 1 (true) or 0 (false) then | ||||
| 14670 | ** the correct answer is still obtained, though perhaps not as quickly. | ||||
| 14671 | ** | ||||
| 14672 | ** The following macros mark these optimizations conditionals. | ||||
| 14673 | */ | ||||
| 14674 | #if defined(SQLITE_MUTATION_TEST) | ||||
| 14675 | # define OK_IF_ALWAYS_TRUE(X)(X) (1) | ||||
| 14676 | # define OK_IF_ALWAYS_FALSE(X)(X) (0) | ||||
| 14677 | #else | ||||
| 14678 | # define OK_IF_ALWAYS_TRUE(X)(X) (X) | ||||
| 14679 | # define OK_IF_ALWAYS_FALSE(X)(X) (X) | ||||
| 14680 | #endif | ||||
| 14681 | |||||
| 14682 | /* | ||||
| 14683 | ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is | ||||
| 14684 | ** defined. We need to defend against those failures when testing with | ||||
| 14685 | ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches | ||||
| 14686 | ** during a normal build. The following macro can be used to disable tests | ||||
| 14687 | ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set. | ||||
| 14688 | */ | ||||
| 14689 | #if defined(SQLITE_TEST_REALLOC_STRESS) | ||||
| 14690 | # define ONLY_IF_REALLOC_STRESS(X)(0) (X) | ||||
| 14691 | #elif !defined(NDEBUG1) | ||||
| 14692 | # define ONLY_IF_REALLOC_STRESS(X)(0) ((X)?(assert(0)((void) (0)),1):0) | ||||
| 14693 | #else | ||||
| 14694 | # define ONLY_IF_REALLOC_STRESS(X)(0) (0) | ||||
| 14695 | #endif | ||||
| 14696 | |||||
| 14697 | /* | ||||
| 14698 | ** Declarations used for tracing the operating system interfaces. | ||||
| 14699 | */ | ||||
| 14700 | #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \ | ||||
| 14701 | (defined(SQLITE_DEBUG) && SQLITE_OS_WIN0) | ||||
| 14702 | extern int sqlite3OSTrace; | ||||
| 14703 | # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X | ||||
| 14704 | # define SQLITE_HAVE_OS_TRACE | ||||
| 14705 | #else | ||||
| 14706 | # define OSTRACE(X) | ||||
| 14707 | # undef SQLITE_HAVE_OS_TRACE | ||||
| 14708 | #endif | ||||
| 14709 | |||||
| 14710 | /* | ||||
| 14711 | ** Is the sqlite3ErrName() function needed in the build? Currently, | ||||
| 14712 | ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when | ||||
| 14713 | ** OSTRACE is enabled), and by several "test*.c" files (which are | ||||
| 14714 | ** compiled using SQLITE_TEST). | ||||
| 14715 | */ | ||||
| 14716 | #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \ | ||||
| 14717 | (defined(SQLITE_DEBUG) && SQLITE_OS_WIN0) | ||||
| 14718 | # define SQLITE_NEED_ERR_NAME | ||||
| 14719 | #else | ||||
| 14720 | # undef SQLITE_NEED_ERR_NAME | ||||
| 14721 | #endif | ||||
| 14722 | |||||
| 14723 | /* | ||||
| 14724 | ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN | ||||
| 14725 | */ | ||||
| 14726 | #ifdef SQLITE_OMIT_EXPLAIN | ||||
| 14727 | # undef SQLITE_ENABLE_EXPLAIN_COMMENTS | ||||
| 14728 | #endif | ||||
| 14729 | |||||
| 14730 | /* | ||||
| 14731 | ** SQLITE_OMIT_VIRTUALTABLE implies SQLITE_OMIT_ALTERTABLE | ||||
| 14732 | */ | ||||
| 14733 | #if defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_ALTERTABLE) | ||||
| 14734 | # define SQLITE_OMIT_ALTERTABLE | ||||
| 14735 | #endif | ||||
| 14736 | |||||
| 14737 | #define SQLITE_DIGIT_SEPARATOR'_' '_' | ||||
| 14738 | |||||
| 14739 | /* | ||||
| 14740 | ** Return true (non-zero) if the input is an integer that is too large | ||||
| 14741 | ** to fit in 32-bits. This macro is used inside of various testcase() | ||||
| 14742 | ** macros to verify that we have tested SQLite for large-file support. | ||||
| 14743 | */ | ||||
| 14744 | #define IS_BIG_INT(X)(((X)&~(i64)0xffffffff)!=0) (((X)&~(i64)0xffffffff)!=0) | ||||
| 14745 | |||||
| 14746 | /* | ||||
| 14747 | ** The macro unlikely() is a hint that surrounds a boolean | ||||
| 14748 | ** expression that is usually false. Macro likely() surrounds | ||||
| 14749 | ** a boolean expression that is usually true. These hints could, | ||||
| 14750 | ** in theory, be used by the compiler to generate better code, but | ||||
| 14751 | ** currently they are just comments for human readers. | ||||
| 14752 | */ | ||||
| 14753 | #define likely(X)(X) (X) | ||||
| 14754 | #define unlikely(X)(X) (X) | ||||
| 14755 | |||||
| 14756 | /************** Include hash.h in the middle of sqliteInt.h ******************/ | ||||
| 14757 | /************** Begin file hash.h ********************************************/ | ||||
| 14758 | /* | ||||
| 14759 | ** 2001 September 22 | ||||
| 14760 | ** | ||||
| 14761 | ** The author disclaims copyright to this source code. In place of | ||||
| 14762 | ** a legal notice, here is a blessing: | ||||
| 14763 | ** | ||||
| 14764 | ** May you do good and not evil. | ||||
| 14765 | ** May you find forgiveness for yourself and forgive others. | ||||
| 14766 | ** May you share freely, never taking more than you give. | ||||
| 14767 | ** | ||||
| 14768 | ************************************************************************* | ||||
| 14769 | ** This is the header file for the generic hash-table implementation | ||||
| 14770 | ** used in SQLite. | ||||
| 14771 | */ | ||||
| 14772 | #ifndef SQLITE_HASH_H | ||||
| 14773 | #define SQLITE_HASH_H | ||||
| 14774 | |||||
| 14775 | /* Forward declarations of structures. */ | ||||
| 14776 | typedef struct Hash Hash; | ||||
| 14777 | typedef struct HashElem HashElem; | ||||
| 14778 | |||||
| 14779 | /* A complete hash table is an instance of the following structure. | ||||
| 14780 | ** The internals of this structure are intended to be opaque -- client | ||||
| 14781 | ** code should not attempt to access or modify the fields of this structure | ||||
| 14782 | ** directly. Change this structure only by using the routines below. | ||||
| 14783 | ** However, some of the "procedures" and "functions" for modifying and | ||||
| 14784 | ** accessing this structure are really macros, so we can't really make | ||||
| 14785 | ** this structure opaque. | ||||
| 14786 | ** | ||||
| 14787 | ** All elements of the hash table are on a single doubly-linked list. | ||||
| 14788 | ** Hash.first points to the head of this list. | ||||
| 14789 | ** | ||||
| 14790 | ** There are Hash.htsize buckets. Each bucket points to a spot in | ||||
| 14791 | ** the global doubly-linked list. The contents of the bucket are the | ||||
| 14792 | ** element pointed to plus the next _ht.count-1 elements in the list. | ||||
| 14793 | ** | ||||
| 14794 | ** Hash.htsize and Hash.ht may be zero. In that case lookup is done | ||||
| 14795 | ** by a linear search of the global list. For small tables, the | ||||
| 14796 | ** Hash.ht table is never allocated because if there are few elements | ||||
| 14797 | ** in the table, it is faster to do a linear search than to manage | ||||
| 14798 | ** the hash table. | ||||
| 14799 | */ | ||||
| 14800 | struct Hash { | ||||
| 14801 | unsigned int htsize; /* Number of buckets in the hash table */ | ||||
| 14802 | unsigned int count; /* Number of entries in this table */ | ||||
| 14803 | HashElem *first; /* The first element of the array */ | ||||
| 14804 | struct _ht { /* the hash table */ | ||||
| 14805 | unsigned int count; /* Number of entries with this hash */ | ||||
| 14806 | HashElem *chain; /* Pointer to first entry with this hash */ | ||||
| 14807 | } *ht; | ||||
| 14808 | }; | ||||
| 14809 | |||||
| 14810 | /* Each element in the hash table is an instance of the following | ||||
| 14811 | ** structure. All elements are stored on a single doubly-linked list. | ||||
| 14812 | ** | ||||
| 14813 | ** Again, this structure is intended to be opaque, but it can't really | ||||
| 14814 | ** be opaque because it is used by macros. | ||||
| 14815 | */ | ||||
| 14816 | struct HashElem { | ||||
| 14817 | HashElem *next, *prev; /* Next and previous elements in the table */ | ||||
| 14818 | void *data; /* Data associated with this element */ | ||||
| 14819 | const char *pKey; /* Key associated with this element */ | ||||
| 14820 | unsigned int h; /* hash for pKey */ | ||||
| 14821 | }; | ||||
| 14822 | |||||
| 14823 | /* | ||||
| 14824 | ** Access routines. To delete, insert a NULL pointer. | ||||
| 14825 | */ | ||||
| 14826 | SQLITE_PRIVATEstatic void sqlite3HashInit(Hash*); | ||||
| 14827 | SQLITE_PRIVATEstatic void *sqlite3HashInsert(Hash*, const char *pKey, void *pData); | ||||
| 14828 | SQLITE_PRIVATEstatic void *sqlite3HashFind(const Hash*, const char *pKey); | ||||
| 14829 | SQLITE_PRIVATEstatic void sqlite3HashClear(Hash*); | ||||
| 14830 | |||||
| 14831 | /* | ||||
| 14832 | ** Macros for looping over all elements of a hash table. The idiom is | ||||
| 14833 | ** like this: | ||||
| 14834 | ** | ||||
| 14835 | ** Hash h; | ||||
| 14836 | ** HashElem *p; | ||||
| 14837 | ** ... | ||||
| 14838 | ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ | ||||
| 14839 | ** SomeStructure *pData = sqliteHashData(p); | ||||
| 14840 | ** // do something with pData | ||||
| 14841 | ** } | ||||
| 14842 | */ | ||||
| 14843 | #define sqliteHashFirst(H)((H)->first) ((H)->first) | ||||
| 14844 | #define sqliteHashNext(E)((E)->next) ((E)->next) | ||||
| 14845 | #define sqliteHashData(E)((E)->data) ((E)->data) | ||||
| 14846 | /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ | ||||
| 14847 | /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ | ||||
| 14848 | |||||
| 14849 | /* | ||||
| 14850 | ** Number of entries in a hash table | ||||
| 14851 | */ | ||||
| 14852 | #define sqliteHashCount(H)((H)->count) ((H)->count) | ||||
| 14853 | |||||
| 14854 | #endif /* SQLITE_HASH_H */ | ||||
| 14855 | |||||
| 14856 | /************** End of hash.h ************************************************/ | ||||
| 14857 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 14858 | /************** Include parse.h in the middle of sqliteInt.h *****************/ | ||||
| 14859 | /************** Begin file parse.h *******************************************/ | ||||
| 14860 | #define TK_SEMI1 1 | ||||
| 14861 | #define TK_EXPLAIN2 2 | ||||
| 14862 | #define TK_QUERY3 3 | ||||
| 14863 | #define TK_PLAN4 4 | ||||
| 14864 | #define TK_BEGIN5 5 | ||||
| 14865 | #define TK_TRANSACTION6 6 | ||||
| 14866 | #define TK_DEFERRED7 7 | ||||
| 14867 | #define TK_IMMEDIATE8 8 | ||||
| 14868 | #define TK_EXCLUSIVE9 9 | ||||
| 14869 | #define TK_COMMIT10 10 | ||||
| 14870 | #define TK_END11 11 | ||||
| 14871 | #define TK_ROLLBACK12 12 | ||||
| 14872 | #define TK_SAVEPOINT13 13 | ||||
| 14873 | #define TK_RELEASE14 14 | ||||
| 14874 | #define TK_TO15 15 | ||||
| 14875 | #define TK_TABLE16 16 | ||||
| 14876 | #define TK_CREATE17 17 | ||||
| 14877 | #define TK_IF18 18 | ||||
| 14878 | #define TK_NOT19 19 | ||||
| 14879 | #define TK_EXISTS20 20 | ||||
| 14880 | #define TK_TEMP21 21 | ||||
| 14881 | #define TK_LP22 22 | ||||
| 14882 | #define TK_RP23 23 | ||||
| 14883 | #define TK_AS24 24 | ||||
| 14884 | #define TK_COMMA25 25 | ||||
| 14885 | #define TK_WITHOUT26 26 | ||||
| 14886 | #define TK_ABORT27 27 | ||||
| 14887 | #define TK_ACTION28 28 | ||||
| 14888 | #define TK_AFTER29 29 | ||||
| 14889 | #define TK_ANALYZE30 30 | ||||
| 14890 | #define TK_ASC31 31 | ||||
| 14891 | #define TK_ATTACH32 32 | ||||
| 14892 | #define TK_BEFORE33 33 | ||||
| 14893 | #define TK_BY34 34 | ||||
| 14894 | #define TK_CASCADE35 35 | ||||
| 14895 | #define TK_CAST36 36 | ||||
| 14896 | #define TK_CONFLICT37 37 | ||||
| 14897 | #define TK_DATABASE38 38 | ||||
| 14898 | #define TK_DESC39 39 | ||||
| 14899 | #define TK_DETACH40 40 | ||||
| 14900 | #define TK_EACH41 41 | ||||
| 14901 | #define TK_FAIL42 42 | ||||
| 14902 | #define TK_OR43 43 | ||||
| 14903 | #define TK_AND44 44 | ||||
| 14904 | #define TK_IS45 45 | ||||
| 14905 | #define TK_ISNOT46 46 | ||||
| 14906 | #define TK_MATCH47 47 | ||||
| 14907 | #define TK_LIKE_KW48 48 | ||||
| 14908 | #define TK_BETWEEN49 49 | ||||
| 14909 | #define TK_IN50 50 | ||||
| 14910 | #define TK_ISNULL51 51 | ||||
| 14911 | #define TK_NOTNULL52 52 | ||||
| 14912 | #define TK_NE53 53 | ||||
| 14913 | #define TK_EQ54 54 | ||||
| 14914 | #define TK_GT55 55 | ||||
| 14915 | #define TK_LE56 56 | ||||
| 14916 | #define TK_LT57 57 | ||||
| 14917 | #define TK_GE58 58 | ||||
| 14918 | #define TK_ESCAPE59 59 | ||||
| 14919 | #define TK_ID60 60 | ||||
| 14920 | #define TK_COLUMNKW61 61 | ||||
| 14921 | #define TK_DO62 62 | ||||
| 14922 | #define TK_FOR63 63 | ||||
| 14923 | #define TK_IGNORE64 64 | ||||
| 14924 | #define TK_INITIALLY65 65 | ||||
| 14925 | #define TK_INSTEAD66 66 | ||||
| 14926 | #define TK_NO67 67 | ||||
| 14927 | #define TK_KEY68 68 | ||||
| 14928 | #define TK_OF69 69 | ||||
| 14929 | #define TK_OFFSET70 70 | ||||
| 14930 | #define TK_PRAGMA71 71 | ||||
| 14931 | #define TK_RAISE72 72 | ||||
| 14932 | #define TK_RECURSIVE73 73 | ||||
| 14933 | #define TK_REPLACE74 74 | ||||
| 14934 | #define TK_RESTRICT75 75 | ||||
| 14935 | #define TK_ROW76 76 | ||||
| 14936 | #define TK_ROWS77 77 | ||||
| 14937 | #define TK_TRIGGER78 78 | ||||
| 14938 | #define TK_VACUUM79 79 | ||||
| 14939 | #define TK_VIEW80 80 | ||||
| 14940 | #define TK_VIRTUAL81 81 | ||||
| 14941 | #define TK_WITH82 82 | ||||
| 14942 | #define TK_NULLS83 83 | ||||
| 14943 | #define TK_FIRST84 84 | ||||
| 14944 | #define TK_LAST85 85 | ||||
| 14945 | #define TK_CURRENT86 86 | ||||
| 14946 | #define TK_FOLLOWING87 87 | ||||
| 14947 | #define TK_PARTITION88 88 | ||||
| 14948 | #define TK_PRECEDING89 89 | ||||
| 14949 | #define TK_RANGE90 90 | ||||
| 14950 | #define TK_UNBOUNDED91 91 | ||||
| 14951 | #define TK_EXCLUDE92 92 | ||||
| 14952 | #define TK_GROUPS93 93 | ||||
| 14953 | #define TK_OTHERS94 94 | ||||
| 14954 | #define TK_TIES95 95 | ||||
| 14955 | #define TK_GENERATED96 96 | ||||
| 14956 | #define TK_ALWAYS97 97 | ||||
| 14957 | #define TK_MATERIALIZED98 98 | ||||
| 14958 | #define TK_REINDEX99 99 | ||||
| 14959 | #define TK_RENAME100 100 | ||||
| 14960 | #define TK_CTIME_KW101 101 | ||||
| 14961 | #define TK_ANY102 102 | ||||
| 14962 | #define TK_BITAND103 103 | ||||
| 14963 | #define TK_BITOR104 104 | ||||
| 14964 | #define TK_LSHIFT105 105 | ||||
| 14965 | #define TK_RSHIFT106 106 | ||||
| 14966 | #define TK_PLUS107 107 | ||||
| 14967 | #define TK_MINUS108 108 | ||||
| 14968 | #define TK_STAR109 109 | ||||
| 14969 | #define TK_SLASH110 110 | ||||
| 14970 | #define TK_REM111 111 | ||||
| 14971 | #define TK_CONCAT112 112 | ||||
| 14972 | #define TK_PTR113 113 | ||||
| 14973 | #define TK_COLLATE114 114 | ||||
| 14974 | #define TK_BITNOT115 115 | ||||
| 14975 | #define TK_ON116 116 | ||||
| 14976 | #define TK_INDEXED117 117 | ||||
| 14977 | #define TK_STRING118 118 | ||||
| 14978 | #define TK_JOIN_KW119 119 | ||||
| 14979 | #define TK_CONSTRAINT120 120 | ||||
| 14980 | #define TK_DEFAULT121 121 | ||||
| 14981 | #define TK_NULL122 122 | ||||
| 14982 | #define TK_PRIMARY123 123 | ||||
| 14983 | #define TK_UNIQUE124 124 | ||||
| 14984 | #define TK_CHECK125 125 | ||||
| 14985 | #define TK_REFERENCES126 126 | ||||
| 14986 | #define TK_AUTOINCR127 127 | ||||
| 14987 | #define TK_INSERT128 128 | ||||
| 14988 | #define TK_DELETE129 129 | ||||
| 14989 | #define TK_UPDATE130 130 | ||||
| 14990 | #define TK_SET131 131 | ||||
| 14991 | #define TK_DEFERRABLE132 132 | ||||
| 14992 | #define TK_FOREIGN133 133 | ||||
| 14993 | #define TK_DROP134 134 | ||||
| 14994 | #define TK_UNION135 135 | ||||
| 14995 | #define TK_ALL136 136 | ||||
| 14996 | #define TK_EXCEPT137 137 | ||||
| 14997 | #define TK_INTERSECT138 138 | ||||
| 14998 | #define TK_SELECT139 139 | ||||
| 14999 | #define TK_VALUES140 140 | ||||
| 15000 | #define TK_DISTINCT141 141 | ||||
| 15001 | #define TK_DOT142 142 | ||||
| 15002 | #define TK_FROM143 143 | ||||
| 15003 | #define TK_JOIN144 144 | ||||
| 15004 | #define TK_USING145 145 | ||||
| 15005 | #define TK_ORDER146 146 | ||||
| 15006 | #define TK_GROUP147 147 | ||||
| 15007 | #define TK_HAVING148 148 | ||||
| 15008 | #define TK_LIMIT149 149 | ||||
| 15009 | #define TK_WHERE150 150 | ||||
| 15010 | #define TK_RETURNING151 151 | ||||
| 15011 | #define TK_INTO152 152 | ||||
| 15012 | #define TK_NOTHING153 153 | ||||
| 15013 | #define TK_FLOAT154 154 | ||||
| 15014 | #define TK_BLOB155 155 | ||||
| 15015 | #define TK_INTEGER156 156 | ||||
| 15016 | #define TK_VARIABLE157 157 | ||||
| 15017 | #define TK_CASE158 158 | ||||
| 15018 | #define TK_WHEN159 159 | ||||
| 15019 | #define TK_THEN160 160 | ||||
| 15020 | #define TK_ELSE161 161 | ||||
| 15021 | #define TK_INDEX162 162 | ||||
| 15022 | #define TK_ALTER163 163 | ||||
| 15023 | #define TK_ADD164 164 | ||||
| 15024 | #define TK_WINDOW165 165 | ||||
| 15025 | #define TK_OVER166 166 | ||||
| 15026 | #define TK_FILTER167 167 | ||||
| 15027 | #define TK_COLUMN168 168 | ||||
| 15028 | #define TK_AGG_FUNCTION169 169 | ||||
| 15029 | #define TK_AGG_COLUMN170 170 | ||||
| 15030 | #define TK_TRUEFALSE171 171 | ||||
| 15031 | #define TK_FUNCTION172 172 | ||||
| 15032 | #define TK_UPLUS173 173 | ||||
| 15033 | #define TK_UMINUS174 174 | ||||
| 15034 | #define TK_TRUTH175 175 | ||||
| 15035 | #define TK_REGISTER176 176 | ||||
| 15036 | #define TK_VECTOR177 177 | ||||
| 15037 | #define TK_SELECT_COLUMN178 178 | ||||
| 15038 | #define TK_IF_NULL_ROW179 179 | ||||
| 15039 | #define TK_ASTERISK180 180 | ||||
| 15040 | #define TK_SPAN181 181 | ||||
| 15041 | #define TK_ERROR182 182 | ||||
| 15042 | #define TK_QNUMBER183 183 | ||||
| 15043 | #define TK_SPACE184 184 | ||||
| 15044 | #define TK_COMMENT185 185 | ||||
| 15045 | #define TK_ILLEGAL186 186 | ||||
| 15046 | |||||
| 15047 | /************** End of parse.h ***********************************************/ | ||||
| 15048 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 15049 | #include <stdio.h> | ||||
| 15050 | #include <stdlib.h> | ||||
| 15051 | #include <string.h> | ||||
| 15052 | #include <assert.h> | ||||
| 15053 | #include <stddef.h> | ||||
| 15054 | #include <ctype.h> | ||||
| 15055 | |||||
| 15056 | /* | ||||
| 15057 | ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY. | ||||
| 15058 | ** This allows better measurements of where memcpy() is used when running | ||||
| 15059 | ** cachegrind. But this macro version of memcpy() is very slow so it | ||||
| 15060 | ** should not be used in production. This is a performance measurement | ||||
| 15061 | ** hack only. | ||||
| 15062 | */ | ||||
| 15063 | #ifdef SQLITE_INLINE_MEMCPY | ||||
| 15064 | # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\ | ||||
| 15065 | int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);} | ||||
| 15066 | #endif | ||||
| 15067 | |||||
| 15068 | /* | ||||
| 15069 | ** If compiling for a processor that lacks floating point support, | ||||
| 15070 | ** substitute integer for floating-point | ||||
| 15071 | */ | ||||
| 15072 | #ifdef SQLITE_OMIT_FLOATING_POINT | ||||
| 15073 | # define double sqlite_int64 | ||||
| 15074 | # define float sqlite_int64 | ||||
| 15075 | # define fabs(X) ((X)<0?-(X):(X)) | ||||
| 15076 | # define sqlite3IsOverflow(X) 0 | ||||
| 15077 | # ifndef SQLITE_BIG_DBL(1e99) | ||||
| 15078 | # define SQLITE_BIG_DBL(1e99) (((sqlite3_int64)1)<<50) | ||||
| 15079 | # endif | ||||
| 15080 | # define SQLITE_OMIT_DATETIME_FUNCS 1 | ||||
| 15081 | # define SQLITE_OMIT_TRACE 1 | ||||
| 15082 | # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT | ||||
| 15083 | # undef SQLITE_HAVE_ISNAN1 | ||||
| 15084 | #endif | ||||
| 15085 | #ifndef SQLITE_BIG_DBL(1e99) | ||||
| 15086 | # define SQLITE_BIG_DBL(1e99) (1e99) | ||||
| 15087 | #endif | ||||
| 15088 | |||||
| 15089 | /* | ||||
| 15090 | ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 | ||||
| 15091 | ** afterward. Having this macro allows us to cause the C compiler | ||||
| 15092 | ** to omit code used by TEMP tables without messy #ifndef statements. | ||||
| 15093 | */ | ||||
| 15094 | #ifdef SQLITE_OMIT_TEMPDB | ||||
| 15095 | #define OMIT_TEMPDB0 1 | ||||
| 15096 | #else | ||||
| 15097 | #define OMIT_TEMPDB0 0 | ||||
| 15098 | #endif | ||||
| 15099 | |||||
| 15100 | /* | ||||
| 15101 | ** The "file format" number is an integer that is incremented whenever | ||||
| 15102 | ** the VDBE-level file format changes. The following macros define the | ||||
| 15103 | ** the default file format for new databases and the maximum file format | ||||
| 15104 | ** that the library can read. | ||||
| 15105 | */ | ||||
| 15106 | #define SQLITE_MAX_FILE_FORMAT4 4 | ||||
| 15107 | #ifndef SQLITE_DEFAULT_FILE_FORMAT4 | ||||
| 15108 | # define SQLITE_DEFAULT_FILE_FORMAT4 4 | ||||
| 15109 | #endif | ||||
| 15110 | |||||
| 15111 | /* | ||||
| 15112 | ** Determine whether triggers are recursive by default. This can be | ||||
| 15113 | ** changed at run-time using a pragma. | ||||
| 15114 | */ | ||||
| 15115 | #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS0 | ||||
| 15116 | # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS0 0 | ||||
| 15117 | #endif | ||||
| 15118 | |||||
| 15119 | /* | ||||
| 15120 | ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified | ||||
| 15121 | ** on the command-line | ||||
| 15122 | */ | ||||
| 15123 | #ifndef SQLITE_TEMP_STORE1 | ||||
| 15124 | # define SQLITE_TEMP_STORE1 1 | ||||
| 15125 | #endif | ||||
| 15126 | |||||
| 15127 | /* | ||||
| 15128 | ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if | ||||
| 15129 | ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it | ||||
| 15130 | ** to zero. | ||||
| 15131 | */ | ||||
| 15132 | #if SQLITE_TEMP_STORE1==3 || SQLITE_THREADSAFE2==0 | ||||
| 15133 | # undef SQLITE_MAX_WORKER_THREADS8 | ||||
| 15134 | # define SQLITE_MAX_WORKER_THREADS8 0 | ||||
| 15135 | #endif | ||||
| 15136 | #ifndef SQLITE_MAX_WORKER_THREADS8 | ||||
| 15137 | # define SQLITE_MAX_WORKER_THREADS8 8 | ||||
| 15138 | #endif | ||||
| 15139 | #ifndef SQLITE_DEFAULT_WORKER_THREADS0 | ||||
| 15140 | # define SQLITE_DEFAULT_WORKER_THREADS0 0 | ||||
| 15141 | #endif | ||||
| 15142 | #if SQLITE_DEFAULT_WORKER_THREADS0>SQLITE_MAX_WORKER_THREADS8 | ||||
| 15143 | # undef SQLITE_MAX_WORKER_THREADS8 | ||||
| 15144 | # define SQLITE_MAX_WORKER_THREADS8 SQLITE_DEFAULT_WORKER_THREADS0 | ||||
| 15145 | #endif | ||||
| 15146 | |||||
| 15147 | /* | ||||
| 15148 | ** The default initial allocation for the pagecache when using separate | ||||
| 15149 | ** pagecaches for each database connection. A positive number is the | ||||
| 15150 | ** number of pages. A negative number N translations means that a buffer | ||||
| 15151 | ** of -1024*N bytes is allocated and used for as many pages as it will hold. | ||||
| 15152 | ** | ||||
| 15153 | ** The default value of "20" was chosen to minimize the run-time of the | ||||
| 15154 | ** speedtest1 test program with options: --shrink-memory --reprepare | ||||
| 15155 | */ | ||||
| 15156 | #ifndef SQLITE_DEFAULT_PCACHE_INITSZ20 | ||||
| 15157 | # define SQLITE_DEFAULT_PCACHE_INITSZ20 20 | ||||
| 15158 | #endif | ||||
| 15159 | |||||
| 15160 | /* | ||||
| 15161 | ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option. | ||||
| 15162 | */ | ||||
| 15163 | #ifndef SQLITE_DEFAULT_SORTERREF_SIZE0x7fffffff | ||||
| 15164 | # define SQLITE_DEFAULT_SORTERREF_SIZE0x7fffffff 0x7fffffff | ||||
| 15165 | #endif | ||||
| 15166 | |||||
| 15167 | /* | ||||
| 15168 | ** The compile-time options SQLITE_MMAP_READWRITE and | ||||
| 15169 | ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another. | ||||
| 15170 | ** You must choose one or the other (or neither) but not both. | ||||
| 15171 | */ | ||||
| 15172 | #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) | ||||
| 15173 | #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE | ||||
| 15174 | #endif | ||||
| 15175 | |||||
| 15176 | /* | ||||
| 15177 | ** GCC does not define the offsetof() macro so we'll have to do it | ||||
| 15178 | ** ourselves. | ||||
| 15179 | */ | ||||
| 15180 | #ifndef offsetof | ||||
| 15181 | #define offsetof(STRUCTURE,FIELD)__builtin_offsetof(STRUCTURE, FIELD) ((size_t)((char*)&((STRUCTURE*)0)->FIELD)) | ||||
| 15182 | #endif | ||||
| 15183 | |||||
| 15184 | /* | ||||
| 15185 | ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as | ||||
| 15186 | ** to avoid complaints from -fsanitize=strict-bounds. | ||||
| 15187 | */ | ||||
| 15188 | #if defined(__STDC_VERSION__201710L) && (__STDC_VERSION__201710L >= 199901L) | ||||
| 15189 | # define FLEXARRAY | ||||
| 15190 | #else | ||||
| 15191 | # define FLEXARRAY 1 | ||||
| 15192 | #endif | ||||
| 15193 | |||||
| 15194 | /* | ||||
| 15195 | ** Macros to compute minimum and maximum of two numbers. | ||||
| 15196 | */ | ||||
| 15197 | #ifndef MIN | ||||
| 15198 | # define MIN(A,B)((A)<(B)?(A):(B)) ((A)<(B)?(A):(B)) | ||||
| 15199 | #endif | ||||
| 15200 | #ifndef MAX | ||||
| 15201 | # define MAX(A,B)((A)>(B)?(A):(B)) ((A)>(B)?(A):(B)) | ||||
| 15202 | #endif | ||||
| 15203 | |||||
| 15204 | /* | ||||
| 15205 | ** Swap two objects of type TYPE. | ||||
| 15206 | */ | ||||
| 15207 | #define SWAP(TYPE,A,B){TYPE t=A; A=B; B=t;} {TYPE t=A; A=B; B=t;} | ||||
| 15208 | |||||
| 15209 | /* | ||||
| 15210 | ** Check to see if this machine uses EBCDIC. (Yes, believe it or | ||||
| 15211 | ** not, there are still machines out there that use EBCDIC.) | ||||
| 15212 | */ | ||||
| 15213 | #if 'A' == '\301' | ||||
| 15214 | # define SQLITE_EBCDIC 1 | ||||
| 15215 | #else | ||||
| 15216 | # define SQLITE_ASCII1 1 | ||||
| 15217 | #endif | ||||
| 15218 | |||||
| 15219 | /* | ||||
| 15220 | ** Integers of known sizes. These typedefs might change for architectures | ||||
| 15221 | ** where the sizes very. Preprocessor macros are available so that the | ||||
| 15222 | ** types can be conveniently redefined at compile-type. Like this: | ||||
| 15223 | ** | ||||
| 15224 | ** cc '-DUINTPTR_TYPE=long long int' ... | ||||
| 15225 | */ | ||||
| 15226 | #ifndef UINT32_TYPEunsigned int | ||||
| 15227 | # ifdef HAVE_UINT32_T | ||||
| 15228 | # define UINT32_TYPEunsigned int uint32_t | ||||
| 15229 | # else | ||||
| 15230 | # define UINT32_TYPEunsigned int unsigned int | ||||
| 15231 | # endif | ||||
| 15232 | #endif | ||||
| 15233 | #ifndef UINT16_TYPEunsigned short int | ||||
| 15234 | # ifdef HAVE_UINT16_T | ||||
| 15235 | # define UINT16_TYPEunsigned short int uint16_t | ||||
| 15236 | # else | ||||
| 15237 | # define UINT16_TYPEunsigned short int unsigned short int | ||||
| 15238 | # endif | ||||
| 15239 | #endif | ||||
| 15240 | #ifndef INT16_TYPEshort int | ||||
| 15241 | # ifdef HAVE_INT16_T | ||||
| 15242 | # define INT16_TYPEshort int int16_t | ||||
| 15243 | # else | ||||
| 15244 | # define INT16_TYPEshort int short int | ||||
| 15245 | # endif | ||||
| 15246 | #endif | ||||
| 15247 | #ifndef UINT8_TYPEunsigned char | ||||
| 15248 | # ifdef HAVE_UINT8_T | ||||
| 15249 | # define UINT8_TYPEunsigned char uint8_t | ||||
| 15250 | # else | ||||
| 15251 | # define UINT8_TYPEunsigned char unsigned char | ||||
| 15252 | # endif | ||||
| 15253 | #endif | ||||
| 15254 | #ifndef INT8_TYPEsigned char | ||||
| 15255 | # ifdef HAVE_INT8_T | ||||
| 15256 | # define INT8_TYPEsigned char int8_t | ||||
| 15257 | # else | ||||
| 15258 | # define INT8_TYPEsigned char signed char | ||||
| 15259 | # endif | ||||
| 15260 | #endif | ||||
| 15261 | typedef sqlite_int64 i64; /* 8-byte signed integer */ | ||||
| 15262 | typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ | ||||
| 15263 | typedef UINT32_TYPEunsigned int u32; /* 4-byte unsigned integer */ | ||||
| 15264 | typedef UINT16_TYPEunsigned short int u16; /* 2-byte unsigned integer */ | ||||
| 15265 | typedef INT16_TYPEshort int i16; /* 2-byte signed integer */ | ||||
| 15266 | typedef UINT8_TYPEunsigned char u8; /* 1-byte unsigned integer */ | ||||
| 15267 | typedef INT8_TYPEsigned char i8; /* 1-byte signed integer */ | ||||
| 15268 | |||||
| 15269 | /* A bitfield type for use inside of structures. Always follow with :N where | ||||
| 15270 | ** N is the number of bits. | ||||
| 15271 | */ | ||||
| 15272 | typedef unsigned bft; /* Bit Field Type */ | ||||
| 15273 | |||||
| 15274 | /* | ||||
| 15275 | ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value | ||||
| 15276 | ** that can be stored in a u32 without loss of data. The value | ||||
| 15277 | ** is 0x00000000ffffffff. But because of quirks of some compilers, we | ||||
| 15278 | ** have to specify the value in the less intuitive manner shown: | ||||
| 15279 | */ | ||||
| 15280 | #define SQLITE_MAX_U32((((u64)1)<<32)-1) ((((u64)1)<<32)-1) | ||||
| 15281 | |||||
| 15282 | /* | ||||
| 15283 | ** The datatype used to store estimates of the number of rows in a | ||||
| 15284 | ** table or index. | ||||
| 15285 | */ | ||||
| 15286 | typedef u64 tRowcnt; | ||||
| 15287 | |||||
| 15288 | /* | ||||
| 15289 | ** Estimated quantities used for query planning are stored as 16-bit | ||||
| 15290 | ** logarithms. For quantity X, the value stored is 10*log2(X). This | ||||
| 15291 | ** gives a possible range of values of approximately 1.0e986 to 1e-986. | ||||
| 15292 | ** But the allowed values are "grainy". Not every value is representable. | ||||
| 15293 | ** For example, quantities 16 and 17 are both represented by a LogEst | ||||
| 15294 | ** of 40. However, since LogEst quantities are suppose to be estimates, | ||||
| 15295 | ** not exact values, this imprecision is not a problem. | ||||
| 15296 | ** | ||||
| 15297 | ** "LogEst" is short for "Logarithmic Estimate". | ||||
| 15298 | ** | ||||
| 15299 | ** Examples: | ||||
| 15300 | ** 1 -> 0 20 -> 43 10000 -> 132 | ||||
| 15301 | ** 2 -> 10 25 -> 46 25000 -> 146 | ||||
| 15302 | ** 3 -> 16 100 -> 66 1000000 -> 199 | ||||
| 15303 | ** 4 -> 20 1000 -> 99 1048576 -> 200 | ||||
| 15304 | ** 10 -> 33 1024 -> 100 4294967296 -> 320 | ||||
| 15305 | ** | ||||
| 15306 | ** The LogEst can be negative to indicate fractional values. | ||||
| 15307 | ** Examples: | ||||
| 15308 | ** | ||||
| 15309 | ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40 | ||||
| 15310 | */ | ||||
| 15311 | typedef INT16_TYPEshort int LogEst; | ||||
| 15312 | #define LOGEST_MIN(-32768) (-32768) | ||||
| 15313 | #define LOGEST_MAX(32767) (32767) | ||||
| 15314 | |||||
| 15315 | /* | ||||
| 15316 | ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer | ||||
| 15317 | */ | ||||
| 15318 | #ifndef SQLITE_PTRSIZE8 | ||||
| 15319 | # if defined(__SIZEOF_POINTER__8) | ||||
| 15320 | # define SQLITE_PTRSIZE8 __SIZEOF_POINTER__8 | ||||
| 15321 | # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \ | ||||
| 15322 | defined(_M_ARM) || defined(__arm__) || defined(__x86) || \ | ||||
| 15323 | (defined(__APPLE__) && defined(__ppc__)) || \ | ||||
| 15324 | (defined(__TOS_AIX__) && !defined(__64BIT__)) | ||||
| 15325 | # define SQLITE_PTRSIZE8 4 | ||||
| 15326 | # else | ||||
| 15327 | # define SQLITE_PTRSIZE8 8 | ||||
| 15328 | # endif | ||||
| 15329 | #endif | ||||
| 15330 | |||||
| 15331 | /* The uptr type is an unsigned integer large enough to hold a pointer | ||||
| 15332 | */ | ||||
| 15333 | #if defined(HAVE_STDINT_H) | ||||
| 15334 | typedef uintptr_t uptr; | ||||
| 15335 | #elif SQLITE_PTRSIZE8==4 | ||||
| 15336 | typedef u32 uptr; | ||||
| 15337 | #else | ||||
| 15338 | typedef u64 uptr; | ||||
| 15339 | #endif | ||||
| 15340 | |||||
| 15341 | /* | ||||
| 15342 | ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to | ||||
| 15343 | ** something between S (inclusive) and E (exclusive). | ||||
| 15344 | ** | ||||
| 15345 | ** In other words, S is a buffer and E is a pointer to the first byte after | ||||
| 15346 | ** the end of buffer S. This macro returns true if P points to something | ||||
| 15347 | ** contained within the buffer S. | ||||
| 15348 | */ | ||||
| 15349 | #define SQLITE_WITHIN(P,S,E)(((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E))) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E))) | ||||
| 15350 | |||||
| 15351 | /* | ||||
| 15352 | ** P is one byte past the end of a large buffer. Return true if a span of bytes | ||||
| 15353 | ** between S..E crosses the end of that buffer. In other words, return true | ||||
| 15354 | ** if the sub-buffer S..E-1 overflows the buffer whose last byte is P-1. | ||||
| 15355 | ** | ||||
| 15356 | ** S is the start of the span. E is one byte past the end of end of span. | ||||
| 15357 | ** | ||||
| 15358 | ** P | ||||
| 15359 | ** |-----------------| FALSE | ||||
| 15360 | ** |-------| | ||||
| 15361 | ** S E | ||||
| 15362 | ** | ||||
| 15363 | ** P | ||||
| 15364 | ** |-----------------| | ||||
| 15365 | ** |-------| TRUE | ||||
| 15366 | ** S E | ||||
| 15367 | ** | ||||
| 15368 | ** P | ||||
| 15369 | ** |-----------------| | ||||
| 15370 | ** |-------| FALSE | ||||
| 15371 | ** S E | ||||
| 15372 | */ | ||||
| 15373 | #define SQLITE_OVERFLOW(P,S,E)(((uptr)(S)<(uptr)(P))&&((uptr)(E)>(uptr)(P))) (((uptr)(S)<(uptr)(P))&&((uptr)(E)>(uptr)(P))) | ||||
| 15374 | |||||
| 15375 | /* | ||||
| 15376 | ** Macros to determine whether the machine is big or little endian, | ||||
| 15377 | ** and whether or not that determination is run-time or compile-time. | ||||
| 15378 | ** | ||||
| 15379 | ** For best performance, an attempt is made to guess at the byte-order | ||||
| 15380 | ** using C-preprocessor macros. If that is unsuccessful, or if | ||||
| 15381 | ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined | ||||
| 15382 | ** at run-time. | ||||
| 15383 | ** | ||||
| 15384 | ** If you are building SQLite on some obscure platform for which the | ||||
| 15385 | ** following ifdef magic does not work, you can always include either: | ||||
| 15386 | ** | ||||
| 15387 | ** -DSQLITE_BYTEORDER=1234 | ||||
| 15388 | ** | ||||
| 15389 | ** or | ||||
| 15390 | ** | ||||
| 15391 | ** -DSQLITE_BYTEORDER=4321 | ||||
| 15392 | ** | ||||
| 15393 | ** to cause the build to work for little-endian or big-endian processors, | ||||
| 15394 | ** respectively. | ||||
| 15395 | */ | ||||
| 15396 | #ifndef SQLITE_BYTEORDER1234 /* Replicate changes at tag-20230904a */ | ||||
| 15397 | # if defined(__BYTE_ORDER__1234) && __BYTE_ORDER__1234==__ORDER_BIG_ENDIAN__4321 | ||||
| 15398 | # define SQLITE_BYTEORDER1234 4321 | ||||
| 15399 | # elif defined(__BYTE_ORDER__1234) && __BYTE_ORDER__1234==__ORDER_LITTLE_ENDIAN__1234 | ||||
| 15400 | # define SQLITE_BYTEORDER1234 1234 | ||||
| 15401 | # elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1 | ||||
| 15402 | # define SQLITE_BYTEORDER1234 4321 | ||||
| 15403 | # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \ | ||||
| 15404 | defined(__x86_641) || defined(__x86_64__1) || defined(_M_X64) || \ | ||||
| 15405 | defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ | ||||
| 15406 | defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64) | ||||
| 15407 | # define SQLITE_BYTEORDER1234 1234 | ||||
| 15408 | # elif defined(sparc) || defined(__ARMEB__) || defined(__AARCH64EB__) | ||||
| 15409 | # define SQLITE_BYTEORDER1234 4321 | ||||
| 15410 | # else | ||||
| 15411 | # define SQLITE_BYTEORDER1234 0 | ||||
| 15412 | # endif | ||||
| 15413 | #endif | ||||
| 15414 | #if SQLITE_BYTEORDER1234==4321 | ||||
| 15415 | # define SQLITE_BIGENDIAN0 1 | ||||
| 15416 | # define SQLITE_LITTLEENDIAN1 0 | ||||
| 15417 | # define SQLITE_UTF16NATIVE2 SQLITE_UTF16BE3 | ||||
| 15418 | #elif SQLITE_BYTEORDER1234==1234 | ||||
| 15419 | # define SQLITE_BIGENDIAN0 0 | ||||
| 15420 | # define SQLITE_LITTLEENDIAN1 1 | ||||
| 15421 | # define SQLITE_UTF16NATIVE2 SQLITE_UTF16LE2 | ||||
| 15422 | #else | ||||
| 15423 | # ifdef SQLITE_AMALGAMATION1 | ||||
| 15424 | const int sqlite3one = 1; | ||||
| 15425 | # else | ||||
| 15426 | extern const int sqlite3one; | ||||
| 15427 | # endif | ||||
| 15428 | # define SQLITE_BIGENDIAN0 (*(char *)(&sqlite3one)==0) | ||||
| 15429 | # define SQLITE_LITTLEENDIAN1 (*(char *)(&sqlite3one)==1) | ||||
| 15430 | # define SQLITE_UTF16NATIVE2 (SQLITE_BIGENDIAN0?SQLITE_UTF16BE3:SQLITE_UTF16LE2) | ||||
| 15431 | #endif | ||||
| 15432 | |||||
| 15433 | /* | ||||
| 15434 | ** Constants for the largest and smallest possible 64-bit signed integers. | ||||
| 15435 | ** These macros are designed to work correctly on both 32-bit and 64-bit | ||||
| 15436 | ** compilers. | ||||
| 15437 | */ | ||||
| 15438 | #define LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)) (0xffffffff|(((i64)0x7fffffff)<<32)) | ||||
| 15439 | #define LARGEST_UINT64(0xffffffff|(((u64)0xffffffff)<<32)) (0xffffffff|(((u64)0xffffffff)<<32)) | ||||
| 15440 | #define SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32))) (((i64)-1) - LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32))) | ||||
| 15441 | |||||
| 15442 | /* | ||||
| 15443 | ** Macro SMXV(n) return the maximum value that can be held in variable n, | ||||
| 15444 | ** assuming n is a signed integer type. UMXV(n) is similar for unsigned | ||||
| 15445 | ** integer types. | ||||
| 15446 | */ | ||||
| 15447 | #define SMXV(n)((((i64)1)<<(sizeof(n)*8-1))-1) ((((i64)1)<<(sizeof(n)*8-1))-1) | ||||
| 15448 | #define UMXV(n)((((i64)1)<<(sizeof(n)*8))-1) ((((i64)1)<<(sizeof(n)*8))-1) | ||||
| 15449 | |||||
| 15450 | /* | ||||
| 15451 | ** Round up a number to the next larger multiple of 8. This is used | ||||
| 15452 | ** to force 8-byte alignment on 64-bit architectures. | ||||
| 15453 | ** | ||||
| 15454 | ** ROUND8() always does the rounding, for any argument. | ||||
| 15455 | ** | ||||
| 15456 | ** ROUND8P() assumes that the argument is already an integer number of | ||||
| 15457 | ** pointers in size, and so it is a no-op on systems where the pointer | ||||
| 15458 | ** size is 8. | ||||
| 15459 | */ | ||||
| 15460 | #define ROUND8(x)(((x)+7)&~7) (((x)+7)&~7) | ||||
| 15461 | #if SQLITE_PTRSIZE8==8 | ||||
| 15462 | # define ROUND8P(x)(x) (x) | ||||
| 15463 | #else | ||||
| 15464 | # define ROUND8P(x)(x) (((x)+7)&~7) | ||||
| 15465 | #endif | ||||
| 15466 | |||||
| 15467 | /* | ||||
| 15468 | ** Round down to the nearest multiple of 8 | ||||
| 15469 | */ | ||||
| 15470 | #define ROUNDDOWN8(x)((x)&~7) ((x)&~7) | ||||
| 15471 | |||||
| 15472 | /* | ||||
| 15473 | ** Assert that the pointer X is aligned to an 8-byte boundary. This | ||||
| 15474 | ** macro is used only within assert() to verify that the code gets | ||||
| 15475 | ** all alignment restrictions correct. | ||||
| 15476 | ** | ||||
| 15477 | ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the | ||||
| 15478 | ** underlying malloc() implementation might return us 4-byte aligned | ||||
| 15479 | ** pointers. In that case, only verify 4-byte alignment. | ||||
| 15480 | */ | ||||
| 15481 | #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC | ||||
| 15482 | # define EIGHT_BYTE_ALIGNMENT(X)((((uptr)(X) - (uptr)0)&7)==0) ((((uptr)(X) - (uptr)0)&3)==0) | ||||
| 15483 | #else | ||||
| 15484 | # define EIGHT_BYTE_ALIGNMENT(X)((((uptr)(X) - (uptr)0)&7)==0) ((((uptr)(X) - (uptr)0)&7)==0) | ||||
| 15485 | #endif | ||||
| 15486 | |||||
| 15487 | /* | ||||
| 15488 | ** Disable MMAP on platforms where it is known to not work | ||||
| 15489 | */ | ||||
| 15490 | #if defined(__OpenBSD__) || defined(__QNXNTO__) | ||||
| 15491 | # undef SQLITE_MAX_MMAP_SIZE20971520 | ||||
| 15492 | # define SQLITE_MAX_MMAP_SIZE20971520 0 | ||||
| 15493 | #endif | ||||
| 15494 | |||||
| 15495 | /* | ||||
| 15496 | ** Default maximum size of memory used by memory-mapped I/O in the VFS | ||||
| 15497 | */ | ||||
| 15498 | #ifdef __APPLE__ | ||||
| 15499 | # include <TargetConditionals.h> | ||||
| 15500 | #endif | ||||
| 15501 | #ifndef SQLITE_MAX_MMAP_SIZE20971520 | ||||
| 15502 | # if defined(__linux__1) \ | ||||
| 15503 | || defined(_WIN32) \ | ||||
| 15504 | || (defined(__APPLE__) && defined(__MACH__)) \ | ||||
| 15505 | || defined(__sun) \ | ||||
| 15506 | || defined(__FreeBSD__) \ | ||||
| 15507 | || defined(__DragonFly__) | ||||
| 15508 | # define SQLITE_MAX_MMAP_SIZE20971520 0x7fff0000 /* 2147418112 */ | ||||
| 15509 | # else | ||||
| 15510 | # define SQLITE_MAX_MMAP_SIZE20971520 0 | ||||
| 15511 | # endif | ||||
| 15512 | #endif | ||||
| 15513 | |||||
| 15514 | /* | ||||
| 15515 | ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger | ||||
| 15516 | ** default MMAP_SIZE is specified at compile-time, make sure that it does | ||||
| 15517 | ** not exceed the maximum mmap size. | ||||
| 15518 | */ | ||||
| 15519 | #ifndef SQLITE_DEFAULT_MMAP_SIZE0 | ||||
| 15520 | # define SQLITE_DEFAULT_MMAP_SIZE0 0 | ||||
| 15521 | #endif | ||||
| 15522 | #if SQLITE_DEFAULT_MMAP_SIZE0>SQLITE_MAX_MMAP_SIZE20971520 | ||||
| 15523 | # undef SQLITE_DEFAULT_MMAP_SIZE0 | ||||
| 15524 | # define SQLITE_DEFAULT_MMAP_SIZE0 SQLITE_MAX_MMAP_SIZE20971520 | ||||
| 15525 | #endif | ||||
| 15526 | |||||
| 15527 | /* | ||||
| 15528 | ** TREETRACE_ENABLED will be either 1 or 0 depending on whether or not | ||||
| 15529 | ** the Abstract Syntax Tree tracing logic is turned on. | ||||
| 15530 | */ | ||||
| 15531 | #if !defined(SQLITE_AMALGAMATION1) | ||||
| 15532 | SQLITE_PRIVATEstatic u32 sqlite3TreeTrace; | ||||
| 15533 | #endif | ||||
| 15534 | #if defined(SQLITE_DEBUG) \ | ||||
| 15535 | && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE) \ | ||||
| 15536 | || defined(SQLITE_ENABLE_TREETRACE)) | ||||
| 15537 | # define TREETRACE_ENABLED0 1 | ||||
| 15538 | # define TREETRACE(K,P,S,X) \ | ||||
| 15539 | if(sqlite3TreeTrace&(K)) \ | ||||
| 15540 | sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\ | ||||
| 15541 | sqlite3DebugPrintf X | ||||
| 15542 | #else | ||||
| 15543 | # define TREETRACE(K,P,S,X) | ||||
| 15544 | # define TREETRACE_ENABLED0 0 | ||||
| 15545 | #endif | ||||
| 15546 | |||||
| 15547 | /* TREETRACE flag meanings: | ||||
| 15548 | ** | ||||
| 15549 | ** 0x00000001 Beginning and end of SELECT processing | ||||
| 15550 | ** 0x00000002 WHERE clause processing | ||||
| 15551 | ** 0x00000004 Query flattener | ||||
| 15552 | ** 0x00000008 Result-set wildcard expansion | ||||
| 15553 | ** 0x00000010 Query name resolution | ||||
| 15554 | ** 0x00000020 Aggregate analysis | ||||
| 15555 | ** 0x00000040 Window functions | ||||
| 15556 | ** 0x00000080 Generated column names | ||||
| 15557 | ** 0x00000100 Move HAVING terms into WHERE | ||||
| 15558 | ** 0x00000200 Count-of-view optimization | ||||
| 15559 | ** 0x00000400 Compound SELECT processing | ||||
| 15560 | ** 0x00000800 Drop superfluous ORDER BY | ||||
| 15561 | ** 0x00001000 LEFT JOIN simplifies to JOIN | ||||
| 15562 | ** 0x00002000 Constant propagation | ||||
| 15563 | ** 0x00004000 Push-down optimization | ||||
| 15564 | ** 0x00008000 After all FROM-clause analysis | ||||
| 15565 | ** 0x00010000 Beginning of DELETE/INSERT/UPDATE processing | ||||
| 15566 | ** 0x00020000 Transform DISTINCT into GROUP BY | ||||
| 15567 | ** 0x00040000 SELECT tree dump after all code has been generated | ||||
| 15568 | ** 0x00080000 NOT NULL strength reduction | ||||
| 15569 | */ | ||||
| 15570 | |||||
| 15571 | /* | ||||
| 15572 | ** Macros for "wheretrace" | ||||
| 15573 | */ | ||||
| 15574 | SQLITE_PRIVATEstatic u32 sqlite3WhereTrace; | ||||
| 15575 | #if defined(SQLITE_DEBUG) \ | ||||
| 15576 | && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) | ||||
| 15577 | # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X | ||||
| 15578 | # define WHERETRACE_ENABLED 1 | ||||
| 15579 | #else | ||||
| 15580 | # define WHERETRACE(K,X) | ||||
| 15581 | #endif | ||||
| 15582 | |||||
| 15583 | /* | ||||
| 15584 | ** Bits for the sqlite3WhereTrace mask: | ||||
| 15585 | ** | ||||
| 15586 | ** (---any--) Top-level block structure | ||||
| 15587 | ** 0x-------F High-level debug messages | ||||
| 15588 | ** 0x----FFF- More detail | ||||
| 15589 | ** 0xFFFF---- Low-level debug messages | ||||
| 15590 | ** | ||||
| 15591 | ** 0x00000001 Code generation | ||||
| 15592 | ** 0x00000002 Solver (Use 0x40000 for less detail) | ||||
| 15593 | ** 0x00000004 Solver costs | ||||
| 15594 | ** 0x00000008 WhereLoop inserts | ||||
| 15595 | ** | ||||
| 15596 | ** 0x00000010 Display sqlite3_index_info xBestIndex calls | ||||
| 15597 | ** 0x00000020 Range an equality scan metrics | ||||
| 15598 | ** 0x00000040 IN operator decisions | ||||
| 15599 | ** 0x00000080 WhereLoop cost adjustments | ||||
| 15600 | ** 0x00000100 | ||||
| 15601 | ** 0x00000200 Covering index decisions | ||||
| 15602 | ** 0x00000400 OR optimization | ||||
| 15603 | ** 0x00000800 Index scanner | ||||
| 15604 | ** 0x00001000 More details associated with code generation | ||||
| 15605 | ** 0x00002000 | ||||
| 15606 | ** 0x00004000 Show all WHERE terms at key points | ||||
| 15607 | ** 0x00008000 Show the full SELECT statement at key places | ||||
| 15608 | ** | ||||
| 15609 | ** 0x00010000 Show more detail when printing WHERE terms | ||||
| 15610 | ** 0x00020000 Show WHERE terms returned from whereScanNext() | ||||
| 15611 | ** 0x00040000 Solver overview messages | ||||
| 15612 | ** 0x00080000 Star-query heuristic | ||||
| 15613 | */ | ||||
| 15614 | |||||
| 15615 | |||||
| 15616 | /* | ||||
| 15617 | ** An instance of the following structure is used to store the busy-handler | ||||
| 15618 | ** callback for a given sqlite handle. | ||||
| 15619 | ** | ||||
| 15620 | ** The sqlite.busyHandler member of the sqlite struct contains the busy | ||||
| 15621 | ** callback for the database handle. Each pager opened via the sqlite | ||||
| 15622 | ** handle is passed a pointer to sqlite.busyHandler. The busy-handler | ||||
| 15623 | ** callback is currently invoked only from within pager.c. | ||||
| 15624 | */ | ||||
| 15625 | typedef struct BusyHandler BusyHandler; | ||||
| 15626 | struct BusyHandler { | ||||
| 15627 | int (*xBusyHandler)(void *,int); /* The busy callback */ | ||||
| 15628 | void *pBusyArg; /* First arg to busy callback */ | ||||
| 15629 | int nBusy; /* Incremented with each busy call */ | ||||
| 15630 | }; | ||||
| 15631 | |||||
| 15632 | /* | ||||
| 15633 | ** Name of table that holds the database schema. | ||||
| 15634 | ** | ||||
| 15635 | ** The PREFERRED names are used wherever possible. But LEGACY is also | ||||
| 15636 | ** used for backwards compatibility. | ||||
| 15637 | ** | ||||
| 15638 | ** 1. Queries can use either the PREFERRED or the LEGACY names | ||||
| 15639 | ** 2. The sqlite3_set_authorizer() callback uses the LEGACY name | ||||
| 15640 | ** 3. The PRAGMA table_list statement uses the PREFERRED name | ||||
| 15641 | ** | ||||
| 15642 | ** The LEGACY names are stored in the internal symbol hash table | ||||
| 15643 | ** in support of (2). Names are translated using sqlite3PreferredTableName() | ||||
| 15644 | ** for (3). The sqlite3FindTable() function takes care of translating | ||||
| 15645 | ** names for (1). | ||||
| 15646 | ** | ||||
| 15647 | ** Note that "sqlite_temp_schema" can also be called "temp.sqlite_schema". | ||||
| 15648 | */ | ||||
| 15649 | #define LEGACY_SCHEMA_TABLE"sqlite_master" "sqlite_master" | ||||
| 15650 | #define LEGACY_TEMP_SCHEMA_TABLE"sqlite_temp_master" "sqlite_temp_master" | ||||
| 15651 | #define PREFERRED_SCHEMA_TABLE"sqlite_schema" "sqlite_schema" | ||||
| 15652 | #define PREFERRED_TEMP_SCHEMA_TABLE"sqlite_temp_schema" "sqlite_temp_schema" | ||||
| 15653 | |||||
| 15654 | |||||
| 15655 | /* | ||||
| 15656 | ** The root-page of the schema table. | ||||
| 15657 | */ | ||||
| 15658 | #define SCHEMA_ROOT1 1 | ||||
| 15659 | |||||
| 15660 | /* | ||||
| 15661 | ** The name of the schema table. The name is different for TEMP. | ||||
| 15662 | */ | ||||
| 15663 | #define SCHEMA_TABLE(x)((!0)&&(x==1)?"sqlite_temp_master":"sqlite_master") \ | ||||
| 15664 | ((!OMIT_TEMPDB0)&&(x==1)?LEGACY_TEMP_SCHEMA_TABLE"sqlite_temp_master":LEGACY_SCHEMA_TABLE"sqlite_master") | ||||
| 15665 | |||||
| 15666 | /* | ||||
| 15667 | ** A convenience macro that returns the number of elements in | ||||
| 15668 | ** an array. | ||||
| 15669 | */ | ||||
| 15670 | #define ArraySize(X)((int)(sizeof(X)/sizeof(X[0]))) ((int)(sizeof(X)/sizeof(X[0]))) | ||||
| 15671 | |||||
| 15672 | /* | ||||
| 15673 | ** Determine if the argument is a power of two | ||||
| 15674 | */ | ||||
| 15675 | #define IsPowerOfTwo(X)(((X)&((X)-1))==0) (((X)&((X)-1))==0) | ||||
| 15676 | |||||
| 15677 | /* | ||||
| 15678 | ** The following value as a destructor means to use sqlite3DbFree(). | ||||
| 15679 | ** The sqlite3DbFree() routine requires two parameters instead of the | ||||
| 15680 | ** one parameter that destructors normally want. So we have to introduce | ||||
| 15681 | ** this magic value that the code knows to handle differently. Any | ||||
| 15682 | ** pointer will work here as long as it is distinct from SQLITE_STATIC | ||||
| 15683 | ** and SQLITE_TRANSIENT. | ||||
| 15684 | */ | ||||
| 15685 | #define SQLITE_DYNAMIC((sqlite3_destructor_type)sqlite3OomClear) ((sqlite3_destructor_type)sqlite3OomClear) | ||||
| 15686 | |||||
| 15687 | /* | ||||
| 15688 | ** When SQLITE_OMIT_WSD is defined, it means that the target platform does | ||||
| 15689 | ** not support Writable Static Data (WSD) such as global and static variables. | ||||
| 15690 | ** All variables must either be on the stack or dynamically allocated from | ||||
| 15691 | ** the heap. When WSD is unsupported, the variable declarations scattered | ||||
| 15692 | ** throughout the SQLite code must become constants instead. The SQLITE_WSD | ||||
| 15693 | ** macro is used for this purpose. And instead of referencing the variable | ||||
| 15694 | ** directly, we use its constant as a key to lookup the run-time allocated | ||||
| 15695 | ** buffer that holds real variable. The constant is also the initializer | ||||
| 15696 | ** for the run-time allocated buffer. | ||||
| 15697 | ** | ||||
| 15698 | ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL | ||||
| 15699 | ** macros become no-ops and have zero performance impact. | ||||
| 15700 | */ | ||||
| 15701 | #ifdef SQLITE_OMIT_WSD | ||||
| 15702 | #define SQLITE_WSD const | ||||
| 15703 | #define GLOBAL(t,v)v (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) | ||||
| 15704 | #define sqlite3GlobalConfigsqlite3Config GLOBAL(struct Sqlite3Config, sqlite3Config)sqlite3Config | ||||
| 15705 | SQLITE_API int sqlite3_wsd_init(int N, int J); | ||||
| 15706 | SQLITE_API void *sqlite3_wsd_find(void *K, int L); | ||||
| 15707 | #else | ||||
| 15708 | #define SQLITE_WSD | ||||
| 15709 | #define GLOBAL(t,v)v v | ||||
| 15710 | #define sqlite3GlobalConfigsqlite3Config sqlite3Config | ||||
| 15711 | #endif | ||||
| 15712 | |||||
| 15713 | /* | ||||
| 15714 | ** The following macros are used to suppress compiler warnings and to | ||||
| 15715 | ** make it clear to human readers when a function parameter is deliberately | ||||
| 15716 | ** left unused within the body of a function. This usually happens when | ||||
| 15717 | ** a function is called via a function pointer. For example the | ||||
| 15718 | ** implementation of an SQL aggregate step callback may not use the | ||||
| 15719 | ** parameter indicating the number of arguments passed to the aggregate, | ||||
| 15720 | ** if it knows that this is enforced elsewhere. | ||||
| 15721 | ** | ||||
| 15722 | ** When a function parameter is not used at all within the body of a function, | ||||
| 15723 | ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. | ||||
| 15724 | ** However, these macros may also be used to suppress warnings related to | ||||
| 15725 | ** parameters that may or may not be used depending on compilation options. | ||||
| 15726 | ** For example those parameters only used in assert() statements. In these | ||||
| 15727 | ** cases the parameters are named as per the usual conventions. | ||||
| 15728 | */ | ||||
| 15729 | #define UNUSED_PARAMETER(x)(void)(x) (void)(x) | ||||
| 15730 | #define UNUSED_PARAMETER2(x,y)(void)(x),(void)(y) UNUSED_PARAMETER(x)(void)(x),UNUSED_PARAMETER(y)(void)(y) | ||||
| 15731 | |||||
| 15732 | /* | ||||
| 15733 | ** Forward references to structures | ||||
| 15734 | */ | ||||
| 15735 | typedef struct AggInfo AggInfo; | ||||
| 15736 | typedef struct AuthContext AuthContext; | ||||
| 15737 | typedef struct AutoincInfo AutoincInfo; | ||||
| 15738 | typedef struct Bitvec Bitvec; | ||||
| 15739 | typedef struct CollSeq CollSeq; | ||||
| 15740 | typedef struct Column Column; | ||||
| 15741 | typedef struct Cte Cte; | ||||
| 15742 | typedef struct CteUse CteUse; | ||||
| 15743 | typedef struct Db Db; | ||||
| 15744 | typedef struct DbClientData DbClientData; | ||||
| 15745 | typedef struct DbFixer DbFixer; | ||||
| 15746 | typedef struct Schema Schema; | ||||
| 15747 | typedef struct Expr Expr; | ||||
| 15748 | typedef struct ExprList ExprList; | ||||
| 15749 | typedef struct FKey FKey; | ||||
| 15750 | typedef struct FpDecode FpDecode; | ||||
| 15751 | typedef struct FuncDestructor FuncDestructor; | ||||
| 15752 | typedef struct FuncDef FuncDef; | ||||
| 15753 | typedef struct FuncDefHash FuncDefHash; | ||||
| 15754 | typedef struct IdList IdList; | ||||
| 15755 | typedef struct Index Index; | ||||
| 15756 | typedef struct IndexedExpr IndexedExpr; | ||||
| 15757 | typedef struct IndexSample IndexSample; | ||||
| 15758 | typedef struct KeyClass KeyClass; | ||||
| 15759 | typedef struct KeyInfo KeyInfo; | ||||
| 15760 | typedef struct Lookaside Lookaside; | ||||
| 15761 | typedef struct LookasideSlot LookasideSlot; | ||||
| 15762 | typedef struct Module Module; | ||||
| 15763 | typedef struct NameContext NameContext; | ||||
| 15764 | typedef struct OnOrUsing OnOrUsing; | ||||
| 15765 | typedef struct Parse Parse; | ||||
| 15766 | typedef struct ParseCleanup ParseCleanup; | ||||
| 15767 | typedef struct PreUpdate PreUpdate; | ||||
| 15768 | typedef struct PrintfArguments PrintfArguments; | ||||
| 15769 | typedef struct RCStr RCStr; | ||||
| 15770 | typedef struct RenameToken RenameToken; | ||||
| 15771 | typedef struct Returning Returning; | ||||
| 15772 | typedef struct RowSet RowSet; | ||||
| 15773 | typedef struct Savepoint Savepoint; | ||||
| 15774 | typedef struct Select Select; | ||||
| 15775 | typedef struct SQLiteThread SQLiteThread; | ||||
| 15776 | typedef struct SelectDest SelectDest; | ||||
| 15777 | typedef struct Subquery Subquery; | ||||
| 15778 | typedef struct SrcItem SrcItem; | ||||
| 15779 | typedef struct SrcList SrcList; | ||||
| 15780 | typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */ | ||||
| 15781 | typedef struct Table Table; | ||||
| 15782 | typedef struct TableLock TableLock; | ||||
| 15783 | typedef struct Token Token; | ||||
| 15784 | typedef struct TreeView TreeView; | ||||
| 15785 | typedef struct Trigger Trigger; | ||||
| 15786 | typedef struct TriggerPrg TriggerPrg; | ||||
| 15787 | typedef struct TriggerStep TriggerStep; | ||||
| 15788 | typedef struct UnpackedRecord UnpackedRecord; | ||||
| 15789 | typedef struct Upsert Upsert; | ||||
| 15790 | typedef struct VTable VTable; | ||||
| 15791 | typedef struct VtabCtx VtabCtx; | ||||
| 15792 | typedef struct Walker Walker; | ||||
| 15793 | typedef struct WhereInfo WhereInfo; | ||||
| 15794 | typedef struct Window Window; | ||||
| 15795 | typedef struct With With; | ||||
| 15796 | |||||
| 15797 | |||||
| 15798 | /* | ||||
| 15799 | ** The bitmask datatype defined below is used for various optimizations. | ||||
| 15800 | ** | ||||
| 15801 | ** Changing this from a 64-bit to a 32-bit type limits the number of | ||||
| 15802 | ** tables in a join to 32 instead of 64. But it also reduces the size | ||||
| 15803 | ** of the library by 738 bytes on ix86. | ||||
| 15804 | */ | ||||
| 15805 | #ifdef SQLITE_BITMASK_TYPE | ||||
| 15806 | typedef SQLITE_BITMASK_TYPE Bitmask; | ||||
| 15807 | #else | ||||
| 15808 | typedef u64 Bitmask; | ||||
| 15809 | #endif | ||||
| 15810 | |||||
| 15811 | /* | ||||
| 15812 | ** The number of bits in a Bitmask. "BMS" means "BitMask Size". | ||||
| 15813 | */ | ||||
| 15814 | #define BMS((int)(sizeof(Bitmask)*8)) ((int)(sizeof(Bitmask)*8)) | ||||
| 15815 | |||||
| 15816 | /* | ||||
| 15817 | ** A bit in a Bitmask | ||||
| 15818 | */ | ||||
| 15819 | #define MASKBIT(n)(((Bitmask)1)<<(n)) (((Bitmask)1)<<(n)) | ||||
| 15820 | #define MASKBIT64(n)(((u64)1)<<(n)) (((u64)1)<<(n)) | ||||
| 15821 | #define MASKBIT32(n)(((unsigned int)1)<<(n)) (((unsigned int)1)<<(n)) | ||||
| 15822 | #define SMASKBIT32(n)((n)<=31?((unsigned int)1)<<(n):0) ((n)<=31?((unsigned int)1)<<(n):0) | ||||
| 15823 | #define ALLBITS((Bitmask)-1) ((Bitmask)-1) | ||||
| 15824 | #define TOPBIT(((Bitmask)1)<<(((int)(sizeof(Bitmask)*8))-1)) (((Bitmask)1)<<(BMS((int)(sizeof(Bitmask)*8))-1)) | ||||
| 15825 | |||||
| 15826 | /* A VList object records a mapping between parameters/variables/wildcards | ||||
| 15827 | ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer | ||||
| 15828 | ** variable number associated with that parameter. See the format description | ||||
| 15829 | ** on the sqlite3VListAdd() routine for more information. A VList is really | ||||
| 15830 | ** just an array of integers. | ||||
| 15831 | */ | ||||
| 15832 | typedef int VList; | ||||
| 15833 | |||||
| 15834 | /* | ||||
| 15835 | ** Defer sourcing vdbe.h and btree.h until after the "u8" and | ||||
| 15836 | ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque | ||||
| 15837 | ** pointer types (i.e. FuncDef) defined above. | ||||
| 15838 | */ | ||||
| 15839 | /************** Include os.h in the middle of sqliteInt.h ********************/ | ||||
| 15840 | /************** Begin file os.h **********************************************/ | ||||
| 15841 | /* | ||||
| 15842 | ** 2001 September 16 | ||||
| 15843 | ** | ||||
| 15844 | ** The author disclaims copyright to this source code. In place of | ||||
| 15845 | ** a legal notice, here is a blessing: | ||||
| 15846 | ** | ||||
| 15847 | ** May you do good and not evil. | ||||
| 15848 | ** May you find forgiveness for yourself and forgive others. | ||||
| 15849 | ** May you share freely, never taking more than you give. | ||||
| 15850 | ** | ||||
| 15851 | ****************************************************************************** | ||||
| 15852 | ** | ||||
| 15853 | ** This header file (together with is companion C source-code file | ||||
| 15854 | ** "os.c") attempt to abstract the underlying operating system so that | ||||
| 15855 | ** the SQLite library will work on both POSIX and windows systems. | ||||
| 15856 | ** | ||||
| 15857 | ** This header file is #include-ed by sqliteInt.h and thus ends up | ||||
| 15858 | ** being included by every source file. | ||||
| 15859 | */ | ||||
| 15860 | #ifndef _SQLITE_OS_H_ | ||||
| 15861 | #define _SQLITE_OS_H_ | ||||
| 15862 | |||||
| 15863 | /* | ||||
| 15864 | ** Attempt to automatically detect the operating system and setup the | ||||
| 15865 | ** necessary pre-processor macros for it. | ||||
| 15866 | */ | ||||
| 15867 | /************** Include os_setup.h in the middle of os.h *********************/ | ||||
| 15868 | /************** Begin file os_setup.h ****************************************/ | ||||
| 15869 | /* | ||||
| 15870 | ** 2013 November 25 | ||||
| 15871 | ** | ||||
| 15872 | ** The author disclaims copyright to this source code. In place of | ||||
| 15873 | ** a legal notice, here is a blessing: | ||||
| 15874 | ** | ||||
| 15875 | ** May you do good and not evil. | ||||
| 15876 | ** May you find forgiveness for yourself and forgive others. | ||||
| 15877 | ** May you share freely, never taking more than you give. | ||||
| 15878 | ** | ||||
| 15879 | ****************************************************************************** | ||||
| 15880 | ** | ||||
| 15881 | ** This file contains pre-processor directives related to operating system | ||||
| 15882 | ** detection and/or setup. | ||||
| 15883 | */ | ||||
| 15884 | #ifndef SQLITE_OS_SETUP_H | ||||
| 15885 | #define SQLITE_OS_SETUP_H | ||||
| 15886 | |||||
| 15887 | /* | ||||
| 15888 | ** Figure out if we are dealing with Unix, Windows, or some other operating | ||||
| 15889 | ** system. | ||||
| 15890 | ** | ||||
| 15891 | ** After the following block of preprocess macros, all of | ||||
| 15892 | ** | ||||
| 15893 | ** SQLITE_OS_KV | ||||
| 15894 | ** SQLITE_OS_OTHER | ||||
| 15895 | ** SQLITE_OS_UNIX | ||||
| 15896 | ** SQLITE_OS_WIN | ||||
| 15897 | ** | ||||
| 15898 | ** will defined to either 1 or 0. One of them will be 1. The others will be 0. | ||||
| 15899 | ** If none of the macros are initially defined, then select either | ||||
| 15900 | ** SQLITE_OS_UNIX or SQLITE_OS_WIN depending on the target platform. | ||||
| 15901 | ** | ||||
| 15902 | ** If SQLITE_OS_OTHER=1 is specified at compile-time, then the application | ||||
| 15903 | ** must provide its own VFS implementation together with sqlite3_os_init() | ||||
| 15904 | ** and sqlite3_os_end() routines. | ||||
| 15905 | */ | ||||
| 15906 | #if !defined(SQLITE_OS_KV0) && !defined(SQLITE_OS_OTHER0) && \ | ||||
| 15907 | !defined(SQLITE_OS_UNIX1) && !defined(SQLITE_OS_WIN0) | ||||
| 15908 | # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \ | ||||
| 15909 | defined(__MINGW32__) || defined(__BORLANDC__) | ||||
| 15910 | # define SQLITE_OS_WIN0 1 | ||||
| 15911 | # define SQLITE_OS_UNIX1 0 | ||||
| 15912 | # else | ||||
| 15913 | # define SQLITE_OS_WIN0 0 | ||||
| 15914 | # define SQLITE_OS_UNIX1 1 | ||||
| 15915 | # endif | ||||
| 15916 | #endif | ||||
| 15917 | #if SQLITE_OS_OTHER0+1>1 | ||||
| 15918 | # undef SQLITE_OS_KV0 | ||||
| 15919 | # define SQLITE_OS_KV0 0 | ||||
| 15920 | # undef SQLITE_OS_UNIX1 | ||||
| 15921 | # define SQLITE_OS_UNIX1 0 | ||||
| 15922 | # undef SQLITE_OS_WIN0 | ||||
| 15923 | # define SQLITE_OS_WIN0 0 | ||||
| 15924 | #endif | ||||
| 15925 | #if SQLITE_OS_KV0+1>1 | ||||
| 15926 | # undef SQLITE_OS_OTHER0 | ||||
| 15927 | # define SQLITE_OS_OTHER0 0 | ||||
| 15928 | # undef SQLITE_OS_UNIX1 | ||||
| 15929 | # define SQLITE_OS_UNIX1 0 | ||||
| 15930 | # undef SQLITE_OS_WIN0 | ||||
| 15931 | # define SQLITE_OS_WIN0 0 | ||||
| 15932 | # define SQLITE_OMIT_LOAD_EXTENSION1 1 | ||||
| 15933 | # define SQLITE_OMIT_WAL 1 | ||||
| 15934 | # define SQLITE_OMIT_DEPRECATED1 1 | ||||
| 15935 | # undef SQLITE_TEMP_STORE1 | ||||
| 15936 | # define SQLITE_TEMP_STORE1 3 /* Always use memory for temporary storage */ | ||||
| 15937 | # define SQLITE_DQS0 0 | ||||
| 15938 | # define SQLITE_OMIT_SHARED_CACHE 1 | ||||
| 15939 | # define SQLITE_OMIT_AUTOINIT 1 | ||||
| 15940 | #endif | ||||
| 15941 | #if SQLITE_OS_UNIX1+1>1 | ||||
| 15942 | # undef SQLITE_OS_KV0 | ||||
| 15943 | # define SQLITE_OS_KV0 0 | ||||
| 15944 | # undef SQLITE_OS_OTHER0 | ||||
| 15945 | # define SQLITE_OS_OTHER0 0 | ||||
| 15946 | # undef SQLITE_OS_WIN0 | ||||
| 15947 | # define SQLITE_OS_WIN0 0 | ||||
| 15948 | #endif | ||||
| 15949 | #if SQLITE_OS_WIN0+1>1 | ||||
| 15950 | # undef SQLITE_OS_KV0 | ||||
| 15951 | # define SQLITE_OS_KV0 0 | ||||
| 15952 | # undef SQLITE_OS_OTHER0 | ||||
| 15953 | # define SQLITE_OS_OTHER0 0 | ||||
| 15954 | # undef SQLITE_OS_UNIX1 | ||||
| 15955 | # define SQLITE_OS_UNIX1 0 | ||||
| 15956 | #endif | ||||
| 15957 | |||||
| 15958 | |||||
| 15959 | #endif /* SQLITE_OS_SETUP_H */ | ||||
| 15960 | |||||
| 15961 | /************** End of os_setup.h ********************************************/ | ||||
| 15962 | /************** Continuing where we left off in os.h *************************/ | ||||
| 15963 | |||||
| 15964 | /* If the SET_FULLSYNC macro is not defined above, then make it | ||||
| 15965 | ** a no-op | ||||
| 15966 | */ | ||||
| 15967 | #ifndef SET_FULLSYNC | ||||
| 15968 | # define SET_FULLSYNC(x,y) | ||||
| 15969 | #endif | ||||
| 15970 | |||||
| 15971 | /* Maximum pathname length. Note: FILENAME_MAX defined by stdio.h | ||||
| 15972 | */ | ||||
| 15973 | #ifndef SQLITE_MAX_PATHLEN4096 | ||||
| 15974 | # define SQLITE_MAX_PATHLEN4096 FILENAME_MAX4096 | ||||
| 15975 | #endif | ||||
| 15976 | |||||
| 15977 | /* Maximum number of symlinks that will be resolved while trying to | ||||
| 15978 | ** expand a filename in xFullPathname() in the VFS. | ||||
| 15979 | */ | ||||
| 15980 | #ifndef SQLITE_MAX_SYMLINK200 | ||||
| 15981 | # define SQLITE_MAX_SYMLINK200 200 | ||||
| 15982 | #endif | ||||
| 15983 | |||||
| 15984 | /* | ||||
| 15985 | ** The default size of a disk sector | ||||
| 15986 | */ | ||||
| 15987 | #ifndef SQLITE_DEFAULT_SECTOR_SIZE4096 | ||||
| 15988 | # define SQLITE_DEFAULT_SECTOR_SIZE4096 4096 | ||||
| 15989 | #endif | ||||
| 15990 | |||||
| 15991 | /* | ||||
| 15992 | ** Temporary files are named starting with this prefix followed by 16 random | ||||
| 15993 | ** alphanumeric characters, and no file extension. They are stored in the | ||||
| 15994 | ** OS's standard temporary file directory, and are deleted prior to exit. | ||||
| 15995 | ** If sqlite is being embedded in another program, you may wish to change the | ||||
| 15996 | ** prefix to reflect your program's name, so that if your program exits | ||||
| 15997 | ** prematurely, old temporary files can be easily identified. This can be done | ||||
| 15998 | ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. | ||||
| 15999 | ** | ||||
| 16000 | ** 2006-10-31: The default prefix used to be "sqlite_". But then | ||||
| 16001 | ** Mcafee started using SQLite in their anti-virus product and it | ||||
| 16002 | ** started putting files with the "sqlite" name in the c:/temp folder. | ||||
| 16003 | ** This annoyed many windows users. Those users would then do a | ||||
| 16004 | ** Google search for "sqlite", find the telephone numbers of the | ||||
| 16005 | ** developers and call to wake them up at night and complain. | ||||
| 16006 | ** For this reason, the default name prefix is changed to be "sqlite" | ||||
| 16007 | ** spelled backwards. So the temp files are still identified, but | ||||
| 16008 | ** anybody smart enough to figure out the code is also likely smart | ||||
| 16009 | ** enough to know that calling the developer will not help get rid | ||||
| 16010 | ** of the file. | ||||
| 16011 | */ | ||||
| 16012 | #ifndef SQLITE_TEMP_FILE_PREFIX"etilqs_" | ||||
| 16013 | # define SQLITE_TEMP_FILE_PREFIX"etilqs_" "etilqs_" | ||||
| 16014 | #endif | ||||
| 16015 | |||||
| 16016 | /* | ||||
| 16017 | ** The following values may be passed as the second argument to | ||||
| 16018 | ** sqlite3OsLock(). The various locks exhibit the following semantics: | ||||
| 16019 | ** | ||||
| 16020 | ** SHARED: Any number of processes may hold a SHARED lock simultaneously. | ||||
| 16021 | ** RESERVED: A single process may hold a RESERVED lock on a file at | ||||
| 16022 | ** any time. Other processes may hold and obtain new SHARED locks. | ||||
| 16023 | ** PENDING: A single process may hold a PENDING lock on a file at | ||||
| 16024 | ** any one time. Existing SHARED locks may persist, but no new | ||||
| 16025 | ** SHARED locks may be obtained by other processes. | ||||
| 16026 | ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. | ||||
| 16027 | ** | ||||
| 16028 | ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a | ||||
| 16029 | ** process that requests an EXCLUSIVE lock may actually obtain a PENDING | ||||
| 16030 | ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to | ||||
| 16031 | ** sqlite3OsLock(). | ||||
| 16032 | */ | ||||
| 16033 | #define NO_LOCK0 0 | ||||
| 16034 | #define SHARED_LOCK1 1 | ||||
| 16035 | #define RESERVED_LOCK2 2 | ||||
| 16036 | #define PENDING_LOCK3 3 | ||||
| 16037 | #define EXCLUSIVE_LOCK4 4 | ||||
| 16038 | |||||
| 16039 | /* | ||||
| 16040 | ** File Locking Notes: (Mostly about windows but also some info for Unix) | ||||
| 16041 | ** | ||||
| 16042 | ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because | ||||
| 16043 | ** those functions are not available. So we use only LockFile() and | ||||
| 16044 | ** UnlockFile(). | ||||
| 16045 | ** | ||||
| 16046 | ** LockFile() prevents not just writing but also reading by other processes. | ||||
| 16047 | ** A SHARED_LOCK is obtained by locking a single randomly-chosen | ||||
| 16048 | ** byte out of a specific range of bytes. The lock byte is obtained at | ||||
| 16049 | ** random so two separate readers can probably access the file at the | ||||
| 16050 | ** same time, unless they are unlucky and choose the same lock byte. | ||||
| 16051 | ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. | ||||
| 16052 | ** There can only be one writer. A RESERVED_LOCK is obtained by locking | ||||
| 16053 | ** a single byte of the file that is designated as the reserved lock byte. | ||||
| 16054 | ** A PENDING_LOCK is obtained by locking a designated byte different from | ||||
| 16055 | ** the RESERVED_LOCK byte. | ||||
| 16056 | ** | ||||
| 16057 | ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, | ||||
| 16058 | ** which means we can use reader/writer locks. When reader/writer locks | ||||
| 16059 | ** are used, the lock is placed on the same range of bytes that is used | ||||
| 16060 | ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme | ||||
| 16061 | ** will support two or more Win95 readers or two or more WinNT readers. | ||||
| 16062 | ** But a single Win95 reader will lock out all WinNT readers and a single | ||||
| 16063 | ** WinNT reader will lock out all other Win95 readers. | ||||
| 16064 | ** | ||||
| 16065 | ** The following #defines specify the range of bytes used for locking. | ||||
| 16066 | ** SHARED_SIZE is the number of bytes available in the pool from which | ||||
| 16067 | ** a random byte is selected for a shared lock. The pool of bytes for | ||||
| 16068 | ** shared locks begins at SHARED_FIRST. | ||||
| 16069 | ** | ||||
| 16070 | ** The same locking strategy and | ||||
| 16071 | ** byte ranges are used for Unix. This leaves open the possibility of having | ||||
| 16072 | ** clients on win95, winNT, and unix all talking to the same shared file | ||||
| 16073 | ** and all locking correctly. To do so would require that samba (or whatever | ||||
| 16074 | ** tool is being used for file sharing) implements locks correctly between | ||||
| 16075 | ** windows and unix. I'm guessing that isn't likely to happen, but by | ||||
| 16076 | ** using the same locking range we are at least open to the possibility. | ||||
| 16077 | ** | ||||
| 16078 | ** Locking in windows is manditory. For this reason, we cannot store | ||||
| 16079 | ** actual data in the bytes used for locking. The pager never allocates | ||||
| 16080 | ** the pages involved in locking therefore. SHARED_SIZE is selected so | ||||
| 16081 | ** that all locks will fit on a single page even at the minimum page size. | ||||
| 16082 | ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE | ||||
| 16083 | ** is set high so that we don't have to allocate an unused page except | ||||
| 16084 | ** for very large databases. But one should test the page skipping logic | ||||
| 16085 | ** by setting PENDING_BYTE low and running the entire regression suite. | ||||
| 16086 | ** | ||||
| 16087 | ** Changing the value of PENDING_BYTE results in a subtly incompatible | ||||
| 16088 | ** file format. Depending on how it is changed, you might not notice | ||||
| 16089 | ** the incompatibility right away, even running a full regression test. | ||||
| 16090 | ** The default location of PENDING_BYTE is the first byte past the | ||||
| 16091 | ** 1GB boundary. | ||||
| 16092 | ** | ||||
| 16093 | */ | ||||
| 16094 | #ifdef SQLITE_OMIT_WSD | ||||
| 16095 | # define PENDING_BYTEsqlite3PendingByte (0x40000000) | ||||
| 16096 | #else | ||||
| 16097 | # define PENDING_BYTEsqlite3PendingByte sqlite3PendingByte | ||||
| 16098 | #endif | ||||
| 16099 | #define RESERVED_BYTE(sqlite3PendingByte+1) (PENDING_BYTEsqlite3PendingByte+1) | ||||
| 16100 | #define SHARED_FIRST(sqlite3PendingByte+2) (PENDING_BYTEsqlite3PendingByte+2) | ||||
| 16101 | #define SHARED_SIZE510 510 | ||||
| 16102 | |||||
| 16103 | /* | ||||
| 16104 | ** Wrapper around OS specific sqlite3_os_init() function. | ||||
| 16105 | */ | ||||
| 16106 | SQLITE_PRIVATEstatic int sqlite3OsInit(void); | ||||
| 16107 | |||||
| 16108 | /* | ||||
| 16109 | ** Functions for accessing sqlite3_file methods | ||||
| 16110 | */ | ||||
| 16111 | SQLITE_PRIVATEstatic void sqlite3OsClose(sqlite3_file*); | ||||
| 16112 | SQLITE_PRIVATEstatic int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); | ||||
| 16113 | SQLITE_PRIVATEstatic int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); | ||||
| 16114 | SQLITE_PRIVATEstatic int sqlite3OsTruncate(sqlite3_file*, i64 size); | ||||
| 16115 | SQLITE_PRIVATEstatic int sqlite3OsSync(sqlite3_file*, int); | ||||
| 16116 | SQLITE_PRIVATEstatic int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); | ||||
| 16117 | SQLITE_PRIVATEstatic int sqlite3OsLock(sqlite3_file*, int); | ||||
| 16118 | SQLITE_PRIVATEstatic int sqlite3OsUnlock(sqlite3_file*, int); | ||||
| 16119 | SQLITE_PRIVATEstatic int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); | ||||
| 16120 | SQLITE_PRIVATEstatic int sqlite3OsFileControl(sqlite3_file*,int,void*); | ||||
| 16121 | SQLITE_PRIVATEstatic void sqlite3OsFileControlHint(sqlite3_file*,int,void*); | ||||
| 16122 | #define SQLITE_FCNTL_DB_UNCHANGED0xca093fa0 0xca093fa0 | ||||
| 16123 | SQLITE_PRIVATEstatic int sqlite3OsSectorSize(sqlite3_file *id); | ||||
| 16124 | SQLITE_PRIVATEstatic int sqlite3OsDeviceCharacteristics(sqlite3_file *id); | ||||
| 16125 | #ifndef SQLITE_OMIT_WAL | ||||
| 16126 | SQLITE_PRIVATEstatic int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); | ||||
| 16127 | SQLITE_PRIVATEstatic int sqlite3OsShmLock(sqlite3_file *id, int, int, int); | ||||
| 16128 | SQLITE_PRIVATEstatic void sqlite3OsShmBarrier(sqlite3_file *id); | ||||
| 16129 | SQLITE_PRIVATEstatic int sqlite3OsShmUnmap(sqlite3_file *id, int); | ||||
| 16130 | #endif /* SQLITE_OMIT_WAL */ | ||||
| 16131 | SQLITE_PRIVATEstatic int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); | ||||
| 16132 | SQLITE_PRIVATEstatic int sqlite3OsUnfetch(sqlite3_file *, i64, void *); | ||||
| 16133 | |||||
| 16134 | |||||
| 16135 | /* | ||||
| 16136 | ** Functions for accessing sqlite3_vfs methods | ||||
| 16137 | */ | ||||
| 16138 | SQLITE_PRIVATEstatic int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); | ||||
| 16139 | SQLITE_PRIVATEstatic int sqlite3OsDelete(sqlite3_vfs *, const char *, int); | ||||
| 16140 | SQLITE_PRIVATEstatic int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); | ||||
| 16141 | SQLITE_PRIVATEstatic int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); | ||||
| 16142 | #ifndef SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 16143 | SQLITE_PRIVATEstatic void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); | ||||
| 16144 | SQLITE_PRIVATEstatic void sqlite3OsDlError(sqlite3_vfs *, int, char *); | ||||
| 16145 | SQLITE_PRIVATEstatic void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); | ||||
| 16146 | SQLITE_PRIVATEstatic void sqlite3OsDlClose(sqlite3_vfs *, void *); | ||||
| 16147 | #endif /* SQLITE_OMIT_LOAD_EXTENSION */ | ||||
| 16148 | SQLITE_PRIVATEstatic int sqlite3OsRandomness(sqlite3_vfs *, int, char *); | ||||
| 16149 | SQLITE_PRIVATEstatic int sqlite3OsSleep(sqlite3_vfs *, int); | ||||
| 16150 | SQLITE_PRIVATEstatic int sqlite3OsGetLastError(sqlite3_vfs*); | ||||
| 16151 | SQLITE_PRIVATEstatic int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); | ||||
| 16152 | |||||
| 16153 | /* | ||||
| 16154 | ** Convenience functions for opening and closing files using | ||||
| 16155 | ** sqlite3_malloc() to obtain space for the file-handle structure. | ||||
| 16156 | */ | ||||
| 16157 | SQLITE_PRIVATEstatic int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); | ||||
| 16158 | SQLITE_PRIVATEstatic void sqlite3OsCloseFree(sqlite3_file *); | ||||
| 16159 | |||||
| 16160 | #endif /* _SQLITE_OS_H_ */ | ||||
| 16161 | |||||
| 16162 | /************** End of os.h **************************************************/ | ||||
| 16163 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 16164 | /************** Include pager.h in the middle of sqliteInt.h *****************/ | ||||
| 16165 | /************** Begin file pager.h *******************************************/ | ||||
| 16166 | /* | ||||
| 16167 | ** 2001 September 15 | ||||
| 16168 | ** | ||||
| 16169 | ** The author disclaims copyright to this source code. In place of | ||||
| 16170 | ** a legal notice, here is a blessing: | ||||
| 16171 | ** | ||||
| 16172 | ** May you do good and not evil. | ||||
| 16173 | ** May you find forgiveness for yourself and forgive others. | ||||
| 16174 | ** May you share freely, never taking more than you give. | ||||
| 16175 | ** | ||||
| 16176 | ************************************************************************* | ||||
| 16177 | ** This header file defines the interface that the sqlite page cache | ||||
| 16178 | ** subsystem. The page cache subsystem reads and writes a file a page | ||||
| 16179 | ** at a time and provides a journal for rollback. | ||||
| 16180 | */ | ||||
| 16181 | |||||
| 16182 | #ifndef SQLITE_PAGER_H | ||||
| 16183 | #define SQLITE_PAGER_H | ||||
| 16184 | |||||
| 16185 | /* | ||||
| 16186 | ** Default maximum size for persistent journal files. A negative | ||||
| 16187 | ** value means no limit. This value may be overridden using the | ||||
| 16188 | ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". | ||||
| 16189 | */ | ||||
| 16190 | #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT32768 | ||||
| 16191 | #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT32768 -1 | ||||
| 16192 | #endif | ||||
| 16193 | |||||
| 16194 | /* | ||||
| 16195 | ** The type used to represent a page number. The first page in a file | ||||
| 16196 | ** is called page 1. 0 is used to represent "not a page". | ||||
| 16197 | */ | ||||
| 16198 | typedef u32 Pgno; | ||||
| 16199 | |||||
| 16200 | /* | ||||
| 16201 | ** Each open file is managed by a separate instance of the "Pager" structure. | ||||
| 16202 | */ | ||||
| 16203 | typedef struct Pager Pager; | ||||
| 16204 | |||||
| 16205 | /* | ||||
| 16206 | ** Handle type for pages. | ||||
| 16207 | */ | ||||
| 16208 | typedef struct PgHdr DbPage; | ||||
| 16209 | |||||
| 16210 | /* | ||||
| 16211 | ** Page number PAGER_SJ_PGNO is never used in an SQLite database (it is | ||||
| 16212 | ** reserved for working around a windows/posix incompatibility). It is | ||||
| 16213 | ** used in the journal to signify that the remainder of the journal file | ||||
| 16214 | ** is devoted to storing a super-journal name - there are no more pages to | ||||
| 16215 | ** roll back. See comments for function writeSuperJournal() in pager.c | ||||
| 16216 | ** for details. | ||||
| 16217 | */ | ||||
| 16218 | #define PAGER_SJ_PGNO_COMPUTED(x)((Pgno)((sqlite3PendingByte/((x)->pageSize))+1)) ((Pgno)((PENDING_BYTEsqlite3PendingByte/((x)->pageSize))+1)) | ||||
| 16219 | #define PAGER_SJ_PGNO(x)((x)->lckPgno) ((x)->lckPgno) | ||||
| 16220 | |||||
| 16221 | /* | ||||
| 16222 | ** Allowed values for the flags parameter to sqlite3PagerOpen(). | ||||
| 16223 | ** | ||||
| 16224 | ** NOTE: These values must match the corresponding BTREE_ values in btree.h. | ||||
| 16225 | */ | ||||
| 16226 | #define PAGER_OMIT_JOURNAL0x0001 0x0001 /* Do not use a rollback journal */ | ||||
| 16227 | #define PAGER_MEMORY0x0002 0x0002 /* In-memory database */ | ||||
| 16228 | |||||
| 16229 | /* | ||||
| 16230 | ** Valid values for the second argument to sqlite3PagerLockingMode(). | ||||
| 16231 | */ | ||||
| 16232 | #define PAGER_LOCKINGMODE_QUERY-1 -1 | ||||
| 16233 | #define PAGER_LOCKINGMODE_NORMAL0 0 | ||||
| 16234 | #define PAGER_LOCKINGMODE_EXCLUSIVE1 1 | ||||
| 16235 | |||||
| 16236 | /* | ||||
| 16237 | ** Numeric constants that encode the journalmode. | ||||
| 16238 | ** | ||||
| 16239 | ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY) | ||||
| 16240 | ** are exposed in the API via the "PRAGMA journal_mode" command and | ||||
| 16241 | ** therefore cannot be changed without a compatibility break. | ||||
| 16242 | */ | ||||
| 16243 | #define PAGER_JOURNALMODE_QUERY(-1) (-1) /* Query the value of journalmode */ | ||||
| 16244 | #define PAGER_JOURNALMODE_DELETE0 0 /* Commit by deleting journal file */ | ||||
| 16245 | #define PAGER_JOURNALMODE_PERSIST1 1 /* Commit by zeroing journal header */ | ||||
| 16246 | #define PAGER_JOURNALMODE_OFF2 2 /* Journal omitted. */ | ||||
| 16247 | #define PAGER_JOURNALMODE_TRUNCATE3 3 /* Commit by truncating journal */ | ||||
| 16248 | #define PAGER_JOURNALMODE_MEMORY4 4 /* In-memory journal file */ | ||||
| 16249 | #define PAGER_JOURNALMODE_WAL5 5 /* Use write-ahead logging */ | ||||
| 16250 | |||||
| 16251 | #define isWalMode(x)((x)==5) ((x)==PAGER_JOURNALMODE_WAL5) | ||||
| 16252 | |||||
| 16253 | /* | ||||
| 16254 | ** The argument to this macro is a file descriptor (type sqlite3_file*). | ||||
| 16255 | ** Return 0 if it is not open, or non-zero (but not 1) if it is. | ||||
| 16256 | ** | ||||
| 16257 | ** This is so that expressions can be written as: | ||||
| 16258 | ** | ||||
| 16259 | ** if( isOpen(pPager->jfd) ){ ... | ||||
| 16260 | ** | ||||
| 16261 | ** instead of | ||||
| 16262 | ** | ||||
| 16263 | ** if( pPager->jfd->pMethods ){ ... | ||||
| 16264 | */ | ||||
| 16265 | #define isOpen(pFd)((pFd)->pMethods!=0) ((pFd)->pMethods!=0) | ||||
| 16266 | |||||
| 16267 | /* | ||||
| 16268 | ** Flags that make up the mask passed to sqlite3PagerGet(). | ||||
| 16269 | */ | ||||
| 16270 | #define PAGER_GET_NOCONTENT0x01 0x01 /* Do not load data from disk */ | ||||
| 16271 | #define PAGER_GET_READONLY0x02 0x02 /* Read-only page is acceptable */ | ||||
| 16272 | |||||
| 16273 | /* | ||||
| 16274 | ** Flags for sqlite3PagerSetFlags() | ||||
| 16275 | ** | ||||
| 16276 | ** Value constraints (enforced via assert()): | ||||
| 16277 | ** PAGER_FULLFSYNC == SQLITE_FullFSync | ||||
| 16278 | ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync | ||||
| 16279 | ** PAGER_CACHE_SPILL == SQLITE_CacheSpill | ||||
| 16280 | */ | ||||
| 16281 | #define PAGER_SYNCHRONOUS_OFF0x01 0x01 /* PRAGMA synchronous=OFF */ | ||||
| 16282 | #define PAGER_SYNCHRONOUS_NORMAL0x02 0x02 /* PRAGMA synchronous=NORMAL */ | ||||
| 16283 | #define PAGER_SYNCHRONOUS_FULL0x03 0x03 /* PRAGMA synchronous=FULL */ | ||||
| 16284 | #define PAGER_SYNCHRONOUS_EXTRA0x04 0x04 /* PRAGMA synchronous=EXTRA */ | ||||
| 16285 | #define PAGER_SYNCHRONOUS_MASK0x07 0x07 /* Mask for four values above */ | ||||
| 16286 | #define PAGER_FULLFSYNC0x08 0x08 /* PRAGMA fullfsync=ON */ | ||||
| 16287 | #define PAGER_CKPT_FULLFSYNC0x10 0x10 /* PRAGMA checkpoint_fullfsync=ON */ | ||||
| 16288 | #define PAGER_CACHESPILL0x20 0x20 /* PRAGMA cache_spill=ON */ | ||||
| 16289 | #define PAGER_FLAGS_MASK0x38 0x38 /* All above except SYNCHRONOUS */ | ||||
| 16290 | |||||
| 16291 | /* | ||||
| 16292 | ** The remainder of this file contains the declarations of the functions | ||||
| 16293 | ** that make up the Pager sub-system API. See source code comments for | ||||
| 16294 | ** a detailed description of each routine. | ||||
| 16295 | */ | ||||
| 16296 | |||||
| 16297 | /* Open and close a Pager connection. */ | ||||
| 16298 | SQLITE_PRIVATEstatic int sqlite3PagerOpen( | ||||
| 16299 | sqlite3_vfs*, | ||||
| 16300 | Pager **ppPager, | ||||
| 16301 | const char*, | ||||
| 16302 | int, | ||||
| 16303 | int, | ||||
| 16304 | int, | ||||
| 16305 | void(*)(DbPage*) | ||||
| 16306 | ); | ||||
| 16307 | SQLITE_PRIVATEstatic int sqlite3PagerClose(Pager *pPager, sqlite3*); | ||||
| 16308 | SQLITE_PRIVATEstatic int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); | ||||
| 16309 | |||||
| 16310 | /* Functions used to configure a Pager object. */ | ||||
| 16311 | SQLITE_PRIVATEstatic void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *); | ||||
| 16312 | SQLITE_PRIVATEstatic int sqlite3PagerSetPagesize(Pager*, u32*, int); | ||||
| 16313 | SQLITE_PRIVATEstatic Pgno sqlite3PagerMaxPageCount(Pager*, Pgno); | ||||
| 16314 | SQLITE_PRIVATEstatic void sqlite3PagerSetCachesize(Pager*, int); | ||||
| 16315 | SQLITE_PRIVATEstatic int sqlite3PagerSetSpillsize(Pager*, int); | ||||
| 16316 | SQLITE_PRIVATEstatic void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); | ||||
| 16317 | SQLITE_PRIVATEstatic void sqlite3PagerShrink(Pager*); | ||||
| 16318 | SQLITE_PRIVATEstatic void sqlite3PagerSetFlags(Pager*,unsigned); | ||||
| 16319 | SQLITE_PRIVATEstatic int sqlite3PagerLockingMode(Pager *, int); | ||||
| 16320 | SQLITE_PRIVATEstatic int sqlite3PagerSetJournalMode(Pager *, int); | ||||
| 16321 | SQLITE_PRIVATEstatic int sqlite3PagerGetJournalMode(Pager*); | ||||
| 16322 | SQLITE_PRIVATEstatic int sqlite3PagerOkToChangeJournalMode(Pager*); | ||||
| 16323 | SQLITE_PRIVATEstatic i64 sqlite3PagerJournalSizeLimit(Pager *, i64); | ||||
| 16324 | SQLITE_PRIVATEstatic sqlite3_backup **sqlite3PagerBackupPtr(Pager*); | ||||
| 16325 | SQLITE_PRIVATEstatic int sqlite3PagerFlush(Pager*); | ||||
| 16326 | |||||
| 16327 | /* Functions used to obtain and release page references. */ | ||||
| 16328 | SQLITE_PRIVATEstatic int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); | ||||
| 16329 | SQLITE_PRIVATEstatic DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); | ||||
| 16330 | SQLITE_PRIVATEstatic void sqlite3PagerRef(DbPage*); | ||||
| 16331 | SQLITE_PRIVATEstatic void sqlite3PagerUnref(DbPage*); | ||||
| 16332 | SQLITE_PRIVATEstatic void sqlite3PagerUnrefNotNull(DbPage*); | ||||
| 16333 | SQLITE_PRIVATEstatic void sqlite3PagerUnrefPageOne(DbPage*); | ||||
| 16334 | |||||
| 16335 | /* Operations on page references. */ | ||||
| 16336 | SQLITE_PRIVATEstatic int sqlite3PagerWrite(DbPage*); | ||||
| 16337 | SQLITE_PRIVATEstatic void sqlite3PagerDontWrite(DbPage*); | ||||
| 16338 | SQLITE_PRIVATEstatic int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); | ||||
| 16339 | SQLITE_PRIVATEstatic int sqlite3PagerPageRefcount(DbPage*); | ||||
| 16340 | SQLITE_PRIVATEstatic void *sqlite3PagerGetData(DbPage *); | ||||
| 16341 | SQLITE_PRIVATEstatic void *sqlite3PagerGetExtra(DbPage *); | ||||
| 16342 | |||||
| 16343 | /* Functions used to manage pager transactions and savepoints. */ | ||||
| 16344 | SQLITE_PRIVATEstatic void sqlite3PagerPagecount(Pager*, int*); | ||||
| 16345 | SQLITE_PRIVATEstatic int sqlite3PagerBegin(Pager*, int exFlag, int); | ||||
| 16346 | SQLITE_PRIVATEstatic int sqlite3PagerCommitPhaseOne(Pager*,const char *zSuper, int); | ||||
| 16347 | SQLITE_PRIVATEstatic int sqlite3PagerExclusiveLock(Pager*); | ||||
| 16348 | SQLITE_PRIVATEstatic int sqlite3PagerSync(Pager *pPager, const char *zSuper); | ||||
| 16349 | SQLITE_PRIVATEstatic int sqlite3PagerCommitPhaseTwo(Pager*); | ||||
| 16350 | SQLITE_PRIVATEstatic int sqlite3PagerRollback(Pager*); | ||||
| 16351 | SQLITE_PRIVATEstatic int sqlite3PagerOpenSavepoint(Pager *pPager, int n); | ||||
| 16352 | SQLITE_PRIVATEstatic int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); | ||||
| 16353 | SQLITE_PRIVATEstatic int sqlite3PagerSharedLock(Pager *pPager); | ||||
| 16354 | |||||
| 16355 | #ifndef SQLITE_OMIT_WAL | ||||
| 16356 | SQLITE_PRIVATEstatic int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*); | ||||
| 16357 | SQLITE_PRIVATEstatic int sqlite3PagerWalSupported(Pager *pPager); | ||||
| 16358 | SQLITE_PRIVATEstatic int sqlite3PagerWalCallback(Pager *pPager); | ||||
| 16359 | SQLITE_PRIVATEstatic int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); | ||||
| 16360 | SQLITE_PRIVATEstatic int sqlite3PagerCloseWal(Pager *pPager, sqlite3*); | ||||
| 16361 | # ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 16362 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot); | ||||
| 16363 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot); | ||||
| 16364 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotRecover(Pager *pPager); | ||||
| 16365 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot); | ||||
| 16366 | SQLITE_PRIVATEstatic void sqlite3PagerSnapshotUnlock(Pager *pPager); | ||||
| 16367 | # endif | ||||
| 16368 | #endif | ||||
| 16369 | |||||
| 16370 | #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT) | ||||
| 16371 | SQLITE_PRIVATEstatic int sqlite3PagerWalWriteLock(Pager*, int)0; | ||||
| 16372 | SQLITE_PRIVATEstatic void sqlite3PagerWalDb(Pager*, sqlite3*); | ||||
| 16373 | #else | ||||
| 16374 | # define sqlite3PagerWalWriteLock(y,z)0 SQLITE_OK0 | ||||
| 16375 | # define sqlite3PagerWalDb(x,y) | ||||
| 16376 | #endif | ||||
| 16377 | |||||
| 16378 | #ifdef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 16379 | SQLITE_PRIVATEstatic int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno); | ||||
| 16380 | #endif | ||||
| 16381 | |||||
| 16382 | #ifdef SQLITE_ENABLE_ZIPVFS | ||||
| 16383 | SQLITE_PRIVATEstatic int sqlite3PagerWalFramesize(Pager *pPager); | ||||
| 16384 | #endif | ||||
| 16385 | |||||
| 16386 | /* Functions used to query pager state and configuration. */ | ||||
| 16387 | SQLITE_PRIVATEstatic u8 sqlite3PagerIsreadonly(Pager*); | ||||
| 16388 | SQLITE_PRIVATEstatic u32 sqlite3PagerDataVersion(Pager*); | ||||
| 16389 | #ifdef SQLITE_DEBUG | ||||
| 16390 | SQLITE_PRIVATEstatic int sqlite3PagerRefcount(Pager*); | ||||
| 16391 | #endif | ||||
| 16392 | SQLITE_PRIVATEstatic int sqlite3PagerMemUsed(Pager*); | ||||
| 16393 | SQLITE_PRIVATEstatic const char *sqlite3PagerFilename(const Pager*, int); | ||||
| 16394 | SQLITE_PRIVATEstatic sqlite3_vfs *sqlite3PagerVfs(Pager*); | ||||
| 16395 | SQLITE_PRIVATEstatic sqlite3_file *sqlite3PagerFile(Pager*); | ||||
| 16396 | SQLITE_PRIVATEstatic sqlite3_file *sqlite3PagerJrnlFile(Pager*); | ||||
| 16397 | SQLITE_PRIVATEstatic const char *sqlite3PagerJournalname(Pager*); | ||||
| 16398 | SQLITE_PRIVATEstatic void *sqlite3PagerTempSpace(Pager*); | ||||
| 16399 | SQLITE_PRIVATEstatic int sqlite3PagerIsMemdb(Pager*); | ||||
| 16400 | SQLITE_PRIVATEstatic void sqlite3PagerCacheStat(Pager *, int, int, u64*); | ||||
| 16401 | SQLITE_PRIVATEstatic void sqlite3PagerClearCache(Pager*); | ||||
| 16402 | SQLITE_PRIVATEstatic int sqlite3SectorSize(sqlite3_file *); | ||||
| 16403 | |||||
| 16404 | /* Functions used to truncate the database file. */ | ||||
| 16405 | SQLITE_PRIVATEstatic void sqlite3PagerTruncateImage(Pager*,Pgno); | ||||
| 16406 | |||||
| 16407 | SQLITE_PRIVATEstatic void sqlite3PagerRekey(DbPage*, Pgno, u16); | ||||
| 16408 | |||||
| 16409 | /* Functions to support testing and debugging. */ | ||||
| 16410 | #if !defined(NDEBUG1) || defined(SQLITE_TEST) | ||||
| 16411 | SQLITE_PRIVATEstatic Pgno sqlite3PagerPagenumber(DbPage*); | ||||
| 16412 | SQLITE_PRIVATEstatic int sqlite3PagerIswriteable(DbPage*); | ||||
| 16413 | #endif | ||||
| 16414 | #ifdef SQLITE_TEST | ||||
| 16415 | SQLITE_PRIVATEstatic int *sqlite3PagerStats(Pager*); | ||||
| 16416 | SQLITE_PRIVATEstatic void sqlite3PagerRefdump(Pager*); | ||||
| 16417 | void disable_simulated_io_errors(void); | ||||
| 16418 | void enable_simulated_io_errors(void); | ||||
| 16419 | #else | ||||
| 16420 | # define disable_simulated_io_errors() | ||||
| 16421 | # define enable_simulated_io_errors() | ||||
| 16422 | #endif | ||||
| 16423 | |||||
| 16424 | #if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL) | ||||
| 16425 | SQLITE_PRIVATEstatic int sqlite3PagerWalSystemErrno(Pager*); | ||||
| 16426 | #endif | ||||
| 16427 | |||||
| 16428 | #endif /* SQLITE_PAGER_H */ | ||||
| 16429 | |||||
| 16430 | /************** End of pager.h ***********************************************/ | ||||
| 16431 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 16432 | /************** Include btree.h in the middle of sqliteInt.h *****************/ | ||||
| 16433 | /************** Begin file btree.h *******************************************/ | ||||
| 16434 | /* | ||||
| 16435 | ** 2001 September 15 | ||||
| 16436 | ** | ||||
| 16437 | ** The author disclaims copyright to this source code. In place of | ||||
| 16438 | ** a legal notice, here is a blessing: | ||||
| 16439 | ** | ||||
| 16440 | ** May you do good and not evil. | ||||
| 16441 | ** May you find forgiveness for yourself and forgive others. | ||||
| 16442 | ** May you share freely, never taking more than you give. | ||||
| 16443 | ** | ||||
| 16444 | ************************************************************************* | ||||
| 16445 | ** This header file defines the interface that the sqlite B-Tree file | ||||
| 16446 | ** subsystem. See comments in the source code for a detailed description | ||||
| 16447 | ** of what each interface routine does. | ||||
| 16448 | */ | ||||
| 16449 | #ifndef SQLITE_BTREE_H | ||||
| 16450 | #define SQLITE_BTREE_H | ||||
| 16451 | |||||
| 16452 | /* TODO: This definition is just included so other modules compile. It | ||||
| 16453 | ** needs to be revisited. | ||||
| 16454 | */ | ||||
| 16455 | #define SQLITE_N_BTREE_META16 16 | ||||
| 16456 | |||||
| 16457 | /* | ||||
| 16458 | ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise | ||||
| 16459 | ** it must be turned on for each database using "PRAGMA auto_vacuum = 1". | ||||
| 16460 | */ | ||||
| 16461 | #ifndef SQLITE_DEFAULT_AUTOVACUUM0 | ||||
| 16462 | #define SQLITE_DEFAULT_AUTOVACUUM0 0 | ||||
| 16463 | #endif | ||||
| 16464 | |||||
| 16465 | #define BTREE_AUTOVACUUM_NONE0 0 /* Do not do auto-vacuum */ | ||||
| 16466 | #define BTREE_AUTOVACUUM_FULL1 1 /* Do full auto-vacuum */ | ||||
| 16467 | #define BTREE_AUTOVACUUM_INCR2 2 /* Incremental vacuum */ | ||||
| 16468 | |||||
| 16469 | /* | ||||
| 16470 | ** Forward declarations of structure | ||||
| 16471 | */ | ||||
| 16472 | typedef struct Btree Btree; | ||||
| 16473 | typedef struct BtCursor BtCursor; | ||||
| 16474 | typedef struct BtShared BtShared; | ||||
| 16475 | typedef struct BtreePayload BtreePayload; | ||||
| 16476 | |||||
| 16477 | |||||
| 16478 | SQLITE_PRIVATEstatic int sqlite3BtreeOpen( | ||||
| 16479 | sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ | ||||
| 16480 | const char *zFilename, /* Name of database file to open */ | ||||
| 16481 | sqlite3 *db, /* Associated database connection */ | ||||
| 16482 | Btree **ppBtree, /* Return open Btree* here */ | ||||
| 16483 | int flags, /* Flags */ | ||||
| 16484 | int vfsFlags /* Flags passed through to VFS open */ | ||||
| 16485 | ); | ||||
| 16486 | |||||
| 16487 | /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the | ||||
| 16488 | ** following values. | ||||
| 16489 | ** | ||||
| 16490 | ** NOTE: These values must match the corresponding PAGER_ values in | ||||
| 16491 | ** pager.h. | ||||
| 16492 | */ | ||||
| 16493 | #define BTREE_OMIT_JOURNAL1 1 /* Do not create or use a rollback journal */ | ||||
| 16494 | #define BTREE_MEMORY2 2 /* This is an in-memory DB */ | ||||
| 16495 | #define BTREE_SINGLE4 4 /* The file contains at most 1 b-tree */ | ||||
| 16496 | #define BTREE_UNORDERED8 8 /* Use of a hash implementation is OK */ | ||||
| 16497 | |||||
| 16498 | SQLITE_PRIVATEstatic int sqlite3BtreeClose(Btree*); | ||||
| 16499 | SQLITE_PRIVATEstatic int sqlite3BtreeSetCacheSize(Btree*,int); | ||||
| 16500 | SQLITE_PRIVATEstatic int sqlite3BtreeSetSpillSize(Btree*,int); | ||||
| 16501 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 16502 | SQLITE_PRIVATEstatic int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); | ||||
| 16503 | #endif | ||||
| 16504 | SQLITE_PRIVATEstatic int sqlite3BtreeSetPagerFlags(Btree*,unsigned); | ||||
| 16505 | SQLITE_PRIVATEstatic int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); | ||||
| 16506 | SQLITE_PRIVATEstatic int sqlite3BtreeGetPageSize(Btree*); | ||||
| 16507 | SQLITE_PRIVATEstatic Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno); | ||||
| 16508 | SQLITE_PRIVATEstatic Pgno sqlite3BtreeLastPage(Btree*); | ||||
| 16509 | SQLITE_PRIVATEstatic int sqlite3BtreeSecureDelete(Btree*,int); | ||||
| 16510 | SQLITE_PRIVATEstatic int sqlite3BtreeGetRequestedReserve(Btree*); | ||||
| 16511 | SQLITE_PRIVATEstatic int sqlite3BtreeGetReserveNoMutex(Btree *p); | ||||
| 16512 | SQLITE_PRIVATEstatic int sqlite3BtreeSetAutoVacuum(Btree *, int); | ||||
| 16513 | SQLITE_PRIVATEstatic int sqlite3BtreeGetAutoVacuum(Btree *); | ||||
| 16514 | SQLITE_PRIVATEstatic int sqlite3BtreeBeginTrans(Btree*,int,int*); | ||||
| 16515 | SQLITE_PRIVATEstatic int sqlite3BtreeCommitPhaseOne(Btree*, const char*); | ||||
| 16516 | SQLITE_PRIVATEstatic int sqlite3BtreeCommitPhaseTwo(Btree*, int); | ||||
| 16517 | SQLITE_PRIVATEstatic int sqlite3BtreeCommit(Btree*); | ||||
| 16518 | SQLITE_PRIVATEstatic int sqlite3BtreeRollback(Btree*,int,int); | ||||
| 16519 | SQLITE_PRIVATEstatic int sqlite3BtreeBeginStmt(Btree*,int); | ||||
| 16520 | SQLITE_PRIVATEstatic int sqlite3BtreeCreateTable(Btree*, Pgno*, int flags); | ||||
| 16521 | SQLITE_PRIVATEstatic int sqlite3BtreeTxnState(Btree*); | ||||
| 16522 | SQLITE_PRIVATEstatic int sqlite3BtreeIsInBackup(Btree*); | ||||
| 16523 | |||||
| 16524 | SQLITE_PRIVATEstatic void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); | ||||
| 16525 | SQLITE_PRIVATEstatic int sqlite3BtreeSchemaLocked(Btree *pBtree); | ||||
| 16526 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 16527 | SQLITE_PRIVATEstatic int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); | ||||
| 16528 | #endif | ||||
| 16529 | |||||
| 16530 | /* Savepoints are named, nestable SQL transactions mostly implemented */ | ||||
| 16531 | /* in vdbe.c and pager.c See https://sqlite.org/lang_savepoint.html */ | ||||
| 16532 | SQLITE_PRIVATEstatic int sqlite3BtreeSavepoint(Btree *, int, int); | ||||
| 16533 | |||||
| 16534 | /* "Checkpoint" only refers to WAL. See https://sqlite.org/wal.html#ckpt */ | ||||
| 16535 | #ifndef SQLITE_OMIT_WAL | ||||
| 16536 | SQLITE_PRIVATEstatic int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); | ||||
| 16537 | #endif | ||||
| 16538 | |||||
| 16539 | SQLITE_PRIVATEstatic const char *sqlite3BtreeGetFilename(Btree *); | ||||
| 16540 | SQLITE_PRIVATEstatic const char *sqlite3BtreeGetJournalname(Btree *); | ||||
| 16541 | SQLITE_PRIVATEstatic int sqlite3BtreeCopyFile(Btree *, Btree *); | ||||
| 16542 | |||||
| 16543 | SQLITE_PRIVATEstatic int sqlite3BtreeIncrVacuum(Btree *); | ||||
| 16544 | |||||
| 16545 | /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR | ||||
| 16546 | ** of the flags shown below. | ||||
| 16547 | ** | ||||
| 16548 | ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. | ||||
| 16549 | ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data | ||||
| 16550 | ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With | ||||
| 16551 | ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored | ||||
| 16552 | ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL | ||||
| 16553 | ** indices.) | ||||
| 16554 | */ | ||||
| 16555 | #define BTREE_INTKEY1 1 /* Table has only 64-bit signed integer keys */ | ||||
| 16556 | #define BTREE_BLOBKEY2 2 /* Table has keys only - no data */ | ||||
| 16557 | |||||
| 16558 | SQLITE_PRIVATEstatic int sqlite3BtreeDropTable(Btree*, int, int*); | ||||
| 16559 | SQLITE_PRIVATEstatic int sqlite3BtreeClearTable(Btree*, int, i64*); | ||||
| 16560 | SQLITE_PRIVATEstatic int sqlite3BtreeClearTableOfCursor(BtCursor*); | ||||
| 16561 | SQLITE_PRIVATEstatic int sqlite3BtreeTripAllCursors(Btree*, int, int); | ||||
| 16562 | |||||
| 16563 | SQLITE_PRIVATEstatic void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); | ||||
| 16564 | SQLITE_PRIVATEstatic int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); | ||||
| 16565 | |||||
| 16566 | SQLITE_PRIVATEstatic int sqlite3BtreeNewDb(Btree *p); | ||||
| 16567 | |||||
| 16568 | /* | ||||
| 16569 | ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta | ||||
| 16570 | ** should be one of the following values. The integer values are assigned | ||||
| 16571 | ** to constants so that the offset of the corresponding field in an | ||||
| 16572 | ** SQLite database header may be found using the following formula: | ||||
| 16573 | ** | ||||
| 16574 | ** offset = 36 + (idx * 4) | ||||
| 16575 | ** | ||||
| 16576 | ** For example, the free-page-count field is located at byte offset 36 of | ||||
| 16577 | ** the database file header. The incr-vacuum-flag field is located at | ||||
| 16578 | ** byte offset 64 (== 36+4*7). | ||||
| 16579 | ** | ||||
| 16580 | ** The BTREE_DATA_VERSION value is not really a value stored in the header. | ||||
| 16581 | ** It is a read-only number computed by the pager. But we merge it with | ||||
| 16582 | ** the header value access routines since its access pattern is the same. | ||||
| 16583 | ** Call it a "virtual meta value". | ||||
| 16584 | */ | ||||
| 16585 | #define BTREE_FREE_PAGE_COUNT0 0 | ||||
| 16586 | #define BTREE_SCHEMA_VERSION1 1 | ||||
| 16587 | #define BTREE_FILE_FORMAT2 2 | ||||
| 16588 | #define BTREE_DEFAULT_CACHE_SIZE3 3 | ||||
| 16589 | #define BTREE_LARGEST_ROOT_PAGE4 4 | ||||
| 16590 | #define BTREE_TEXT_ENCODING5 5 | ||||
| 16591 | #define BTREE_USER_VERSION6 6 | ||||
| 16592 | #define BTREE_INCR_VACUUM7 7 | ||||
| 16593 | #define BTREE_APPLICATION_ID8 8 | ||||
| 16594 | #define BTREE_DATA_VERSION15 15 /* A virtual meta-value */ | ||||
| 16595 | |||||
| 16596 | /* | ||||
| 16597 | ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint() | ||||
| 16598 | ** interface. | ||||
| 16599 | ** | ||||
| 16600 | ** BTREE_HINT_RANGE (arguments: Expr*, Mem*) | ||||
| 16601 | ** | ||||
| 16602 | ** The first argument is an Expr* (which is guaranteed to be constant for | ||||
| 16603 | ** the lifetime of the cursor) that defines constraints on which rows | ||||
| 16604 | ** might be fetched with this cursor. The Expr* tree may contain | ||||
| 16605 | ** TK_REGISTER nodes that refer to values stored in the array of registers | ||||
| 16606 | ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER | ||||
| 16607 | ** then the value of the node is the value in Mem[pExpr.iTable]. Any | ||||
| 16608 | ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th | ||||
| 16609 | ** column of the b-tree of the cursor. The Expr tree will not contain | ||||
| 16610 | ** any function calls nor subqueries nor references to b-trees other than | ||||
| 16611 | ** the cursor being hinted. | ||||
| 16612 | ** | ||||
| 16613 | ** The design of the _RANGE hint is aid b-tree implementations that try | ||||
| 16614 | ** to prefetch content from remote machines - to provide those | ||||
| 16615 | ** implementations with limits on what needs to be prefetched and thereby | ||||
| 16616 | ** reduce network bandwidth. | ||||
| 16617 | ** | ||||
| 16618 | ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by | ||||
| 16619 | ** standard SQLite. The other hints are provided for extensions that use | ||||
| 16620 | ** the SQLite parser and code generator but substitute their own storage | ||||
| 16621 | ** engine. | ||||
| 16622 | */ | ||||
| 16623 | #define BTREE_HINT_RANGE0 0 /* Range constraints on queries */ | ||||
| 16624 | |||||
| 16625 | /* | ||||
| 16626 | ** Values that may be OR'd together to form the argument to the | ||||
| 16627 | ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint(): | ||||
| 16628 | ** | ||||
| 16629 | ** The BTREE_BULKLOAD flag is set on index cursors when the index is going | ||||
| 16630 | ** to be filled with content that is already in sorted order. | ||||
| 16631 | ** | ||||
| 16632 | ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or | ||||
| 16633 | ** OP_SeekLE opcodes for a range search, but where the range of entries | ||||
| 16634 | ** selected will all have the same key. In other words, the cursor will | ||||
| 16635 | ** be used only for equality key searches. | ||||
| 16636 | ** | ||||
| 16637 | */ | ||||
| 16638 | #define BTREE_BULKLOAD0x00000001 0x00000001 /* Used to full index in sorted order */ | ||||
| 16639 | #define BTREE_SEEK_EQ0x00000002 0x00000002 /* EQ seeks only - no range seeks */ | ||||
| 16640 | |||||
| 16641 | /* | ||||
| 16642 | ** Flags passed as the third argument to sqlite3BtreeCursor(). | ||||
| 16643 | ** | ||||
| 16644 | ** For read-only cursors the wrFlag argument is always zero. For read-write | ||||
| 16645 | ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just | ||||
| 16646 | ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will | ||||
| 16647 | ** only be used by SQLite for the following: | ||||
| 16648 | ** | ||||
| 16649 | ** * to seek to and then delete specific entries, and/or | ||||
| 16650 | ** | ||||
| 16651 | ** * to read values that will be used to create keys that other | ||||
| 16652 | ** BTREE_FORDELETE cursors will seek to and delete. | ||||
| 16653 | ** | ||||
| 16654 | ** The BTREE_FORDELETE flag is an optimization hint. It is not used by | ||||
| 16655 | ** by this, the native b-tree engine of SQLite, but it is available to | ||||
| 16656 | ** alternative storage engines that might be substituted in place of this | ||||
| 16657 | ** b-tree system. For alternative storage engines in which a delete of | ||||
| 16658 | ** the main table row automatically deletes corresponding index rows, | ||||
| 16659 | ** the FORDELETE flag hint allows those alternative storage engines to | ||||
| 16660 | ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK | ||||
| 16661 | ** and DELETE operations as no-ops, and any READ operation against a | ||||
| 16662 | ** FORDELETE cursor may return a null row: 0x01 0x00. | ||||
| 16663 | */ | ||||
| 16664 | #define BTREE_WRCSR0x00000004 0x00000004 /* read-write cursor */ | ||||
| 16665 | #define BTREE_FORDELETE0x00000008 0x00000008 /* Cursor is for seek/delete only */ | ||||
| 16666 | |||||
| 16667 | SQLITE_PRIVATEstatic int sqlite3BtreeCursor( | ||||
| 16668 | Btree*, /* BTree containing table to open */ | ||||
| 16669 | Pgno iTable, /* Index of root page */ | ||||
| 16670 | int wrFlag, /* 1 for writing. 0 for read-only */ | ||||
| 16671 | struct KeyInfo*, /* First argument to compare function */ | ||||
| 16672 | BtCursor *pCursor /* Space to write cursor structure */ | ||||
| 16673 | ); | ||||
| 16674 | SQLITE_PRIVATEstatic BtCursor *sqlite3BtreeFakeValidCursor(void); | ||||
| 16675 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorSize(void); | ||||
| 16676 | #ifdef SQLITE_DEBUG | ||||
| 16677 | SQLITE_PRIVATEstatic int sqlite3BtreeClosesWithCursor(Btree*,BtCursor*); | ||||
| 16678 | #endif | ||||
| 16679 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorZero(BtCursor*); | ||||
| 16680 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned); | ||||
| 16681 | #ifdef SQLITE_ENABLE_CURSOR_HINTS | ||||
| 16682 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorHint(BtCursor*, int, ...); | ||||
| 16683 | #endif | ||||
| 16684 | |||||
| 16685 | SQLITE_PRIVATEstatic int sqlite3BtreeCloseCursor(BtCursor*); | ||||
| 16686 | SQLITE_PRIVATEstatic int sqlite3BtreeTableMoveto( | ||||
| 16687 | BtCursor*, | ||||
| 16688 | i64 intKey, | ||||
| 16689 | int bias, | ||||
| 16690 | int *pRes | ||||
| 16691 | ); | ||||
| 16692 | SQLITE_PRIVATEstatic int sqlite3BtreeIndexMoveto( | ||||
| 16693 | BtCursor*, | ||||
| 16694 | UnpackedRecord *pUnKey, | ||||
| 16695 | int *pRes | ||||
| 16696 | ); | ||||
| 16697 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorHasMoved(BtCursor*); | ||||
| 16698 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorRestore(BtCursor*, int*); | ||||
| 16699 | SQLITE_PRIVATEstatic int sqlite3BtreeDelete(BtCursor*, u8 flags); | ||||
| 16700 | |||||
| 16701 | /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */ | ||||
| 16702 | #define BTREE_SAVEPOSITION0x02 0x02 /* Leave cursor pointing at NEXT or PREV */ | ||||
| 16703 | #define BTREE_AUXDELETE0x04 0x04 /* not the primary delete operation */ | ||||
| 16704 | #define BTREE_APPEND0x08 0x08 /* Insert is likely an append */ | ||||
| 16705 | #define BTREE_PREFORMAT0x80 0x80 /* Inserted data is a preformated cell */ | ||||
| 16706 | |||||
| 16707 | /* An instance of the BtreePayload object describes the content of a single | ||||
| 16708 | ** entry in either an index or table btree. | ||||
| 16709 | ** | ||||
| 16710 | ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain | ||||
| 16711 | ** an arbitrary key and no data. These btrees have pKey,nKey set to the | ||||
| 16712 | ** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem | ||||
| 16713 | ** fields give an array of Mem objects that are a decomposition of the key. | ||||
| 16714 | ** The nMem field might be zero, indicating that no decomposition is available. | ||||
| 16715 | ** | ||||
| 16716 | ** Table btrees (used for rowid tables) contain an integer rowid used as | ||||
| 16717 | ** the key and passed in the nKey field. The pKey field is zero. | ||||
| 16718 | ** pData,nData hold the content of the new entry. nZero extra zero bytes | ||||
| 16719 | ** are appended to the end of the content when constructing the entry. | ||||
| 16720 | ** The aMem,nMem fields are uninitialized for table btrees. | ||||
| 16721 | ** | ||||
| 16722 | ** Field usage summary: | ||||
| 16723 | ** | ||||
| 16724 | ** Table BTrees Index Btrees | ||||
| 16725 | ** | ||||
| 16726 | ** pKey always NULL encoded key | ||||
| 16727 | ** nKey the ROWID length of pKey | ||||
| 16728 | ** pData data not used | ||||
| 16729 | ** aMem not used decomposed key value | ||||
| 16730 | ** nMem not used entries in aMem | ||||
| 16731 | ** nData length of pData not used | ||||
| 16732 | ** nZero extra zeros after pData not used | ||||
| 16733 | ** | ||||
| 16734 | ** This object is used to pass information into sqlite3BtreeInsert(). The | ||||
| 16735 | ** same information used to be passed as five separate parameters. But placing | ||||
| 16736 | ** the information into this object helps to keep the interface more | ||||
| 16737 | ** organized and understandable, and it also helps the resulting code to | ||||
| 16738 | ** run a little faster by using fewer registers for parameter passing. | ||||
| 16739 | */ | ||||
| 16740 | struct BtreePayload { | ||||
| 16741 | const void *pKey; /* Key content for indexes. NULL for tables */ | ||||
| 16742 | sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */ | ||||
| 16743 | const void *pData; /* Data for tables. */ | ||||
| 16744 | sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */ | ||||
| 16745 | u16 nMem; /* Number of aMem[] value. Might be zero */ | ||||
| 16746 | int nData; /* Size of pData. 0 if none. */ | ||||
| 16747 | int nZero; /* Extra zero data appended after pData,nData */ | ||||
| 16748 | }; | ||||
| 16749 | |||||
| 16750 | SQLITE_PRIVATEstatic int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload, | ||||
| 16751 | int flags, int seekResult); | ||||
| 16752 | SQLITE_PRIVATEstatic int sqlite3BtreeFirst(BtCursor*, int *pRes); | ||||
| 16753 | SQLITE_PRIVATEstatic int sqlite3BtreeLast(BtCursor*, int *pRes); | ||||
| 16754 | SQLITE_PRIVATEstatic int sqlite3BtreeNext(BtCursor*, int flags); | ||||
| 16755 | SQLITE_PRIVATEstatic int sqlite3BtreeEof(BtCursor*); | ||||
| 16756 | SQLITE_PRIVATEstatic int sqlite3BtreePrevious(BtCursor*, int flags); | ||||
| 16757 | SQLITE_PRIVATEstatic i64 sqlite3BtreeIntegerKey(BtCursor*); | ||||
| 16758 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorPin(BtCursor*); | ||||
| 16759 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorUnpin(BtCursor*); | ||||
| 16760 | SQLITE_PRIVATEstatic i64 sqlite3BtreeOffset(BtCursor*); | ||||
| 16761 | SQLITE_PRIVATEstatic int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*); | ||||
| 16762 | SQLITE_PRIVATEstatic const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt); | ||||
| 16763 | SQLITE_PRIVATEstatic u32 sqlite3BtreePayloadSize(BtCursor*); | ||||
| 16764 | SQLITE_PRIVATEstatic sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*); | ||||
| 16765 | |||||
| 16766 | SQLITE_PRIVATEstatic int sqlite3BtreeIntegrityCheck( | ||||
| 16767 | sqlite3 *db, /* Database connection that is running the check */ | ||||
| 16768 | Btree *p, /* The btree to be checked */ | ||||
| 16769 | Pgno *aRoot, /* An array of root pages numbers for individual trees */ | ||||
| 16770 | sqlite3_value *aCnt, /* OUT: entry counts for each btree in aRoot[] */ | ||||
| 16771 | int nRoot, /* Number of entries in aRoot[] */ | ||||
| 16772 | int mxErr, /* Stop reporting errors after this many */ | ||||
| 16773 | int *pnErr, /* OUT: Write number of errors seen to this variable */ | ||||
| 16774 | char **pzOut /* OUT: Write the error message string here */ | ||||
| 16775 | ); | ||||
| 16776 | SQLITE_PRIVATEstatic struct Pager *sqlite3BtreePager(Btree*); | ||||
| 16777 | SQLITE_PRIVATEstatic i64 sqlite3BtreeRowCountEst(BtCursor*); | ||||
| 16778 | |||||
| 16779 | #ifndef SQLITE_OMIT_INCRBLOB | ||||
| 16780 | SQLITE_PRIVATEstatic int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*); | ||||
| 16781 | SQLITE_PRIVATEstatic int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); | ||||
| 16782 | SQLITE_PRIVATEstatic void sqlite3BtreeIncrblobCursor(BtCursor *); | ||||
| 16783 | #endif | ||||
| 16784 | SQLITE_PRIVATEstatic void sqlite3BtreeClearCursor(BtCursor *); | ||||
| 16785 | SQLITE_PRIVATEstatic int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); | ||||
| 16786 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask); | ||||
| 16787 | SQLITE_PRIVATEstatic int sqlite3BtreeIsReadonly(Btree *pBt); | ||||
| 16788 | SQLITE_PRIVATEstatic int sqlite3HeaderSizeBtree(void); | ||||
| 16789 | |||||
| 16790 | #ifdef SQLITE_DEBUG | ||||
| 16791 | SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3BtreeSeekCount(Btree*)0; | ||||
| 16792 | #else | ||||
| 16793 | # define sqlite3BtreeSeekCount(X)0 0 | ||||
| 16794 | #endif | ||||
| 16795 | |||||
| 16796 | #ifndef NDEBUG1 | ||||
| 16797 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorIsValid(BtCursor*); | ||||
| 16798 | #endif | ||||
| 16799 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorIsValidNN(BtCursor*); | ||||
| 16800 | |||||
| 16801 | SQLITE_PRIVATEstatic int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*); | ||||
| 16802 | |||||
| 16803 | #ifdef SQLITE_TEST | ||||
| 16804 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorInfo(BtCursor*, int*, int); | ||||
| 16805 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorList(Btree*); | ||||
| 16806 | #endif | ||||
| 16807 | |||||
| 16808 | #ifndef SQLITE_OMIT_WAL | ||||
| 16809 | SQLITE_PRIVATEstatic int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); | ||||
| 16810 | #endif | ||||
| 16811 | |||||
| 16812 | SQLITE_PRIVATEstatic int sqlite3BtreeTransferRow(BtCursor*, BtCursor*, i64); | ||||
| 16813 | |||||
| 16814 | SQLITE_PRIVATEstatic void sqlite3BtreeClearCache(Btree*); | ||||
| 16815 | |||||
| 16816 | /* | ||||
| 16817 | ** If we are not using shared cache, then there is no need to | ||||
| 16818 | ** use mutexes to access the BtShared structures. So make the | ||||
| 16819 | ** Enter and Leave procedures no-ops. | ||||
| 16820 | */ | ||||
| 16821 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 16822 | SQLITE_PRIVATEstatic void sqlite3BtreeEnter(Btree*); | ||||
| 16823 | SQLITE_PRIVATEstatic void sqlite3BtreeEnterAll(sqlite3*); | ||||
| 16824 | SQLITE_PRIVATEstatic int sqlite3BtreeSharable(Btree*); | ||||
| 16825 | SQLITE_PRIVATEstatic void sqlite3BtreeEnterCursor(BtCursor*); | ||||
| 16826 | SQLITE_PRIVATEstatic int sqlite3BtreeConnectionCount(Btree*); | ||||
| 16827 | #else | ||||
| 16828 | # define sqlite3BtreeEnter(X) | ||||
| 16829 | # define sqlite3BtreeEnterAll(X) | ||||
| 16830 | # define sqlite3BtreeSharable(X) 0 | ||||
| 16831 | # define sqlite3BtreeEnterCursor(X) | ||||
| 16832 | # define sqlite3BtreeConnectionCount(X) 1 | ||||
| 16833 | #endif | ||||
| 16834 | |||||
| 16835 | #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE2 | ||||
| 16836 | SQLITE_PRIVATEstatic void sqlite3BtreeLeave(Btree*); | ||||
| 16837 | SQLITE_PRIVATEstatic void sqlite3BtreeLeaveCursor(BtCursor*); | ||||
| 16838 | SQLITE_PRIVATEstatic void sqlite3BtreeLeaveAll(sqlite3*); | ||||
| 16839 | #ifndef NDEBUG1 | ||||
| 16840 | /* These routines are used inside assert() statements only. */ | ||||
| 16841 | SQLITE_PRIVATEstatic int sqlite3BtreeHoldsMutex(Btree*); | ||||
| 16842 | SQLITE_PRIVATEstatic int sqlite3BtreeHoldsAllMutexes(sqlite3*); | ||||
| 16843 | SQLITE_PRIVATEstatic int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); | ||||
| 16844 | #endif | ||||
| 16845 | #else | ||||
| 16846 | |||||
| 16847 | # define sqlite3BtreeLeave(X) | ||||
| 16848 | # define sqlite3BtreeLeaveCursor(X) | ||||
| 16849 | # define sqlite3BtreeLeaveAll(X) | ||||
| 16850 | |||||
| 16851 | # define sqlite3BtreeHoldsMutex(X) 1 | ||||
| 16852 | # define sqlite3BtreeHoldsAllMutexes(X) 1 | ||||
| 16853 | # define sqlite3SchemaMutexHeld(X,Y,Z) 1 | ||||
| 16854 | #endif | ||||
| 16855 | |||||
| 16856 | |||||
| 16857 | #endif /* SQLITE_BTREE_H */ | ||||
| 16858 | |||||
| 16859 | /************** End of btree.h ***********************************************/ | ||||
| 16860 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 16861 | /************** Include vdbe.h in the middle of sqliteInt.h ******************/ | ||||
| 16862 | /************** Begin file vdbe.h ********************************************/ | ||||
| 16863 | /* | ||||
| 16864 | ** 2001 September 15 | ||||
| 16865 | ** | ||||
| 16866 | ** The author disclaims copyright to this source code. In place of | ||||
| 16867 | ** a legal notice, here is a blessing: | ||||
| 16868 | ** | ||||
| 16869 | ** May you do good and not evil. | ||||
| 16870 | ** May you find forgiveness for yourself and forgive others. | ||||
| 16871 | ** May you share freely, never taking more than you give. | ||||
| 16872 | ** | ||||
| 16873 | ************************************************************************* | ||||
| 16874 | ** Header file for the Virtual DataBase Engine (VDBE) | ||||
| 16875 | ** | ||||
| 16876 | ** This header defines the interface to the virtual database engine | ||||
| 16877 | ** or VDBE. The VDBE implements an abstract machine that runs a | ||||
| 16878 | ** simple program to access and modify the underlying database. | ||||
| 16879 | */ | ||||
| 16880 | #ifndef SQLITE_VDBE_H | ||||
| 16881 | #define SQLITE_VDBE_H | ||||
| 16882 | /* #include <stdio.h> */ | ||||
| 16883 | |||||
| 16884 | /* | ||||
| 16885 | ** A single VDBE is an opaque structure named "Vdbe". Only routines | ||||
| 16886 | ** in the source file sqliteVdbe.c are allowed to see the insides | ||||
| 16887 | ** of this structure. | ||||
| 16888 | */ | ||||
| 16889 | typedef struct Vdbe Vdbe; | ||||
| 16890 | |||||
| 16891 | /* | ||||
| 16892 | ** The names of the following types declared in vdbeInt.h are required | ||||
| 16893 | ** for the VdbeOp definition. | ||||
| 16894 | */ | ||||
| 16895 | typedef struct sqlite3_value Mem; | ||||
| 16896 | typedef struct SubProgram SubProgram; | ||||
| 16897 | typedef struct SubrtnSig SubrtnSig; | ||||
| 16898 | |||||
| 16899 | /* | ||||
| 16900 | ** A signature for a reusable subroutine that materializes the RHS of | ||||
| 16901 | ** an IN operator. | ||||
| 16902 | */ | ||||
| 16903 | struct SubrtnSig { | ||||
| 16904 | int selId; /* SELECT-id for the SELECT statement on the RHS */ | ||||
| 16905 | u8 bComplete; /* True if fully coded and available for reusable */ | ||||
| 16906 | char *zAff; /* Affinity of the overall IN expression */ | ||||
| 16907 | int iTable; /* Ephemeral table generated by the subroutine */ | ||||
| 16908 | int iAddr; /* Subroutine entry address */ | ||||
| 16909 | int regReturn; /* Register used to hold return address */ | ||||
| 16910 | }; | ||||
| 16911 | |||||
| 16912 | /* | ||||
| 16913 | ** A single instruction of the virtual machine has an opcode | ||||
| 16914 | ** and as many as three operands. The instruction is recorded | ||||
| 16915 | ** as an instance of the following structure: | ||||
| 16916 | */ | ||||
| 16917 | struct VdbeOp { | ||||
| 16918 | u8 opcode; /* What operation to perform */ | ||||
| 16919 | signed char p4type; /* One of the P4_xxx constants for p4 */ | ||||
| 16920 | u16 p5; /* Fifth parameter is an unsigned 16-bit integer */ | ||||
| 16921 | int p1; /* First operand */ | ||||
| 16922 | int p2; /* Second parameter (often the jump destination) */ | ||||
| 16923 | int p3; /* The third parameter */ | ||||
| 16924 | union p4union { /* fourth parameter */ | ||||
| 16925 | int i; /* Integer value if p4type==P4_INT32 */ | ||||
| 16926 | void *p; /* Generic pointer */ | ||||
| 16927 | char *z; /* Pointer to data for string (char array) types */ | ||||
| 16928 | i64 *pI64; /* Used when p4type is P4_INT64 */ | ||||
| 16929 | double *pReal; /* Used when p4type is P4_REAL */ | ||||
| 16930 | FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ | ||||
| 16931 | sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */ | ||||
| 16932 | CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ | ||||
| 16933 | Mem *pMem; /* Used when p4type is P4_MEM */ | ||||
| 16934 | VTable *pVtab; /* Used when p4type is P4_VTAB */ | ||||
| 16935 | KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ | ||||
| 16936 | u32 *ai; /* Used when p4type is P4_INTARRAY */ | ||||
| 16937 | SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ | ||||
| 16938 | Table *pTab; /* Used when p4type is P4_TABLE */ | ||||
| 16939 | SubrtnSig *pSubrtnSig; /* Used when p4type is P4_SUBRTNSIG */ | ||||
| 16940 | #ifdef SQLITE_ENABLE_CURSOR_HINTS | ||||
| 16941 | Expr *pExpr; /* Used when p4type is P4_EXPR */ | ||||
| 16942 | #endif | ||||
| 16943 | } p4; | ||||
| 16944 | #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS | ||||
| 16945 | char *zComment; /* Comment to improve readability */ | ||||
| 16946 | #endif | ||||
| 16947 | #ifdef SQLITE_VDBE_COVERAGE | ||||
| 16948 | u32 iSrcLine; /* Source-code line that generated this opcode | ||||
| 16949 | ** with flags in the upper 8 bits */ | ||||
| 16950 | #endif | ||||
| 16951 | #if defined(SQLITE_ENABLE_STMT_SCANSTATUS1) || defined(VDBE_PROFILE) | ||||
| 16952 | u64 nExec; | ||||
| 16953 | u64 nCycle; | ||||
| 16954 | #endif | ||||
| 16955 | }; | ||||
| 16956 | typedef struct VdbeOp VdbeOp; | ||||
| 16957 | |||||
| 16958 | |||||
| 16959 | /* | ||||
| 16960 | ** A sub-routine used to implement a trigger program. | ||||
| 16961 | */ | ||||
| 16962 | struct SubProgram { | ||||
| 16963 | VdbeOp *aOp; /* Array of opcodes for sub-program */ | ||||
| 16964 | int nOp; /* Elements in aOp[] */ | ||||
| 16965 | int nMem; /* Number of memory cells required */ | ||||
| 16966 | int nCsr; /* Number of cursors required */ | ||||
| 16967 | u8 *aOnce; /* Array of OP_Once flags */ | ||||
| 16968 | void *token; /* id that may be used to recursive triggers */ | ||||
| 16969 | SubProgram *pNext; /* Next sub-program already visited */ | ||||
| 16970 | }; | ||||
| 16971 | |||||
| 16972 | /* | ||||
| 16973 | ** A smaller version of VdbeOp used for the VdbeAddOpList() function because | ||||
| 16974 | ** it takes up less space. | ||||
| 16975 | */ | ||||
| 16976 | struct VdbeOpList { | ||||
| 16977 | u8 opcode; /* What operation to perform */ | ||||
| 16978 | signed char p1; /* First operand */ | ||||
| 16979 | signed char p2; /* Second parameter (often the jump destination) */ | ||||
| 16980 | signed char p3; /* Third parameter */ | ||||
| 16981 | }; | ||||
| 16982 | typedef struct VdbeOpList VdbeOpList; | ||||
| 16983 | |||||
| 16984 | /* | ||||
| 16985 | ** Allowed values of VdbeOp.p4type | ||||
| 16986 | */ | ||||
| 16987 | #define P4_NOTUSED0 0 /* The P4 parameter is not used */ | ||||
| 16988 | #define P4_TRANSIENT0 0 /* P4 is a pointer to a transient string */ | ||||
| 16989 | #define P4_STATIC(-1) (-1) /* Pointer to a static string */ | ||||
| 16990 | #define P4_COLLSEQ(-2) (-2) /* P4 is a pointer to a CollSeq structure */ | ||||
| 16991 | #define P4_INT32(-3) (-3) /* P4 is a 32-bit signed integer */ | ||||
| 16992 | #define P4_SUBPROGRAM(-4) (-4) /* P4 is a pointer to a SubProgram structure */ | ||||
| 16993 | #define P4_TABLE(-5) (-5) /* P4 is a pointer to a Table structure */ | ||||
| 16994 | /* Above do not own any resources. Must free those below */ | ||||
| 16995 | #define P4_FREE_IF_LE(-6) (-6) | ||||
| 16996 | #define P4_DYNAMIC(-6) (-6) /* Pointer to memory from sqliteMalloc() */ | ||||
| 16997 | #define P4_FUNCDEF(-7) (-7) /* P4 is a pointer to a FuncDef structure */ | ||||
| 16998 | #define P4_KEYINFO(-8) (-8) /* P4 is a pointer to a KeyInfo structure */ | ||||
| 16999 | #define P4_EXPR(-9) (-9) /* P4 is a pointer to an Expr tree */ | ||||
| 17000 | #define P4_MEM(-10) (-10) /* P4 is a pointer to a Mem* structure */ | ||||
| 17001 | #define P4_VTAB(-11) (-11) /* P4 is a pointer to an sqlite3_vtab structure */ | ||||
| 17002 | #define P4_REAL(-12) (-12) /* P4 is a 64-bit floating point value */ | ||||
| 17003 | #define P4_INT64(-13) (-13) /* P4 is a 64-bit signed integer */ | ||||
| 17004 | #define P4_INTARRAY(-14) (-14) /* P4 is a vector of 32-bit integers */ | ||||
| 17005 | #define P4_FUNCCTX(-15) (-15) /* P4 is a pointer to an sqlite3_context object */ | ||||
| 17006 | #define P4_TABLEREF(-16) (-16) /* Like P4_TABLE, but reference counted */ | ||||
| 17007 | #define P4_SUBRTNSIG(-17) (-17) /* P4 is a SubrtnSig pointer */ | ||||
| 17008 | |||||
| 17009 | /* Error message codes for OP_Halt */ | ||||
| 17010 | #define P5_ConstraintNotNull1 1 | ||||
| 17011 | #define P5_ConstraintUnique2 2 | ||||
| 17012 | #define P5_ConstraintCheck3 3 | ||||
| 17013 | #define P5_ConstraintFK4 4 | ||||
| 17014 | |||||
| 17015 | /* | ||||
| 17016 | ** The Vdbe.aColName array contains 5n Mem structures, where n is the | ||||
| 17017 | ** number of columns of data returned by the statement. | ||||
| 17018 | */ | ||||
| 17019 | #define COLNAME_NAME0 0 | ||||
| 17020 | #define COLNAME_DECLTYPE1 1 | ||||
| 17021 | #define COLNAME_DATABASE2 2 | ||||
| 17022 | #define COLNAME_TABLE3 3 | ||||
| 17023 | #define COLNAME_COLUMN4 4 | ||||
| 17024 | #ifdef SQLITE_ENABLE_COLUMN_METADATA1 | ||||
| 17025 | # define COLNAME_N5 5 /* Number of COLNAME_xxx symbols */ | ||||
| 17026 | #else | ||||
| 17027 | # ifdef SQLITE_OMIT_DECLTYPE | ||||
| 17028 | # define COLNAME_N5 1 /* Store only the name */ | ||||
| 17029 | # else | ||||
| 17030 | # define COLNAME_N5 2 /* Store the name and decltype */ | ||||
| 17031 | # endif | ||||
| 17032 | #endif | ||||
| 17033 | |||||
| 17034 | /* | ||||
| 17035 | ** The following macro converts a label returned by sqlite3VdbeMakeLabel() | ||||
| 17036 | ** into an index into the Parse.aLabel[] array that contains the resolved | ||||
| 17037 | ** address of that label. | ||||
| 17038 | */ | ||||
| 17039 | #define ADDR(X)(~(X)) (~(X)) | ||||
| 17040 | |||||
| 17041 | /* | ||||
| 17042 | ** The makefile scans the vdbe.c source file and creates the "opcodes.h" | ||||
| 17043 | ** header file that defines a number for each opcode used by the VDBE. | ||||
| 17044 | */ | ||||
| 17045 | /************** Include opcodes.h in the middle of vdbe.h ********************/ | ||||
| 17046 | /************** Begin file opcodes.h *****************************************/ | ||||
| 17047 | /* Automatically generated. Do not edit */ | ||||
| 17048 | /* See the tool/mkopcodeh.tcl script for details */ | ||||
| 17049 | #define OP_Savepoint0 0 | ||||
| 17050 | #define OP_AutoCommit1 1 | ||||
| 17051 | #define OP_Transaction2 2 | ||||
| 17052 | #define OP_Checkpoint3 3 | ||||
| 17053 | #define OP_JournalMode4 4 | ||||
| 17054 | #define OP_Vacuum5 5 | ||||
| 17055 | #define OP_VFilter6 6 /* jump, synopsis: iplan=r[P3] zplan='P4' */ | ||||
| 17056 | #define OP_VUpdate7 7 /* synopsis: data=r[P3@P2] */ | ||||
| 17057 | #define OP_Init8 8 /* jump0, synopsis: Start at P2 */ | ||||
| 17058 | #define OP_Goto9 9 /* jump */ | ||||
| 17059 | #define OP_Gosub10 10 /* jump */ | ||||
| 17060 | #define OP_InitCoroutine11 11 /* jump0 */ | ||||
| 17061 | #define OP_Yield12 12 /* jump0 */ | ||||
| 17062 | #define OP_MustBeInt13 13 /* jump0 */ | ||||
| 17063 | #define OP_Jump14 14 /* jump */ | ||||
| 17064 | #define OP_Once15 15 /* jump */ | ||||
| 17065 | #define OP_If16 16 /* jump */ | ||||
| 17066 | #define OP_IfNot17 17 /* jump */ | ||||
| 17067 | #define OP_IsType18 18 /* jump, synopsis: if typeof(P1.P3) in P5 goto P2 */ | ||||
| 17068 | #define OP_Not19 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */ | ||||
| 17069 | #define OP_IfNullRow20 20 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */ | ||||
| 17070 | #define OP_SeekLT21 21 /* jump0, synopsis: key=r[P3@P4] */ | ||||
| 17071 | #define OP_SeekLE22 22 /* jump0, synopsis: key=r[P3@P4] */ | ||||
| 17072 | #define OP_SeekGE23 23 /* jump0, synopsis: key=r[P3@P4] */ | ||||
| 17073 | #define OP_SeekGT24 24 /* jump0, synopsis: key=r[P3@P4] */ | ||||
| 17074 | #define OP_IfNotOpen25 25 /* jump, synopsis: if( !csr[P1] ) goto P2 */ | ||||
| 17075 | #define OP_IfNoHope26 26 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17076 | #define OP_NoConflict27 27 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17077 | #define OP_NotFound28 28 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17078 | #define OP_Found29 29 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17079 | #define OP_SeekRowid30 30 /* jump0, synopsis: intkey=r[P3] */ | ||||
| 17080 | #define OP_NotExists31 31 /* jump, synopsis: intkey=r[P3] */ | ||||
| 17081 | #define OP_Last32 32 /* jump0 */ | ||||
| 17082 | #define OP_IfSizeBetween33 33 /* jump */ | ||||
| 17083 | #define OP_SorterSort34 34 /* jump */ | ||||
| 17084 | #define OP_Sort35 35 /* jump */ | ||||
| 17085 | #define OP_Rewind36 36 /* jump0 */ | ||||
| 17086 | #define OP_SorterNext37 37 /* jump */ | ||||
| 17087 | #define OP_Prev38 38 /* jump */ | ||||
| 17088 | #define OP_Next39 39 /* jump */ | ||||
| 17089 | #define OP_IdxLE40 40 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17090 | #define OP_IdxGT41 41 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17091 | #define OP_IdxLT42 42 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17092 | #define OP_Or43 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ | ||||
| 17093 | #define OP_And44 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ | ||||
| 17094 | #define OP_IdxGE45 45 /* jump, synopsis: key=r[P3@P4] */ | ||||
| 17095 | #define OP_RowSetRead46 46 /* jump, synopsis: r[P3]=rowset(P1) */ | ||||
| 17096 | #define OP_RowSetTest47 47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */ | ||||
| 17097 | #define OP_Program48 48 /* jump0 */ | ||||
| 17098 | #define OP_FkIfZero49 49 /* jump, synopsis: if fkctr[P1]==0 goto P2 */ | ||||
| 17099 | #define OP_IfPos50 50 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ | ||||
| 17100 | #define OP_IsNull51 51 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ | ||||
| 17101 | #define OP_NotNull52 52 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ | ||||
| 17102 | #define OP_Ne53 53 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */ | ||||
| 17103 | #define OP_Eq54 54 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */ | ||||
| 17104 | #define OP_Gt55 55 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */ | ||||
| 17105 | #define OP_Le56 56 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */ | ||||
| 17106 | #define OP_Lt57 57 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */ | ||||
| 17107 | #define OP_Ge58 58 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */ | ||||
| 17108 | #define OP_ElseEq59 59 /* jump, same as TK_ESCAPE */ | ||||
| 17109 | #define OP_IfNotZero60 60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */ | ||||
| 17110 | #define OP_DecrJumpZero61 61 /* jump, synopsis: if (--r[P1])==0 goto P2 */ | ||||
| 17111 | #define OP_IncrVacuum62 62 /* jump */ | ||||
| 17112 | #define OP_VNext63 63 /* jump */ | ||||
| 17113 | #define OP_Filter64 64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */ | ||||
| 17114 | #define OP_PureFunc65 65 /* synopsis: r[P3]=func(r[P2@NP]) */ | ||||
| 17115 | #define OP_Function66 66 /* synopsis: r[P3]=func(r[P2@NP]) */ | ||||
| 17116 | #define OP_Return67 67 | ||||
| 17117 | #define OP_EndCoroutine68 68 | ||||
| 17118 | #define OP_HaltIfNull69 69 /* synopsis: if r[P3]=null halt */ | ||||
| 17119 | #define OP_Halt70 70 | ||||
| 17120 | #define OP_Integer71 71 /* synopsis: r[P2]=P1 */ | ||||
| 17121 | #define OP_Int6472 72 /* synopsis: r[P2]=P4 */ | ||||
| 17122 | #define OP_String73 73 /* synopsis: r[P2]='P4' (len=P1) */ | ||||
| 17123 | #define OP_BeginSubrtn74 74 /* synopsis: r[P2]=NULL */ | ||||
| 17124 | #define OP_Null75 75 /* synopsis: r[P2..P3]=NULL */ | ||||
| 17125 | #define OP_SoftNull76 76 /* synopsis: r[P1]=NULL */ | ||||
| 17126 | #define OP_Blob77 77 /* synopsis: r[P2]=P4 (len=P1) */ | ||||
| 17127 | #define OP_Variable78 78 /* synopsis: r[P2]=parameter(P1) */ | ||||
| 17128 | #define OP_Move79 79 /* synopsis: r[P2@P3]=r[P1@P3] */ | ||||
| 17129 | #define OP_Copy80 80 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ | ||||
| 17130 | #define OP_SCopy81 81 /* synopsis: r[P2]=r[P1] */ | ||||
| 17131 | #define OP_IntCopy82 82 /* synopsis: r[P2]=r[P1] */ | ||||
| 17132 | #define OP_FkCheck83 83 | ||||
| 17133 | #define OP_ResultRow84 84 /* synopsis: output=r[P1@P2] */ | ||||
| 17134 | #define OP_CollSeq85 85 | ||||
| 17135 | #define OP_AddImm86 86 /* synopsis: r[P1]=r[P1]+P2 */ | ||||
| 17136 | #define OP_RealAffinity87 87 | ||||
| 17137 | #define OP_Cast88 88 /* synopsis: affinity(r[P1]) */ | ||||
| 17138 | #define OP_Permutation89 89 | ||||
| 17139 | #define OP_Compare90 90 /* synopsis: r[P1@P3] <-> r[P2@P3] */ | ||||
| 17140 | #define OP_IsTrue91 91 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */ | ||||
| 17141 | #define OP_ZeroOrNull92 92 /* synopsis: r[P2] = 0 OR NULL */ | ||||
| 17142 | #define OP_Offset93 93 /* synopsis: r[P3] = sqlite_offset(P1) */ | ||||
| 17143 | #define OP_Column94 94 /* synopsis: r[P3]=PX cursor P1 column P2 */ | ||||
| 17144 | #define OP_TypeCheck95 95 /* synopsis: typecheck(r[P1@P2]) */ | ||||
| 17145 | #define OP_Affinity96 96 /* synopsis: affinity(r[P1@P2]) */ | ||||
| 17146 | #define OP_MakeRecord97 97 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ | ||||
| 17147 | #define OP_Count98 98 /* synopsis: r[P2]=count() */ | ||||
| 17148 | #define OP_ReadCookie99 99 | ||||
| 17149 | #define OP_SetCookie100 100 | ||||
| 17150 | #define OP_ReopenIdx101 101 /* synopsis: root=P2 iDb=P3 */ | ||||
| 17151 | #define OP_OpenRead102 102 /* synopsis: root=P2 iDb=P3 */ | ||||
| 17152 | #define OP_BitAnd103 103 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ | ||||
| 17153 | #define OP_BitOr104 104 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ | ||||
| 17154 | #define OP_ShiftLeft105 105 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */ | ||||
| 17155 | #define OP_ShiftRight106 106 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */ | ||||
| 17156 | #define OP_Add107 107 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ | ||||
| 17157 | #define OP_Subtract108 108 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ | ||||
| 17158 | #define OP_Multiply109 109 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ | ||||
| 17159 | #define OP_Divide110 110 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ | ||||
| 17160 | #define OP_Remainder111 111 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ | ||||
| 17161 | #define OP_Concat112 112 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ | ||||
| 17162 | #define OP_OpenWrite113 113 /* synopsis: root=P2 iDb=P3 */ | ||||
| 17163 | #define OP_OpenDup114 114 | ||||
| 17164 | #define OP_BitNot115 115 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */ | ||||
| 17165 | #define OP_OpenAutoindex116 116 /* synopsis: nColumn=P2 */ | ||||
| 17166 | #define OP_OpenEphemeral117 117 /* synopsis: nColumn=P2 */ | ||||
| 17167 | #define OP_String8118 118 /* same as TK_STRING, synopsis: r[P2]='P4' */ | ||||
| 17168 | #define OP_SorterOpen119 119 | ||||
| 17169 | #define OP_SequenceTest120 120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ | ||||
| 17170 | #define OP_OpenPseudo121 121 /* synopsis: P3 columns in r[P2] */ | ||||
| 17171 | #define OP_Close122 122 | ||||
| 17172 | #define OP_ColumnsUsed123 123 | ||||
| 17173 | #define OP_SeekScan124 124 /* synopsis: Scan-ahead up to P1 rows */ | ||||
| 17174 | #define OP_SeekHit125 125 /* synopsis: set P2<=seekHit<=P3 */ | ||||
| 17175 | #define OP_Sequence126 126 /* synopsis: r[P2]=cursor[P1].ctr++ */ | ||||
| 17176 | #define OP_NewRowid127 127 /* synopsis: r[P2]=rowid */ | ||||
| 17177 | #define OP_Insert128 128 /* synopsis: intkey=r[P3] data=r[P2] */ | ||||
| 17178 | #define OP_RowCell129 129 | ||||
| 17179 | #define OP_Delete130 130 | ||||
| 17180 | #define OP_ResetCount131 131 | ||||
| 17181 | #define OP_SorterCompare132 132 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ | ||||
| 17182 | #define OP_SorterData133 133 /* synopsis: r[P2]=data */ | ||||
| 17183 | #define OP_RowData134 134 /* synopsis: r[P2]=data */ | ||||
| 17184 | #define OP_Rowid135 135 /* synopsis: r[P2]=PX rowid of P1 */ | ||||
| 17185 | #define OP_NullRow136 136 | ||||
| 17186 | #define OP_SeekEnd137 137 | ||||
| 17187 | #define OP_IdxInsert138 138 /* synopsis: key=r[P2] */ | ||||
| 17188 | #define OP_SorterInsert139 139 /* synopsis: key=r[P2] */ | ||||
| 17189 | #define OP_IdxDelete140 140 /* synopsis: key=r[P2@P3] */ | ||||
| 17190 | #define OP_DeferredSeek141 141 /* synopsis: Move P3 to P1.rowid if needed */ | ||||
| 17191 | #define OP_IdxRowid142 142 /* synopsis: r[P2]=rowid */ | ||||
| 17192 | #define OP_FinishSeek143 143 | ||||
| 17193 | #define OP_Destroy144 144 | ||||
| 17194 | #define OP_Clear145 145 | ||||
| 17195 | #define OP_ResetSorter146 146 | ||||
| 17196 | #define OP_CreateBtree147 147 /* synopsis: r[P2]=root iDb=P1 flags=P3 */ | ||||
| 17197 | #define OP_SqlExec148 148 | ||||
| 17198 | #define OP_ParseSchema149 149 | ||||
| 17199 | #define OP_LoadAnalysis150 150 | ||||
| 17200 | #define OP_DropTable151 151 | ||||
| 17201 | #define OP_DropIndex152 152 | ||||
| 17202 | #define OP_DropTrigger153 153 | ||||
| 17203 | #define OP_Real154 154 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ | ||||
| 17204 | #define OP_IntegrityCk155 155 | ||||
| 17205 | #define OP_RowSetAdd156 156 /* synopsis: rowset(P1)=r[P2] */ | ||||
| 17206 | #define OP_Param157 157 | ||||
| 17207 | #define OP_FkCounter158 158 /* synopsis: fkctr[P1]+=P2 */ | ||||
| 17208 | #define OP_MemMax159 159 /* synopsis: r[P1]=max(r[P1],r[P2]) */ | ||||
| 17209 | #define OP_OffsetLimit160 160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ | ||||
| 17210 | #define OP_AggInverse161 161 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */ | ||||
| 17211 | #define OP_AggStep162 162 /* synopsis: accum=r[P3] step(r[P2@P5]) */ | ||||
| 17212 | #define OP_AggStep1163 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */ | ||||
| 17213 | #define OP_AggValue164 164 /* synopsis: r[P3]=value N=P2 */ | ||||
| 17214 | #define OP_AggFinal165 165 /* synopsis: accum=r[P1] N=P2 */ | ||||
| 17215 | #define OP_Expire166 166 | ||||
| 17216 | #define OP_CursorLock167 167 | ||||
| 17217 | #define OP_CursorUnlock168 168 | ||||
| 17218 | #define OP_TableLock169 169 /* synopsis: iDb=P1 root=P2 write=P3 */ | ||||
| 17219 | #define OP_VBegin170 170 | ||||
| 17220 | #define OP_VCreate171 171 | ||||
| 17221 | #define OP_VDestroy172 172 | ||||
| 17222 | #define OP_VOpen173 173 | ||||
| 17223 | #define OP_VCheck174 174 | ||||
| 17224 | #define OP_VInitIn175 175 /* synopsis: r[P2]=ValueList(P1,P3) */ | ||||
| 17225 | #define OP_VColumn176 176 /* synopsis: r[P3]=vcolumn(P2) */ | ||||
| 17226 | #define OP_VRename177 177 | ||||
| 17227 | #define OP_Pagecount178 178 | ||||
| 17228 | #define OP_MaxPgcnt179 179 | ||||
| 17229 | #define OP_ClrSubtype180 180 /* synopsis: r[P1].subtype = 0 */ | ||||
| 17230 | #define OP_GetSubtype181 181 /* synopsis: r[P2] = r[P1].subtype */ | ||||
| 17231 | #define OP_SetSubtype182 182 /* synopsis: r[P2].subtype = r[P1] */ | ||||
| 17232 | #define OP_FilterAdd183 183 /* synopsis: filter(P1) += key(P3@P4) */ | ||||
| 17233 | #define OP_Trace184 184 | ||||
| 17234 | #define OP_CursorHint185 185 | ||||
| 17235 | #define OP_ReleaseReg186 186 /* synopsis: release r[P1@P2] mask P3 */ | ||||
| 17236 | #define OP_Noop187 187 | ||||
| 17237 | #define OP_Explain188 188 | ||||
| 17238 | #define OP_Abortable189 189 | ||||
| 17239 | |||||
| 17240 | /* Properties such as "out2" or "jump" that are specified in | ||||
| 17241 | ** comments following the "case" for each opcode in the vdbe.c | ||||
| 17242 | ** are encoded into bitvectors as follows: | ||||
| 17243 | */ | ||||
| 17244 | #define OPFLG_JUMP0x01 0x01 /* jump: P2 holds jmp target */ | ||||
| 17245 | #define OPFLG_IN10x02 0x02 /* in1: P1 is an input */ | ||||
| 17246 | #define OPFLG_IN20x04 0x04 /* in2: P2 is an input */ | ||||
| 17247 | #define OPFLG_IN30x08 0x08 /* in3: P3 is an input */ | ||||
| 17248 | #define OPFLG_OUT20x10 0x10 /* out2: P2 is an output */ | ||||
| 17249 | #define OPFLG_OUT30x20 0x20 /* out3: P3 is an output */ | ||||
| 17250 | #define OPFLG_NCYCLE0x40 0x40 /* ncycle:Cycles count against P1 */ | ||||
| 17251 | #define OPFLG_JUMP00x80 0x80 /* jump0: P2 might be zero */ | ||||
| 17252 | #define OPFLG_INITIALIZER{ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00, 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01, 0x03, 0x03, 0x01, 0x12, 0x01 , 0xc9, 0xc9, 0xc9, 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49, 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41, 0x41, 0x41 , 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b, 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01 , 0x41, 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00 , 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26, 0x26 , 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40 , 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40, 0x10, 0x00, 0x00 , 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50, 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , 0x00,} {\ | ||||
| 17253 | /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00,\ | ||||
| 17254 | /* 8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\ | ||||
| 17255 | /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\ | ||||
| 17256 | /* 24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\ | ||||
| 17257 | /* 32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\ | ||||
| 17258 | /* 40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\ | ||||
| 17259 | /* 48 */ 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\ | ||||
| 17260 | /* 56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x41,\ | ||||
| 17261 | /* 64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\ | ||||
| 17262 | /* 72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\ | ||||
| 17263 | /* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\ | ||||
| 17264 | /* 88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\ | ||||
| 17265 | /* 96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26,\ | ||||
| 17266 | /* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\ | ||||
| 17267 | /* 112 */ 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00,\ | ||||
| 17268 | /* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\ | ||||
| 17269 | /* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\ | ||||
| 17270 | /* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\ | ||||
| 17271 | /* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\ | ||||
| 17272 | /* 152 */ 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04,\ | ||||
| 17273 | /* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ | ||||
| 17274 | /* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\ | ||||
| 17275 | /* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\ | ||||
| 17276 | /* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,} | ||||
| 17277 | |||||
| 17278 | /* The resolve3P2Values() routine is able to run faster if it knows | ||||
| 17279 | ** the value of the largest JUMP opcode. The smaller the maximum | ||||
| 17280 | ** JUMP opcode the better, so the mkopcodeh.tcl script that | ||||
| 17281 | ** generated this include file strives to group all JUMP opcodes | ||||
| 17282 | ** together near the beginning of the list. | ||||
| 17283 | */ | ||||
| 17284 | #define SQLITE_MX_JUMP_OPCODE64 64 /* Maximum JUMP opcode */ | ||||
| 17285 | |||||
| 17286 | /************** End of opcodes.h *********************************************/ | ||||
| 17287 | /************** Continuing where we left off in vdbe.h ***********************/ | ||||
| 17288 | |||||
| 17289 | /* | ||||
| 17290 | ** Additional non-public SQLITE_PREPARE_* flags | ||||
| 17291 | */ | ||||
| 17292 | #define SQLITE_PREPARE_SAVESQL0x80 0x80 /* Preserve SQL text */ | ||||
| 17293 | #define SQLITE_PREPARE_MASK0x1f 0x1f /* Mask of public flags */ | ||||
| 17294 | |||||
| 17295 | /* | ||||
| 17296 | ** Prototypes for the VDBE interface. See comments on the implementation | ||||
| 17297 | ** for a description of what each of these routines does. | ||||
| 17298 | */ | ||||
| 17299 | SQLITE_PRIVATEstatic Vdbe *sqlite3VdbeCreate(Parse*); | ||||
| 17300 | SQLITE_PRIVATEstatic Parse *sqlite3VdbeParser(Vdbe*); | ||||
| 17301 | SQLITE_PRIVATEstatic int sqlite3VdbeAddOp0(Vdbe*,int); | ||||
| 17302 | SQLITE_PRIVATEstatic int sqlite3VdbeAddOp1(Vdbe*,int,int); | ||||
| 17303 | SQLITE_PRIVATEstatic int sqlite3VdbeAddOp2(Vdbe*,int,int,int); | ||||
| 17304 | SQLITE_PRIVATEstatic int sqlite3VdbeGoto(Vdbe*,int); | ||||
| 17305 | SQLITE_PRIVATEstatic int sqlite3VdbeLoadString(Vdbe*,int,const char*); | ||||
| 17306 | SQLITE_PRIVATEstatic void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...); | ||||
| 17307 | SQLITE_PRIVATEstatic int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); | ||||
| 17308 | SQLITE_PRIVATEstatic int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); | ||||
| 17309 | SQLITE_PRIVATEstatic int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int); | ||||
| 17310 | SQLITE_PRIVATEstatic int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); | ||||
| 17311 | SQLITE_PRIVATEstatic int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int); | ||||
| 17312 | SQLITE_PRIVATEstatic void sqlite3VdbeEndCoroutine(Vdbe*,int); | ||||
| 17313 | #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) | ||||
| 17314 | SQLITE_PRIVATEstatic void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N); | ||||
| 17315 | SQLITE_PRIVATEstatic void sqlite3VdbeVerifyNoResultRow(Vdbe *p); | ||||
| 17316 | #else | ||||
| 17317 | # define sqlite3VdbeVerifyNoMallocRequired(A,B) | ||||
| 17318 | # define sqlite3VdbeVerifyNoResultRow(A) | ||||
| 17319 | #endif | ||||
| 17320 | #if defined(SQLITE_DEBUG) | ||||
| 17321 | SQLITE_PRIVATEstatic void sqlite3VdbeVerifyAbortable(Vdbe *p, int); | ||||
| 17322 | SQLITE_PRIVATEstatic void sqlite3VdbeNoJumpsOutsideSubrtn(Vdbe*,int,int,int); | ||||
| 17323 | #else | ||||
| 17324 | # define sqlite3VdbeVerifyAbortable(A,B) | ||||
| 17325 | # define sqlite3VdbeNoJumpsOutsideSubrtn(A,B,C,D) | ||||
| 17326 | #endif | ||||
| 17327 | SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno); | ||||
| 17328 | #ifndef SQLITE_OMIT_EXPLAIN | ||||
| 17329 | SQLITE_PRIVATEstatic int sqlite3VdbeExplain(Parse*,u8,const char*,...); | ||||
| 17330 | SQLITE_PRIVATEstatic void sqlite3VdbeExplainPop(Parse*); | ||||
| 17331 | SQLITE_PRIVATEstatic int sqlite3VdbeExplainParent(Parse*); | ||||
| 17332 | # define ExplainQueryPlan(P)sqlite3VdbeExplain P sqlite3VdbeExplain P | ||||
| 17333 | # ifdef SQLITE_ENABLE_STMT_SCANSTATUS1 | ||||
| 17334 | # define ExplainQueryPlan2(V,P)(V = sqlite3VdbeExplain P) (V = sqlite3VdbeExplain P) | ||||
| 17335 | # else | ||||
| 17336 | # define ExplainQueryPlan2(V,P)(V = sqlite3VdbeExplain P) ExplainQueryPlan(P)sqlite3VdbeExplain P | ||||
| 17337 | # endif | ||||
| 17338 | # define ExplainQueryPlanPop(P)sqlite3VdbeExplainPop(P) sqlite3VdbeExplainPop(P) | ||||
| 17339 | # define ExplainQueryPlanParent(P)sqlite3VdbeExplainParent(P) sqlite3VdbeExplainParent(P) | ||||
| 17340 | #else | ||||
| 17341 | # define ExplainQueryPlan(P)sqlite3VdbeExplain P | ||||
| 17342 | # define ExplainQueryPlan2(V,P)(V = sqlite3VdbeExplain P) | ||||
| 17343 | # define ExplainQueryPlanPop(P)sqlite3VdbeExplainPop(P) | ||||
| 17344 | # define ExplainQueryPlanParent(P)sqlite3VdbeExplainParent(P) 0 | ||||
| 17345 | # define sqlite3ExplainBreakpoint(A,B) /*no-op*/ | ||||
| 17346 | #endif | ||||
| 17347 | #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN) | ||||
| 17348 | SQLITE_PRIVATEstatic void sqlite3ExplainBreakpoint(const char*,const char*); | ||||
| 17349 | #else | ||||
| 17350 | # define sqlite3ExplainBreakpoint(A,B) /*no-op*/ | ||||
| 17351 | #endif | ||||
| 17352 | SQLITE_PRIVATEstatic void sqlite3VdbeAddParseSchemaOp(Vdbe*, int, char*, u16); | ||||
| 17353 | SQLITE_PRIVATEstatic void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8); | ||||
| 17354 | SQLITE_PRIVATEstatic void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); | ||||
| 17355 | SQLITE_PRIVATEstatic void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); | ||||
| 17356 | SQLITE_PRIVATEstatic void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); | ||||
| 17357 | SQLITE_PRIVATEstatic void sqlite3VdbeChangeP5(Vdbe*, u16 P5); | ||||
| 17358 | SQLITE_PRIVATEstatic void sqlite3VdbeTypeofColumn(Vdbe*, int); | ||||
| 17359 | SQLITE_PRIVATEstatic void sqlite3VdbeJumpHere(Vdbe*, int addr); | ||||
| 17360 | SQLITE_PRIVATEstatic void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr); | ||||
| 17361 | SQLITE_PRIVATEstatic int sqlite3VdbeChangeToNoop(Vdbe*, int addr); | ||||
| 17362 | SQLITE_PRIVATEstatic int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op); | ||||
| 17363 | #ifdef SQLITE_DEBUG | ||||
| 17364 | SQLITE_PRIVATEstatic void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int); | ||||
| 17365 | #else | ||||
| 17366 | # define sqlite3VdbeReleaseRegisters(P,A,N,M,F) | ||||
| 17367 | #endif | ||||
| 17368 | SQLITE_PRIVATEstatic void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); | ||||
| 17369 | SQLITE_PRIVATEstatic void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type); | ||||
| 17370 | SQLITE_PRIVATEstatic void sqlite3VdbeSetP4KeyInfo(Parse*, Index*); | ||||
| 17371 | SQLITE_PRIVATEstatic void sqlite3VdbeUsesBtree(Vdbe*, int); | ||||
| 17372 | SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); | ||||
| 17373 | SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeGetLastOp(Vdbe*); | ||||
| 17374 | SQLITE_PRIVATEstatic int sqlite3VdbeMakeLabel(Parse*); | ||||
| 17375 | SQLITE_PRIVATEstatic void sqlite3VdbeRunOnlyOnce(Vdbe*); | ||||
| 17376 | SQLITE_PRIVATEstatic void sqlite3VdbeReusable(Vdbe*); | ||||
| 17377 | SQLITE_PRIVATEstatic void sqlite3VdbeDelete(Vdbe*); | ||||
| 17378 | SQLITE_PRIVATEstatic void sqlite3VdbeMakeReady(Vdbe*,Parse*); | ||||
| 17379 | SQLITE_PRIVATEstatic int sqlite3VdbeFinalize(Vdbe*); | ||||
| 17380 | SQLITE_PRIVATEstatic void sqlite3VdbeResolveLabel(Vdbe*, int); | ||||
| 17381 | SQLITE_PRIVATEstatic int sqlite3VdbeCurrentAddr(Vdbe*); | ||||
| 17382 | #ifdef SQLITE_DEBUG | ||||
| 17383 | SQLITE_PRIVATEstatic int sqlite3VdbeAssertMayAbort(Vdbe *, int); | ||||
| 17384 | #endif | ||||
| 17385 | SQLITE_PRIVATEstatic void sqlite3VdbeResetStepResult(Vdbe*); | ||||
| 17386 | SQLITE_PRIVATEstatic void sqlite3VdbeRewind(Vdbe*); | ||||
| 17387 | SQLITE_PRIVATEstatic int sqlite3VdbeReset(Vdbe*); | ||||
| 17388 | SQLITE_PRIVATEstatic void sqlite3VdbeSetNumCols(Vdbe*,int); | ||||
| 17389 | SQLITE_PRIVATEstatic int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); | ||||
| 17390 | SQLITE_PRIVATEstatic void sqlite3VdbeCountChanges(Vdbe*); | ||||
| 17391 | SQLITE_PRIVATEstatic sqlite3 *sqlite3VdbeDb(Vdbe*); | ||||
| 17392 | SQLITE_PRIVATEstatic u8 sqlite3VdbePrepareFlags(Vdbe*); | ||||
| 17393 | SQLITE_PRIVATEstatic void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8); | ||||
| 17394 | #ifdef SQLITE_ENABLE_NORMALIZE | ||||
| 17395 | SQLITE_PRIVATEstatic void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*); | ||||
| 17396 | SQLITE_PRIVATEstatic int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*); | ||||
| 17397 | #endif | ||||
| 17398 | SQLITE_PRIVATEstatic void sqlite3VdbeSwap(Vdbe*,Vdbe*); | ||||
| 17399 | SQLITE_PRIVATEstatic VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); | ||||
| 17400 | SQLITE_PRIVATEstatic sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); | ||||
| 17401 | SQLITE_PRIVATEstatic void sqlite3VdbeSetVarmask(Vdbe*, int); | ||||
| 17402 | #ifndef SQLITE_OMIT_TRACE | ||||
| 17403 | SQLITE_PRIVATEstatic char *sqlite3VdbeExpandSql(Vdbe*, const char*); | ||||
| 17404 | #endif | ||||
| 17405 | SQLITE_PRIVATEstatic int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); | ||||
| 17406 | SQLITE_PRIVATEstatic int sqlite3BlobCompare(const Mem*, const Mem*); | ||||
| 17407 | |||||
| 17408 | SQLITE_PRIVATEstatic void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); | ||||
| 17409 | SQLITE_PRIVATEstatic int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); | ||||
| 17410 | SQLITE_PRIVATEstatic int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int); | ||||
| 17411 | SQLITE_PRIVATEstatic UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*); | ||||
| 17412 | |||||
| 17413 | typedef int (*RecordCompare)(int,const void*,UnpackedRecord*); | ||||
| 17414 | SQLITE_PRIVATEstatic RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*); | ||||
| 17415 | |||||
| 17416 | SQLITE_PRIVATEstatic void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); | ||||
| 17417 | SQLITE_PRIVATEstatic int sqlite3VdbeHasSubProgram(Vdbe*); | ||||
| 17418 | |||||
| 17419 | SQLITE_PRIVATEstatic void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val); | ||||
| 17420 | |||||
| 17421 | SQLITE_PRIVATEstatic int sqlite3NotPureFunc(sqlite3_context*); | ||||
| 17422 | #ifdef SQLITE_ENABLE_BYTECODE_VTAB | ||||
| 17423 | SQLITE_PRIVATEstatic int sqlite3VdbeBytecodeVtabInit(sqlite3*); | ||||
| 17424 | #endif | ||||
| 17425 | |||||
| 17426 | /* Use SQLITE_ENABLE_EXPLAIN_COMMENTS to enable generation of extra | ||||
| 17427 | ** comments on each VDBE opcode. | ||||
| 17428 | ** | ||||
| 17429 | ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op | ||||
| 17430 | ** comments in VDBE programs that show key decision points in the code | ||||
| 17431 | ** generator. | ||||
| 17432 | */ | ||||
| 17433 | #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS | ||||
| 17434 | SQLITE_PRIVATEstatic void sqlite3VdbeComment(Vdbe*, const char*, ...); | ||||
| 17435 | # define VdbeComment(X) sqlite3VdbeComment X | ||||
| 17436 | SQLITE_PRIVATEstatic void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); | ||||
| 17437 | # define VdbeNoopComment(X) sqlite3VdbeNoopComment X | ||||
| 17438 | # ifdef SQLITE_ENABLE_MODULE_COMMENTS | ||||
| 17439 | # define VdbeModuleComment(X) sqlite3VdbeNoopComment X | ||||
| 17440 | # else | ||||
| 17441 | # define VdbeModuleComment(X) | ||||
| 17442 | # endif | ||||
| 17443 | #else | ||||
| 17444 | # define VdbeComment(X) | ||||
| 17445 | # define VdbeNoopComment(X) | ||||
| 17446 | # define VdbeModuleComment(X) | ||||
| 17447 | #endif | ||||
| 17448 | |||||
| 17449 | /* | ||||
| 17450 | ** The VdbeCoverage macros are used to set a coverage testing point | ||||
| 17451 | ** for VDBE branch instructions. The coverage testing points are line | ||||
| 17452 | ** numbers in the sqlite3.c source file. VDBE branch coverage testing | ||||
| 17453 | ** only works with an amalgamation build. That's ok since a VDBE branch | ||||
| 17454 | ** coverage build designed for testing the test suite only. No application | ||||
| 17455 | ** should ever ship with VDBE branch coverage measuring turned on. | ||||
| 17456 | ** | ||||
| 17457 | ** VdbeCoverage(v) // Mark the previously coded instruction | ||||
| 17458 | ** // as a branch | ||||
| 17459 | ** | ||||
| 17460 | ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true | ||||
| 17461 | ** | ||||
| 17462 | ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken | ||||
| 17463 | ** | ||||
| 17464 | ** VdbeCoverageNeverTaken(v) // Previous branch is never taken | ||||
| 17465 | ** | ||||
| 17466 | ** VdbeCoverageNeverNull(v) // Previous three-way branch is only | ||||
| 17467 | ** // taken on the first two ways. The | ||||
| 17468 | ** // NULL option is not possible | ||||
| 17469 | ** | ||||
| 17470 | ** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested | ||||
| 17471 | ** // in distinguishing equal and not-equal. | ||||
| 17472 | ** | ||||
| 17473 | ** Every VDBE branch operation must be tagged with one of the macros above. | ||||
| 17474 | ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and | ||||
| 17475 | ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch() | ||||
| 17476 | ** routine in vdbe.c, alerting the developer to the missed tag. | ||||
| 17477 | ** | ||||
| 17478 | ** During testing, the test application will invoke | ||||
| 17479 | ** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback | ||||
| 17480 | ** routine that is invoked as each bytecode branch is taken. The callback | ||||
| 17481 | ** contains the sqlite3.c source line number of the VdbeCoverage macro and | ||||
| 17482 | ** flags to indicate whether or not the branch was taken. The test application | ||||
| 17483 | ** is responsible for keeping track of this and reporting byte-code branches | ||||
| 17484 | ** that are never taken. | ||||
| 17485 | ** | ||||
| 17486 | ** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the | ||||
| 17487 | ** vdbe.c source file for additional information. | ||||
| 17488 | */ | ||||
| 17489 | #ifdef SQLITE_VDBE_COVERAGE | ||||
| 17490 | SQLITE_PRIVATEstatic void sqlite3VdbeSetLineNumber(Vdbe*,int); | ||||
| 17491 | # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__17491) | ||||
| 17492 | # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__17492) | ||||
| 17493 | # define VdbeCoverageAlwaysTaken(v) \ | ||||
| 17494 | sqlite3VdbeSetLineNumber(v,__LINE__17494|0x5000000); | ||||
| 17495 | # define VdbeCoverageNeverTaken(v) \ | ||||
| 17496 | sqlite3VdbeSetLineNumber(v,__LINE__17496|0x6000000); | ||||
| 17497 | # define VdbeCoverageNeverNull(v) \ | ||||
| 17498 | sqlite3VdbeSetLineNumber(v,__LINE__17498|0x4000000); | ||||
| 17499 | # define VdbeCoverageNeverNullIf(v,x) \ | ||||
| 17500 | if(x)sqlite3VdbeSetLineNumber(v,__LINE__17500|0x4000000); | ||||
| 17501 | # define VdbeCoverageEqNe(v) \ | ||||
| 17502 | sqlite3VdbeSetLineNumber(v,__LINE__17502|0x8000000); | ||||
| 17503 | # define VDBE_OFFSET_LINENO(x)0 (__LINE__17503+x) | ||||
| 17504 | #else | ||||
| 17505 | # define VdbeCoverage(v) | ||||
| 17506 | # define VdbeCoverageIf(v,x) | ||||
| 17507 | # define VdbeCoverageAlwaysTaken(v) | ||||
| 17508 | # define VdbeCoverageNeverTaken(v) | ||||
| 17509 | # define VdbeCoverageNeverNull(v) | ||||
| 17510 | # define VdbeCoverageNeverNullIf(v,x) | ||||
| 17511 | # define VdbeCoverageEqNe(v) | ||||
| 17512 | # define VDBE_OFFSET_LINENO(x)0 0 | ||||
| 17513 | #endif | ||||
| 17514 | |||||
| 17515 | #ifdef SQLITE_ENABLE_STMT_SCANSTATUS1 | ||||
| 17516 | SQLITE_PRIVATEstatic void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*); | ||||
| 17517 | SQLITE_PRIVATEstatic void sqlite3VdbeScanStatusRange(Vdbe*, int, int, int); | ||||
| 17518 | SQLITE_PRIVATEstatic void sqlite3VdbeScanStatusCounters(Vdbe*, int, int, int); | ||||
| 17519 | #else | ||||
| 17520 | # define sqlite3VdbeScanStatus(a,b,c,d,e,f) | ||||
| 17521 | # define sqlite3VdbeScanStatusRange(a,b,c,d) | ||||
| 17522 | # define sqlite3VdbeScanStatusCounters(a,b,c,d) | ||||
| 17523 | #endif | ||||
| 17524 | |||||
| 17525 | #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) | ||||
| 17526 | SQLITE_PRIVATEstatic void sqlite3VdbePrintOp(FILE*, int, VdbeOp*); | ||||
| 17527 | #endif | ||||
| 17528 | |||||
| 17529 | #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG) | ||||
| 17530 | SQLITE_PRIVATEstatic int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr); | ||||
| 17531 | #endif | ||||
| 17532 | |||||
| 17533 | #endif /* SQLITE_VDBE_H */ | ||||
| 17534 | |||||
| 17535 | /************** End of vdbe.h ************************************************/ | ||||
| 17536 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 17537 | /************** Include pcache.h in the middle of sqliteInt.h ****************/ | ||||
| 17538 | /************** Begin file pcache.h ******************************************/ | ||||
| 17539 | /* | ||||
| 17540 | ** 2008 August 05 | ||||
| 17541 | ** | ||||
| 17542 | ** The author disclaims copyright to this source code. In place of | ||||
| 17543 | ** a legal notice, here is a blessing: | ||||
| 17544 | ** | ||||
| 17545 | ** May you do good and not evil. | ||||
| 17546 | ** May you find forgiveness for yourself and forgive others. | ||||
| 17547 | ** May you share freely, never taking more than you give. | ||||
| 17548 | ** | ||||
| 17549 | ************************************************************************* | ||||
| 17550 | ** This header file defines the interface that the sqlite page cache | ||||
| 17551 | ** subsystem. | ||||
| 17552 | */ | ||||
| 17553 | |||||
| 17554 | #ifndef _PCACHE_H_ | ||||
| 17555 | |||||
| 17556 | typedef struct PgHdr PgHdr; | ||||
| 17557 | typedef struct PCache PCache; | ||||
| 17558 | |||||
| 17559 | /* | ||||
| 17560 | ** Every page in the cache is controlled by an instance of the following | ||||
| 17561 | ** structure. | ||||
| 17562 | */ | ||||
| 17563 | struct PgHdr { | ||||
| 17564 | sqlite3_pcache_page *pPage; /* Pcache object page handle */ | ||||
| 17565 | void *pData; /* Page data */ | ||||
| 17566 | void *pExtra; /* Extra content */ | ||||
| 17567 | PCache *pCache; /* PRIVATE: Cache that owns this page */ | ||||
| 17568 | PgHdr *pDirty; /* Transient list of dirty sorted by pgno */ | ||||
| 17569 | Pager *pPager; /* The pager this page is part of */ | ||||
| 17570 | Pgno pgno; /* Page number for this page */ | ||||
| 17571 | #ifdef SQLITE_CHECK_PAGES | ||||
| 17572 | u32 pageHash; /* Hash of page content */ | ||||
| 17573 | #endif | ||||
| 17574 | u16 flags; /* PGHDR flags defined below */ | ||||
| 17575 | |||||
| 17576 | /********************************************************************** | ||||
| 17577 | ** Elements above, except pCache, are public. All that follow are | ||||
| 17578 | ** private to pcache.c and should not be accessed by other modules. | ||||
| 17579 | ** pCache is grouped with the public elements for efficiency. | ||||
| 17580 | */ | ||||
| 17581 | i64 nRef; /* Number of users of this page */ | ||||
| 17582 | PgHdr *pDirtyNext; /* Next element in list of dirty pages */ | ||||
| 17583 | PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ | ||||
| 17584 | /* NB: pDirtyNext and pDirtyPrev are undefined if the | ||||
| 17585 | ** PgHdr object is not dirty */ | ||||
| 17586 | }; | ||||
| 17587 | |||||
| 17588 | /* Bit values for PgHdr.flags */ | ||||
| 17589 | #define PGHDR_CLEAN0x001 0x001 /* Page not on the PCache.pDirty list */ | ||||
| 17590 | #define PGHDR_DIRTY0x002 0x002 /* Page is on the PCache.pDirty list */ | ||||
| 17591 | #define PGHDR_WRITEABLE0x004 0x004 /* Journaled and ready to modify */ | ||||
| 17592 | #define PGHDR_NEED_SYNC0x008 0x008 /* Fsync the rollback journal before | ||||
| 17593 | ** writing this page to the database */ | ||||
| 17594 | #define PGHDR_DONT_WRITE0x010 0x010 /* Do not write content to disk */ | ||||
| 17595 | #define PGHDR_MMAP0x020 0x020 /* This is an mmap page object */ | ||||
| 17596 | |||||
| 17597 | #define PGHDR_WAL_APPEND0x040 0x040 /* Appended to wal file */ | ||||
| 17598 | |||||
| 17599 | /* Initialize and shutdown the page cache subsystem */ | ||||
| 17600 | SQLITE_PRIVATEstatic int sqlite3PcacheInitialize(void); | ||||
| 17601 | SQLITE_PRIVATEstatic void sqlite3PcacheShutdown(void); | ||||
| 17602 | |||||
| 17603 | /* Page cache buffer management: | ||||
| 17604 | ** These routines implement SQLITE_CONFIG_PAGECACHE. | ||||
| 17605 | */ | ||||
| 17606 | SQLITE_PRIVATEstatic void sqlite3PCacheBufferSetup(void *, int sz, int n); | ||||
| 17607 | |||||
| 17608 | /* Create a new pager cache. | ||||
| 17609 | ** Under memory stress, invoke xStress to try to make pages clean. | ||||
| 17610 | ** Only clean and unpinned pages can be reclaimed. | ||||
| 17611 | */ | ||||
| 17612 | SQLITE_PRIVATEstatic int sqlite3PcacheOpen( | ||||
| 17613 | int szPage, /* Size of every page */ | ||||
| 17614 | int szExtra, /* Extra space associated with each page */ | ||||
| 17615 | int bPurgeable, /* True if pages are on backing store */ | ||||
| 17616 | int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ | ||||
| 17617 | void *pStress, /* Argument to xStress */ | ||||
| 17618 | PCache *pToInit /* Preallocated space for the PCache */ | ||||
| 17619 | ); | ||||
| 17620 | |||||
| 17621 | /* Modify the page-size after the cache has been created. */ | ||||
| 17622 | SQLITE_PRIVATEstatic int sqlite3PcacheSetPageSize(PCache *, int); | ||||
| 17623 | |||||
| 17624 | /* Return the size in bytes of a PCache object. Used to preallocate | ||||
| 17625 | ** storage space. | ||||
| 17626 | */ | ||||
| 17627 | SQLITE_PRIVATEstatic int sqlite3PcacheSize(void); | ||||
| 17628 | |||||
| 17629 | /* One release per successful fetch. Page is pinned until released. | ||||
| 17630 | ** Reference counted. | ||||
| 17631 | */ | ||||
| 17632 | SQLITE_PRIVATEstatic sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag); | ||||
| 17633 | SQLITE_PRIVATEstatic int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**); | ||||
| 17634 | SQLITE_PRIVATEstatic PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage); | ||||
| 17635 | SQLITE_PRIVATEstatic void sqlite3PcacheRelease(PgHdr*); | ||||
| 17636 | |||||
| 17637 | SQLITE_PRIVATEstatic void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ | ||||
| 17638 | SQLITE_PRIVATEstatic void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ | ||||
| 17639 | SQLITE_PRIVATEstatic void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ | ||||
| 17640 | SQLITE_PRIVATEstatic void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ | ||||
| 17641 | SQLITE_PRIVATEstatic void sqlite3PcacheClearWritable(PCache*); | ||||
| 17642 | |||||
| 17643 | /* Change a page number. Used by incr-vacuum. */ | ||||
| 17644 | SQLITE_PRIVATEstatic void sqlite3PcacheMove(PgHdr*, Pgno); | ||||
| 17645 | |||||
| 17646 | /* Remove all pages with pgno>x. Reset the cache if x==0 */ | ||||
| 17647 | SQLITE_PRIVATEstatic void sqlite3PcacheTruncate(PCache*, Pgno x); | ||||
| 17648 | |||||
| 17649 | /* Get a list of all dirty pages in the cache, sorted by page number */ | ||||
| 17650 | SQLITE_PRIVATEstatic PgHdr *sqlite3PcacheDirtyList(PCache*); | ||||
| 17651 | |||||
| 17652 | /* Reset and close the cache object */ | ||||
| 17653 | SQLITE_PRIVATEstatic void sqlite3PcacheClose(PCache*); | ||||
| 17654 | |||||
| 17655 | /* Clear flags from pages of the page cache */ | ||||
| 17656 | SQLITE_PRIVATEstatic void sqlite3PcacheClearSyncFlags(PCache *); | ||||
| 17657 | |||||
| 17658 | /* Discard the contents of the cache */ | ||||
| 17659 | SQLITE_PRIVATEstatic void sqlite3PcacheClear(PCache*); | ||||
| 17660 | |||||
| 17661 | /* Return the total number of outstanding page references */ | ||||
| 17662 | SQLITE_PRIVATEstatic i64 sqlite3PcacheRefCount(PCache*); | ||||
| 17663 | |||||
| 17664 | /* Increment the reference count of an existing page */ | ||||
| 17665 | SQLITE_PRIVATEstatic void sqlite3PcacheRef(PgHdr*); | ||||
| 17666 | |||||
| 17667 | SQLITE_PRIVATEstatic i64 sqlite3PcachePageRefcount(PgHdr*); | ||||
| 17668 | |||||
| 17669 | /* Return the total number of pages stored in the cache */ | ||||
| 17670 | SQLITE_PRIVATEstatic int sqlite3PcachePagecount(PCache*); | ||||
| 17671 | |||||
| 17672 | #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) | ||||
| 17673 | /* Iterate through all dirty pages currently stored in the cache. This | ||||
| 17674 | ** interface is only available if SQLITE_CHECK_PAGES is defined when the | ||||
| 17675 | ** library is built. | ||||
| 17676 | */ | ||||
| 17677 | SQLITE_PRIVATEstatic void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); | ||||
| 17678 | #endif | ||||
| 17679 | |||||
| 17680 | #if defined(SQLITE_DEBUG) | ||||
| 17681 | /* Check invariants on a PgHdr object */ | ||||
| 17682 | SQLITE_PRIVATEstatic int sqlite3PcachePageSanity(PgHdr*); | ||||
| 17683 | #endif | ||||
| 17684 | |||||
| 17685 | /* Set and get the suggested cache-size for the specified pager-cache. | ||||
| 17686 | ** | ||||
| 17687 | ** If no global maximum is configured, then the system attempts to limit | ||||
| 17688 | ** the total number of pages cached by purgeable pager-caches to the sum | ||||
| 17689 | ** of the suggested cache-sizes. | ||||
| 17690 | */ | ||||
| 17691 | SQLITE_PRIVATEstatic void sqlite3PcacheSetCachesize(PCache *, int); | ||||
| 17692 | #ifdef SQLITE_TEST | ||||
| 17693 | SQLITE_PRIVATEstatic int sqlite3PcacheGetCachesize(PCache *); | ||||
| 17694 | #endif | ||||
| 17695 | |||||
| 17696 | /* Set or get the suggested spill-size for the specified pager-cache. | ||||
| 17697 | ** | ||||
| 17698 | ** The spill-size is the minimum number of pages in cache before the cache | ||||
| 17699 | ** will attempt to spill dirty pages by calling xStress. | ||||
| 17700 | */ | ||||
| 17701 | SQLITE_PRIVATEstatic int sqlite3PcacheSetSpillsize(PCache *, int); | ||||
| 17702 | |||||
| 17703 | /* Free up as much memory as possible from the page cache */ | ||||
| 17704 | SQLITE_PRIVATEstatic void sqlite3PcacheShrink(PCache*); | ||||
| 17705 | |||||
| 17706 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 17707 | /* Try to return memory used by the pcache module to the main memory heap */ | ||||
| 17708 | SQLITE_PRIVATEstatic int sqlite3PcacheReleaseMemory(int); | ||||
| 17709 | #endif | ||||
| 17710 | |||||
| 17711 | #ifdef SQLITE_TEST | ||||
| 17712 | SQLITE_PRIVATEstatic void sqlite3PcacheStats(int*,int*,int*,int*); | ||||
| 17713 | #endif | ||||
| 17714 | |||||
| 17715 | SQLITE_PRIVATEstatic void sqlite3PCacheSetDefault(void); | ||||
| 17716 | |||||
| 17717 | /* Return the header size */ | ||||
| 17718 | SQLITE_PRIVATEstatic int sqlite3HeaderSizePcache(void); | ||||
| 17719 | SQLITE_PRIVATEstatic int sqlite3HeaderSizePcache1(void); | ||||
| 17720 | |||||
| 17721 | /* Number of dirty pages as a percentage of the configured cache size */ | ||||
| 17722 | SQLITE_PRIVATEstatic int sqlite3PCachePercentDirty(PCache*); | ||||
| 17723 | |||||
| 17724 | #ifdef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 17725 | SQLITE_PRIVATEstatic int sqlite3PCacheIsDirty(PCache *pCache); | ||||
| 17726 | #endif | ||||
| 17727 | |||||
| 17728 | #endif /* _PCACHE_H_ */ | ||||
| 17729 | |||||
| 17730 | /************** End of pcache.h **********************************************/ | ||||
| 17731 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 17732 | /************** Include mutex.h in the middle of sqliteInt.h *****************/ | ||||
| 17733 | /************** Begin file mutex.h *******************************************/ | ||||
| 17734 | /* | ||||
| 17735 | ** 2007 August 28 | ||||
| 17736 | ** | ||||
| 17737 | ** The author disclaims copyright to this source code. In place of | ||||
| 17738 | ** a legal notice, here is a blessing: | ||||
| 17739 | ** | ||||
| 17740 | ** May you do good and not evil. | ||||
| 17741 | ** May you find forgiveness for yourself and forgive others. | ||||
| 17742 | ** May you share freely, never taking more than you give. | ||||
| 17743 | ** | ||||
| 17744 | ************************************************************************* | ||||
| 17745 | ** | ||||
| 17746 | ** This file contains the common header for all mutex implementations. | ||||
| 17747 | ** The sqliteInt.h header #includes this file so that it is available | ||||
| 17748 | ** to all source files. We break it out in an effort to keep the code | ||||
| 17749 | ** better organized. | ||||
| 17750 | ** | ||||
| 17751 | ** NOTE: source files should *not* #include this header file directly. | ||||
| 17752 | ** Source files should #include the sqliteInt.h file and let that file | ||||
| 17753 | ** include this one indirectly. | ||||
| 17754 | */ | ||||
| 17755 | |||||
| 17756 | |||||
| 17757 | /* | ||||
| 17758 | ** Figure out what version of the code to use. The choices are | ||||
| 17759 | ** | ||||
| 17760 | ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The | ||||
| 17761 | ** mutexes implementation cannot be overridden | ||||
| 17762 | ** at start-time. | ||||
| 17763 | ** | ||||
| 17764 | ** SQLITE_MUTEX_NOOP For single-threaded applications. No | ||||
| 17765 | ** mutual exclusion is provided. But this | ||||
| 17766 | ** implementation can be overridden at | ||||
| 17767 | ** start-time. | ||||
| 17768 | ** | ||||
| 17769 | ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. | ||||
| 17770 | ** | ||||
| 17771 | ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. | ||||
| 17772 | */ | ||||
| 17773 | #if !SQLITE_THREADSAFE2 | ||||
| 17774 | # define SQLITE_MUTEX_OMIT | ||||
| 17775 | #endif | ||||
| 17776 | #if SQLITE_THREADSAFE2 && !defined(SQLITE_MUTEX_NOOP) | ||||
| 17777 | # if SQLITE_OS_UNIX1 | ||||
| 17778 | # define SQLITE_MUTEX_PTHREADS | ||||
| 17779 | # elif SQLITE_OS_WIN0 | ||||
| 17780 | # define SQLITE_MUTEX_W32 | ||||
| 17781 | # else | ||||
| 17782 | # define SQLITE_MUTEX_NOOP | ||||
| 17783 | # endif | ||||
| 17784 | #endif | ||||
| 17785 | |||||
| 17786 | #ifdef SQLITE_MUTEX_OMIT | ||||
| 17787 | /* | ||||
| 17788 | ** If this is a no-op implementation, implement everything as macros. | ||||
| 17789 | */ | ||||
| 17790 | #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) | ||||
| 17791 | #define sqlite3_mutex_free(X) | ||||
| 17792 | #define sqlite3_mutex_enter(X) | ||||
| 17793 | #define sqlite3_mutex_try(X) SQLITE_OK0 | ||||
| 17794 | #define sqlite3_mutex_leave(X) | ||||
| 17795 | #define sqlite3_mutex_held(X) ((void)(X),1) | ||||
| 17796 | #define sqlite3_mutex_notheld(X) ((void)(X),1) | ||||
| 17797 | #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) | ||||
| 17798 | #define sqlite3MutexInit() SQLITE_OK0 | ||||
| 17799 | #define sqlite3MutexEnd() | ||||
| 17800 | #define MUTEX_LOGIC(X)X | ||||
| 17801 | #else | ||||
| 17802 | #define MUTEX_LOGIC(X)X X | ||||
| 17803 | SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); | ||||
| 17804 | #endif /* defined(SQLITE_MUTEX_OMIT) */ | ||||
| 17805 | |||||
| 17806 | /************** End of mutex.h ***********************************************/ | ||||
| 17807 | /************** Continuing where we left off in sqliteInt.h ******************/ | ||||
| 17808 | |||||
| 17809 | /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default | ||||
| 17810 | ** synchronous setting to EXTRA. It is no longer supported. | ||||
| 17811 | */ | ||||
| 17812 | #ifdef SQLITE_EXTRA_DURABLE | ||||
| 17813 | # warning Use SQLITE_DEFAULT_SYNCHRONOUS2=3 instead of SQLITE_EXTRA_DURABLE | ||||
| 17814 | # define SQLITE_DEFAULT_SYNCHRONOUS2 3 | ||||
| 17815 | #endif | ||||
| 17816 | |||||
| 17817 | /* | ||||
| 17818 | ** Default synchronous levels. | ||||
| 17819 | ** | ||||
| 17820 | ** Note that (for historical reasons) the PAGER_SYNCHRONOUS_* macros differ | ||||
| 17821 | ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1. | ||||
| 17822 | ** | ||||
| 17823 | ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS | ||||
| 17824 | ** OFF 1 0 | ||||
| 17825 | ** NORMAL 2 1 | ||||
| 17826 | ** FULL 3 2 | ||||
| 17827 | ** EXTRA 4 3 | ||||
| 17828 | ** | ||||
| 17829 | ** The "PRAGMA synchronous" statement also uses the zero-based numbers. | ||||
| 17830 | ** In other words, the zero-based numbers are used for all external interfaces | ||||
| 17831 | ** and the one-based values are used internally. | ||||
| 17832 | */ | ||||
| 17833 | #ifndef SQLITE_DEFAULT_SYNCHRONOUS2 | ||||
| 17834 | # define SQLITE_DEFAULT_SYNCHRONOUS2 2 | ||||
| 17835 | #endif | ||||
| 17836 | #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS1 | ||||
| 17837 | # define SQLITE_DEFAULT_WAL_SYNCHRONOUS1 SQLITE_DEFAULT_SYNCHRONOUS2 | ||||
| 17838 | #endif | ||||
| 17839 | |||||
| 17840 | /* | ||||
| 17841 | ** Each database file to be accessed by the system is an instance | ||||
| 17842 | ** of the following structure. There are normally two of these structures | ||||
| 17843 | ** in the sqlite.aDb[] array. aDb[0] is the main database file and | ||||
| 17844 | ** aDb[1] is the database file used to hold temporary tables. Additional | ||||
| 17845 | ** databases may be attached. | ||||
| 17846 | */ | ||||
| 17847 | struct Db { | ||||
| 17848 | char *zDbSName; /* Name of this database. (schema name, not filename) */ | ||||
| 17849 | Btree *pBt; /* The B*Tree structure for this database file */ | ||||
| 17850 | u8 safety_level; /* How aggressive at syncing data to disk */ | ||||
| 17851 | u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */ | ||||
| 17852 | Schema *pSchema; /* Pointer to database schema (possibly shared) */ | ||||
| 17853 | }; | ||||
| 17854 | |||||
| 17855 | /* | ||||
| 17856 | ** An instance of the following structure stores a database schema. | ||||
| 17857 | ** | ||||
| 17858 | ** Most Schema objects are associated with a Btree. The exception is | ||||
| 17859 | ** the Schema for the TEMP database (sqlite3.aDb[1]) which is free-standing. | ||||
| 17860 | ** In shared cache mode, a single Schema object can be shared by multiple | ||||
| 17861 | ** Btrees that refer to the same underlying BtShared object. | ||||
| 17862 | ** | ||||
| 17863 | ** Schema objects are automatically deallocated when the last Btree that | ||||
| 17864 | ** references them is destroyed. The TEMP Schema is manually freed by | ||||
| 17865 | ** sqlite3_close(). | ||||
| 17866 | * | ||||
| 17867 | ** A thread must be holding a mutex on the corresponding Btree in order | ||||
| 17868 | ** to access Schema content. This implies that the thread must also be | ||||
| 17869 | ** holding a mutex on the sqlite3 connection pointer that owns the Btree. | ||||
| 17870 | ** For a TEMP Schema, only the connection mutex is required. | ||||
| 17871 | */ | ||||
| 17872 | struct Schema { | ||||
| 17873 | int schema_cookie; /* Database schema version number for this file */ | ||||
| 17874 | int iGeneration; /* Generation counter. Incremented with each change */ | ||||
| 17875 | Hash tblHash; /* All tables indexed by name */ | ||||
| 17876 | Hash idxHash; /* All (named) indices indexed by name */ | ||||
| 17877 | Hash trigHash; /* All triggers indexed by name */ | ||||
| 17878 | Hash fkeyHash; /* All foreign keys by referenced table name */ | ||||
| 17879 | Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ | ||||
| 17880 | u8 file_format; /* Schema format version for this file */ | ||||
| 17881 | u8 enc; /* Text encoding used by this database */ | ||||
| 17882 | u16 schemaFlags; /* Flags associated with this schema */ | ||||
| 17883 | int cache_size; /* Number of pages to use in the cache */ | ||||
| 17884 | }; | ||||
| 17885 | |||||
| 17886 | /* | ||||
| 17887 | ** These macros can be used to test, set, or clear bits in the | ||||
| 17888 | ** Db.pSchema->flags field. | ||||
| 17889 | */ | ||||
| 17890 | #define DbHasProperty(D,I,P)(((D)->aDb[I].pSchema->schemaFlags&(P))==(P)) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P)) | ||||
| 17891 | #define DbHasAnyProperty(D,I,P)(((D)->aDb[I].pSchema->schemaFlags&(P))!=0) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0) | ||||
| 17892 | #define DbSetProperty(D,I,P)(D)->aDb[I].pSchema->schemaFlags|=(P) (D)->aDb[I].pSchema->schemaFlags|=(P) | ||||
| 17893 | #define DbClearProperty(D,I,P)(D)->aDb[I].pSchema->schemaFlags&=~(P) (D)->aDb[I].pSchema->schemaFlags&=~(P) | ||||
| 17894 | |||||
| 17895 | /* | ||||
| 17896 | ** Allowed values for the DB.pSchema->flags field. | ||||
| 17897 | ** | ||||
| 17898 | ** The DB_SchemaLoaded flag is set after the database schema has been | ||||
| 17899 | ** read into internal hash tables. | ||||
| 17900 | ** | ||||
| 17901 | ** DB_UnresetViews means that one or more views have column names that | ||||
| 17902 | ** have been filled out. If the schema changes, these column names might | ||||
| 17903 | ** changes and so the view will need to be reset. | ||||
| 17904 | */ | ||||
| 17905 | #define DB_SchemaLoaded0x0001 0x0001 /* The schema has been loaded */ | ||||
| 17906 | #define DB_UnresetViews0x0002 0x0002 /* Some views have defined column names */ | ||||
| 17907 | #define DB_ResetWanted0x0008 0x0008 /* Reset the schema when nSchemaLock==0 */ | ||||
| 17908 | |||||
| 17909 | /* | ||||
| 17910 | ** The number of different kinds of things that can be limited | ||||
| 17911 | ** using the sqlite3_limit() interface. | ||||
| 17912 | */ | ||||
| 17913 | #define SQLITE_N_LIMIT(11 +1) (SQLITE_LIMIT_WORKER_THREADS11+1) | ||||
| 17914 | |||||
| 17915 | /* | ||||
| 17916 | ** Lookaside malloc is a set of fixed-size buffers that can be used | ||||
| 17917 | ** to satisfy small transient memory allocation requests for objects | ||||
| 17918 | ** associated with a particular database connection. The use of | ||||
| 17919 | ** lookaside malloc provides a significant performance enhancement | ||||
| 17920 | ** (approx 10%) by avoiding numerous malloc/free requests while parsing | ||||
| 17921 | ** SQL statements. | ||||
| 17922 | ** | ||||
| 17923 | ** The Lookaside structure holds configuration information about the | ||||
| 17924 | ** lookaside malloc subsystem. Each available memory allocation in | ||||
| 17925 | ** the lookaside subsystem is stored on a linked list of LookasideSlot | ||||
| 17926 | ** objects. | ||||
| 17927 | ** | ||||
| 17928 | ** Lookaside allocations are only allowed for objects that are associated | ||||
| 17929 | ** with a particular database connection. Hence, schema information cannot | ||||
| 17930 | ** be stored in lookaside because in shared cache mode the schema information | ||||
| 17931 | ** is shared by multiple database connections. Therefore, while parsing | ||||
| 17932 | ** schema information, the Lookaside.bEnabled flag is cleared so that | ||||
| 17933 | ** lookaside allocations are not used to construct the schema objects. | ||||
| 17934 | ** | ||||
| 17935 | ** New lookaside allocations are only allowed if bDisable==0. When | ||||
| 17936 | ** bDisable is greater than zero, sz is set to zero which effectively | ||||
| 17937 | ** disables lookaside without adding a new test for the bDisable flag | ||||
| 17938 | ** in a performance-critical path. sz should be set by to szTrue whenever | ||||
| 17939 | ** bDisable changes back to zero. | ||||
| 17940 | ** | ||||
| 17941 | ** Lookaside buffers are initially held on the pInit list. As they are | ||||
| 17942 | ** used and freed, they are added back to the pFree list. New allocations | ||||
| 17943 | ** come off of pFree first, then pInit as a fallback. This dual-list | ||||
| 17944 | ** allows use to compute a high-water mark - the maximum number of allocations | ||||
| 17945 | ** outstanding at any point in the past - by subtracting the number of | ||||
| 17946 | ** allocations on the pInit list from the total number of allocations. | ||||
| 17947 | ** | ||||
| 17948 | ** Enhancement on 2019-12-12: Two-size-lookaside | ||||
| 17949 | ** The default lookaside configuration is 100 slots of 1200 bytes each. | ||||
| 17950 | ** The larger slot sizes are important for performance, but they waste | ||||
| 17951 | ** a lot of space, as most lookaside allocations are less than 128 bytes. | ||||
| 17952 | ** The two-size-lookaside enhancement breaks up the lookaside allocation | ||||
| 17953 | ** into two pools: One of 128-byte slots and the other of the default size | ||||
| 17954 | ** (1200-byte) slots. Allocations are filled from the small-pool first, | ||||
| 17955 | ** failing over to the full-size pool if that does not work. Thus more | ||||
| 17956 | ** lookaside slots are available while also using less memory. | ||||
| 17957 | ** This enhancement can be omitted by compiling with | ||||
| 17958 | ** SQLITE_OMIT_TWOSIZE_LOOKASIDE. | ||||
| 17959 | */ | ||||
| 17960 | struct Lookaside { | ||||
| 17961 | u32 bDisable; /* Only operate the lookaside when zero */ | ||||
| 17962 | u16 sz; /* Size of each buffer in bytes */ | ||||
| 17963 | u16 szTrue; /* True value of sz, even if disabled */ | ||||
| 17964 | u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ | ||||
| 17965 | u32 nSlot; /* Number of lookaside slots allocated */ | ||||
| 17966 | u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ | ||||
| 17967 | LookasideSlot *pInit; /* List of buffers not previously used */ | ||||
| 17968 | LookasideSlot *pFree; /* List of available buffers */ | ||||
| 17969 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 17970 | LookasideSlot *pSmallInit; /* List of small buffers not previously used */ | ||||
| 17971 | LookasideSlot *pSmallFree; /* List of available small buffers */ | ||||
| 17972 | void *pMiddle; /* First byte past end of full-size buffers and | ||||
| 17973 | ** the first byte of LOOKASIDE_SMALL buffers */ | ||||
| 17974 | #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ | ||||
| 17975 | void *pStart; /* First byte of available memory space */ | ||||
| 17976 | void *pEnd; /* First byte past end of available space */ | ||||
| 17977 | void *pTrueEnd; /* True value of pEnd, when db->pnBytesFreed!=0 */ | ||||
| 17978 | }; | ||||
| 17979 | struct LookasideSlot { | ||||
| 17980 | LookasideSlot *pNext; /* Next buffer in the list of free buffers */ | ||||
| 17981 | }; | ||||
| 17982 | |||||
| 17983 | #define DisableLookasidedb->lookaside.bDisable++;db->lookaside.sz=0 db->lookaside.bDisable++;db->lookaside.sz=0 | ||||
| 17984 | #define EnableLookasidedb->lookaside.bDisable--; db->lookaside.sz=db->lookaside .bDisable?0:db->lookaside.szTrue db->lookaside.bDisable--;\ | ||||
| 17985 | db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue | ||||
| 17986 | |||||
| 17987 | /* Size of the smaller allocations in two-size lookaside */ | ||||
| 17988 | #ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 17989 | # define LOOKASIDE_SMALL128 0 | ||||
| 17990 | #else | ||||
| 17991 | # define LOOKASIDE_SMALL128 128 | ||||
| 17992 | #endif | ||||
| 17993 | |||||
| 17994 | /* | ||||
| 17995 | ** A hash table for built-in function definitions. (Application-defined | ||||
| 17996 | ** functions use a regular table table from hash.h.) | ||||
| 17997 | ** | ||||
| 17998 | ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. | ||||
| 17999 | ** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH() | ||||
| 18000 | ** macro to compute a hash on the function name. | ||||
| 18001 | */ | ||||
| 18002 | #define SQLITE_FUNC_HASH_SZ23 23 | ||||
| 18003 | struct FuncDefHash { | ||||
| 18004 | FuncDef *a[SQLITE_FUNC_HASH_SZ23]; /* Hash table for functions */ | ||||
| 18005 | }; | ||||
| 18006 | #define SQLITE_FUNC_HASH(C,L)(((C)+(L))%23) (((C)+(L))%SQLITE_FUNC_HASH_SZ23) | ||||
| 18007 | |||||
| 18008 | /* | ||||
| 18009 | ** typedef for the authorization callback function. | ||||
| 18010 | */ | ||||
| 18011 | typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, | ||||
| 18012 | const char*); | ||||
| 18013 | |||||
| 18014 | #ifndef SQLITE_OMIT_DEPRECATED1 | ||||
| 18015 | /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing | ||||
| 18016 | ** in the style of sqlite3_trace() | ||||
| 18017 | */ | ||||
| 18018 | #define SQLITE_TRACE_LEGACY0 0x40 /* Use the legacy xTrace */ | ||||
| 18019 | #define SQLITE_TRACE_XPROFILE0 0x80 /* Use the legacy xProfile */ | ||||
| 18020 | #else | ||||
| 18021 | #define SQLITE_TRACE_LEGACY0 0 | ||||
| 18022 | #define SQLITE_TRACE_XPROFILE0 0 | ||||
| 18023 | #endif /* SQLITE_OMIT_DEPRECATED */ | ||||
| 18024 | #define SQLITE_TRACE_NONLEGACY_MASK0x0f 0x0f /* Normal flags */ | ||||
| 18025 | |||||
| 18026 | /* | ||||
| 18027 | ** Maximum number of sqlite3.aDb[] entries. This is the number of attached | ||||
| 18028 | ** databases plus 2 for "main" and "temp". | ||||
| 18029 | */ | ||||
| 18030 | #define SQLITE_MAX_DB(10 +2) (SQLITE_MAX_ATTACHED10+2) | ||||
| 18031 | |||||
| 18032 | /* | ||||
| 18033 | ** Each database connection is an instance of the following structure. | ||||
| 18034 | */ | ||||
| 18035 | struct sqlite3 { | ||||
| 18036 | sqlite3_vfs *pVfs; /* OS Interface */ | ||||
| 18037 | struct Vdbe *pVdbe; /* List of active virtual machines */ | ||||
| 18038 | CollSeq *pDfltColl; /* BINARY collseq for the database encoding */ | ||||
| 18039 | sqlite3_mutex *mutex; /* Connection mutex */ | ||||
| 18040 | Db *aDb; /* All backends */ | ||||
| 18041 | int nDb; /* Number of backends currently in use */ | ||||
| 18042 | u32 mDbFlags; /* flags recording internal state */ | ||||
| 18043 | u64 flags; /* flags settable by pragmas. See below */ | ||||
| 18044 | i64 lastRowid; /* ROWID of most recent insert (see above) */ | ||||
| 18045 | i64 szMmap; /* Default mmap_size setting */ | ||||
| 18046 | u32 nSchemaLock; /* Do not reset the schema when non-zero */ | ||||
| 18047 | unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ | ||||
| 18048 | int errCode; /* Most recent error code (SQLITE_*) */ | ||||
| 18049 | int errByteOffset; /* Byte offset of error in SQL statement */ | ||||
| 18050 | int errMask; /* & result codes with this before returning */ | ||||
| 18051 | int iSysErrno; /* Errno value from last system error */ | ||||
| 18052 | u32 dbOptFlags; /* Flags to enable/disable optimizations */ | ||||
| 18053 | u8 enc; /* Text encoding */ | ||||
| 18054 | u8 autoCommit; /* The auto-commit flag. */ | ||||
| 18055 | u8 temp_store; /* 1: file 2: memory 0: default */ | ||||
| 18056 | u8 mallocFailed; /* True if we have seen a malloc failure */ | ||||
| 18057 | u8 bBenignMalloc; /* Do not require OOMs if true */ | ||||
| 18058 | u8 dfltLockMode; /* Default locking-mode for attached dbs */ | ||||
| 18059 | signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ | ||||
| 18060 | u8 suppressErr; /* Do not issue error messages if true */ | ||||
| 18061 | u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ | ||||
| 18062 | u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ | ||||
| 18063 | u8 mTrace; /* zero or more SQLITE_TRACE flags */ | ||||
| 18064 | u8 noSharedCache; /* True if no shared-cache backends */ | ||||
| 18065 | u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */ | ||||
| 18066 | u8 eOpenState; /* Current condition of the connection */ | ||||
| 18067 | int nextPagesize; /* Pagesize after VACUUM if >0 */ | ||||
| 18068 | i64 nChange; /* Value returned by sqlite3_changes() */ | ||||
| 18069 | i64 nTotalChange; /* Value returned by sqlite3_total_changes() */ | ||||
| 18070 | int aLimit[SQLITE_N_LIMIT(11 +1)]; /* Limits */ | ||||
| 18071 | int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */ | ||||
| 18072 | struct sqlite3InitInfo { /* Information used during initialization */ | ||||
| 18073 | Pgno newTnum; /* Rootpage of table being initialized */ | ||||
| 18074 | u8 iDb; /* Which db file is being initialized */ | ||||
| 18075 | u8 busy; /* TRUE if currently initializing */ | ||||
| 18076 | unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */ | ||||
| 18077 | unsigned imposterTable : 1; /* Building an imposter table */ | ||||
| 18078 | unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */ | ||||
| 18079 | const char **azInit; /* "type", "name", and "tbl_name" columns */ | ||||
| 18080 | } init; | ||||
| 18081 | int nVdbeActive; /* Number of VDBEs currently running */ | ||||
| 18082 | int nVdbeRead; /* Number of active VDBEs that read or write */ | ||||
| 18083 | int nVdbeWrite; /* Number of active VDBEs that read and write */ | ||||
| 18084 | int nVdbeExec; /* Number of nested calls to VdbeExec() */ | ||||
| 18085 | int nVDestroy; /* Number of active OP_VDestroy operations */ | ||||
| 18086 | int nExtension; /* Number of loaded extensions */ | ||||
| 18087 | void **aExtension; /* Array of shared library handles */ | ||||
| 18088 | union { | ||||
| 18089 | void (*xLegacy)(void*,const char*); /* mTrace==SQLITE_TRACE_LEGACY */ | ||||
| 18090 | int (*xV2)(u32,void*,void*,void*); /* All other mTrace values */ | ||||
| 18091 | } trace; | ||||
| 18092 | void *pTraceArg; /* Argument to the trace function */ | ||||
| 18093 | #ifndef SQLITE_OMIT_DEPRECATED1 | ||||
| 18094 | void (*xProfile)(void*,const char*,u64); /* Profiling function */ | ||||
| 18095 | void *pProfileArg; /* Argument to profile function */ | ||||
| 18096 | #endif | ||||
| 18097 | void *pCommitArg; /* Argument to xCommitCallback() */ | ||||
| 18098 | int (*xCommitCallback)(void*); /* Invoked at every commit. */ | ||||
| 18099 | void *pRollbackArg; /* Argument to xRollbackCallback() */ | ||||
| 18100 | void (*xRollbackCallback)(void*); /* Invoked at every commit. */ | ||||
| 18101 | void *pUpdateArg; | ||||
| 18102 | void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); | ||||
| 18103 | void *pAutovacPagesArg; /* Client argument to autovac_pages */ | ||||
| 18104 | void (*xAutovacDestr)(void*); /* Destructor for pAutovacPAgesArg */ | ||||
| 18105 | unsigned int (*xAutovacPages)(void*,const char*,u32,u32,u32); | ||||
| 18106 | Parse *pParse; /* Current parse */ | ||||
| 18107 | #ifdef SQLITE_ENABLE_PREUPDATE_HOOK1 | ||||
| 18108 | void *pPreUpdateArg; /* First argument to xPreUpdateCallback */ | ||||
| 18109 | void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */ | ||||
| 18110 | void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64 | ||||
| 18111 | ); | ||||
| 18112 | PreUpdate *pPreUpdate; /* Context for active pre-update callback */ | ||||
| 18113 | #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ | ||||
| 18114 | #ifndef SQLITE_OMIT_WAL | ||||
| 18115 | int (*xWalCallback)(void *, sqlite3 *, const char *, int); | ||||
| 18116 | void *pWalArg; | ||||
| 18117 | #endif | ||||
| 18118 | void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); | ||||
| 18119 | void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); | ||||
| 18120 | void *pCollNeededArg; | ||||
| 18121 | sqlite3_value *pErr; /* Most recent error message */ | ||||
| 18122 | union { | ||||
| 18123 | volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ | ||||
| 18124 | double notUsed1; /* Spacer */ | ||||
| 18125 | } u1; | ||||
| 18126 | Lookaside lookaside; /* Lookaside malloc configuration */ | ||||
| 18127 | #ifndef SQLITE_OMIT_AUTHORIZATION | ||||
| 18128 | sqlite3_xauth xAuth; /* Access authorization function */ | ||||
| 18129 | void *pAuthArg; /* 1st argument to the access auth function */ | ||||
| 18130 | #endif | ||||
| 18131 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK1 | ||||
| 18132 | int (*xProgress)(void *); /* The progress callback */ | ||||
| 18133 | void *pProgressArg; /* Argument to the progress callback */ | ||||
| 18134 | unsigned nProgressOps; /* Number of opcodes for progress callback */ | ||||
| 18135 | #endif | ||||
| 18136 | #ifndef SQLITE_OMIT_VIRTUALTABLE | ||||
| 18137 | int nVTrans; /* Allocated size of aVTrans */ | ||||
| 18138 | Hash aModule; /* populated by sqlite3_create_module() */ | ||||
| 18139 | VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ | ||||
| 18140 | VTable **aVTrans; /* Virtual tables with open transactions */ | ||||
| 18141 | VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ | ||||
| 18142 | #endif | ||||
| 18143 | Hash aFunc; /* Hash table of connection functions */ | ||||
| 18144 | Hash aCollSeq; /* All collating sequences */ | ||||
| 18145 | BusyHandler busyHandler; /* Busy callback */ | ||||
| 18146 | Db aDbStatic[2]; /* Static space for the 2 default backends */ | ||||
| 18147 | Savepoint *pSavepoint; /* List of active savepoints */ | ||||
| 18148 | int nAnalysisLimit; /* Number of index rows to ANALYZE */ | ||||
| 18149 | int busyTimeout; /* Busy handler timeout, in msec */ | ||||
| 18150 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 18151 | int setlkTimeout; /* Blocking lock timeout, in msec. -1 -> inf. */ | ||||
| 18152 | int setlkFlags; /* Flags passed to setlk_timeout() */ | ||||
| 18153 | #endif | ||||
| 18154 | int nSavepoint; /* Number of non-transaction savepoints */ | ||||
| 18155 | int nStatement; /* Number of nested statement-transactions */ | ||||
| 18156 | i64 nDeferredCons; /* Net deferred constraints this transaction. */ | ||||
| 18157 | i64 nDeferredImmCons; /* Net deferred immediate constraints */ | ||||
| 18158 | int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ | ||||
| 18159 | DbClientData *pDbData; /* sqlite3_set_clientdata() content */ | ||||
| 18160 | #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY | ||||
| 18161 | /* The following variables are all protected by the STATIC_MAIN | ||||
| 18162 | ** mutex, not by sqlite3.mutex. They are used by code in notify.c. | ||||
| 18163 | ** | ||||
| 18164 | ** When X.pUnlockConnection==Y, that means that X is waiting for Y to | ||||
| 18165 | ** unlock so that it can proceed. | ||||
| 18166 | ** | ||||
| 18167 | ** When X.pBlockingConnection==Y, that means that something that X tried | ||||
| 18168 | ** tried to do recently failed with an SQLITE_LOCKED error due to locks | ||||
| 18169 | ** held by Y. | ||||
| 18170 | */ | ||||
| 18171 | sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ | ||||
| 18172 | sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ | ||||
| 18173 | void *pUnlockArg; /* Argument to xUnlockNotify */ | ||||
| 18174 | void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ | ||||
| 18175 | sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ | ||||
| 18176 | #endif | ||||
| 18177 | }; | ||||
| 18178 | |||||
| 18179 | /* | ||||
| 18180 | ** A macro to discover the encoding of a database. | ||||
| 18181 | */ | ||||
| 18182 | #define SCHEMA_ENC(db)((db)->aDb[0].pSchema->enc) ((db)->aDb[0].pSchema->enc) | ||||
| 18183 | #define ENC(db)((db)->enc) ((db)->enc) | ||||
| 18184 | |||||
| 18185 | /* | ||||
| 18186 | ** A u64 constant where the lower 32 bits are all zeros. Only the | ||||
| 18187 | ** upper 32 bits are included in the argument. Necessary because some | ||||
| 18188 | ** C-compilers still do not accept LL integer literals. | ||||
| 18189 | */ | ||||
| 18190 | #define HI(X)((u64)(X)<<32) ((u64)(X)<<32) | ||||
| 18191 | |||||
| 18192 | /* | ||||
| 18193 | ** Possible values for the sqlite3.flags. | ||||
| 18194 | ** | ||||
| 18195 | ** Value constraints (enforced via assert()): | ||||
| 18196 | ** SQLITE_FullFSync == PAGER_FULLFSYNC | ||||
| 18197 | ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC | ||||
| 18198 | ** SQLITE_CacheSpill == PAGER_CACHE_SPILL | ||||
| 18199 | */ | ||||
| 18200 | #define SQLITE_WriteSchema0x00000001 0x00000001 /* OK to update SQLITE_SCHEMA */ | ||||
| 18201 | #define SQLITE_LegacyFileFmt0x00000002 0x00000002 /* Create new databases in format 1 */ | ||||
| 18202 | #define SQLITE_FullColNames0x00000004 0x00000004 /* Show full column names on SELECT */ | ||||
| 18203 | #define SQLITE_FullFSync0x00000008 0x00000008 /* Use full fsync on the backend */ | ||||
| 18204 | #define SQLITE_CkptFullFSync0x00000010 0x00000010 /* Use full fsync for checkpoint */ | ||||
| 18205 | #define SQLITE_CacheSpill0x00000020 0x00000020 /* OK to spill pager cache */ | ||||
| 18206 | #define SQLITE_ShortColNames0x00000040 0x00000040 /* Show short columns names */ | ||||
| 18207 | #define SQLITE_TrustedSchema0x00000080 0x00000080 /* Allow unsafe functions and | ||||
| 18208 | ** vtabs in the schema definition */ | ||||
| 18209 | #define SQLITE_NullCallback0x00000100 0x00000100 /* Invoke the callback once if the */ | ||||
| 18210 | /* result set is empty */ | ||||
| 18211 | #define SQLITE_IgnoreChecks0x00000200 0x00000200 /* Do not enforce check constraints */ | ||||
| 18212 | #define SQLITE_StmtScanStatus0x00000400 0x00000400 /* Enable stmt_scanstats() counters */ | ||||
| 18213 | #define SQLITE_NoCkptOnClose0x00000800 0x00000800 /* No checkpoint on close()/DETACH */ | ||||
| 18214 | #define SQLITE_ReverseOrder0x00001000 0x00001000 /* Reverse unordered SELECTs */ | ||||
| 18215 | #define SQLITE_RecTriggers0x00002000 0x00002000 /* Enable recursive triggers */ | ||||
| 18216 | #define SQLITE_ForeignKeys0x00004000 0x00004000 /* Enforce foreign key constraints */ | ||||
| 18217 | #define SQLITE_AutoIndex0x00008000 0x00008000 /* Enable automatic indexes */ | ||||
| 18218 | #define SQLITE_LoadExtension0x00010000 0x00010000 /* Enable load_extension */ | ||||
| 18219 | #define SQLITE_LoadExtFunc0x00020000 0x00020000 /* Enable load_extension() SQL func */ | ||||
| 18220 | #define SQLITE_EnableTrigger0x00040000 0x00040000 /* True to enable triggers */ | ||||
| 18221 | #define SQLITE_DeferFKs0x00080000 0x00080000 /* Defer all FK constraints */ | ||||
| 18222 | #define SQLITE_QueryOnly0x00100000 0x00100000 /* Disable database changes */ | ||||
| 18223 | #define SQLITE_CellSizeCk0x00200000 0x00200000 /* Check btree cell sizes on load */ | ||||
| 18224 | #define SQLITE_Fts3Tokenizer0x00400000 0x00400000 /* Enable fts3_tokenizer(2) */ | ||||
| 18225 | #define SQLITE_EnableQPSG0x00800000 0x00800000 /* Query Planner Stability Guarantee*/ | ||||
| 18226 | #define SQLITE_TriggerEQP0x01000000 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */ | ||||
| 18227 | #define SQLITE_ResetDatabase0x02000000 0x02000000 /* Reset the database */ | ||||
| 18228 | #define SQLITE_LegacyAlter0x04000000 0x04000000 /* Legacy ALTER TABLE behaviour */ | ||||
| 18229 | #define SQLITE_NoSchemaError0x08000000 0x08000000 /* Do not report schema parse errors*/ | ||||
| 18230 | #define SQLITE_Defensive0x10000000 0x10000000 /* Input SQL is likely hostile */ | ||||
| 18231 | #define SQLITE_DqsDDL0x20000000 0x20000000 /* dbl-quoted strings allowed in DDL*/ | ||||
| 18232 | #define SQLITE_DqsDML0x40000000 0x40000000 /* dbl-quoted strings allowed in DML*/ | ||||
| 18233 | #define SQLITE_EnableView0x80000000 0x80000000 /* Enable the use of views */ | ||||
| 18234 | #define SQLITE_CountRows((u64)(0x00001)<<32) HI(0x00001)((u64)(0x00001)<<32) /* Count rows changed by INSERT, */ | ||||
| 18235 | /* DELETE, or UPDATE and return */ | ||||
| 18236 | /* the count using a callback. */ | ||||
| 18237 | #define SQLITE_CorruptRdOnly((u64)(0x00002)<<32) HI(0x00002)((u64)(0x00002)<<32) /* Prohibit writes due to error */ | ||||
| 18238 | #define SQLITE_ReadUncommit((u64)(0x00004)<<32) HI(0x00004)((u64)(0x00004)<<32) /* READ UNCOMMITTED in shared-cache */ | ||||
| 18239 | #define SQLITE_FkNoAction((u64)(0x00008)<<32) HI(0x00008)((u64)(0x00008)<<32) /* Treat all FK as NO ACTION */ | ||||
| 18240 | #define SQLITE_AttachCreate((u64)(0x00010)<<32) HI(0x00010)((u64)(0x00010)<<32) /* ATTACH allowed to create new dbs */ | ||||
| 18241 | #define SQLITE_AttachWrite((u64)(0x00020)<<32) HI(0x00020)((u64)(0x00020)<<32) /* ATTACH allowed to open for write */ | ||||
| 18242 | #define SQLITE_Comments((u64)(0x00040)<<32) HI(0x00040)((u64)(0x00040)<<32) /* Enable SQL comments */ | ||||
| 18243 | |||||
| 18244 | /* Flags used only if debugging */ | ||||
| 18245 | #ifdef SQLITE_DEBUG | ||||
| 18246 | #define SQLITE_SqlTrace HI(0x0100000)((u64)(0x0100000)<<32) /* Debug print SQL as it executes */ | ||||
| 18247 | #define SQLITE_VdbeListing HI(0x0200000)((u64)(0x0200000)<<32) /* Debug listings of VDBE progs */ | ||||
| 18248 | #define SQLITE_VdbeTrace HI(0x0400000)((u64)(0x0400000)<<32) /* True to trace VDBE execution */ | ||||
| 18249 | #define SQLITE_VdbeAddopTrace HI(0x0800000)((u64)(0x0800000)<<32) /* Trace sqlite3VdbeAddOp() calls */ | ||||
| 18250 | #define SQLITE_VdbeEQP HI(0x1000000)((u64)(0x1000000)<<32) /* Debug EXPLAIN QUERY PLAN */ | ||||
| 18251 | #define SQLITE_ParserTrace HI(0x2000000)((u64)(0x2000000)<<32) /* PRAGMA parser_trace=ON */ | ||||
| 18252 | #endif | ||||
| 18253 | |||||
| 18254 | /* | ||||
| 18255 | ** Allowed values for sqlite3.mDbFlags | ||||
| 18256 | */ | ||||
| 18257 | #define DBFLAG_SchemaChange0x0001 0x0001 /* Uncommitted Hash table changes */ | ||||
| 18258 | #define DBFLAG_PreferBuiltin0x0002 0x0002 /* Preference to built-in funcs */ | ||||
| 18259 | #define DBFLAG_Vacuum0x0004 0x0004 /* Currently in a VACUUM */ | ||||
| 18260 | #define DBFLAG_VacuumInto0x0008 0x0008 /* Currently running VACUUM INTO */ | ||||
| 18261 | #define DBFLAG_SchemaKnownOk0x0010 0x0010 /* Schema is known to be valid */ | ||||
| 18262 | #define DBFLAG_InternalFunc0x0020 0x0020 /* Allow use of internal functions */ | ||||
| 18263 | #define DBFLAG_EncodingFixed0x0040 0x0040 /* No longer possible to change enc. */ | ||||
| 18264 | |||||
| 18265 | /* | ||||
| 18266 | ** Bits of the sqlite3.dbOptFlags field that are used by the | ||||
| 18267 | ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to | ||||
| 18268 | ** selectively disable various optimizations. | ||||
| 18269 | */ | ||||
| 18270 | #define SQLITE_QueryFlattener0x00000001 0x00000001 /* Query flattening */ | ||||
| 18271 | #define SQLITE_WindowFunc0x00000002 0x00000002 /* Use xInverse for window functions */ | ||||
| 18272 | #define SQLITE_GroupByOrder0x00000004 0x00000004 /* GROUPBY cover of ORDERBY */ | ||||
| 18273 | #define SQLITE_FactorOutConst0x00000008 0x00000008 /* Constant factoring */ | ||||
| 18274 | #define SQLITE_DistinctOpt0x00000010 0x00000010 /* DISTINCT using indexes */ | ||||
| 18275 | #define SQLITE_CoverIdxScan0x00000020 0x00000020 /* Covering index scans */ | ||||
| 18276 | #define SQLITE_OrderByIdxJoin0x00000040 0x00000040 /* ORDER BY of joins via index */ | ||||
| 18277 | #define SQLITE_Transitive0x00000080 0x00000080 /* Transitive constraints */ | ||||
| 18278 | #define SQLITE_OmitNoopJoin0x00000100 0x00000100 /* Omit unused tables in joins */ | ||||
| 18279 | #define SQLITE_CountOfView0x00000200 0x00000200 /* The count-of-view optimization */ | ||||
| 18280 | #define SQLITE_CursorHints0x00000400 0x00000400 /* Add OP_CursorHint opcodes */ | ||||
| 18281 | #define SQLITE_Stat40x00000800 0x00000800 /* Use STAT4 data */ | ||||
| 18282 | /* TH3 expects this value ^^^^^^^^^^ to be 0x0000800. Don't change it */ | ||||
| 18283 | #define SQLITE_PushDown0x00001000 0x00001000 /* WHERE-clause push-down opt */ | ||||
| 18284 | #define SQLITE_SimplifyJoin0x00002000 0x00002000 /* Convert LEFT JOIN to JOIN */ | ||||
| 18285 | #define SQLITE_SkipScan0x00004000 0x00004000 /* Skip-scans */ | ||||
| 18286 | #define SQLITE_PropagateConst0x00008000 0x00008000 /* The constant propagation opt */ | ||||
| 18287 | #define SQLITE_MinMaxOpt0x00010000 0x00010000 /* The min/max optimization */ | ||||
| 18288 | #define SQLITE_SeekScan0x00020000 0x00020000 /* The OP_SeekScan optimization */ | ||||
| 18289 | #define SQLITE_OmitOrderBy0x00040000 0x00040000 /* Omit pointless ORDER BY */ | ||||
| 18290 | /* TH3 expects this value ^^^^^^^^^^ to be 0x40000. Coordinate any change */ | ||||
| 18291 | #define SQLITE_BloomFilter0x00080000 0x00080000 /* Use a Bloom filter on searches */ | ||||
| 18292 | #define SQLITE_BloomPulldown0x00100000 0x00100000 /* Run Bloom filters early */ | ||||
| 18293 | #define SQLITE_BalancedMerge0x00200000 0x00200000 /* Balance multi-way merges */ | ||||
| 18294 | #define SQLITE_ReleaseReg0x00400000 0x00400000 /* Use OP_ReleaseReg for testing */ | ||||
| 18295 | #define SQLITE_FlttnUnionAll0x00800000 0x00800000 /* Disable the UNION ALL flattener */ | ||||
| 18296 | /* TH3 expects this value ^^^^^^^^^^ See flatten04.test */ | ||||
| 18297 | #define SQLITE_IndexedExpr0x01000000 0x01000000 /* Pull exprs from index when able */ | ||||
| 18298 | #define SQLITE_Coroutines0x02000000 0x02000000 /* Co-routines for subqueries */ | ||||
| 18299 | #define SQLITE_NullUnusedCols0x04000000 0x04000000 /* NULL unused columns in subqueries */ | ||||
| 18300 | #define SQLITE_OnePass0x08000000 0x08000000 /* Single-pass DELETE and UPDATE */ | ||||
| 18301 | #define SQLITE_OrderBySubq0x10000000 0x10000000 /* ORDER BY in subquery helps outer */ | ||||
| 18302 | #define SQLITE_StarQuery0x20000000 0x20000000 /* Heurists for star queries */ | ||||
| 18303 | #define SQLITE_AllOpts0xffffffff 0xffffffff /* All optimizations */ | ||||
| 18304 | |||||
| 18305 | /* | ||||
| 18306 | ** Macros for testing whether or not optimizations are enabled or disabled. | ||||
| 18307 | */ | ||||
| 18308 | #define OptimizationDisabled(db, mask)(((db)->dbOptFlags&(mask))!=0) (((db)->dbOptFlags&(mask))!=0) | ||||
| 18309 | #define OptimizationEnabled(db, mask)(((db)->dbOptFlags&(mask))==0) (((db)->dbOptFlags&(mask))==0) | ||||
| 18310 | |||||
| 18311 | /* | ||||
| 18312 | ** Return true if it OK to factor constant expressions into the initialization | ||||
| 18313 | ** code. The argument is a Parse object for the code generator. | ||||
| 18314 | */ | ||||
| 18315 | #define ConstFactorOk(P)((P)->okConstFactor) ((P)->okConstFactor) | ||||
| 18316 | |||||
| 18317 | /* Possible values for the sqlite3.eOpenState field. | ||||
| 18318 | ** The numbers are randomly selected such that a minimum of three bits must | ||||
| 18319 | ** change to convert any number to another or to zero | ||||
| 18320 | */ | ||||
| 18321 | #define SQLITE_STATE_OPEN0x76 0x76 /* Database is open */ | ||||
| 18322 | #define SQLITE_STATE_CLOSED0xce 0xce /* Database is closed */ | ||||
| 18323 | #define SQLITE_STATE_SICK0xba 0xba /* Error and awaiting close */ | ||||
| 18324 | #define SQLITE_STATE_BUSY0x6d 0x6d /* Database currently in use */ | ||||
| 18325 | #define SQLITE_STATE_ERROR0xd5 0xd5 /* An SQLITE_MISUSE error occurred */ | ||||
| 18326 | #define SQLITE_STATE_ZOMBIE0xa7 0xa7 /* Close with last statement close */ | ||||
| 18327 | |||||
| 18328 | /* | ||||
| 18329 | ** Each SQL function is defined by an instance of the following | ||||
| 18330 | ** structure. For global built-in functions (ex: substr(), max(), count()) | ||||
| 18331 | ** a pointer to this structure is held in the sqlite3BuiltinFunctions object. | ||||
| 18332 | ** For per-connection application-defined functions, a pointer to this | ||||
| 18333 | ** structure is held in the db->aHash hash table. | ||||
| 18334 | ** | ||||
| 18335 | ** The u.pHash field is used by the global built-ins. The u.pDestructor | ||||
| 18336 | ** field is used by per-connection app-def functions. | ||||
| 18337 | */ | ||||
| 18338 | struct FuncDef { | ||||
| 18339 | i16 nArg; /* Number of arguments. -1 means unlimited */ | ||||
| 18340 | u32 funcFlags; /* Some combination of SQLITE_FUNC_* */ | ||||
| 18341 | void *pUserData; /* User data parameter */ | ||||
| 18342 | FuncDef *pNext; /* Next function with same name */ | ||||
| 18343 | void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */ | ||||
| 18344 | void (*xFinalize)(sqlite3_context*); /* Agg finalizer */ | ||||
| 18345 | void (*xValue)(sqlite3_context*); /* Current agg value */ | ||||
| 18346 | void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */ | ||||
| 18347 | const char *zName; /* SQL name of the function. */ | ||||
| 18348 | union { | ||||
| 18349 | FuncDef *pHash; /* Next with a different name but the same hash */ | ||||
| 18350 | FuncDestructor *pDestructor; /* Reference counted destructor function */ | ||||
| 18351 | } u; /* pHash if SQLITE_FUNC_BUILTIN, pDestructor otherwise */ | ||||
| 18352 | }; | ||||
| 18353 | |||||
| 18354 | /* | ||||
| 18355 | ** This structure encapsulates a user-function destructor callback (as | ||||
| 18356 | ** configured using create_function_v2()) and a reference counter. When | ||||
| 18357 | ** create_function_v2() is called to create a function with a destructor, | ||||
| 18358 | ** a single object of this type is allocated. FuncDestructor.nRef is set to | ||||
| 18359 | ** the number of FuncDef objects created (either 1 or 3, depending on whether | ||||
| 18360 | ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor | ||||
| 18361 | ** member of each of the new FuncDef objects is set to point to the allocated | ||||
| 18362 | ** FuncDestructor. | ||||
| 18363 | ** | ||||
| 18364 | ** Thereafter, when one of the FuncDef objects is deleted, the reference | ||||
| 18365 | ** count on this object is decremented. When it reaches 0, the destructor | ||||
| 18366 | ** is invoked and the FuncDestructor structure freed. | ||||
| 18367 | */ | ||||
| 18368 | struct FuncDestructor { | ||||
| 18369 | int nRef; | ||||
| 18370 | void (*xDestroy)(void *); | ||||
| 18371 | void *pUserData; | ||||
| 18372 | }; | ||||
| 18373 | |||||
| 18374 | /* | ||||
| 18375 | ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF | ||||
| 18376 | ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And | ||||
| 18377 | ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There | ||||
| 18378 | ** are assert() statements in the code to verify this. | ||||
| 18379 | ** | ||||
| 18380 | ** Value constraints (enforced via assert()): | ||||
| 18381 | ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg | ||||
| 18382 | ** SQLITE_FUNC_ANYORDER == NC_OrderAgg == SF_OrderByReqd | ||||
| 18383 | ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG | ||||
| 18384 | ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG | ||||
| 18385 | ** SQLITE_FUNC_BYTELEN == OPFLAG_BYTELENARG | ||||
| 18386 | ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API | ||||
| 18387 | ** SQLITE_FUNC_DIRECT == SQLITE_DIRECTONLY from the API | ||||
| 18388 | ** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS -- opposite meanings!!! | ||||
| 18389 | ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API | ||||
| 18390 | ** | ||||
| 18391 | ** Note that even though SQLITE_FUNC_UNSAFE and SQLITE_INNOCUOUS have the | ||||
| 18392 | ** same bit value, their meanings are inverted. SQLITE_FUNC_UNSAFE is | ||||
| 18393 | ** used internally and if set means that the function has side effects. | ||||
| 18394 | ** SQLITE_INNOCUOUS is used by application code and means "not unsafe". | ||||
| 18395 | ** See multiple instances of tag-20230109-1. | ||||
| 18396 | */ | ||||
| 18397 | #define SQLITE_FUNC_ENCMASK0x0003 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */ | ||||
| 18398 | #define SQLITE_FUNC_LIKE0x0004 0x0004 /* Candidate for the LIKE optimization */ | ||||
| 18399 | #define SQLITE_FUNC_CASE0x0008 0x0008 /* Case-sensitive LIKE-type function */ | ||||
| 18400 | #define SQLITE_FUNC_EPHEM0x0010 0x0010 /* Ephemeral. Delete with VDBE */ | ||||
| 18401 | #define SQLITE_FUNC_NEEDCOLL0x0020 0x0020 /* sqlite3GetFuncCollSeq() might be called*/ | ||||
| 18402 | #define SQLITE_FUNC_LENGTH0x0040 0x0040 /* Built-in length() function */ | ||||
| 18403 | #define SQLITE_FUNC_TYPEOF0x0080 0x0080 /* Built-in typeof() function */ | ||||
| 18404 | #define SQLITE_FUNC_BYTELEN0x00c0 0x00c0 /* Built-in octet_length() function */ | ||||
| 18405 | #define SQLITE_FUNC_COUNT0x0100 0x0100 /* Built-in count(*) aggregate */ | ||||
| 18406 | /* 0x0200 -- available for reuse */ | ||||
| 18407 | #define SQLITE_FUNC_UNLIKELY0x0400 0x0400 /* Built-in unlikely() function */ | ||||
| 18408 | #define SQLITE_FUNC_CONSTANT0x0800 0x0800 /* Constant inputs give a constant output */ | ||||
| 18409 | #define SQLITE_FUNC_MINMAX0x1000 0x1000 /* True for min() and max() aggregates */ | ||||
| 18410 | #define SQLITE_FUNC_SLOCHNG0x2000 0x2000 /* "Slow Change". Value constant during a | ||||
| 18411 | ** single query - might change over time */ | ||||
| 18412 | #define SQLITE_FUNC_TEST0x4000 0x4000 /* Built-in testing functions */ | ||||
| 18413 | #define SQLITE_FUNC_RUNONLY0x8000 0x8000 /* Cannot be used by valueFromFunction */ | ||||
| 18414 | #define SQLITE_FUNC_WINDOW0x00010000 0x00010000 /* Built-in window-only function */ | ||||
| 18415 | #define SQLITE_FUNC_INTERNAL0x00040000 0x00040000 /* For use by NestedParse() only */ | ||||
| 18416 | #define SQLITE_FUNC_DIRECT0x00080000 0x00080000 /* Not for use in TRIGGERs or VIEWs */ | ||||
| 18417 | /* SQLITE_SUBTYPE 0x00100000 // Consumer of subtypes */ | ||||
| 18418 | #define SQLITE_FUNC_UNSAFE0x00200000 0x00200000 /* Function has side effects */ | ||||
| 18419 | #define SQLITE_FUNC_INLINE0x00400000 0x00400000 /* Functions implemented in-line */ | ||||
| 18420 | #define SQLITE_FUNC_BUILTIN0x00800000 0x00800000 /* This is a built-in function */ | ||||
| 18421 | /* SQLITE_RESULT_SUBTYPE 0x01000000 // Generator of subtypes */ | ||||
| 18422 | #define SQLITE_FUNC_ANYORDER0x08000000 0x08000000 /* count/min/max aggregate */ | ||||
| 18423 | |||||
| 18424 | /* Identifier numbers for each in-line function */ | ||||
| 18425 | #define INLINEFUNC_coalesce0 0 | ||||
| 18426 | #define INLINEFUNC_implies_nonnull_row1 1 | ||||
| 18427 | #define INLINEFUNC_expr_implies_expr2 2 | ||||
| 18428 | #define INLINEFUNC_expr_compare3 3 | ||||
| 18429 | #define INLINEFUNC_affinity4 4 | ||||
| 18430 | #define INLINEFUNC_iif5 5 | ||||
| 18431 | #define INLINEFUNC_sqlite_offset6 6 | ||||
| 18432 | #define INLINEFUNC_unlikely99 99 /* Default case */ | ||||
| 18433 | |||||
| 18434 | /* | ||||
| 18435 | ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are | ||||
| 18436 | ** used to create the initializers for the FuncDef structures. | ||||
| 18437 | ** | ||||
| 18438 | ** FUNCTION(zName, nArg, iArg, bNC, xFunc) | ||||
| 18439 | ** Used to create a scalar function definition of a function zName | ||||
| 18440 | ** implemented by C function xFunc that accepts nArg arguments. The | ||||
| 18441 | ** value passed as iArg is cast to a (void*) and made available | ||||
| 18442 | ** as the user-data (sqlite3_user_data()) for the function. If | ||||
| 18443 | ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. | ||||
| 18444 | ** | ||||
| 18445 | ** VFUNCTION(zName, nArg, iArg, bNC, xFunc) | ||||
| 18446 | ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag. | ||||
| 18447 | ** | ||||
| 18448 | ** SFUNCTION(zName, nArg, iArg, bNC, xFunc) | ||||
| 18449 | ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and | ||||
| 18450 | ** adds the SQLITE_DIRECTONLY flag. | ||||
| 18451 | ** | ||||
| 18452 | ** INLINE_FUNC(zName, nArg, iFuncId, mFlags) | ||||
| 18453 | ** zName is the name of a function that is implemented by in-line | ||||
| 18454 | ** byte code rather than by the usual callbacks. The iFuncId | ||||
| 18455 | ** parameter determines the function id. The mFlags parameter is | ||||
| 18456 | ** optional SQLITE_FUNC_ flags for this function. | ||||
| 18457 | ** | ||||
| 18458 | ** TEST_FUNC(zName, nArg, iFuncId, mFlags) | ||||
| 18459 | ** zName is the name of a test-only function implemented by in-line | ||||
| 18460 | ** byte code rather than by the usual callbacks. The iFuncId | ||||
| 18461 | ** parameter determines the function id. The mFlags parameter is | ||||
| 18462 | ** optional SQLITE_FUNC_ flags for this function. | ||||
| 18463 | ** | ||||
| 18464 | ** DFUNCTION(zName, nArg, iArg, bNC, xFunc) | ||||
| 18465 | ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and | ||||
| 18466 | ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions | ||||
| 18467 | ** and functions like sqlite_version() that can change, but not during | ||||
| 18468 | ** a single query. The iArg is ignored. The user-data is always set | ||||
| 18469 | ** to a NULL pointer. The bNC parameter is not used. | ||||
| 18470 | ** | ||||
| 18471 | ** MFUNCTION(zName, nArg, xPtr, xFunc) | ||||
| 18472 | ** For math-library functions. xPtr is an arbitrary pointer. | ||||
| 18473 | ** | ||||
| 18474 | ** PURE_DATE(zName, nArg, iArg, bNC, xFunc) | ||||
| 18475 | ** Used for "pure" date/time functions, this macro is like DFUNCTION | ||||
| 18476 | ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is | ||||
| 18477 | ** ignored and the user-data for these functions is set to an | ||||
| 18478 | ** arbitrary non-NULL pointer. The bNC parameter is not used. | ||||
| 18479 | ** | ||||
| 18480 | ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) | ||||
| 18481 | ** Used to create an aggregate function definition implemented by | ||||
| 18482 | ** the C functions xStep and xFinal. The first four parameters | ||||
| 18483 | ** are interpreted in the same way as the first 4 parameters to | ||||
| 18484 | ** FUNCTION(). | ||||
| 18485 | ** | ||||
| 18486 | ** WAGGREGATE(zName, nArg, iArg, xStep, xFinal, xValue, xInverse) | ||||
| 18487 | ** Used to create an aggregate function definition implemented by | ||||
| 18488 | ** the C functions xStep and xFinal. The first four parameters | ||||
| 18489 | ** are interpreted in the same way as the first 4 parameters to | ||||
| 18490 | ** FUNCTION(). | ||||
| 18491 | ** | ||||
| 18492 | ** LIKEFUNC(zName, nArg, pArg, flags) | ||||
| 18493 | ** Used to create a scalar function definition of a function zName | ||||
| 18494 | ** that accepts nArg arguments and is implemented by a call to C | ||||
| 18495 | ** function likeFunc. Argument pArg is cast to a (void *) and made | ||||
| 18496 | ** available as the function user-data (sqlite3_user_data()). The | ||||
| 18497 | ** FuncDef.flags variable is set to the value passed as the flags | ||||
| 18498 | ** parameter. | ||||
| 18499 | */ | ||||
| 18500 | #define FUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000| 0x0800|1|(bNC*0x0020), ((void*)(long int)( iArg)), 0, xFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18501 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|\ | ||||
| 18502 | SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020), \ | ||||
| 18503 | SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18504 | #define VFUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000|1|(bNC*0x0020), ((void*)(long int)(iArg)), 0 , xFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18505 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020), \ | ||||
| 18506 | SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18507 | #define SFUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000|1|0x000080000|0x00200000, ((void*)(long int )(iArg)), 0, xFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18508 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_UTF81|SQLITE_DIRECTONLY0x000080000|SQLITE_FUNC_UNSAFE0x00200000, \ | ||||
| 18509 | SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18510 | #define MFUNCTION(zName, nArg, xPtr, xFunc){nArg, 0x00800000|0x0800|1, xPtr, 0, xFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18511 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81, \ | ||||
| 18512 | xPtr, 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18513 | #define JFUNCTION(zName, nArg, bUseCache, bWS, bRS, bJsonB, iArg, xFunc){nArg, 0x00800000|0x000000800|0x0800| 1|((bUseCache)*0x8000)| ((bRS)*0x000100000)|((bWS)*0x001000000), ((void*)(long int)( iArg|((bJsonB)*0x08))),0,xFunc,0, 0, 0, "zName", {0} } \ | ||||
| 18514 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_DETERMINISTIC0x000000800|SQLITE_FUNC_CONSTANT0x0800|\ | ||||
| 18515 | SQLITE_UTF81|((bUseCache)*SQLITE_FUNC_RUNONLY0x8000)|\ | ||||
| 18516 | ((bRS)*SQLITE_SUBTYPE0x000100000)|((bWS)*SQLITE_RESULT_SUBTYPE0x001000000), \ | ||||
| 18517 | SQLITE_INT_TO_PTR(iArg|((bJsonB)*JSON_BLOB))((void*)(long int)(iArg|((bJsonB)*0x08))),0,xFunc,0, 0, 0, #zName, {0} } | ||||
| 18518 | #define INLINE_FUNC(zName, nArg, iArg, mFlags){nArg, 0x00800000| 1|0x00400000|0x0800|(mFlags), ((void*)(long int)(iArg)), 0, versionFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18519 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|\ | ||||
| 18520 | SQLITE_UTF81|SQLITE_FUNC_INLINE0x00400000|SQLITE_FUNC_CONSTANT0x0800|(mFlags), \ | ||||
| 18521 | SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, noopFuncversionFunc, 0, 0, 0, #zName, {0} } | ||||
| 18522 | #define TEST_FUNC(zName, nArg, iArg, mFlags){nArg, 0x00800000| 1|0x00040000|0x4000| 0x00400000|0x0800|(mFlags ), ((void*)(long int)(iArg)), 0, versionFunc, 0, 0, 0, "zName" , {0} } \ | ||||
| 18523 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|\ | ||||
| 18524 | SQLITE_UTF81|SQLITE_FUNC_INTERNAL0x00040000|SQLITE_FUNC_TEST0x4000| \ | ||||
| 18525 | SQLITE_FUNC_INLINE0x00400000|SQLITE_FUNC_CONSTANT0x0800|(mFlags), \ | ||||
| 18526 | SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, noopFuncversionFunc, 0, 0, 0, #zName, {0} } | ||||
| 18527 | #define DFUNCTION(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000|0x2000|1, 0, 0, xFunc, 0, 0, 0, "zName", {0 } } \ | ||||
| 18528 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_FUNC_SLOCHNG0x2000|SQLITE_UTF81, \ | ||||
| 18529 | 0, 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18530 | #define PURE_DATE(zName, nArg, iArg, bNC, xFunc){nArg, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config , 0, xFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18531 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|\ | ||||
| 18532 | SQLITE_FUNC_SLOCHNG0x2000|SQLITE_UTF81|SQLITE_FUNC_CONSTANT0x0800, \ | ||||
| 18533 | (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18534 | #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags){nArg, 0x00800000| 0x0800|1|(bNC*0x0020)|extraFlags, ((void*) (long int)(iArg)), 0, xFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18535 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|\ | ||||
| 18536 | SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020)|extraFlags,\ | ||||
| 18537 | SQLITE_INT_TO_PTR(iArg)((void*)(long int)(iArg)), 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18538 | #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc){nArg, 0x00800000| 0x2000|1|(bNC*0x0020), pArg, 0, xFunc, 0, 0 , 0, "zName", } \ | ||||
| 18539 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|\ | ||||
| 18540 | SQLITE_FUNC_SLOCHNG0x2000|SQLITE_UTF81|(bNC*SQLITE_FUNC_NEEDCOLL0x0020), \ | ||||
| 18541 | pArg, 0, xFunc, 0, 0, 0, #zName, } | ||||
| 18542 | #define LIKEFUNC(zName, nArg, arg, flags){nArg, 0x00800000|0x0800|1|flags, (void *)arg, 0, likeFunc, 0 , 0, 0, "zName", {0} } \ | ||||
| 18543 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_FUNC_CONSTANT0x0800|SQLITE_UTF81|flags, \ | ||||
| 18544 | (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} } | ||||
| 18545 | #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f){nArg, 0x00800000|1|(nc*0x0020)|f, ((void*)(long int)(arg)), 0 , xStep,xFinal,xValue,xInverse,"zName", {0}} \ | ||||
| 18546 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|SQLITE_UTF81|(nc*SQLITE_FUNC_NEEDCOLL0x0020)|f, \ | ||||
| 18547 | SQLITE_INT_TO_PTR(arg)((void*)(long int)(arg)), 0, xStep,xFinal,xValue,xInverse,#zName, {0}} | ||||
| 18548 | #define INTERNAL_FUNCTION(zName, nArg, xFunc){nArg, 0x00800000| 0x00040000|1|0x0800, 0, 0, xFunc, 0, 0, 0, "zName", {0} } \ | ||||
| 18549 | {nArg, SQLITE_FUNC_BUILTIN0x00800000|\ | ||||
| 18550 | SQLITE_FUNC_INTERNAL0x00040000|SQLITE_UTF81|SQLITE_FUNC_CONSTANT0x0800, \ | ||||
| 18551 | 0, 0, xFunc, 0, 0, 0, #zName, {0} } | ||||
| 18552 | |||||
| 18553 | |||||
| 18554 | /* | ||||
| 18555 | ** All current savepoints are stored in a linked list starting at | ||||
| 18556 | ** sqlite3.pSavepoint. The first element in the list is the most recently | ||||
| 18557 | ** opened savepoint. Savepoints are added to the list by the vdbe | ||||
| 18558 | ** OP_Savepoint instruction. | ||||
| 18559 | */ | ||||
| 18560 | struct Savepoint { | ||||
| 18561 | char *zName; /* Savepoint name (nul-terminated) */ | ||||
| 18562 | i64 nDeferredCons; /* Number of deferred fk violations */ | ||||
| 18563 | i64 nDeferredImmCons; /* Number of deferred imm fk. */ | ||||
| 18564 | Savepoint *pNext; /* Parent savepoint (if any) */ | ||||
| 18565 | }; | ||||
| 18566 | |||||
| 18567 | /* | ||||
| 18568 | ** The following are used as the second parameter to sqlite3Savepoint(), | ||||
| 18569 | ** and as the P1 argument to the OP_Savepoint instruction. | ||||
| 18570 | */ | ||||
| 18571 | #define SAVEPOINT_BEGIN0 0 | ||||
| 18572 | #define SAVEPOINT_RELEASE1 1 | ||||
| 18573 | #define SAVEPOINT_ROLLBACK2 2 | ||||
| 18574 | |||||
| 18575 | |||||
| 18576 | /* | ||||
| 18577 | ** Each SQLite module (virtual table definition) is defined by an | ||||
| 18578 | ** instance of the following structure, stored in the sqlite3.aModule | ||||
| 18579 | ** hash table. | ||||
| 18580 | */ | ||||
| 18581 | struct Module { | ||||
| 18582 | const sqlite3_module *pModule; /* Callback pointers */ | ||||
| 18583 | const char *zName; /* Name passed to create_module() */ | ||||
| 18584 | int nRefModule; /* Number of pointers to this object */ | ||||
| 18585 | void *pAux; /* pAux passed to create_module() */ | ||||
| 18586 | void (*xDestroy)(void *); /* Module destructor function */ | ||||
| 18587 | Table *pEpoTab; /* Eponymous table for this module */ | ||||
| 18588 | }; | ||||
| 18589 | |||||
| 18590 | /* | ||||
| 18591 | ** Information about each column of an SQL table is held in an instance | ||||
| 18592 | ** of the Column structure, in the Table.aCol[] array. | ||||
| 18593 | ** | ||||
| 18594 | ** Definitions: | ||||
| 18595 | ** | ||||
| 18596 | ** "table column index" This is the index of the column in the | ||||
| 18597 | ** Table.aCol[] array, and also the index of | ||||
| 18598 | ** the column in the original CREATE TABLE stmt. | ||||
| 18599 | ** | ||||
| 18600 | ** "storage column index" This is the index of the column in the | ||||
| 18601 | ** record BLOB generated by the OP_MakeRecord | ||||
| 18602 | ** opcode. The storage column index is less than | ||||
| 18603 | ** or equal to the table column index. It is | ||||
| 18604 | ** equal if and only if there are no VIRTUAL | ||||
| 18605 | ** columns to the left. | ||||
| 18606 | ** | ||||
| 18607 | ** Notes on zCnName: | ||||
| 18608 | ** The zCnName field stores the name of the column, the datatype of the | ||||
| 18609 | ** column, and the collating sequence for the column, in that order, all in | ||||
| 18610 | ** a single allocation. Each string is 0x00 terminated. The datatype | ||||
| 18611 | ** is only included if the COLFLAG_HASTYPE bit of colFlags is set and the | ||||
| 18612 | ** collating sequence name is only included if the COLFLAG_HASCOLL bit is | ||||
| 18613 | ** set. | ||||
| 18614 | */ | ||||
| 18615 | struct Column { | ||||
| 18616 | char *zCnName; /* Name of this column */ | ||||
| 18617 | unsigned notNull :4; /* An OE_ code for handling a NOT NULL constraint */ | ||||
| 18618 | unsigned eCType :4; /* One of the standard types */ | ||||
| 18619 | char affinity; /* One of the SQLITE_AFF_... values */ | ||||
| 18620 | u8 szEst; /* Est size of value in this column. sizeof(INT)==1 */ | ||||
| 18621 | u8 hName; /* Column name hash for faster lookup */ | ||||
| 18622 | u16 iDflt; /* 1-based index of DEFAULT. 0 means "none" */ | ||||
| 18623 | u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */ | ||||
| 18624 | }; | ||||
| 18625 | |||||
| 18626 | /* Allowed values for Column.eCType. | ||||
| 18627 | ** | ||||
| 18628 | ** Values must match entries in the global constant arrays | ||||
| 18629 | ** sqlite3StdTypeLen[] and sqlite3StdType[]. Each value is one more | ||||
| 18630 | ** than the offset into these arrays for the corresponding name. | ||||
| 18631 | ** Adjust the SQLITE_N_STDTYPE value if adding or removing entries. | ||||
| 18632 | */ | ||||
| 18633 | #define COLTYPE_CUSTOM0 0 /* Type appended to zName */ | ||||
| 18634 | #define COLTYPE_ANY1 1 | ||||
| 18635 | #define COLTYPE_BLOB2 2 | ||||
| 18636 | #define COLTYPE_INT3 3 | ||||
| 18637 | #define COLTYPE_INTEGER4 4 | ||||
| 18638 | #define COLTYPE_REAL5 5 | ||||
| 18639 | #define COLTYPE_TEXT6 6 | ||||
| 18640 | #define SQLITE_N_STDTYPE6 6 /* Number of standard types */ | ||||
| 18641 | |||||
| 18642 | /* Allowed values for Column.colFlags. | ||||
| 18643 | ** | ||||
| 18644 | ** Constraints: | ||||
| 18645 | ** TF_HasVirtual == COLFLAG_VIRTUAL | ||||
| 18646 | ** TF_HasStored == COLFLAG_STORED | ||||
| 18647 | ** TF_HasHidden == COLFLAG_HIDDEN | ||||
| 18648 | */ | ||||
| 18649 | #define COLFLAG_PRIMKEY0x0001 0x0001 /* Column is part of the primary key */ | ||||
| 18650 | #define COLFLAG_HIDDEN0x0002 0x0002 /* A hidden column in a virtual table */ | ||||
| 18651 | #define COLFLAG_HASTYPE0x0004 0x0004 /* Type name follows column name */ | ||||
| 18652 | #define COLFLAG_UNIQUE0x0008 0x0008 /* Column def contains "UNIQUE" or "PK" */ | ||||
| 18653 | #define COLFLAG_SORTERREF0x0010 0x0010 /* Use sorter-refs with this column */ | ||||
| 18654 | #define COLFLAG_VIRTUAL0x0020 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */ | ||||
| 18655 | #define COLFLAG_STORED0x0040 0x0040 /* GENERATED ALWAYS AS ... STORED */ | ||||
| 18656 | #define COLFLAG_NOTAVAIL0x0080 0x0080 /* STORED column not yet calculated */ | ||||
| 18657 | #define COLFLAG_BUSY0x0100 0x0100 /* Blocks recursion on GENERATED columns */ | ||||
| 18658 | #define COLFLAG_HASCOLL0x0200 0x0200 /* Has collating sequence name in zCnName */ | ||||
| 18659 | #define COLFLAG_NOEXPAND0x0400 0x0400 /* Omit this column when expanding "*" */ | ||||
| 18660 | #define COLFLAG_GENERATED0x0060 0x0060 /* Combo: _STORED, _VIRTUAL */ | ||||
| 18661 | #define COLFLAG_NOINSERT0x0062 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */ | ||||
| 18662 | |||||
| 18663 | /* | ||||
| 18664 | ** A "Collating Sequence" is defined by an instance of the following | ||||
| 18665 | ** structure. Conceptually, a collating sequence consists of a name and | ||||
| 18666 | ** a comparison routine that defines the order of that sequence. | ||||
| 18667 | ** | ||||
| 18668 | ** If CollSeq.xCmp is NULL, it means that the | ||||
| 18669 | ** collating sequence is undefined. Indices built on an undefined | ||||
| 18670 | ** collating sequence may not be read or written. | ||||
| 18671 | */ | ||||
| 18672 | struct CollSeq { | ||||
| 18673 | char *zName; /* Name of the collating sequence, UTF-8 encoded */ | ||||
| 18674 | u8 enc; /* Text encoding handled by xCmp() */ | ||||
| 18675 | void *pUser; /* First argument to xCmp() */ | ||||
| 18676 | int (*xCmp)(void*,int, const void*, int, const void*); | ||||
| 18677 | void (*xDel)(void*); /* Destructor for pUser */ | ||||
| 18678 | }; | ||||
| 18679 | |||||
| 18680 | /* | ||||
| 18681 | ** A sort order can be either ASC or DESC. | ||||
| 18682 | */ | ||||
| 18683 | #define SQLITE_SO_ASC0 0 /* Sort in ascending order */ | ||||
| 18684 | #define SQLITE_SO_DESC1 1 /* Sort in ascending order */ | ||||
| 18685 | #define SQLITE_SO_UNDEFINED-1 -1 /* No sort order specified */ | ||||
| 18686 | |||||
| 18687 | /* | ||||
| 18688 | ** Column affinity types. | ||||
| 18689 | ** | ||||
| 18690 | ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and | ||||
| 18691 | ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve | ||||
| 18692 | ** the speed a little by numbering the values consecutively. | ||||
| 18693 | ** | ||||
| 18694 | ** But rather than start with 0 or 1, we begin with 'A'. That way, | ||||
| 18695 | ** when multiple affinity types are concatenated into a string and | ||||
| 18696 | ** used as the P4 operand, they will be more readable. | ||||
| 18697 | ** | ||||
| 18698 | ** Note also that the numeric types are grouped together so that testing | ||||
| 18699 | ** for a numeric type is a single comparison. And the BLOB type is first. | ||||
| 18700 | */ | ||||
| 18701 | #define SQLITE_AFF_NONE0x40 0x40 /* '@' */ | ||||
| 18702 | #define SQLITE_AFF_BLOB0x41 0x41 /* 'A' */ | ||||
| 18703 | #define SQLITE_AFF_TEXT0x42 0x42 /* 'B' */ | ||||
| 18704 | #define SQLITE_AFF_NUMERIC0x43 0x43 /* 'C' */ | ||||
| 18705 | #define SQLITE_AFF_INTEGER0x44 0x44 /* 'D' */ | ||||
| 18706 | #define SQLITE_AFF_REAL0x45 0x45 /* 'E' */ | ||||
| 18707 | #define SQLITE_AFF_FLEXNUM0x46 0x46 /* 'F' */ | ||||
| 18708 | #define SQLITE_AFF_DEFER0x58 0x58 /* 'X' - defer computation until later */ | ||||
| 18709 | |||||
| 18710 | #define sqlite3IsNumericAffinity(X)((X)>=0x43) ((X)>=SQLITE_AFF_NUMERIC0x43) | ||||
| 18711 | |||||
| 18712 | /* | ||||
| 18713 | ** The SQLITE_AFF_MASK values masks off the significant bits of an | ||||
| 18714 | ** affinity value. | ||||
| 18715 | */ | ||||
| 18716 | #define SQLITE_AFF_MASK0x47 0x47 | ||||
| 18717 | |||||
| 18718 | /* | ||||
| 18719 | ** Additional bit values that can be ORed with an affinity without | ||||
| 18720 | ** changing the affinity. | ||||
| 18721 | ** | ||||
| 18722 | ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL. | ||||
| 18723 | ** It causes an assert() to fire if either operand to a comparison | ||||
| 18724 | ** operator is NULL. It is added to certain comparison operators to | ||||
| 18725 | ** prove that the operands are always NOT NULL. | ||||
| 18726 | */ | ||||
| 18727 | #define SQLITE_JUMPIFNULL0x10 0x10 /* jumps if either operand is NULL */ | ||||
| 18728 | #define SQLITE_NULLEQ0x80 0x80 /* NULL=NULL */ | ||||
| 18729 | #define SQLITE_NOTNULL0x90 0x90 /* Assert that operands are never NULL */ | ||||
| 18730 | |||||
| 18731 | /* | ||||
| 18732 | ** An object of this type is created for each virtual table present in | ||||
| 18733 | ** the database schema. | ||||
| 18734 | ** | ||||
| 18735 | ** If the database schema is shared, then there is one instance of this | ||||
| 18736 | ** structure for each database connection (sqlite3*) that uses the shared | ||||
| 18737 | ** schema. This is because each database connection requires its own unique | ||||
| 18738 | ** instance of the sqlite3_vtab* handle used to access the virtual table | ||||
| 18739 | ** implementation. sqlite3_vtab* handles can not be shared between | ||||
| 18740 | ** database connections, even when the rest of the in-memory database | ||||
| 18741 | ** schema is shared, as the implementation often stores the database | ||||
| 18742 | ** connection handle passed to it via the xConnect() or xCreate() method | ||||
| 18743 | ** during initialization internally. This database connection handle may | ||||
| 18744 | ** then be used by the virtual table implementation to access real tables | ||||
| 18745 | ** within the database. So that they appear as part of the callers | ||||
| 18746 | ** transaction, these accesses need to be made via the same database | ||||
| 18747 | ** connection as that used to execute SQL operations on the virtual table. | ||||
| 18748 | ** | ||||
| 18749 | ** All VTable objects that correspond to a single table in a shared | ||||
| 18750 | ** database schema are initially stored in a linked-list pointed to by | ||||
| 18751 | ** the Table.pVTable member variable of the corresponding Table object. | ||||
| 18752 | ** When an sqlite3_prepare() operation is required to access the virtual | ||||
| 18753 | ** table, it searches the list for the VTable that corresponds to the | ||||
| 18754 | ** database connection doing the preparing so as to use the correct | ||||
| 18755 | ** sqlite3_vtab* handle in the compiled query. | ||||
| 18756 | ** | ||||
| 18757 | ** When an in-memory Table object is deleted (for example when the | ||||
| 18758 | ** schema is being reloaded for some reason), the VTable objects are not | ||||
| 18759 | ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed | ||||
| 18760 | ** immediately. Instead, they are moved from the Table.pVTable list to | ||||
| 18761 | ** another linked list headed by the sqlite3.pDisconnect member of the | ||||
| 18762 | ** corresponding sqlite3 structure. They are then deleted/xDisconnected | ||||
| 18763 | ** next time a statement is prepared using said sqlite3*. This is done | ||||
| 18764 | ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. | ||||
| 18765 | ** Refer to comments above function sqlite3VtabUnlockList() for an | ||||
| 18766 | ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect | ||||
| 18767 | ** list without holding the corresponding sqlite3.mutex mutex. | ||||
| 18768 | ** | ||||
| 18769 | ** The memory for objects of this type is always allocated by | ||||
| 18770 | ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as | ||||
| 18771 | ** the first argument. | ||||
| 18772 | */ | ||||
| 18773 | struct VTable { | ||||
| 18774 | sqlite3 *db; /* Database connection associated with this table */ | ||||
| 18775 | Module *pMod; /* Pointer to module implementation */ | ||||
| 18776 | sqlite3_vtab *pVtab; /* Pointer to vtab instance */ | ||||
| 18777 | int nRef; /* Number of pointers to this structure */ | ||||
| 18778 | u8 bConstraint; /* True if constraints are supported */ | ||||
| 18779 | u8 bAllSchemas; /* True if might use any attached schema */ | ||||
| 18780 | u8 eVtabRisk; /* Riskiness of allowing hacker access */ | ||||
| 18781 | int iSavepoint; /* Depth of the SAVEPOINT stack */ | ||||
| 18782 | VTable *pNext; /* Next in linked list (see above) */ | ||||
| 18783 | }; | ||||
| 18784 | |||||
| 18785 | /* Allowed values for VTable.eVtabRisk | ||||
| 18786 | */ | ||||
| 18787 | #define SQLITE_VTABRISK_Low0 0 | ||||
| 18788 | #define SQLITE_VTABRISK_Normal1 1 | ||||
| 18789 | #define SQLITE_VTABRISK_High2 2 | ||||
| 18790 | |||||
| 18791 | /* | ||||
| 18792 | ** The schema for each SQL table, virtual table, and view is represented | ||||
| 18793 | ** in memory by an instance of the following structure. | ||||
| 18794 | */ | ||||
| 18795 | struct Table { | ||||
| 18796 | char *zName; /* Name of the table or view */ | ||||
| 18797 | Column *aCol; /* Information about each column */ | ||||
| 18798 | Index *pIndex; /* List of SQL indexes on this table. */ | ||||
| 18799 | char *zColAff; /* String defining the affinity of each column */ | ||||
| 18800 | ExprList *pCheck; /* All CHECK constraints */ | ||||
| 18801 | /* ... also used as column name list in a VIEW */ | ||||
| 18802 | Pgno tnum; /* Root BTree page for this table */ | ||||
| 18803 | u32 nTabRef; /* Number of pointers to this Table */ | ||||
| 18804 | u32 tabFlags; /* Mask of TF_* values */ | ||||
| 18805 | i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */ | ||||
| 18806 | i16 nCol; /* Number of columns in this table */ | ||||
| 18807 | i16 nNVCol; /* Number of columns that are not VIRTUAL */ | ||||
| 18808 | LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */ | ||||
| 18809 | LogEst szTabRow; /* Estimated size of each table row in bytes */ | ||||
| 18810 | #ifdef SQLITE_ENABLE_COSTMULT | ||||
| 18811 | LogEst costMult; /* Cost multiplier for using this table */ | ||||
| 18812 | #endif | ||||
| 18813 | u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ | ||||
| 18814 | u8 eTabType; /* 0: normal, 1: virtual, 2: view */ | ||||
| 18815 | union { | ||||
| 18816 | struct { /* Used by ordinary tables: */ | ||||
| 18817 | int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ | ||||
| 18818 | FKey *pFKey; /* Linked list of all foreign keys in this table */ | ||||
| 18819 | ExprList *pDfltList; /* DEFAULT clauses on various columns. | ||||
| 18820 | ** Or the AS clause for generated columns. */ | ||||
| 18821 | } tab; | ||||
| 18822 | struct { /* Used by views: */ | ||||
| 18823 | Select *pSelect; /* View definition */ | ||||
| 18824 | } view; | ||||
| 18825 | struct { /* Used by virtual tables only: */ | ||||
| 18826 | int nArg; /* Number of arguments to the module */ | ||||
| 18827 | char **azArg; /* 0: module 1: schema 2: vtab name 3...: args */ | ||||
| 18828 | VTable *p; /* List of VTable objects. */ | ||||
| 18829 | } vtab; | ||||
| 18830 | } u; | ||||
| 18831 | Trigger *pTrigger; /* List of triggers on this object */ | ||||
| 18832 | Schema *pSchema; /* Schema that contains this table */ | ||||
| 18833 | u8 aHx[16]; /* Column aHt[K%sizeof(aHt)] might have hash K */ | ||||
| 18834 | }; | ||||
| 18835 | |||||
| 18836 | /* | ||||
| 18837 | ** Allowed values for Table.tabFlags. | ||||
| 18838 | ** | ||||
| 18839 | ** TF_OOOHidden applies to tables or view that have hidden columns that are | ||||
| 18840 | ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING | ||||
| 18841 | ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden, | ||||
| 18842 | ** the TF_OOOHidden attribute would apply in this case. Such tables require | ||||
| 18843 | ** special handling during INSERT processing. The "OOO" means "Out Of Order". | ||||
| 18844 | ** | ||||
| 18845 | ** Constraints: | ||||
| 18846 | ** | ||||
| 18847 | ** TF_HasVirtual == COLFLAG_VIRTUAL | ||||
| 18848 | ** TF_HasStored == COLFLAG_STORED | ||||
| 18849 | ** TF_HasHidden == COLFLAG_HIDDEN | ||||
| 18850 | */ | ||||
| 18851 | #define TF_Readonly0x00000001 0x00000001 /* Read-only system table */ | ||||
| 18852 | #define TF_HasHidden0x00000002 0x00000002 /* Has one or more hidden columns */ | ||||
| 18853 | #define TF_HasPrimaryKey0x00000004 0x00000004 /* Table has a primary key */ | ||||
| 18854 | #define TF_Autoincrement0x00000008 0x00000008 /* Integer primary key is autoincrement */ | ||||
| 18855 | #define TF_HasStat10x00000010 0x00000010 /* nRowLogEst set from sqlite_stat1 */ | ||||
| 18856 | #define TF_HasVirtual0x00000020 0x00000020 /* Has one or more VIRTUAL columns */ | ||||
| 18857 | #define TF_HasStored0x00000040 0x00000040 /* Has one or more STORED columns */ | ||||
| 18858 | #define TF_HasGenerated0x00000060 0x00000060 /* Combo: HasVirtual + HasStored */ | ||||
| 18859 | #define TF_WithoutRowid0x00000080 0x00000080 /* No rowid. PRIMARY KEY is the key */ | ||||
| 18860 | #define TF_MaybeReanalyze0x00000100 0x00000100 /* Maybe run ANALYZE on this table */ | ||||
| 18861 | #define TF_NoVisibleRowid0x00000200 0x00000200 /* No user-visible "rowid" column */ | ||||
| 18862 | #define TF_OOOHidden0x00000400 0x00000400 /* Out-of-Order hidden columns */ | ||||
| 18863 | #define TF_HasNotNull0x00000800 0x00000800 /* Contains NOT NULL constraints */ | ||||
| 18864 | #define TF_Shadow0x00001000 0x00001000 /* True for a shadow table */ | ||||
| 18865 | #define TF_HasStat40x00002000 0x00002000 /* STAT4 info available for this table */ | ||||
| 18866 | #define TF_Ephemeral0x00004000 0x00004000 /* An ephemeral table */ | ||||
| 18867 | #define TF_Eponymous0x00008000 0x00008000 /* An eponymous virtual table */ | ||||
| 18868 | #define TF_Strict0x00010000 0x00010000 /* STRICT mode */ | ||||
| 18869 | |||||
| 18870 | /* | ||||
| 18871 | ** Allowed values for Table.eTabType | ||||
| 18872 | */ | ||||
| 18873 | #define TABTYP_NORM0 0 /* Ordinary table */ | ||||
| 18874 | #define TABTYP_VTAB1 1 /* Virtual table */ | ||||
| 18875 | #define TABTYP_VIEW2 2 /* A view */ | ||||
| 18876 | |||||
| 18877 | #define IsView(X)((X)->eTabType==2) ((X)->eTabType==TABTYP_VIEW2) | ||||
| 18878 | #define IsOrdinaryTable(X)((X)->eTabType==0) ((X)->eTabType==TABTYP_NORM0) | ||||
| 18879 | |||||
| 18880 | /* | ||||
| 18881 | ** Test to see whether or not a table is a virtual table. This is | ||||
| 18882 | ** done as a macro so that it will be optimized out when virtual | ||||
| 18883 | ** table support is omitted from the build. | ||||
| 18884 | */ | ||||
| 18885 | #ifndef SQLITE_OMIT_VIRTUALTABLE | ||||
| 18886 | # define IsVirtual(X)((X)->eTabType==1) ((X)->eTabType==TABTYP_VTAB1) | ||||
| 18887 | # define ExprIsVtab(X)((X)->op==168 && (X)->y.pTab->eTabType==1) \ | ||||
| 18888 | ((X)->op==TK_COLUMN168 && (X)->y.pTab->eTabType==TABTYP_VTAB1) | ||||
| 18889 | #else | ||||
| 18890 | # define IsVirtual(X)((X)->eTabType==1) 0 | ||||
| 18891 | # define ExprIsVtab(X)((X)->op==168 && (X)->y.pTab->eTabType==1) 0 | ||||
| 18892 | #endif | ||||
| 18893 | |||||
| 18894 | /* | ||||
| 18895 | ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn() | ||||
| 18896 | ** only works for non-virtual tables (ordinary tables and views) and is | ||||
| 18897 | ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The | ||||
| 18898 | ** IsHiddenColumn() macro is general purpose. | ||||
| 18899 | */ | ||||
| 18900 | #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS) | ||||
| 18901 | # define IsHiddenColumn(X)(((X)->colFlags & 0x0002)!=0) (((X)->colFlags & COLFLAG_HIDDEN0x0002)!=0) | ||||
| 18902 | # define IsOrdinaryHiddenColumn(X)0 (((X)->colFlags & COLFLAG_HIDDEN0x0002)!=0) | ||||
| 18903 | #elif !defined(SQLITE_OMIT_VIRTUALTABLE) | ||||
| 18904 | # define IsHiddenColumn(X)(((X)->colFlags & 0x0002)!=0) (((X)->colFlags & COLFLAG_HIDDEN0x0002)!=0) | ||||
| 18905 | # define IsOrdinaryHiddenColumn(X)0 0 | ||||
| 18906 | #else | ||||
| 18907 | # define IsHiddenColumn(X)(((X)->colFlags & 0x0002)!=0) 0 | ||||
| 18908 | # define IsOrdinaryHiddenColumn(X)0 0 | ||||
| 18909 | #endif | ||||
| 18910 | |||||
| 18911 | |||||
| 18912 | /* Does the table have a rowid */ | ||||
| 18913 | #define HasRowid(X)(((X)->tabFlags & 0x00000080)==0) (((X)->tabFlags & TF_WithoutRowid0x00000080)==0) | ||||
| 18914 | #define VisibleRowid(X)(((X)->tabFlags & 0x00000200)==0) (((X)->tabFlags & TF_NoVisibleRowid0x00000200)==0) | ||||
| 18915 | |||||
| 18916 | /* Macro is true if the SQLITE_ALLOW_ROWID_IN_VIEW (mis-)feature is | ||||
| 18917 | ** available. By default, this macro is false | ||||
| 18918 | */ | ||||
| 18919 | #ifndef SQLITE_ALLOW_ROWID_IN_VIEW | ||||
| 18920 | # define ViewCanHaveRowid0 0 | ||||
| 18921 | #else | ||||
| 18922 | # define ViewCanHaveRowid0 (sqlite3Config.mNoVisibleRowid==0) | ||||
| 18923 | #endif | ||||
| 18924 | |||||
| 18925 | /* | ||||
| 18926 | ** Each foreign key constraint is an instance of the following structure. | ||||
| 18927 | ** | ||||
| 18928 | ** A foreign key is associated with two tables. The "from" table is | ||||
| 18929 | ** the table that contains the REFERENCES clause that creates the foreign | ||||
| 18930 | ** key. The "to" table is the table that is named in the REFERENCES clause. | ||||
| 18931 | ** Consider this example: | ||||
| 18932 | ** | ||||
| 18933 | ** CREATE TABLE ex1( | ||||
| 18934 | ** a INTEGER PRIMARY KEY, | ||||
| 18935 | ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) | ||||
| 18936 | ** ); | ||||
| 18937 | ** | ||||
| 18938 | ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". | ||||
| 18939 | ** Equivalent names: | ||||
| 18940 | ** | ||||
| 18941 | ** from-table == child-table | ||||
| 18942 | ** to-table == parent-table | ||||
| 18943 | ** | ||||
| 18944 | ** Each REFERENCES clause generates an instance of the following structure | ||||
| 18945 | ** which is attached to the from-table. The to-table need not exist when | ||||
| 18946 | ** the from-table is created. The existence of the to-table is not checked. | ||||
| 18947 | ** | ||||
| 18948 | ** The list of all parents for child Table X is held at X.pFKey. | ||||
| 18949 | ** | ||||
| 18950 | ** A list of all children for a table named Z (which might not even exist) | ||||
| 18951 | ** is held in Schema.fkeyHash with a hash key of Z. | ||||
| 18952 | */ | ||||
| 18953 | struct FKey { | ||||
| 18954 | Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ | ||||
| 18955 | FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */ | ||||
| 18956 | char *zTo; /* Name of table that the key points to (aka: Parent) */ | ||||
| 18957 | FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */ | ||||
| 18958 | FKey *pPrevTo; /* Previous with the same zTo */ | ||||
| 18959 | int nCol; /* Number of columns in this key */ | ||||
| 18960 | /* EV: R-30323-21917 */ | ||||
| 18961 | u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ | ||||
| 18962 | u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ | ||||
| 18963 | Trigger *apTrigger[2];/* Triggers for aAction[] actions */ | ||||
| 18964 | struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ | ||||
| 18965 | int iFrom; /* Index of column in pFrom */ | ||||
| 18966 | char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */ | ||||
| 18967 | } aCol[FLEXARRAY]; /* One entry for each of nCol columns */ | ||||
| 18968 | }; | ||||
| 18969 | |||||
| 18970 | /* The size (in bytes) of an FKey object holding N columns. The answer | ||||
| 18971 | ** does NOT include space to hold the zTo name. */ | ||||
| 18972 | #define SZ_FKEY(N)(__builtin_offsetof(FKey, aCol)+(N)*sizeof(struct sColMap)) (offsetof(FKey,aCol)__builtin_offsetof(FKey, aCol)+(N)*sizeof(struct sColMap)) | ||||
| 18973 | |||||
| 18974 | /* | ||||
| 18975 | ** SQLite supports many different ways to resolve a constraint | ||||
| 18976 | ** error. ROLLBACK processing means that a constraint violation | ||||
| 18977 | ** causes the operation in process to fail and for the current transaction | ||||
| 18978 | ** to be rolled back. ABORT processing means the operation in process | ||||
| 18979 | ** fails and any prior changes from that one operation are backed out, | ||||
| 18980 | ** but the transaction is not rolled back. FAIL processing means that | ||||
| 18981 | ** the operation in progress stops and returns an error code. But prior | ||||
| 18982 | ** changes due to the same operation are not backed out and no rollback | ||||
| 18983 | ** occurs. IGNORE means that the particular row that caused the constraint | ||||
| 18984 | ** error is not inserted or updated. Processing continues and no error | ||||
| 18985 | ** is returned. REPLACE means that preexisting database rows that caused | ||||
| 18986 | ** a UNIQUE constraint violation are removed so that the new insert or | ||||
| 18987 | ** update can proceed. Processing continues and no error is reported. | ||||
| 18988 | ** UPDATE applies to insert operations only and means that the insert | ||||
| 18989 | ** is omitted and the DO UPDATE clause of an upsert is run instead. | ||||
| 18990 | ** | ||||
| 18991 | ** RESTRICT, SETNULL, SETDFLT, and CASCADE actions apply only to foreign keys. | ||||
| 18992 | ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the | ||||
| 18993 | ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign | ||||
| 18994 | ** key is set to NULL. SETDFLT means that the foreign key is set | ||||
| 18995 | ** to its default value. CASCADE means that a DELETE or UPDATE of the | ||||
| 18996 | ** referenced table row is propagated into the row that holds the | ||||
| 18997 | ** foreign key. | ||||
| 18998 | ** | ||||
| 18999 | ** The OE_Default value is a place holder that means to use whatever | ||||
| 19000 | ** conflict resolution algorithm is required from context. | ||||
| 19001 | ** | ||||
| 19002 | ** The following symbolic values are used to record which type | ||||
| 19003 | ** of conflict resolution action to take. | ||||
| 19004 | */ | ||||
| 19005 | #define OE_None0 0 /* There is no constraint to check */ | ||||
| 19006 | #define OE_Rollback1 1 /* Fail the operation and rollback the transaction */ | ||||
| 19007 | #define OE_Abort2 2 /* Back out changes but do no rollback transaction */ | ||||
| 19008 | #define OE_Fail3 3 /* Stop the operation but leave all prior changes */ | ||||
| 19009 | #define OE_Ignore4 4 /* Ignore the error. Do not do the INSERT or UPDATE */ | ||||
| 19010 | #define OE_Replace5 5 /* Delete existing record, then do INSERT or UPDATE */ | ||||
| 19011 | #define OE_Update6 6 /* Process as a DO UPDATE in an upsert */ | ||||
| 19012 | #define OE_Restrict7 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ | ||||
| 19013 | #define OE_SetNull8 8 /* Set the foreign key value to NULL */ | ||||
| 19014 | #define OE_SetDflt9 9 /* Set the foreign key value to its default */ | ||||
| 19015 | #define OE_Cascade10 10 /* Cascade the changes */ | ||||
| 19016 | #define OE_Default11 11 /* Do whatever the default action is */ | ||||
| 19017 | |||||
| 19018 | |||||
| 19019 | /* | ||||
| 19020 | ** An instance of the following structure is passed as the first | ||||
| 19021 | ** argument to sqlite3VdbeKeyCompare and is used to control the | ||||
| 19022 | ** comparison of the two index keys. | ||||
| 19023 | ** | ||||
| 19024 | ** Note that aSortOrder[] and aColl[] have nField+1 slots. There | ||||
| 19025 | ** are nField slots for the columns of an index then one extra slot | ||||
| 19026 | ** for the rowid at the end. | ||||
| 19027 | */ | ||||
| 19028 | struct KeyInfo { | ||||
| 19029 | u32 nRef; /* Number of references to this KeyInfo object */ | ||||
| 19030 | u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ | ||||
| 19031 | u16 nKeyField; /* Number of key columns in the index */ | ||||
| 19032 | u16 nAllField; /* Total columns, including key plus others */ | ||||
| 19033 | sqlite3 *db; /* The database connection */ | ||||
| 19034 | u8 *aSortFlags; /* Sort order for each column. */ | ||||
| 19035 | CollSeq *aColl[FLEXARRAY]; /* Collating sequence for each term of the key */ | ||||
| 19036 | }; | ||||
| 19037 | |||||
| 19038 | /* The size (in bytes) of a KeyInfo object with up to N fields */ | ||||
| 19039 | #define SZ_KEYINFO(N)(__builtin_offsetof(KeyInfo, aColl) + (N)*sizeof(CollSeq*)) (offsetof(KeyInfo,aColl)__builtin_offsetof(KeyInfo, aColl) + (N)*sizeof(CollSeq*)) | ||||
| 19040 | |||||
| 19041 | /* | ||||
| 19042 | ** Allowed bit values for entries in the KeyInfo.aSortFlags[] array. | ||||
| 19043 | */ | ||||
| 19044 | #define KEYINFO_ORDER_DESC0x01 0x01 /* DESC sort order */ | ||||
| 19045 | #define KEYINFO_ORDER_BIGNULL0x02 0x02 /* NULL is larger than any other value */ | ||||
| 19046 | |||||
| 19047 | /* | ||||
| 19048 | ** This object holds a record which has been parsed out into individual | ||||
| 19049 | ** fields, for the purposes of doing a comparison. | ||||
| 19050 | ** | ||||
| 19051 | ** A record is an object that contains one or more fields of data. | ||||
| 19052 | ** Records are used to store the content of a table row and to store | ||||
| 19053 | ** the key of an index. A blob encoding of a record is created by | ||||
| 19054 | ** the OP_MakeRecord opcode of the VDBE and is disassembled by the | ||||
| 19055 | ** OP_Column opcode. | ||||
| 19056 | ** | ||||
| 19057 | ** An instance of this object serves as a "key" for doing a search on | ||||
| 19058 | ** an index b+tree. The goal of the search is to find the entry that | ||||
| 19059 | ** is closed to the key described by this object. This object might hold | ||||
| 19060 | ** just a prefix of the key. The number of fields is given by | ||||
| 19061 | ** pKeyInfo->nField. | ||||
| 19062 | ** | ||||
| 19063 | ** The r1 and r2 fields are the values to return if this key is less than | ||||
| 19064 | ** or greater than a key in the btree, respectively. These are normally | ||||
| 19065 | ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree | ||||
| 19066 | ** is in DESC order. | ||||
| 19067 | ** | ||||
| 19068 | ** The key comparison functions actually return default_rc when they find | ||||
| 19069 | ** an equals comparison. default_rc can be -1, 0, or +1. If there are | ||||
| 19070 | ** multiple entries in the b-tree with the same key (when only looking | ||||
| 19071 | ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to | ||||
| 19072 | ** cause the search to find the last match, or +1 to cause the search to | ||||
| 19073 | ** find the first match. | ||||
| 19074 | ** | ||||
| 19075 | ** The key comparison functions will set eqSeen to true if they ever | ||||
| 19076 | ** get and equal results when comparing this structure to a b-tree record. | ||||
| 19077 | ** When default_rc!=0, the search might end up on the record immediately | ||||
| 19078 | ** before the first match or immediately after the last match. The | ||||
| 19079 | ** eqSeen field will indicate whether or not an exact match exists in the | ||||
| 19080 | ** b-tree. | ||||
| 19081 | */ | ||||
| 19082 | struct UnpackedRecord { | ||||
| 19083 | KeyInfo *pKeyInfo; /* Collation and sort-order information */ | ||||
| 19084 | Mem *aMem; /* Values */ | ||||
| 19085 | union { | ||||
| 19086 | char *z; /* Cache of aMem[0].z for vdbeRecordCompareString() */ | ||||
| 19087 | i64 i; /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */ | ||||
| 19088 | } u; | ||||
| 19089 | int n; /* Cache of aMem[0].n used by vdbeRecordCompareString() */ | ||||
| 19090 | u16 nField; /* Number of entries in apMem[] */ | ||||
| 19091 | i8 default_rc; /* Comparison result if keys are equal */ | ||||
| 19092 | u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */ | ||||
| 19093 | i8 r1; /* Value to return if (lhs < rhs) */ | ||||
| 19094 | i8 r2; /* Value to return if (lhs > rhs) */ | ||||
| 19095 | u8 eqSeen; /* True if an equality comparison has been seen */ | ||||
| 19096 | }; | ||||
| 19097 | |||||
| 19098 | |||||
| 19099 | /* | ||||
| 19100 | ** Each SQL index is represented in memory by an | ||||
| 19101 | ** instance of the following structure. | ||||
| 19102 | ** | ||||
| 19103 | ** The columns of the table that are to be indexed are described | ||||
| 19104 | ** by the aiColumn[] field of this structure. For example, suppose | ||||
| 19105 | ** we have the following table and index: | ||||
| 19106 | ** | ||||
| 19107 | ** CREATE TABLE Ex1(c1 int, c2 int, c3 text); | ||||
| 19108 | ** CREATE INDEX Ex2 ON Ex1(c3,c1); | ||||
| 19109 | ** | ||||
| 19110 | ** In the Table structure describing Ex1, nCol==3 because there are | ||||
| 19111 | ** three columns in the table. In the Index structure describing | ||||
| 19112 | ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. | ||||
| 19113 | ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the | ||||
| 19114 | ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. | ||||
| 19115 | ** The second column to be indexed (c1) has an index of 0 in | ||||
| 19116 | ** Ex1.aCol[], hence Ex2.aiColumn[1]==0. | ||||
| 19117 | ** | ||||
| 19118 | ** The Index.onError field determines whether or not the indexed columns | ||||
| 19119 | ** must be unique and what to do if they are not. When Index.onError=OE_None, | ||||
| 19120 | ** it means this is not a unique index. Otherwise it is a unique index | ||||
| 19121 | ** and the value of Index.onError indicates which conflict resolution | ||||
| 19122 | ** algorithm to employ when an attempt is made to insert a non-unique | ||||
| 19123 | ** element. | ||||
| 19124 | ** | ||||
| 19125 | ** The colNotIdxed bitmask is used in combination with SrcItem.colUsed | ||||
| 19126 | ** for a fast test to see if an index can serve as a covering index. | ||||
| 19127 | ** colNotIdxed has a 1 bit for every column of the original table that | ||||
| 19128 | ** is *not* available in the index. Thus the expression | ||||
| 19129 | ** "colUsed & colNotIdxed" will be non-zero if the index is not a | ||||
| 19130 | ** covering index. The most significant bit of of colNotIdxed will always | ||||
| 19131 | ** be true (note-20221022-a). If a column beyond the 63rd column of the | ||||
| 19132 | ** table is used, the "colUsed & colNotIdxed" test will always be non-zero | ||||
| 19133 | ** and we have to assume either that the index is not covering, or use | ||||
| 19134 | ** an alternative (slower) algorithm to determine whether or not | ||||
| 19135 | ** the index is covering. | ||||
| 19136 | ** | ||||
| 19137 | ** While parsing a CREATE TABLE or CREATE INDEX statement in order to | ||||
| 19138 | ** generate VDBE code (as opposed to parsing one read from an sqlite_schema | ||||
| 19139 | ** table as part of parsing an existing database schema), transient instances | ||||
| 19140 | ** of this structure may be created. In this case the Index.tnum variable is | ||||
| 19141 | ** used to store the address of a VDBE instruction, not a database page | ||||
| 19142 | ** number (it cannot - the database page is not allocated until the VDBE | ||||
| 19143 | ** program is executed). See convertToWithoutRowidTable() for details. | ||||
| 19144 | */ | ||||
| 19145 | struct Index { | ||||
| 19146 | char *zName; /* Name of this index */ | ||||
| 19147 | i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */ | ||||
| 19148 | LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */ | ||||
| 19149 | Table *pTable; /* The SQL table being indexed */ | ||||
| 19150 | char *zColAff; /* String defining the affinity of each column */ | ||||
| 19151 | Index *pNext; /* The next index associated with the same table */ | ||||
| 19152 | Schema *pSchema; /* Schema containing this index */ | ||||
| 19153 | u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ | ||||
| 19154 | const char **azColl; /* Array of collation sequence names for index */ | ||||
| 19155 | Expr *pPartIdxWhere; /* WHERE clause for partial indices */ | ||||
| 19156 | ExprList *aColExpr; /* Column expressions */ | ||||
| 19157 | Pgno tnum; /* DB Page containing root of this index */ | ||||
| 19158 | LogEst szIdxRow; /* Estimated average row size in bytes */ | ||||
| 19159 | u16 nKeyCol; /* Number of columns forming the key */ | ||||
| 19160 | u16 nColumn; /* Nr columns in btree. Can be 2*Table.nCol */ | ||||
| 19161 | u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ | ||||
| 19162 | unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */ | ||||
| 19163 | unsigned bUnordered:1; /* Use this index for == or IN queries only */ | ||||
| 19164 | unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */ | ||||
| 19165 | unsigned isResized:1; /* True if resizeIndexObject() has been called */ | ||||
| 19166 | unsigned isCovering:1; /* True if this is a covering index */ | ||||
| 19167 | unsigned noSkipScan:1; /* Do not try to use skip-scan if true */ | ||||
| 19168 | unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */ | ||||
| 19169 | unsigned bNoQuery:1; /* Do not use this index to optimize queries */ | ||||
| 19170 | unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */ | ||||
| 19171 | unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */ | ||||
| 19172 | unsigned bHasExpr:1; /* Index contains an expression, either a literal | ||||
| 19173 | ** expression, or a reference to a VIRTUAL column */ | ||||
| 19174 | #ifdef SQLITE_ENABLE_STAT4 | ||||
| 19175 | int nSample; /* Number of elements in aSample[] */ | ||||
| 19176 | int mxSample; /* Number of slots allocated to aSample[] */ | ||||
| 19177 | int nSampleCol; /* Size of IndexSample.anEq[] and so on */ | ||||
| 19178 | tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */ | ||||
| 19179 | IndexSample *aSample; /* Samples of the left-most key */ | ||||
| 19180 | tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */ | ||||
| 19181 | tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */ | ||||
| 19182 | #endif | ||||
| 19183 | Bitmask colNotIdxed; /* Unindexed columns in pTab */ | ||||
| 19184 | }; | ||||
| 19185 | |||||
| 19186 | /* | ||||
| 19187 | ** Allowed values for Index.idxType | ||||
| 19188 | */ | ||||
| 19189 | #define SQLITE_IDXTYPE_APPDEF0 0 /* Created using CREATE INDEX */ | ||||
| 19190 | #define SQLITE_IDXTYPE_UNIQUE1 1 /* Implements a UNIQUE constraint */ | ||||
| 19191 | #define SQLITE_IDXTYPE_PRIMARYKEY2 2 /* Is the PRIMARY KEY for the table */ | ||||
| 19192 | #define SQLITE_IDXTYPE_IPK3 3 /* INTEGER PRIMARY KEY index */ | ||||
| 19193 | |||||
| 19194 | /* Return true if index X is a PRIMARY KEY index */ | ||||
| 19195 | #define IsPrimaryKeyIndex(X)((X)->idxType==2) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY2) | ||||
| 19196 | |||||
| 19197 | /* Return true if index X is a UNIQUE index */ | ||||
| 19198 | #define IsUniqueIndex(X)((X)->onError!=0) ((X)->onError!=OE_None0) | ||||
| 19199 | |||||
| 19200 | /* The Index.aiColumn[] values are normally positive integer. But | ||||
| 19201 | ** there are some negative values that have special meaning: | ||||
| 19202 | */ | ||||
| 19203 | #define XN_ROWID(-1) (-1) /* Indexed column is the rowid */ | ||||
| 19204 | #define XN_EXPR(-2) (-2) /* Indexed column is an expression */ | ||||
| 19205 | |||||
| 19206 | /* | ||||
| 19207 | ** Each sample stored in the sqlite_stat4 table is represented in memory | ||||
| 19208 | ** using a structure of this type. See documentation at the top of the | ||||
| 19209 | ** analyze.c source file for additional information. | ||||
| 19210 | */ | ||||
| 19211 | struct IndexSample { | ||||
| 19212 | void *p; /* Pointer to sampled record */ | ||||
| 19213 | int n; /* Size of record in bytes */ | ||||
| 19214 | tRowcnt *anEq; /* Est. number of rows where the key equals this sample */ | ||||
| 19215 | tRowcnt *anLt; /* Est. number of rows where key is less than this sample */ | ||||
| 19216 | tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */ | ||||
| 19217 | }; | ||||
| 19218 | |||||
| 19219 | /* | ||||
| 19220 | ** Possible values to use within the flags argument to sqlite3GetToken(). | ||||
| 19221 | */ | ||||
| 19222 | #define SQLITE_TOKEN_QUOTED0x1 0x1 /* Token is a quoted identifier. */ | ||||
| 19223 | #define SQLITE_TOKEN_KEYWORD0x2 0x2 /* Token is a keyword. */ | ||||
| 19224 | |||||
| 19225 | /* | ||||
| 19226 | ** Each token coming out of the lexer is an instance of | ||||
| 19227 | ** this structure. Tokens are also used as part of an expression. | ||||
| 19228 | ** | ||||
| 19229 | ** The memory that "z" points to is owned by other objects. Take care | ||||
| 19230 | ** that the owner of the "z" string does not deallocate the string before | ||||
| 19231 | ** the Token goes out of scope! Very often, the "z" points to some place | ||||
| 19232 | ** in the middle of the Parse.zSql text. But it might also point to a | ||||
| 19233 | ** static string. | ||||
| 19234 | */ | ||||
| 19235 | struct Token { | ||||
| 19236 | const char *z; /* Text of the token. Not NULL-terminated! */ | ||||
| 19237 | unsigned int n; /* Number of characters in this token */ | ||||
| 19238 | }; | ||||
| 19239 | |||||
| 19240 | /* | ||||
| 19241 | ** An instance of this structure contains information needed to generate | ||||
| 19242 | ** code for a SELECT that contains aggregate functions. | ||||
| 19243 | ** | ||||
| 19244 | ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a | ||||
| 19245 | ** pointer to this structure. The Expr.iAgg field is the index in | ||||
| 19246 | ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate | ||||
| 19247 | ** code for that node. | ||||
| 19248 | ** | ||||
| 19249 | ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the | ||||
| 19250 | ** original Select structure that describes the SELECT statement. These | ||||
| 19251 | ** fields do not need to be freed when deallocating the AggInfo structure. | ||||
| 19252 | */ | ||||
| 19253 | struct AggInfo { | ||||
| 19254 | u8 directMode; /* Direct rendering mode means take data directly | ||||
| 19255 | ** from source tables rather than from accumulators */ | ||||
| 19256 | u8 useSortingIdx; /* In direct mode, reference the sorting index rather | ||||
| 19257 | ** than the source table */ | ||||
| 19258 | u32 nSortingColumn; /* Number of columns in the sorting index */ | ||||
| 19259 | int sortingIdx; /* Cursor number of the sorting index */ | ||||
| 19260 | int sortingIdxPTab; /* Cursor number of pseudo-table */ | ||||
| 19261 | int iFirstReg; /* First register in range for aCol[] and aFunc[] */ | ||||
| 19262 | ExprList *pGroupBy; /* The group by clause */ | ||||
| 19263 | struct AggInfo_col { /* For each column used in source tables */ | ||||
| 19264 | Table *pTab; /* Source table */ | ||||
| 19265 | Expr *pCExpr; /* The original expression */ | ||||
| 19266 | int iTable; /* Cursor number of the source table */ | ||||
| 19267 | int iColumn; /* Column number within the source table */ | ||||
| 19268 | int iSorterColumn; /* Column number in the sorting index */ | ||||
| 19269 | } *aCol; | ||||
| 19270 | int nColumn; /* Number of used entries in aCol[] */ | ||||
| 19271 | int nAccumulator; /* Number of columns that show through to the output. | ||||
| 19272 | ** Additional columns are used only as parameters to | ||||
| 19273 | ** aggregate functions */ | ||||
| 19274 | struct AggInfo_func { /* For each aggregate function */ | ||||
| 19275 | Expr *pFExpr; /* Expression encoding the function */ | ||||
| 19276 | FuncDef *pFunc; /* The aggregate function implementation */ | ||||
| 19277 | int iDistinct; /* Ephemeral table used to enforce DISTINCT */ | ||||
| 19278 | int iDistAddr; /* Address of OP_OpenEphemeral */ | ||||
| 19279 | int iOBTab; /* Ephemeral table to implement ORDER BY */ | ||||
| 19280 | u8 bOBPayload; /* iOBTab has payload columns separate from key */ | ||||
| 19281 | u8 bOBUnique; /* Enforce uniqueness on iOBTab keys */ | ||||
| 19282 | u8 bUseSubtype; /* Transfer subtype info through sorter */ | ||||
| 19283 | } *aFunc; | ||||
| 19284 | int nFunc; /* Number of entries in aFunc[] */ | ||||
| 19285 | u32 selId; /* Select to which this AggInfo belongs */ | ||||
| 19286 | #ifdef SQLITE_DEBUG | ||||
| 19287 | Select *pSelect; /* SELECT statement that this AggInfo supports */ | ||||
| 19288 | #endif | ||||
| 19289 | }; | ||||
| 19290 | |||||
| 19291 | /* | ||||
| 19292 | ** Macros to compute aCol[] and aFunc[] register numbers. | ||||
| 19293 | ** | ||||
| 19294 | ** These macros should not be used prior to the call to | ||||
| 19295 | ** assignAggregateRegisters() that computes the value of pAggInfo->iFirstReg. | ||||
| 19296 | ** The assert()s that are part of this macro verify that constraint. | ||||
| 19297 | */ | ||||
| 19298 | #ifndef NDEBUG1 | ||||
| 19299 | #define AggInfoColumnReg(A,I)((A)->iFirstReg+(I)) (assert((A)->iFirstReg)((void) (0)),(A)->iFirstReg+(I)) | ||||
| 19300 | #define AggInfoFuncReg(A,I)((A)->iFirstReg+(A)->nColumn+(I)) \ | ||||
| 19301 | (assert((A)->iFirstReg)((void) (0)),(A)->iFirstReg+(A)->nColumn+(I)) | ||||
| 19302 | #else | ||||
| 19303 | #define AggInfoColumnReg(A,I)((A)->iFirstReg+(I)) ((A)->iFirstReg+(I)) | ||||
| 19304 | #define AggInfoFuncReg(A,I)((A)->iFirstReg+(A)->nColumn+(I)) \ | ||||
| 19305 | ((A)->iFirstReg+(A)->nColumn+(I)) | ||||
| 19306 | #endif | ||||
| 19307 | |||||
| 19308 | /* | ||||
| 19309 | ** The datatype ynVar is a signed integer, either 16-bit or 32-bit. | ||||
| 19310 | ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater | ||||
| 19311 | ** than 32767 we have to make it 32-bit. 16-bit is preferred because | ||||
| 19312 | ** it uses less memory in the Expr object, which is a big memory user | ||||
| 19313 | ** in systems with lots of prepared statements. And few applications | ||||
| 19314 | ** need more than about 10 or 20 variables. But some extreme users want | ||||
| 19315 | ** to have prepared statements with over 32766 variables, and for them | ||||
| 19316 | ** the option is available (at compile-time). | ||||
| 19317 | */ | ||||
| 19318 | #if SQLITE_MAX_VARIABLE_NUMBER500000<32767 | ||||
| 19319 | typedef i16 ynVar; | ||||
| 19320 | #else | ||||
| 19321 | typedef int ynVar; | ||||
| 19322 | #endif | ||||
| 19323 | |||||
| 19324 | /* | ||||
| 19325 | ** Each node of an expression in the parse tree is an instance | ||||
| 19326 | ** of this structure. | ||||
| 19327 | ** | ||||
| 19328 | ** Expr.op is the opcode. The integer parser token codes are reused | ||||
| 19329 | ** as opcodes here. For example, the parser defines TK_GE to be an integer | ||||
| 19330 | ** code representing the ">=" operator. This same integer code is reused | ||||
| 19331 | ** to represent the greater-than-or-equal-to operator in the expression | ||||
| 19332 | ** tree. | ||||
| 19333 | ** | ||||
| 19334 | ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, | ||||
| 19335 | ** or TK_STRING), then Expr.u.zToken contains the text of the SQL literal. If | ||||
| 19336 | ** the expression is a variable (TK_VARIABLE), then Expr.u.zToken contains the | ||||
| 19337 | ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), | ||||
| 19338 | ** then Expr.u.zToken contains the name of the function. | ||||
| 19339 | ** | ||||
| 19340 | ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a | ||||
| 19341 | ** binary operator. Either or both may be NULL. | ||||
| 19342 | ** | ||||
| 19343 | ** Expr.x.pList is a list of arguments if the expression is an SQL function, | ||||
| 19344 | ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)". | ||||
| 19345 | ** Expr.x.pSelect is used if the expression is a sub-select or an expression of | ||||
| 19346 | ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the | ||||
| 19347 | ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is | ||||
| 19348 | ** valid. | ||||
| 19349 | ** | ||||
| 19350 | ** An expression of the form ID or ID.ID refers to a column in a table. | ||||
| 19351 | ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is | ||||
| 19352 | ** the integer cursor number of a VDBE cursor pointing to that table and | ||||
| 19353 | ** Expr.iColumn is the column number for the specific column. If the | ||||
| 19354 | ** expression is used as a result in an aggregate SELECT, then the | ||||
| 19355 | ** value is also stored in the Expr.iAgg column in the aggregate so that | ||||
| 19356 | ** it can be accessed after all aggregates are computed. | ||||
| 19357 | ** | ||||
| 19358 | ** If the expression is an unbound variable marker (a question mark | ||||
| 19359 | ** character '?' in the original SQL) then the Expr.iTable holds the index | ||||
| 19360 | ** number for that variable. | ||||
| 19361 | ** | ||||
| 19362 | ** If the expression is a subquery then Expr.iColumn holds an integer | ||||
| 19363 | ** register number containing the result of the subquery. If the | ||||
| 19364 | ** subquery gives a constant result, then iTable is -1. If the subquery | ||||
| 19365 | ** gives a different answer at different times during statement processing | ||||
| 19366 | ** then iTable is the address of a subroutine that computes the subquery. | ||||
| 19367 | ** | ||||
| 19368 | ** If the Expr is of type OP_Column, and the table it is selecting from | ||||
| 19369 | ** is a disk table or the "old.*" pseudo-table, then pTab points to the | ||||
| 19370 | ** corresponding table definition. | ||||
| 19371 | ** | ||||
| 19372 | ** ALLOCATION NOTES: | ||||
| 19373 | ** | ||||
| 19374 | ** Expr objects can use a lot of memory space in database schema. To | ||||
| 19375 | ** help reduce memory requirements, sometimes an Expr object will be | ||||
| 19376 | ** truncated. And to reduce the number of memory allocations, sometimes | ||||
| 19377 | ** two or more Expr objects will be stored in a single memory allocation, | ||||
| 19378 | ** together with Expr.u.zToken strings. | ||||
| 19379 | ** | ||||
| 19380 | ** If the EP_Reduced and EP_TokenOnly flags are set when | ||||
| 19381 | ** an Expr object is truncated. When EP_Reduced is set, then all | ||||
| 19382 | ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees | ||||
| 19383 | ** are contained within the same memory allocation. Note, however, that | ||||
| 19384 | ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately | ||||
| 19385 | ** allocated, regardless of whether or not EP_Reduced is set. | ||||
| 19386 | */ | ||||
| 19387 | struct Expr { | ||||
| 19388 | u8 op; /* Operation performed by this node */ | ||||
| 19389 | char affExpr; /* affinity, or RAISE type */ | ||||
| 19390 | u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op | ||||
| 19391 | ** TK_COLUMN: the value of p5 for OP_Column | ||||
| 19392 | ** TK_AGG_FUNCTION: nesting depth | ||||
| 19393 | ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */ | ||||
| 19394 | #ifdef SQLITE_DEBUG | ||||
| 19395 | u8 vvaFlags; /* Verification flags. */ | ||||
| 19396 | #endif | ||||
| 19397 | u32 flags; /* Various flags. EP_* See below */ | ||||
| 19398 | union { | ||||
| 19399 | char *zToken; /* Token value. Zero terminated and dequoted */ | ||||
| 19400 | int iValue; /* Non-negative integer value if EP_IntValue */ | ||||
| 19401 | } u; | ||||
| 19402 | |||||
| 19403 | /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no | ||||
| 19404 | ** space is allocated for the fields below this point. An attempt to | ||||
| 19405 | ** access them will result in a segfault or malfunction. | ||||
| 19406 | *********************************************************************/ | ||||
| 19407 | |||||
| 19408 | Expr *pLeft; /* Left subnode */ | ||||
| 19409 | Expr *pRight; /* Right subnode */ | ||||
| 19410 | union { | ||||
| 19411 | ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */ | ||||
| 19412 | Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */ | ||||
| 19413 | } x; | ||||
| 19414 | |||||
| 19415 | /* If the EP_Reduced flag is set in the Expr.flags mask, then no | ||||
| 19416 | ** space is allocated for the fields below this point. An attempt to | ||||
| 19417 | ** access them will result in a segfault or malfunction. | ||||
| 19418 | *********************************************************************/ | ||||
| 19419 | |||||
| 19420 | #if SQLITE_MAX_EXPR_DEPTH1000>0 | ||||
| 19421 | int nHeight; /* Height of the tree headed by this node */ | ||||
| 19422 | #endif | ||||
| 19423 | int iTable; /* TK_COLUMN: cursor number of table holding column | ||||
| 19424 | ** TK_REGISTER: register number | ||||
| 19425 | ** TK_TRIGGER: 1 -> new, 0 -> old | ||||
| 19426 | ** EP_Unlikely: 134217728 times likelihood | ||||
| 19427 | ** TK_IN: ephemeral table holding RHS | ||||
| 19428 | ** TK_SELECT_COLUMN: Number of columns on the LHS | ||||
| 19429 | ** TK_SELECT: 1st register of result vector */ | ||||
| 19430 | ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid. | ||||
| 19431 | ** TK_VARIABLE: variable number (always >= 1). | ||||
| 19432 | ** TK_SELECT_COLUMN: column of the result vector */ | ||||
| 19433 | i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */ | ||||
| 19434 | union { | ||||
| 19435 | int iJoin; /* If EP_OuterON or EP_InnerON, the right table */ | ||||
| 19436 | int iOfst; /* else: start of token from start of statement */ | ||||
| 19437 | } w; | ||||
| 19438 | AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */ | ||||
| 19439 | union { | ||||
| 19440 | Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL | ||||
| 19441 | ** for a column of an index on an expression */ | ||||
| 19442 | Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */ | ||||
| 19443 | struct { /* TK_IN, TK_SELECT, and TK_EXISTS */ | ||||
| 19444 | int iAddr; /* Subroutine entry address */ | ||||
| 19445 | int regReturn; /* Register used to hold return address */ | ||||
| 19446 | } sub; | ||||
| 19447 | } y; | ||||
| 19448 | }; | ||||
| 19449 | |||||
| 19450 | /* The following are the meanings of bits in the Expr.flags field. | ||||
| 19451 | ** Value restrictions: | ||||
| 19452 | ** | ||||
| 19453 | ** EP_Agg == NC_HasAgg == SF_HasAgg | ||||
| 19454 | ** EP_Win == NC_HasWin | ||||
| 19455 | */ | ||||
| 19456 | #define EP_OuterON0x000001 0x000001 /* Originates in ON/USING clause of outer join */ | ||||
| 19457 | #define EP_InnerON0x000002 0x000002 /* Originates in ON/USING of an inner join */ | ||||
| 19458 | #define EP_Distinct0x000004 0x000004 /* Aggregate function with DISTINCT keyword */ | ||||
| 19459 | #define EP_HasFunc0x000008 0x000008 /* Contains one or more functions of any kind */ | ||||
| 19460 | #define EP_Agg0x000010 0x000010 /* Contains one or more aggregate functions */ | ||||
| 19461 | #define EP_FixedCol0x000020 0x000020 /* TK_Column with a known fixed value */ | ||||
| 19462 | #define EP_VarSelect0x000040 0x000040 /* pSelect is correlated, not constant */ | ||||
| 19463 | #define EP_DblQuoted0x000080 0x000080 /* token.z was originally in "..." */ | ||||
| 19464 | #define EP_InfixFunc0x000100 0x000100 /* True for an infix function: LIKE, GLOB, etc */ | ||||
| 19465 | #define EP_Collate0x000200 0x000200 /* Tree contains a TK_COLLATE operator */ | ||||
| 19466 | #define EP_Commuted0x000400 0x000400 /* Comparison operator has been commuted */ | ||||
| 19467 | #define EP_IntValue0x000800 0x000800 /* Integer value contained in u.iValue */ | ||||
| 19468 | #define EP_xIsSelect0x001000 0x001000 /* x.pSelect is valid (otherwise x.pList is) */ | ||||
| 19469 | #define EP_Skip0x002000 0x002000 /* Operator does not contribute to affinity */ | ||||
| 19470 | #define EP_Reduced0x004000 0x004000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ | ||||
| 19471 | #define EP_Win0x008000 0x008000 /* Contains window functions */ | ||||
| 19472 | #define EP_TokenOnly0x010000 0x010000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ | ||||
| 19473 | #define EP_FullSize0x020000 0x020000 /* Expr structure must remain full sized */ | ||||
| 19474 | #define EP_IfNullRow0x040000 0x040000 /* The TK_IF_NULL_ROW opcode */ | ||||
| 19475 | #define EP_Unlikely0x080000 0x080000 /* unlikely() or likelihood() function */ | ||||
| 19476 | #define EP_ConstFunc0x100000 0x100000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */ | ||||
| 19477 | #define EP_CanBeNull0x200000 0x200000 /* Can be null despite NOT NULL constraint */ | ||||
| 19478 | #define EP_Subquery0x400000 0x400000 /* Tree contains a TK_SELECT operator */ | ||||
| 19479 | #define EP_Leaf0x800000 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */ | ||||
| 19480 | #define EP_WinFunc0x1000000 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */ | ||||
| 19481 | #define EP_Subrtn0x2000000 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */ | ||||
| 19482 | #define EP_Quoted0x4000000 0x4000000 /* TK_ID was originally quoted */ | ||||
| 19483 | #define EP_Static0x8000000 0x8000000 /* Held in memory not obtained from malloc() */ | ||||
| 19484 | #define EP_IsTrue0x10000000 0x10000000 /* Always has boolean value of TRUE */ | ||||
| 19485 | #define EP_IsFalse0x20000000 0x20000000 /* Always has boolean value of FALSE */ | ||||
| 19486 | #define EP_FromDDL0x40000000 0x40000000 /* Originates from sqlite_schema */ | ||||
| 19487 | #define EP_SubtArg0x80000000 0x80000000 /* Is argument to SQLITE_SUBTYPE function */ | ||||
| 19488 | |||||
| 19489 | /* The EP_Propagate mask is a set of properties that automatically propagate | ||||
| 19490 | ** upwards into parent nodes. | ||||
| 19491 | */ | ||||
| 19492 | #define EP_Propagate(0x000200|0x400000|0x000008) (EP_Collate0x000200|EP_Subquery0x400000|EP_HasFunc0x000008) | ||||
| 19493 | |||||
| 19494 | /* Macros can be used to test, set, or clear bits in the | ||||
| 19495 | ** Expr.flags field. | ||||
| 19496 | */ | ||||
| 19497 | #define ExprHasProperty(E,P)(((E)->flags&(u32)(P))!=0) (((E)->flags&(u32)(P))!=0) | ||||
| 19498 | #define ExprHasAllProperty(E,P)(((E)->flags&(u32)(P))==(u32)(P)) (((E)->flags&(u32)(P))==(u32)(P)) | ||||
| 19499 | #define ExprSetProperty(E,P)(E)->flags|=(u32)(P) (E)->flags|=(u32)(P) | ||||
| 19500 | #define ExprClearProperty(E,P)(E)->flags&=~(u32)(P) (E)->flags&=~(u32)(P) | ||||
| 19501 | #define ExprAlwaysTrue(E)(((E)->flags&(0x000001|0x10000000))==0x10000000) (((E)->flags&(EP_OuterON0x000001|EP_IsTrue0x10000000))==EP_IsTrue0x10000000) | ||||
| 19502 | #define ExprAlwaysFalse(E)(((E)->flags&(0x000001|0x20000000))==0x20000000) (((E)->flags&(EP_OuterON0x000001|EP_IsFalse0x20000000))==EP_IsFalse0x20000000) | ||||
| 19503 | #define ExprIsFullSize(E)(((E)->flags&(0x004000|0x010000))==0) (((E)->flags&(EP_Reduced0x004000|EP_TokenOnly0x010000))==0) | ||||
| 19504 | |||||
| 19505 | /* Macros used to ensure that the correct members of unions are accessed | ||||
| 19506 | ** in Expr. | ||||
| 19507 | */ | ||||
| 19508 | #define ExprUseUToken(E)(((E)->flags&0x000800)==0) (((E)->flags&EP_IntValue0x000800)==0) | ||||
| 19509 | #define ExprUseUValue(E)(((E)->flags&0x000800)!=0) (((E)->flags&EP_IntValue0x000800)!=0) | ||||
| 19510 | #define ExprUseWOfst(E)(((E)->flags&(0x000002|0x000001))==0) (((E)->flags&(EP_InnerON0x000002|EP_OuterON0x000001))==0) | ||||
| 19511 | #define ExprUseWJoin(E)(((E)->flags&(0x000002|0x000001))!=0) (((E)->flags&(EP_InnerON0x000002|EP_OuterON0x000001))!=0) | ||||
| 19512 | #define ExprUseXList(E)(((E)->flags&0x001000)==0) (((E)->flags&EP_xIsSelect0x001000)==0) | ||||
| 19513 | #define ExprUseXSelect(E)(((E)->flags&0x001000)!=0) (((E)->flags&EP_xIsSelect0x001000)!=0) | ||||
| 19514 | #define ExprUseYTab(E)(((E)->flags&(0x1000000|0x2000000))==0) (((E)->flags&(EP_WinFunc0x1000000|EP_Subrtn0x2000000))==0) | ||||
| 19515 | #define ExprUseYWin(E)(((E)->flags&0x1000000)!=0) (((E)->flags&EP_WinFunc0x1000000)!=0) | ||||
| 19516 | #define ExprUseYSub(E)(((E)->flags&0x2000000)!=0) (((E)->flags&EP_Subrtn0x2000000)!=0) | ||||
| 19517 | |||||
| 19518 | /* Flags for use with Expr.vvaFlags | ||||
| 19519 | */ | ||||
| 19520 | #define EP_NoReduce0x01 0x01 /* Cannot EXPRDUP_REDUCE this Expr */ | ||||
| 19521 | #define EP_Immutable0x02 0x02 /* Do not change this Expr node */ | ||||
| 19522 | |||||
| 19523 | /* The ExprSetVVAProperty() macro is used for Verification, Validation, | ||||
| 19524 | ** and Accreditation only. It works like ExprSetProperty() during VVA | ||||
| 19525 | ** processes but is a no-op for delivery. | ||||
| 19526 | */ | ||||
| 19527 | #ifdef SQLITE_DEBUG | ||||
| 19528 | # define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P) | ||||
| 19529 | # define ExprHasVVAProperty(E,P)0 (((E)->vvaFlags&(P))!=0) | ||||
| 19530 | # define ExprClearVVAProperties(E) (E)->vvaFlags = 0 | ||||
| 19531 | #else | ||||
| 19532 | # define ExprSetVVAProperty(E,P) | ||||
| 19533 | # define ExprHasVVAProperty(E,P)0 0 | ||||
| 19534 | # define ExprClearVVAProperties(E) | ||||
| 19535 | #endif | ||||
| 19536 | |||||
| 19537 | /* | ||||
| 19538 | ** Macros to determine the number of bytes required by a normal Expr | ||||
| 19539 | ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags | ||||
| 19540 | ** and an Expr struct with the EP_TokenOnly flag set. | ||||
| 19541 | */ | ||||
| 19542 | #define EXPR_FULLSIZEsizeof(Expr) sizeof(Expr) /* Full size */ | ||||
| 19543 | #define EXPR_REDUCEDSIZE__builtin_offsetof(Expr, iTable) offsetof(Expr,iTable)__builtin_offsetof(Expr, iTable) /* Common features */ | ||||
| 19544 | #define EXPR_TOKENONLYSIZE__builtin_offsetof(Expr, pLeft) offsetof(Expr,pLeft)__builtin_offsetof(Expr, pLeft) /* Fewer features */ | ||||
| 19545 | |||||
| 19546 | /* | ||||
| 19547 | ** Flags passed to the sqlite3ExprDup() function. See the header comment | ||||
| 19548 | ** above sqlite3ExprDup() for details. | ||||
| 19549 | */ | ||||
| 19550 | #define EXPRDUP_REDUCE0x0001 0x0001 /* Used reduced-size Expr nodes */ | ||||
| 19551 | |||||
| 19552 | /* | ||||
| 19553 | ** True if the expression passed as an argument was a function with | ||||
| 19554 | ** an OVER() clause (a window function). | ||||
| 19555 | */ | ||||
| 19556 | #ifdef SQLITE_OMIT_WINDOWFUNC | ||||
| 19557 | # define IsWindowFunc(p)( ((((p))->flags&(u32)(0x1000000))!=0) && p-> y.pWin->eFrmType!=167 ) 0 | ||||
| 19558 | #else | ||||
| 19559 | # define IsWindowFunc(p)( ((((p))->flags&(u32)(0x1000000))!=0) && p-> y.pWin->eFrmType!=167 ) ( \ | ||||
| 19560 | ExprHasProperty((p), EP_WinFunc)((((p))->flags&(u32)(0x1000000))!=0) && p->y.pWin->eFrmType!=TK_FILTER167 \ | ||||
| 19561 | ) | ||||
| 19562 | #endif | ||||
| 19563 | |||||
| 19564 | /* | ||||
| 19565 | ** A list of expressions. Each expression may optionally have a | ||||
| 19566 | ** name. An expr/name combination can be used in several ways, such | ||||
| 19567 | ** as the list of "expr AS ID" fields following a "SELECT" or in the | ||||
| 19568 | ** list of "ID = expr" items in an UPDATE. A list of expressions can | ||||
| 19569 | ** also be used as the argument to a function, in which case the a.zName | ||||
| 19570 | ** field is not used. | ||||
| 19571 | ** | ||||
| 19572 | ** In order to try to keep memory usage down, the Expr.a.zEName field | ||||
| 19573 | ** is used for multiple purposes: | ||||
| 19574 | ** | ||||
| 19575 | ** eEName Usage | ||||
| 19576 | ** ---------- ------------------------- | ||||
| 19577 | ** ENAME_NAME (1) the AS of result set column | ||||
| 19578 | ** (2) COLUMN= of an UPDATE | ||||
| 19579 | ** | ||||
| 19580 | ** ENAME_TAB DB.TABLE.NAME used to resolve names | ||||
| 19581 | ** of subqueries | ||||
| 19582 | ** | ||||
| 19583 | ** ENAME_SPAN Text of the original result set | ||||
| 19584 | ** expression. | ||||
| 19585 | */ | ||||
| 19586 | struct ExprList { | ||||
| 19587 | int nExpr; /* Number of expressions on the list */ | ||||
| 19588 | int nAlloc; /* Number of a[] slots allocated */ | ||||
| 19589 | struct ExprList_item { /* For each expression in the list */ | ||||
| 19590 | Expr *pExpr; /* The parse tree for this expression */ | ||||
| 19591 | char *zEName; /* Token associated with this expression */ | ||||
| 19592 | struct { | ||||
| 19593 | u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */ | ||||
| 19594 | unsigned eEName :2; /* Meaning of zEName */ | ||||
| 19595 | unsigned done :1; /* Indicates when processing is finished */ | ||||
| 19596 | unsigned reusable :1; /* Constant expression is reusable */ | ||||
| 19597 | unsigned bSorterRef :1; /* Defer evaluation until after sorting */ | ||||
| 19598 | unsigned bNulls :1; /* True if explicit "NULLS FIRST/LAST" */ | ||||
| 19599 | unsigned bUsed :1; /* This column used in a SF_NestedFrom subquery */ | ||||
| 19600 | unsigned bUsingTerm:1; /* Term from the USING clause of a NestedFrom */ | ||||
| 19601 | unsigned bNoExpand: 1; /* Term is an auxiliary in NestedFrom and should | ||||
| 19602 | ** not be expanded by "*" in parent queries */ | ||||
| 19603 | } fg; | ||||
| 19604 | union { | ||||
| 19605 | struct { /* Used by any ExprList other than Parse.pConsExpr */ | ||||
| 19606 | u16 iOrderByCol; /* For ORDER BY, column number in result set */ | ||||
| 19607 | u16 iAlias; /* Index into Parse.aAlias[] for zName */ | ||||
| 19608 | } x; | ||||
| 19609 | int iConstExprReg; /* Register in which Expr value is cached. Used only | ||||
| 19610 | ** by Parse.pConstExpr */ | ||||
| 19611 | } u; | ||||
| 19612 | } a[FLEXARRAY]; /* One slot for each expression in the list */ | ||||
| 19613 | }; | ||||
| 19614 | |||||
| 19615 | /* The size (in bytes) of an ExprList object that is big enough to hold | ||||
| 19616 | ** as many as N expressions. */ | ||||
| 19617 | #define SZ_EXPRLIST(N)(__builtin_offsetof(ExprList, a) + (N)*sizeof(struct ExprList_item )) \ | ||||
| 19618 | (offsetof(ExprList,a)__builtin_offsetof(ExprList, a) + (N)*sizeof(struct ExprList_item)) | ||||
| 19619 | |||||
| 19620 | /* | ||||
| 19621 | ** Allowed values for Expr.a.eEName | ||||
| 19622 | */ | ||||
| 19623 | #define ENAME_NAME0 0 /* The AS clause of a result set */ | ||||
| 19624 | #define ENAME_SPAN1 1 /* Complete text of the result set expression */ | ||||
| 19625 | #define ENAME_TAB2 2 /* "DB.TABLE.NAME" for the result set */ | ||||
| 19626 | #define ENAME_ROWID3 3 /* "DB.TABLE._rowid_" for * expansion of rowid */ | ||||
| 19627 | |||||
| 19628 | /* | ||||
| 19629 | ** An instance of this structure can hold a simple list of identifiers, | ||||
| 19630 | ** such as the list "a,b,c" in the following statements: | ||||
| 19631 | ** | ||||
| 19632 | ** INSERT INTO t(a,b,c) VALUES ...; | ||||
| 19633 | ** CREATE INDEX idx ON t(a,b,c); | ||||
| 19634 | ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...; | ||||
| 19635 | ** | ||||
| 19636 | ** The IdList.a.idx field is used when the IdList represents the list of | ||||
| 19637 | ** column names after a table name in an INSERT statement. In the statement | ||||
| 19638 | ** | ||||
| 19639 | ** INSERT INTO t(a,b,c) ... | ||||
| 19640 | ** | ||||
| 19641 | ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k. | ||||
| 19642 | */ | ||||
| 19643 | struct IdList { | ||||
| 19644 | int nId; /* Number of identifiers on the list */ | ||||
| 19645 | struct IdList_item { | ||||
| 19646 | char *zName; /* Name of the identifier */ | ||||
| 19647 | } a[FLEXARRAY]; | ||||
| 19648 | }; | ||||
| 19649 | |||||
| 19650 | /* The size (in bytes) of an IdList object that can hold up to N IDs. */ | ||||
| 19651 | #define SZ_IDLIST(N)(__builtin_offsetof(IdList, a)+(N)*sizeof(struct IdList_item) ) (offsetof(IdList,a)__builtin_offsetof(IdList, a)+(N)*sizeof(struct IdList_item)) | ||||
| 19652 | |||||
| 19653 | /* | ||||
| 19654 | ** Allowed values for IdList.eType, which determines which value of the a.u4 | ||||
| 19655 | ** is valid. | ||||
| 19656 | */ | ||||
| 19657 | #define EU4_NONE0 0 /* Does not use IdList.a.u4 */ | ||||
| 19658 | #define EU4_IDX1 1 /* Uses IdList.a.u4.idx */ | ||||
| 19659 | #define EU4_EXPR2 2 /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */ | ||||
| 19660 | |||||
| 19661 | /* | ||||
| 19662 | ** Details of the implementation of a subquery. | ||||
| 19663 | */ | ||||
| 19664 | struct Subquery { | ||||
| 19665 | Select *pSelect; /* A SELECT statement used in place of a table name */ | ||||
| 19666 | int addrFillSub; /* Address of subroutine to initialize a subquery */ | ||||
| 19667 | int regReturn; /* Register holding return address of addrFillSub */ | ||||
| 19668 | int regResult; /* Registers holding results of a co-routine */ | ||||
| 19669 | }; | ||||
| 19670 | |||||
| 19671 | /* | ||||
| 19672 | ** The SrcItem object represents a single term in the FROM clause of a query. | ||||
| 19673 | ** The SrcList object is mostly an array of SrcItems. | ||||
| 19674 | ** | ||||
| 19675 | ** The jointype starts out showing the join type between the current table | ||||
| 19676 | ** and the next table on the list. The parser builds the list this way. | ||||
| 19677 | ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each | ||||
| 19678 | ** jointype expresses the join between the table and the previous table. | ||||
| 19679 | ** | ||||
| 19680 | ** In the colUsed field, the high-order bit (bit 63) is set if the table | ||||
| 19681 | ** contains more than 63 columns and the 64-th or later column is used. | ||||
| 19682 | ** | ||||
| 19683 | ** Aggressive use of "union" helps keep the size of the object small. This | ||||
| 19684 | ** has been shown to boost performance, in addition to saving memory. | ||||
| 19685 | ** Access to union elements is gated by the following rules which should | ||||
| 19686 | ** always be checked, either by an if-statement or by an assert(). | ||||
| 19687 | ** | ||||
| 19688 | ** Field Only access if this is true | ||||
| 19689 | ** --------------- ----------------------------------- | ||||
| 19690 | ** u1.zIndexedBy fg.isIndexedBy | ||||
| 19691 | ** u1.pFuncArg fg.isTabFunc | ||||
| 19692 | ** u1.nRow !fg.isTabFunc && !fg.isIndexedBy | ||||
| 19693 | ** | ||||
| 19694 | ** u2.pIBIndex fg.isIndexedBy | ||||
| 19695 | ** u2.pCteUse fg.isCte | ||||
| 19696 | ** | ||||
| 19697 | ** u3.pOn !fg.isUsing | ||||
| 19698 | ** u3.pUsing fg.isUsing | ||||
| 19699 | ** | ||||
| 19700 | ** u4.zDatabase !fg.fixedSchema && !fg.isSubquery | ||||
| 19701 | ** u4.pSchema fg.fixedSchema | ||||
| 19702 | ** u4.pSubq fg.isSubquery | ||||
| 19703 | ** | ||||
| 19704 | ** See also the sqlite3SrcListDelete() routine for assert() statements that | ||||
| 19705 | ** check invariants on the fields of this object, especially the flags | ||||
| 19706 | ** inside the fg struct. | ||||
| 19707 | */ | ||||
| 19708 | struct SrcItem { | ||||
| 19709 | char *zName; /* Name of the table */ | ||||
| 19710 | char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */ | ||||
| 19711 | Table *pSTab; /* Table object for zName. Mnemonic: Srcitem-TABle */ | ||||
| 19712 | struct { | ||||
| 19713 | u8 jointype; /* Type of join between this table and the previous */ | ||||
| 19714 | unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */ | ||||
| 19715 | unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */ | ||||
| 19716 | unsigned isSubquery :1; /* True if this term is a subquery */ | ||||
| 19717 | unsigned isTabFunc :1; /* True if table-valued-function syntax */ | ||||
| 19718 | unsigned isCorrelated :1; /* True if sub-query is correlated */ | ||||
| 19719 | unsigned isMaterialized:1; /* This is a materialized view */ | ||||
| 19720 | unsigned viaCoroutine :1; /* Implemented as a co-routine */ | ||||
| 19721 | unsigned isRecursive :1; /* True for recursive reference in WITH */ | ||||
| 19722 | unsigned fromDDL :1; /* Comes from sqlite_schema */ | ||||
| 19723 | unsigned isCte :1; /* This is a CTE */ | ||||
| 19724 | unsigned notCte :1; /* This item may not match a CTE */ | ||||
| 19725 | unsigned isUsing :1; /* u3.pUsing is valid */ | ||||
| 19726 | unsigned isOn :1; /* u3.pOn was once valid and non-NULL */ | ||||
| 19727 | unsigned isSynthUsing :1; /* u3.pUsing is synthesized from NATURAL */ | ||||
| 19728 | unsigned isNestedFrom :1; /* pSelect is a SF_NestedFrom subquery */ | ||||
| 19729 | unsigned rowidUsed :1; /* The ROWID of this table is referenced */ | ||||
| 19730 | unsigned fixedSchema :1; /* Uses u4.pSchema, not u4.zDatabase */ | ||||
| 19731 | unsigned hadSchema :1; /* Had u4.zDatabase before u4.pSchema */ | ||||
| 19732 | } fg; | ||||
| 19733 | int iCursor; /* The VDBE cursor number used to access this table */ | ||||
| 19734 | Bitmask colUsed; /* Bit N set if column N used. Details above for N>62 */ | ||||
| 19735 | union { | ||||
| 19736 | char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */ | ||||
| 19737 | ExprList *pFuncArg; /* Arguments to table-valued-function */ | ||||
| 19738 | u32 nRow; /* Number of rows in a VALUES clause */ | ||||
| 19739 | } u1; | ||||
| 19740 | union { | ||||
| 19741 | Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */ | ||||
| 19742 | CteUse *pCteUse; /* CTE Usage info when fg.isCte is true */ | ||||
| 19743 | } u2; | ||||
| 19744 | union { | ||||
| 19745 | Expr *pOn; /* fg.isUsing==0 => The ON clause of a join */ | ||||
| 19746 | IdList *pUsing; /* fg.isUsing==1 => The USING clause of a join */ | ||||
| 19747 | } u3; | ||||
| 19748 | union { | ||||
| 19749 | Schema *pSchema; /* Schema to which this item is fixed */ | ||||
| 19750 | char *zDatabase; /* Name of database holding this table */ | ||||
| 19751 | Subquery *pSubq; /* Description of a subquery */ | ||||
| 19752 | } u4; | ||||
| 19753 | }; | ||||
| 19754 | |||||
| 19755 | /* | ||||
| 19756 | ** The OnOrUsing object represents either an ON clause or a USING clause. | ||||
| 19757 | ** It can never be both at the same time, but it can be neither. | ||||
| 19758 | */ | ||||
| 19759 | struct OnOrUsing { | ||||
| 19760 | Expr *pOn; /* The ON clause of a join */ | ||||
| 19761 | IdList *pUsing; /* The USING clause of a join */ | ||||
| 19762 | }; | ||||
| 19763 | |||||
| 19764 | /* | ||||
| 19765 | ** This object represents one or more tables that are the source of | ||||
| 19766 | ** content for an SQL statement. For example, a single SrcList object | ||||
| 19767 | ** is used to hold the FROM clause of a SELECT statement. SrcList also | ||||
| 19768 | ** represents the target tables for DELETE, INSERT, and UPDATE statements. | ||||
| 19769 | ** | ||||
| 19770 | */ | ||||
| 19771 | struct SrcList { | ||||
| 19772 | int nSrc; /* Number of tables or subqueries in the FROM clause */ | ||||
| 19773 | u32 nAlloc; /* Number of entries allocated in a[] below */ | ||||
| 19774 | SrcItem a[FLEXARRAY]; /* One entry for each identifier on the list */ | ||||
| 19775 | }; | ||||
| 19776 | |||||
| 19777 | /* Size (in bytes) of a SrcList object that can hold as many as N | ||||
| 19778 | ** SrcItem objects. */ | ||||
| 19779 | #define SZ_SRCLIST(N)(__builtin_offsetof(SrcList, a)+(N)*sizeof(SrcItem)) (offsetof(SrcList,a)__builtin_offsetof(SrcList, a)+(N)*sizeof(SrcItem)) | ||||
| 19780 | |||||
| 19781 | /* Size (in bytes( of a SrcList object that holds 1 SrcItem. This is a | ||||
| 19782 | ** special case of SZ_SRCITEM(1) that comes up often. */ | ||||
| 19783 | #define SZ_SRCLIST_1(__builtin_offsetof(SrcList, a)+sizeof(SrcItem)) (offsetof(SrcList,a)__builtin_offsetof(SrcList, a)+sizeof(SrcItem)) | ||||
| 19784 | |||||
| 19785 | /* | ||||
| 19786 | ** Permitted values of the SrcList.a.jointype field | ||||
| 19787 | */ | ||||
| 19788 | #define JT_INNER0x01 0x01 /* Any kind of inner or cross join */ | ||||
| 19789 | #define JT_CROSS0x02 0x02 /* Explicit use of the CROSS keyword */ | ||||
| 19790 | #define JT_NATURAL0x04 0x04 /* True for a "natural" join */ | ||||
| 19791 | #define JT_LEFT0x08 0x08 /* Left outer join */ | ||||
| 19792 | #define JT_RIGHT0x10 0x10 /* Right outer join */ | ||||
| 19793 | #define JT_OUTER0x20 0x20 /* The "OUTER" keyword is present */ | ||||
| 19794 | #define JT_LTORJ0x40 0x40 /* One of the LEFT operands of a RIGHT JOIN | ||||
| 19795 | ** Mnemonic: Left Table Of Right Join */ | ||||
| 19796 | #define JT_ERROR0x80 0x80 /* unknown or unsupported join type */ | ||||
| 19797 | |||||
| 19798 | /* | ||||
| 19799 | ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin() | ||||
| 19800 | ** and the WhereInfo.wctrlFlags member. | ||||
| 19801 | ** | ||||
| 19802 | ** Value constraints (enforced via assert()): | ||||
| 19803 | ** WHERE_USE_LIMIT == SF_FixedLimit | ||||
| 19804 | */ | ||||
| 19805 | #define WHERE_ORDERBY_NORMAL0x0000 0x0000 /* No-op */ | ||||
| 19806 | #define WHERE_ORDERBY_MIN0x0001 0x0001 /* ORDER BY processing for min() func */ | ||||
| 19807 | #define WHERE_ORDERBY_MAX0x0002 0x0002 /* ORDER BY processing for max() func */ | ||||
| 19808 | #define WHERE_ONEPASS_DESIRED0x0004 0x0004 /* Want to do one-pass UPDATE/DELETE */ | ||||
| 19809 | #define WHERE_ONEPASS_MULTIROW0x0008 0x0008 /* ONEPASS is ok with multiple rows */ | ||||
| 19810 | #define WHERE_DUPLICATES_OK0x0010 0x0010 /* Ok to return a row more than once */ | ||||
| 19811 | #define WHERE_OR_SUBCLAUSE0x0020 0x0020 /* Processing a sub-WHERE as part of | ||||
| 19812 | ** the OR optimization */ | ||||
| 19813 | #define WHERE_GROUPBY0x0040 0x0040 /* pOrderBy is really a GROUP BY */ | ||||
| 19814 | #define WHERE_DISTINCTBY0x0080 0x0080 /* pOrderby is really a DISTINCT clause */ | ||||
| 19815 | #define WHERE_WANT_DISTINCT0x0100 0x0100 /* All output needs to be distinct */ | ||||
| 19816 | #define WHERE_SORTBYGROUP0x0200 0x0200 /* Support sqlite3WhereIsSorted() */ | ||||
| 19817 | #define WHERE_AGG_DISTINCT0x0400 0x0400 /* Query is "SELECT agg(DISTINCT ...)" */ | ||||
| 19818 | #define WHERE_ORDERBY_LIMIT0x0800 0x0800 /* ORDERBY+LIMIT on the inner loop */ | ||||
| 19819 | #define WHERE_RIGHT_JOIN0x1000 0x1000 /* Processing a RIGHT JOIN */ | ||||
| 19820 | #define WHERE_KEEP_ALL_JOINS0x2000 0x2000 /* Do not do the omit-noop-join opt */ | ||||
| 19821 | #define WHERE_USE_LIMIT0x4000 0x4000 /* Use the LIMIT in cost estimates */ | ||||
| 19822 | /* 0x8000 not currently used */ | ||||
| 19823 | |||||
| 19824 | /* Allowed return values from sqlite3WhereIsDistinct() | ||||
| 19825 | */ | ||||
| 19826 | #define WHERE_DISTINCT_NOOP0 0 /* DISTINCT keyword not used */ | ||||
| 19827 | #define WHERE_DISTINCT_UNIQUE1 1 /* No duplicates */ | ||||
| 19828 | #define WHERE_DISTINCT_ORDERED2 2 /* All duplicates are adjacent */ | ||||
| 19829 | #define WHERE_DISTINCT_UNORDERED3 3 /* Duplicates are scattered */ | ||||
| 19830 | |||||
| 19831 | /* | ||||
| 19832 | ** A NameContext defines a context in which to resolve table and column | ||||
| 19833 | ** names. The context consists of a list of tables (the pSrcList) field and | ||||
| 19834 | ** a list of named expression (pEList). The named expression list may | ||||
| 19835 | ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or | ||||
| 19836 | ** to the table being operated on by INSERT, UPDATE, or DELETE. The | ||||
| 19837 | ** pEList corresponds to the result set of a SELECT and is NULL for | ||||
| 19838 | ** other statements. | ||||
| 19839 | ** | ||||
| 19840 | ** NameContexts can be nested. When resolving names, the inner-most | ||||
| 19841 | ** context is searched first. If no match is found, the next outer | ||||
| 19842 | ** context is checked. If there is still no match, the next context | ||||
| 19843 | ** is checked. This process continues until either a match is found | ||||
| 19844 | ** or all contexts are check. When a match is found, the nRef member of | ||||
| 19845 | ** the context containing the match is incremented. | ||||
| 19846 | ** | ||||
| 19847 | ** Each subquery gets a new NameContext. The pNext field points to the | ||||
| 19848 | ** NameContext in the parent query. Thus the process of scanning the | ||||
| 19849 | ** NameContext list corresponds to searching through successively outer | ||||
| 19850 | ** subqueries looking for a match. | ||||
| 19851 | */ | ||||
| 19852 | struct NameContext { | ||||
| 19853 | Parse *pParse; /* The parser */ | ||||
| 19854 | SrcList *pSrcList; /* One or more tables used to resolve names */ | ||||
| 19855 | union { | ||||
| 19856 | ExprList *pEList; /* Optional list of result-set columns */ | ||||
| 19857 | AggInfo *pAggInfo; /* Information about aggregates at this level */ | ||||
| 19858 | Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */ | ||||
| 19859 | int iBaseReg; /* For TK_REGISTER when parsing RETURNING */ | ||||
| 19860 | } uNC; | ||||
| 19861 | NameContext *pNext; /* Next outer name context. NULL for outermost */ | ||||
| 19862 | int nRef; /* Number of names resolved by this context */ | ||||
| 19863 | int nNcErr; /* Number of errors encountered while resolving names */ | ||||
| 19864 | int ncFlags; /* Zero or more NC_* flags defined below */ | ||||
| 19865 | u32 nNestedSelect; /* Number of nested selects using this NC */ | ||||
| 19866 | Select *pWinSelect; /* SELECT statement for any window functions */ | ||||
| 19867 | }; | ||||
| 19868 | |||||
| 19869 | /* | ||||
| 19870 | ** Allowed values for the NameContext, ncFlags field. | ||||
| 19871 | ** | ||||
| 19872 | ** Value constraints (all checked via assert()): | ||||
| 19873 | ** NC_HasAgg == SF_HasAgg == EP_Agg | ||||
| 19874 | ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX | ||||
| 19875 | ** NC_OrderAgg == SF_OrderByReqd == SQLITE_FUNC_ANYORDER | ||||
| 19876 | ** NC_HasWin == EP_Win | ||||
| 19877 | ** | ||||
| 19878 | */ | ||||
| 19879 | #define NC_AllowAgg0x000001 0x000001 /* Aggregate functions are allowed here */ | ||||
| 19880 | #define NC_PartIdx0x000002 0x000002 /* True if resolving a partial index WHERE */ | ||||
| 19881 | #define NC_IsCheck0x000004 0x000004 /* True if resolving a CHECK constraint */ | ||||
| 19882 | #define NC_GenCol0x000008 0x000008 /* True for a GENERATED ALWAYS AS clause */ | ||||
| 19883 | #define NC_HasAgg0x000010 0x000010 /* One or more aggregate functions seen */ | ||||
| 19884 | #define NC_IdxExpr0x000020 0x000020 /* True if resolving columns of CREATE INDEX */ | ||||
| 19885 | #define NC_SelfRef0x00002e 0x00002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */ | ||||
| 19886 | #define NC_Subquery0x000040 0x000040 /* A subquery has been seen */ | ||||
| 19887 | #define NC_UEList0x000080 0x000080 /* True if uNC.pEList is used */ | ||||
| 19888 | #define NC_UAggInfo0x000100 0x000100 /* True if uNC.pAggInfo is used */ | ||||
| 19889 | #define NC_UUpsert0x000200 0x000200 /* True if uNC.pUpsert is used */ | ||||
| 19890 | #define NC_UBaseReg0x000400 0x000400 /* True if uNC.iBaseReg is used */ | ||||
| 19891 | #define NC_MinMaxAgg0x001000 0x001000 /* min/max aggregates seen. See note above */ | ||||
| 19892 | /* 0x002000 // available for reuse */ | ||||
| 19893 | #define NC_AllowWin0x004000 0x004000 /* Window functions are allowed here */ | ||||
| 19894 | #define NC_HasWin0x008000 0x008000 /* One or more window functions seen */ | ||||
| 19895 | #define NC_IsDDL0x010000 0x010000 /* Resolving names in a CREATE statement */ | ||||
| 19896 | #define NC_InAggFunc0x020000 0x020000 /* True if analyzing arguments to an agg func */ | ||||
| 19897 | #define NC_FromDDL0x040000 0x040000 /* SQL text comes from sqlite_schema */ | ||||
| 19898 | #define NC_NoSelect0x080000 0x080000 /* Do not descend into sub-selects */ | ||||
| 19899 | #define NC_Where0x100000 0x100000 /* Processing WHERE clause of a SELECT */ | ||||
| 19900 | #define NC_OrderAgg0x8000000 0x8000000 /* Has an aggregate other than count/min/max */ | ||||
| 19901 | |||||
| 19902 | /* | ||||
| 19903 | ** An instance of the following object describes a single ON CONFLICT | ||||
| 19904 | ** clause in an upsert. | ||||
| 19905 | ** | ||||
| 19906 | ** The pUpsertTarget field is only set if the ON CONFLICT clause includes | ||||
| 19907 | ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the | ||||
| 19908 | ** conflict-target clause.) The pUpsertTargetWhere is the optional | ||||
| 19909 | ** WHERE clause used to identify partial unique indexes. | ||||
| 19910 | ** | ||||
| 19911 | ** pUpsertSet is the list of column=expr terms of the UPDATE statement. | ||||
| 19912 | ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The | ||||
| 19913 | ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the | ||||
| 19914 | ** WHERE clause is omitted. | ||||
| 19915 | */ | ||||
| 19916 | struct Upsert { | ||||
| 19917 | ExprList *pUpsertTarget; /* Optional description of conflict target */ | ||||
| 19918 | Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */ | ||||
| 19919 | ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */ | ||||
| 19920 | Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */ | ||||
| 19921 | Upsert *pNextUpsert; /* Next ON CONFLICT clause in the list */ | ||||
| 19922 | u8 isDoUpdate; /* True for DO UPDATE. False for DO NOTHING */ | ||||
| 19923 | u8 isDup; /* True if 2nd or later with same pUpsertIdx */ | ||||
| 19924 | /* Above this point is the parse tree for the ON CONFLICT clauses. | ||||
| 19925 | ** The next group of fields stores intermediate data. */ | ||||
| 19926 | void *pToFree; /* Free memory when deleting the Upsert object */ | ||||
| 19927 | /* All fields above are owned by the Upsert object and must be freed | ||||
| 19928 | ** when the Upsert is destroyed. The fields below are used to transfer | ||||
| 19929 | ** information from the INSERT processing down into the UPDATE processing | ||||
| 19930 | ** while generating code. The fields below are owned by the INSERT | ||||
| 19931 | ** statement and will be freed by INSERT processing. */ | ||||
| 19932 | Index *pUpsertIdx; /* UNIQUE constraint specified by pUpsertTarget */ | ||||
| 19933 | SrcList *pUpsertSrc; /* Table to be updated */ | ||||
| 19934 | int regData; /* First register holding array of VALUES */ | ||||
| 19935 | int iDataCur; /* Index of the data cursor */ | ||||
| 19936 | int iIdxCur; /* Index of the first index cursor */ | ||||
| 19937 | }; | ||||
| 19938 | |||||
| 19939 | /* | ||||
| 19940 | ** An instance of the following structure contains all information | ||||
| 19941 | ** needed to generate code for a single SELECT statement. | ||||
| 19942 | ** | ||||
| 19943 | ** See the header comment on the computeLimitRegisters() routine for a | ||||
| 19944 | ** detailed description of the meaning of the iLimit and iOffset fields. | ||||
| 19945 | ** | ||||
| 19946 | ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. | ||||
| 19947 | ** These addresses must be stored so that we can go back and fill in | ||||
| 19948 | ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor | ||||
| 19949 | ** the number of columns in P2 can be computed at the same time | ||||
| 19950 | ** as the OP_OpenEphm instruction is coded because not | ||||
| 19951 | ** enough information about the compound query is known at that point. | ||||
| 19952 | ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences | ||||
| 19953 | ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating | ||||
| 19954 | ** sequences for the ORDER BY clause. | ||||
| 19955 | */ | ||||
| 19956 | struct Select { | ||||
| 19957 | u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ | ||||
| 19958 | LogEst nSelectRow; /* Estimated number of result rows */ | ||||
| 19959 | u32 selFlags; /* Various SF_* values */ | ||||
| 19960 | int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ | ||||
| 19961 | u32 selId; /* Unique identifier number for this SELECT */ | ||||
| 19962 | int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */ | ||||
| 19963 | ExprList *pEList; /* The fields of the result */ | ||||
| 19964 | SrcList *pSrc; /* The FROM clause */ | ||||
| 19965 | Expr *pWhere; /* The WHERE clause */ | ||||
| 19966 | ExprList *pGroupBy; /* The GROUP BY clause */ | ||||
| 19967 | Expr *pHaving; /* The HAVING clause */ | ||||
| 19968 | ExprList *pOrderBy; /* The ORDER BY clause */ | ||||
| 19969 | Select *pPrior; /* Prior select in a compound select statement */ | ||||
| 19970 | Select *pNext; /* Next select to the left in a compound */ | ||||
| 19971 | Expr *pLimit; /* LIMIT expression. NULL means not used. */ | ||||
| 19972 | With *pWith; /* WITH clause attached to this select. Or NULL. */ | ||||
| 19973 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 19974 | Window *pWin; /* List of window functions */ | ||||
| 19975 | Window *pWinDefn; /* List of named window definitions */ | ||||
| 19976 | #endif | ||||
| 19977 | }; | ||||
| 19978 | |||||
| 19979 | /* | ||||
| 19980 | ** Allowed values for Select.selFlags. The "SF" prefix stands for | ||||
| 19981 | ** "Select Flag". | ||||
| 19982 | ** | ||||
| 19983 | ** Value constraints (all checked via assert()) | ||||
| 19984 | ** SF_HasAgg == NC_HasAgg | ||||
| 19985 | ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX | ||||
| 19986 | ** SF_OrderByReqd == NC_OrderAgg == SQLITE_FUNC_ANYORDER | ||||
| 19987 | ** SF_FixedLimit == WHERE_USE_LIMIT | ||||
| 19988 | */ | ||||
| 19989 | #define SF_Distinct0x0000001 0x0000001 /* Output should be DISTINCT */ | ||||
| 19990 | #define SF_All0x0000002 0x0000002 /* Includes the ALL keyword */ | ||||
| 19991 | #define SF_Resolved0x0000004 0x0000004 /* Identifiers have been resolved */ | ||||
| 19992 | #define SF_Aggregate0x0000008 0x0000008 /* Contains agg functions or a GROUP BY */ | ||||
| 19993 | #define SF_HasAgg0x0000010 0x0000010 /* Contains aggregate functions */ | ||||
| 19994 | #define SF_UsesEphemeral0x0000020 0x0000020 /* Uses the OpenEphemeral opcode */ | ||||
| 19995 | #define SF_Expanded0x0000040 0x0000040 /* sqlite3SelectExpand() called on this */ | ||||
| 19996 | #define SF_HasTypeInfo0x0000080 0x0000080 /* FROM subqueries have Table metadata */ | ||||
| 19997 | #define SF_Compound0x0000100 0x0000100 /* Part of a compound query */ | ||||
| 19998 | #define SF_Values0x0000200 0x0000200 /* Synthesized from VALUES clause */ | ||||
| 19999 | #define SF_MultiValue0x0000400 0x0000400 /* Single VALUES term with multiple rows */ | ||||
| 20000 | #define SF_NestedFrom0x0000800 0x0000800 /* Part of a parenthesized FROM clause */ | ||||
| 20001 | #define SF_MinMaxAgg0x0001000 0x0001000 /* Aggregate containing min() or max() */ | ||||
| 20002 | #define SF_Recursive0x0002000 0x0002000 /* The recursive part of a recursive CTE */ | ||||
| 20003 | #define SF_FixedLimit0x0004000 0x0004000 /* nSelectRow set by a constant LIMIT */ | ||||
| 20004 | #define SF_MaybeConvert0x0008000 0x0008000 /* Need convertCompoundSelectToSubquery() */ | ||||
| 20005 | #define SF_Converted0x0010000 0x0010000 /* By convertCompoundSelectToSubquery() */ | ||||
| 20006 | #define SF_IncludeHidden0x0020000 0x0020000 /* Include hidden columns in output */ | ||||
| 20007 | #define SF_ComplexResult0x0040000 0x0040000 /* Result contains subquery or function */ | ||||
| 20008 | #define SF_WhereBegin0x0080000 0x0080000 /* Really a WhereBegin() call. Debug Only */ | ||||
| 20009 | #define SF_WinRewrite0x0100000 0x0100000 /* Window function rewrite accomplished */ | ||||
| 20010 | #define SF_View0x0200000 0x0200000 /* SELECT statement is a view */ | ||||
| 20011 | #define SF_NoopOrderBy0x0400000 0x0400000 /* ORDER BY is ignored for this query */ | ||||
| 20012 | #define SF_UFSrcCheck0x0800000 0x0800000 /* Check pSrc as required by UPDATE...FROM */ | ||||
| 20013 | #define SF_PushDown0x1000000 0x1000000 /* Modified by WHERE-clause push-down opt */ | ||||
| 20014 | #define SF_MultiPart0x2000000 0x2000000 /* Has multiple incompatible PARTITIONs */ | ||||
| 20015 | #define SF_CopyCte0x4000000 0x4000000 /* SELECT statement is a copy of a CTE */ | ||||
| 20016 | #define SF_OrderByReqd0x8000000 0x8000000 /* The ORDER BY clause may not be omitted */ | ||||
| 20017 | #define SF_UpdateFrom0x10000000 0x10000000 /* Query originates with UPDATE FROM */ | ||||
| 20018 | #define SF_Correlated0x20000000 0x20000000 /* True if references the outer context */ | ||||
| 20019 | |||||
| 20020 | /* True if SrcItem X is a subquery that has SF_NestedFrom */ | ||||
| 20021 | #define IsNestedFrom(X)((X)->fg.isSubquery && ((X)->u4.pSubq->pSelect ->selFlags&0x0000800)!=0) \ | ||||
| 20022 | ((X)->fg.isSubquery && \ | ||||
| 20023 | ((X)->u4.pSubq->pSelect->selFlags&SF_NestedFrom0x0000800)!=0) | ||||
| 20024 | |||||
| 20025 | /* | ||||
| 20026 | ** The results of a SELECT can be distributed in several ways, as defined | ||||
| 20027 | ** by one of the following macros. The "SRT" prefix means "SELECT Result | ||||
| 20028 | ** Type". | ||||
| 20029 | ** | ||||
| 20030 | ** SRT_Union Store results as a key in a temporary index | ||||
| 20031 | ** identified by pDest->iSDParm. | ||||
| 20032 | ** | ||||
| 20033 | ** SRT_Except Remove results from the temporary index pDest->iSDParm. | ||||
| 20034 | ** | ||||
| 20035 | ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result | ||||
| 20036 | ** set is not empty. | ||||
| 20037 | ** | ||||
| 20038 | ** SRT_Discard Throw the results away. This is used by SELECT | ||||
| 20039 | ** statements within triggers whose only purpose is | ||||
| 20040 | ** the side-effects of functions. | ||||
| 20041 | ** | ||||
| 20042 | ** SRT_Output Generate a row of output (using the OP_ResultRow | ||||
| 20043 | ** opcode) for each row in the result set. | ||||
| 20044 | ** | ||||
| 20045 | ** SRT_Mem Only valid if the result is a single column. | ||||
| 20046 | ** Store the first column of the first result row | ||||
| 20047 | ** in register pDest->iSDParm then abandon the rest | ||||
| 20048 | ** of the query. This destination implies "LIMIT 1". | ||||
| 20049 | ** | ||||
| 20050 | ** SRT_Set The result must be a single column. Store each | ||||
| 20051 | ** row of result as the key in table pDest->iSDParm. | ||||
| 20052 | ** Apply the affinity pDest->affSdst before storing | ||||
| 20053 | ** results. if pDest->iSDParm2 is positive, then it is | ||||
| 20054 | ** a register holding a Bloom filter for the IN operator | ||||
| 20055 | ** that should be populated in addition to the | ||||
| 20056 | ** pDest->iSDParm table. This SRT is used to | ||||
| 20057 | ** implement "IN (SELECT ...)". | ||||
| 20058 | ** | ||||
| 20059 | ** SRT_EphemTab Create an temporary table pDest->iSDParm and store | ||||
| 20060 | ** the result there. The cursor is left open after | ||||
| 20061 | ** returning. This is like SRT_Table except that | ||||
| 20062 | ** this destination uses OP_OpenEphemeral to create | ||||
| 20063 | ** the table first. | ||||
| 20064 | ** | ||||
| 20065 | ** SRT_Coroutine Generate a co-routine that returns a new row of | ||||
| 20066 | ** results each time it is invoked. The entry point | ||||
| 20067 | ** of the co-routine is stored in register pDest->iSDParm | ||||
| 20068 | ** and the result row is stored in pDest->nDest registers | ||||
| 20069 | ** starting with pDest->iSdst. | ||||
| 20070 | ** | ||||
| 20071 | ** SRT_Table Store results in temporary table pDest->iSDParm. | ||||
| 20072 | ** SRT_Fifo This is like SRT_EphemTab except that the table | ||||
| 20073 | ** is assumed to already be open. SRT_Fifo has | ||||
| 20074 | ** the additional property of being able to ignore | ||||
| 20075 | ** the ORDER BY clause. | ||||
| 20076 | ** | ||||
| 20077 | ** SRT_DistFifo Store results in a temporary table pDest->iSDParm. | ||||
| 20078 | ** But also use temporary table pDest->iSDParm+1 as | ||||
| 20079 | ** a record of all prior results and ignore any duplicate | ||||
| 20080 | ** rows. Name means: "Distinct Fifo". | ||||
| 20081 | ** | ||||
| 20082 | ** SRT_Queue Store results in priority queue pDest->iSDParm (really | ||||
| 20083 | ** an index). Append a sequence number so that all entries | ||||
| 20084 | ** are distinct. | ||||
| 20085 | ** | ||||
| 20086 | ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if | ||||
| 20087 | ** the same record has never been stored before. The | ||||
| 20088 | ** index at pDest->iSDParm+1 hold all prior stores. | ||||
| 20089 | ** | ||||
| 20090 | ** SRT_Upfrom Store results in the temporary table already opened by | ||||
| 20091 | ** pDest->iSDParm. If (pDest->iSDParm<0), then the temp | ||||
| 20092 | ** table is an intkey table - in this case the first | ||||
| 20093 | ** column returned by the SELECT is used as the integer | ||||
| 20094 | ** key. If (pDest->iSDParm>0), then the table is an index | ||||
| 20095 | ** table. (pDest->iSDParm) is the number of key columns in | ||||
| 20096 | ** each index record in this case. | ||||
| 20097 | */ | ||||
| 20098 | #define SRT_Union1 1 /* Store result as keys in an index */ | ||||
| 20099 | #define SRT_Except2 2 /* Remove result from a UNION index */ | ||||
| 20100 | #define SRT_Exists3 3 /* Store 1 if the result is not empty */ | ||||
| 20101 | #define SRT_Discard4 4 /* Do not save the results anywhere */ | ||||
| 20102 | #define SRT_DistFifo5 5 /* Like SRT_Fifo, but unique results only */ | ||||
| 20103 | #define SRT_DistQueue6 6 /* Like SRT_Queue, but unique results only */ | ||||
| 20104 | |||||
| 20105 | /* The DISTINCT clause is ignored for all of the above. Not that | ||||
| 20106 | ** IgnorableDistinct() implies IgnorableOrderby() */ | ||||
| 20107 | #define IgnorableDistinct(X)((X->eDest)<=6) ((X->eDest)<=SRT_DistQueue6) | ||||
| 20108 | |||||
| 20109 | #define SRT_Queue7 7 /* Store result in an queue */ | ||||
| 20110 | #define SRT_Fifo8 8 /* Store result as data with an automatic rowid */ | ||||
| 20111 | |||||
| 20112 | /* The ORDER BY clause is ignored for all of the above */ | ||||
| 20113 | #define IgnorableOrderby(X)((X->eDest)<=8) ((X->eDest)<=SRT_Fifo8) | ||||
| 20114 | |||||
| 20115 | #define SRT_Output9 9 /* Output each row of result */ | ||||
| 20116 | #define SRT_Mem10 10 /* Store result in a memory cell */ | ||||
| 20117 | #define SRT_Set11 11 /* Store results as keys in an index */ | ||||
| 20118 | #define SRT_EphemTab12 12 /* Create transient tab and store like SRT_Table */ | ||||
| 20119 | #define SRT_Coroutine13 13 /* Generate a single row of result */ | ||||
| 20120 | #define SRT_Table14 14 /* Store result as data with an automatic rowid */ | ||||
| 20121 | #define SRT_Upfrom15 15 /* Store result as data with rowid */ | ||||
| 20122 | |||||
| 20123 | /* | ||||
| 20124 | ** An instance of this object describes where to put of the results of | ||||
| 20125 | ** a SELECT statement. | ||||
| 20126 | */ | ||||
| 20127 | struct SelectDest { | ||||
| 20128 | u8 eDest; /* How to dispose of the results. One of SRT_* above. */ | ||||
| 20129 | int iSDParm; /* A parameter used by the eDest disposal method */ | ||||
| 20130 | int iSDParm2; /* A second parameter for the eDest disposal method */ | ||||
| 20131 | int iSdst; /* Base register where results are written */ | ||||
| 20132 | int nSdst; /* Number of registers allocated */ | ||||
| 20133 | char *zAffSdst; /* Affinity used for SRT_Set */ | ||||
| 20134 | ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */ | ||||
| 20135 | }; | ||||
| 20136 | |||||
| 20137 | /* | ||||
| 20138 | ** During code generation of statements that do inserts into AUTOINCREMENT | ||||
| 20139 | ** tables, the following information is attached to the Table.u.autoInc.p | ||||
| 20140 | ** pointer of each autoincrement table to record some side information that | ||||
| 20141 | ** the code generator needs. We have to keep per-table autoincrement | ||||
| 20142 | ** information in case inserts are done within triggers. Triggers do not | ||||
| 20143 | ** normally coordinate their activities, but we do need to coordinate the | ||||
| 20144 | ** loading and saving of autoincrement information. | ||||
| 20145 | */ | ||||
| 20146 | struct AutoincInfo { | ||||
| 20147 | AutoincInfo *pNext; /* Next info block in a list of them all */ | ||||
| 20148 | Table *pTab; /* Table this info block refers to */ | ||||
| 20149 | int iDb; /* Index in sqlite3.aDb[] of database holding pTab */ | ||||
| 20150 | int regCtr; /* Memory register holding the rowid counter */ | ||||
| 20151 | }; | ||||
| 20152 | |||||
| 20153 | /* | ||||
| 20154 | ** At least one instance of the following structure is created for each | ||||
| 20155 | ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE | ||||
| 20156 | ** statement. All such objects are stored in the linked list headed at | ||||
| 20157 | ** Parse.pTriggerPrg and deleted once statement compilation has been | ||||
| 20158 | ** completed. | ||||
| 20159 | ** | ||||
| 20160 | ** A Vdbe sub-program that implements the body and WHEN clause of trigger | ||||
| 20161 | ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of | ||||
| 20162 | ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable. | ||||
| 20163 | ** The Parse.pTriggerPrg list never contains two entries with the same | ||||
| 20164 | ** values for both pTrigger and orconf. | ||||
| 20165 | ** | ||||
| 20166 | ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns | ||||
| 20167 | ** accessed (or set to 0 for triggers fired as a result of INSERT | ||||
| 20168 | ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to | ||||
| 20169 | ** a mask of new.* columns used by the program. | ||||
| 20170 | */ | ||||
| 20171 | struct TriggerPrg { | ||||
| 20172 | Trigger *pTrigger; /* Trigger this program was coded from */ | ||||
| 20173 | TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */ | ||||
| 20174 | SubProgram *pProgram; /* Program implementing pTrigger/orconf */ | ||||
| 20175 | int orconf; /* Default ON CONFLICT policy */ | ||||
| 20176 | u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */ | ||||
| 20177 | }; | ||||
| 20178 | |||||
| 20179 | /* | ||||
| 20180 | ** The yDbMask datatype for the bitmask of all attached databases. | ||||
| 20181 | */ | ||||
| 20182 | #if SQLITE_MAX_ATTACHED10>30 | ||||
| 20183 | typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED10+9)/8]; | ||||
| 20184 | # define DbMaskTest(M,I)(((M)&(((yDbMask)1)<<(I)))!=0) (((M)[(I)/8]&(1<<((I)&7)))!=0) | ||||
| 20185 | # define DbMaskZero(M)((M)=0) memset((M),0,sizeof(M)) | ||||
| 20186 | # define DbMaskSet(M,I)((M)|=(((yDbMask)1)<<(I))) (M)[(I)/8]|=(1<<((I)&7)) | ||||
| 20187 | # define DbMaskAllZero(M)((M)==0) sqlite3DbMaskAllZero(M) | ||||
| 20188 | # define DbMaskNonZero(M)((M)!=0) (sqlite3DbMaskAllZero(M)==0) | ||||
| 20189 | #else | ||||
| 20190 | typedef unsigned int yDbMask; | ||||
| 20191 | # define DbMaskTest(M,I)(((M)&(((yDbMask)1)<<(I)))!=0) (((M)&(((yDbMask)1)<<(I)))!=0) | ||||
| 20192 | # define DbMaskZero(M)((M)=0) ((M)=0) | ||||
| 20193 | # define DbMaskSet(M,I)((M)|=(((yDbMask)1)<<(I))) ((M)|=(((yDbMask)1)<<(I))) | ||||
| 20194 | # define DbMaskAllZero(M)((M)==0) ((M)==0) | ||||
| 20195 | # define DbMaskNonZero(M)((M)!=0) ((M)!=0) | ||||
| 20196 | #endif | ||||
| 20197 | |||||
| 20198 | /* | ||||
| 20199 | ** For each index X that has as one of its arguments either an expression | ||||
| 20200 | ** or the name of a virtual generated column, and if X is in scope such that | ||||
| 20201 | ** the value of the expression can simply be read from the index, then | ||||
| 20202 | ** there is an instance of this object on the Parse.pIdxExpr list. | ||||
| 20203 | ** | ||||
| 20204 | ** During code generation, while generating code to evaluate expressions, | ||||
| 20205 | ** this list is consulted and if a matching expression is found, the value | ||||
| 20206 | ** is read from the index rather than being recomputed. | ||||
| 20207 | */ | ||||
| 20208 | struct IndexedExpr { | ||||
| 20209 | Expr *pExpr; /* The expression contained in the index */ | ||||
| 20210 | int iDataCur; /* The data cursor associated with the index */ | ||||
| 20211 | int iIdxCur; /* The index cursor */ | ||||
| 20212 | int iIdxCol; /* The index column that contains value of pExpr */ | ||||
| 20213 | u8 bMaybeNullRow; /* True if we need an OP_IfNullRow check */ | ||||
| 20214 | u8 aff; /* Affinity of the pExpr expression */ | ||||
| 20215 | IndexedExpr *pIENext; /* Next in a list of all indexed expressions */ | ||||
| 20216 | #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS | ||||
| 20217 | const char *zIdxName; /* Name of index, used only for bytecode comments */ | ||||
| 20218 | #endif | ||||
| 20219 | }; | ||||
| 20220 | |||||
| 20221 | /* | ||||
| 20222 | ** An instance of the ParseCleanup object specifies an operation that | ||||
| 20223 | ** should be performed after parsing to deallocation resources obtained | ||||
| 20224 | ** during the parse and which are no longer needed. | ||||
| 20225 | */ | ||||
| 20226 | struct ParseCleanup { | ||||
| 20227 | ParseCleanup *pNext; /* Next cleanup task */ | ||||
| 20228 | void *pPtr; /* Pointer to object to deallocate */ | ||||
| 20229 | void (*xCleanup)(sqlite3*,void*); /* Deallocation routine */ | ||||
| 20230 | }; | ||||
| 20231 | |||||
| 20232 | /* | ||||
| 20233 | ** An SQL parser context. A copy of this structure is passed through | ||||
| 20234 | ** the parser and down into all the parser action routine in order to | ||||
| 20235 | ** carry around information that is global to the entire parse. | ||||
| 20236 | ** | ||||
| 20237 | ** The structure is divided into two parts. When the parser and code | ||||
| 20238 | ** generate call themselves recursively, the first part of the structure | ||||
| 20239 | ** is constant but the second part is reset at the beginning and end of | ||||
| 20240 | ** each recursion. | ||||
| 20241 | ** | ||||
| 20242 | ** The nTableLock and aTableLock variables are only used if the shared-cache | ||||
| 20243 | ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are | ||||
| 20244 | ** used to store the set of table-locks required by the statement being | ||||
| 20245 | ** compiled. Function sqlite3TableLock() is used to add entries to the | ||||
| 20246 | ** list. | ||||
| 20247 | */ | ||||
| 20248 | struct Parse { | ||||
| 20249 | sqlite3 *db; /* The main database structure */ | ||||
| 20250 | char *zErrMsg; /* An error message */ | ||||
| 20251 | Vdbe *pVdbe; /* An engine for executing database bytecode */ | ||||
| 20252 | int rc; /* Return code from execution */ | ||||
| 20253 | LogEst nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ | ||||
| 20254 | u8 nested; /* Number of nested calls to the parser/code generator */ | ||||
| 20255 | u8 nTempReg; /* Number of temporary registers in aTempReg[] */ | ||||
| 20256 | u8 isMultiWrite; /* True if statement may modify/insert multiple rows */ | ||||
| 20257 | u8 mayAbort; /* True if statement may throw an ABORT exception */ | ||||
| 20258 | u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */ | ||||
| 20259 | u8 disableLookaside; /* Number of times lookaside has been disabled */ | ||||
| 20260 | u8 prepFlags; /* SQLITE_PREPARE_* flags */ | ||||
| 20261 | u8 withinRJSubrtn; /* Nesting level for RIGHT JOIN body subroutines */ | ||||
| 20262 | u8 mSubrtnSig; /* mini Bloom filter on available SubrtnSig.selId */ | ||||
| 20263 | u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */ | ||||
| 20264 | u8 bReturning; /* Coding a RETURNING trigger */ | ||||
| 20265 | u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */ | ||||
| 20266 | u8 disableTriggers; /* True to disable triggers */ | ||||
| 20267 | #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) | ||||
| 20268 | u8 earlyCleanup; /* OOM inside sqlite3ParserAddCleanup() */ | ||||
| 20269 | #endif | ||||
| 20270 | #ifdef SQLITE_DEBUG | ||||
| 20271 | u8 ifNotExists; /* Might be true if IF NOT EXISTS. Assert()s only */ | ||||
| 20272 | u8 isCreate; /* CREATE TABLE, INDEX, or VIEW (but not TRIGGER) | ||||
| 20273 | ** and ALTER TABLE ADD COLUMN. */ | ||||
| 20274 | #endif | ||||
| 20275 | bft colNamesSet :1; /* TRUE after OP_ColumnName has been issued to pVdbe */ | ||||
| 20276 | bft bHasWith :1; /* True if statement contains WITH */ | ||||
| 20277 | bft okConstFactor :1; /* OK to factor out constants */ | ||||
| 20278 | bft checkSchema :1; /* Causes schema cookie check after an error */ | ||||
| 20279 | int nRangeReg; /* Size of the temporary register block */ | ||||
| 20280 | int iRangeReg; /* First register in temporary register block */ | ||||
| 20281 | int nErr; /* Number of errors seen */ | ||||
| 20282 | int nTab; /* Number of previously allocated VDBE cursors */ | ||||
| 20283 | int nMem; /* Number of memory cells used so far */ | ||||
| 20284 | int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */ | ||||
| 20285 | int iSelfTab; /* Table associated with an index on expr, or negative | ||||
| 20286 | ** of the base register during check-constraint eval */ | ||||
| 20287 | int nLabel; /* The *negative* of the number of labels used */ | ||||
| 20288 | int nLabelAlloc; /* Number of slots in aLabel */ | ||||
| 20289 | int *aLabel; /* Space to hold the labels */ | ||||
| 20290 | ExprList *pConstExpr;/* Constant expressions */ | ||||
| 20291 | IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */ | ||||
| 20292 | IndexedExpr *pIdxPartExpr; /* Exprs constrained by index WHERE clauses */ | ||||
| 20293 | yDbMask writeMask; /* Start a write transaction on these databases */ | ||||
| 20294 | yDbMask cookieMask; /* Bitmask of schema verified databases */ | ||||
| 20295 | int nMaxArg; /* Max args to xUpdate and xFilter vtab methods */ | ||||
| 20296 | int nSelect; /* Number of SELECT stmts. Counter for Select.selId */ | ||||
| 20297 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK1 | ||||
| 20298 | u32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */ | ||||
| 20299 | #endif | ||||
| 20300 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 20301 | int nTableLock; /* Number of locks in aTableLock */ | ||||
| 20302 | TableLock *aTableLock; /* Required table locks for shared-cache mode */ | ||||
| 20303 | #endif | ||||
| 20304 | AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */ | ||||
| 20305 | Parse *pToplevel; /* Parse structure for main program (or NULL) */ | ||||
| 20306 | Table *pTriggerTab; /* Table triggers are being coded for */ | ||||
| 20307 | TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ | ||||
| 20308 | ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */ | ||||
| 20309 | |||||
| 20310 | /************************************************************************** | ||||
| 20311 | ** Fields above must be initialized to zero. The fields that follow, | ||||
| 20312 | ** down to the beginning of the recursive section, do not need to be | ||||
| 20313 | ** initialized as they will be set before being used. The boundary is | ||||
| 20314 | ** determined by offsetof(Parse,aTempReg). | ||||
| 20315 | **************************************************************************/ | ||||
| 20316 | |||||
| 20317 | int aTempReg[8]; /* Holding area for temporary registers */ | ||||
| 20318 | Parse *pOuterParse; /* Outer Parse object when nested */ | ||||
| 20319 | Token sNameToken; /* Token with unqualified schema object name */ | ||||
| 20320 | u32 oldmask; /* Mask of old.* columns referenced */ | ||||
| 20321 | u32 newmask; /* Mask of new.* columns referenced */ | ||||
| 20322 | union { | ||||
| 20323 | struct { /* These fields available when isCreate is true */ | ||||
| 20324 | int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */ | ||||
| 20325 | int regRowid; /* Register holding rowid of CREATE TABLE entry */ | ||||
| 20326 | int regRoot; /* Register holding root page for new objects */ | ||||
| 20327 | Token constraintName; /* Name of the constraint currently being parsed */ | ||||
| 20328 | } cr; | ||||
| 20329 | struct { /* These fields available to all other statements */ | ||||
| 20330 | Returning *pReturning; /* The RETURNING clause */ | ||||
| 20331 | } d; | ||||
| 20332 | } u1; | ||||
| 20333 | |||||
| 20334 | /************************************************************************ | ||||
| 20335 | ** Above is constant between recursions. Below is reset before and after | ||||
| 20336 | ** each recursion. The boundary between these two regions is determined | ||||
| 20337 | ** using offsetof(Parse,sLastToken) so the sLastToken field must be the | ||||
| 20338 | ** first field in the recursive region. | ||||
| 20339 | ************************************************************************/ | ||||
| 20340 | |||||
| 20341 | Token sLastToken; /* The last token parsed */ | ||||
| 20342 | ynVar nVar; /* Number of '?' variables seen in the SQL so far */ | ||||
| 20343 | u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */ | ||||
| 20344 | u8 explain; /* True if the EXPLAIN flag is found on the query */ | ||||
| 20345 | u8 eParseMode; /* PARSE_MODE_XXX constant */ | ||||
| 20346 | #ifndef SQLITE_OMIT_VIRTUALTABLE | ||||
| 20347 | int nVtabLock; /* Number of virtual tables to lock */ | ||||
| 20348 | #endif | ||||
| 20349 | int nHeight; /* Expression tree height of current sub-select */ | ||||
| 20350 | int addrExplain; /* Address of current OP_Explain opcode */ | ||||
| 20351 | VList *pVList; /* Mapping between variable names and numbers */ | ||||
| 20352 | Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ | ||||
| 20353 | const char *zTail; /* All SQL text past the last semicolon parsed */ | ||||
| 20354 | Table *pNewTable; /* A table being constructed by CREATE TABLE */ | ||||
| 20355 | Index *pNewIndex; /* An index being constructed by CREATE INDEX. | ||||
| 20356 | ** Also used to hold redundant UNIQUE constraints | ||||
| 20357 | ** during a RENAME COLUMN */ | ||||
| 20358 | Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */ | ||||
| 20359 | const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */ | ||||
| 20360 | #ifndef SQLITE_OMIT_VIRTUALTABLE | ||||
| 20361 | Token sArg; /* Complete text of a module argument */ | ||||
| 20362 | Table **apVtabLock; /* Pointer to virtual tables needing locking */ | ||||
| 20363 | #endif | ||||
| 20364 | With *pWith; /* Current WITH clause, or NULL */ | ||||
| 20365 | #ifndef SQLITE_OMIT_ALTERTABLE | ||||
| 20366 | RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */ | ||||
| 20367 | #endif | ||||
| 20368 | }; | ||||
| 20369 | |||||
| 20370 | /* Allowed values for Parse.eParseMode | ||||
| 20371 | */ | ||||
| 20372 | #define PARSE_MODE_NORMAL0 0 | ||||
| 20373 | #define PARSE_MODE_DECLARE_VTAB1 1 | ||||
| 20374 | #define PARSE_MODE_RENAME2 2 | ||||
| 20375 | #define PARSE_MODE_UNMAP3 3 | ||||
| 20376 | |||||
| 20377 | /* | ||||
| 20378 | ** Sizes and pointers of various parts of the Parse object. | ||||
| 20379 | */ | ||||
| 20380 | #define PARSE_HDR(X)(((char*)(X))+__builtin_offsetof(Parse, zErrMsg)) (((char*)(X))+offsetof(Parse,zErrMsg)__builtin_offsetof(Parse, zErrMsg)) | ||||
| 20381 | #define PARSE_HDR_SZ(__builtin_offsetof(Parse, aTempReg)-__builtin_offsetof(Parse , zErrMsg)) (offsetof(Parse,aTempReg)__builtin_offsetof(Parse, aTempReg)-offsetof(Parse,zErrMsg)__builtin_offsetof(Parse, zErrMsg)) /* Recursive part w/o aColCache*/ | ||||
| 20382 | #define PARSE_RECURSE_SZ__builtin_offsetof(Parse, sLastToken) offsetof(Parse,sLastToken)__builtin_offsetof(Parse, sLastToken) /* Recursive part */ | ||||
| 20383 | #define PARSE_TAIL_SZ(sizeof(Parse)-__builtin_offsetof(Parse, sLastToken)) (sizeof(Parse)-PARSE_RECURSE_SZ__builtin_offsetof(Parse, sLastToken)) /* Non-recursive part */ | ||||
| 20384 | #define PARSE_TAIL(X)(((char*)(X))+__builtin_offsetof(Parse, sLastToken)) (((char*)(X))+PARSE_RECURSE_SZ__builtin_offsetof(Parse, sLastToken)) /* Pointer to tail */ | ||||
| 20385 | |||||
| 20386 | /* | ||||
| 20387 | ** Return true if currently inside an sqlite3_declare_vtab() call. | ||||
| 20388 | */ | ||||
| 20389 | #ifdef SQLITE_OMIT_VIRTUALTABLE | ||||
| 20390 | #define IN_DECLARE_VTAB(pParse->eParseMode==1) 0 | ||||
| 20391 | #else | ||||
| 20392 | #define IN_DECLARE_VTAB(pParse->eParseMode==1) (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB1) | ||||
| 20393 | #endif | ||||
| 20394 | |||||
| 20395 | #if defined(SQLITE_OMIT_ALTERTABLE) | ||||
| 20396 | #define IN_RENAME_OBJECT(pParse->eParseMode>=2) 0 | ||||
| 20397 | #else | ||||
| 20398 | #define IN_RENAME_OBJECT(pParse->eParseMode>=2) (pParse->eParseMode>=PARSE_MODE_RENAME2) | ||||
| 20399 | #endif | ||||
| 20400 | |||||
| 20401 | #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE) | ||||
| 20402 | #define IN_SPECIAL_PARSE(pParse->eParseMode!=0) 0 | ||||
| 20403 | #else | ||||
| 20404 | #define IN_SPECIAL_PARSE(pParse->eParseMode!=0) (pParse->eParseMode!=PARSE_MODE_NORMAL0) | ||||
| 20405 | #endif | ||||
| 20406 | |||||
| 20407 | /* | ||||
| 20408 | ** An instance of the following structure can be declared on a stack and used | ||||
| 20409 | ** to save the Parse.zAuthContext value so that it can be restored later. | ||||
| 20410 | */ | ||||
| 20411 | struct AuthContext { | ||||
| 20412 | const char *zAuthContext; /* Put saved Parse.zAuthContext here */ | ||||
| 20413 | Parse *pParse; /* The Parse structure */ | ||||
| 20414 | }; | ||||
| 20415 | |||||
| 20416 | /* | ||||
| 20417 | ** Bitfield flags for P5 value in various opcodes. | ||||
| 20418 | ** | ||||
| 20419 | ** Value constraints (enforced via assert()): | ||||
| 20420 | ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH | ||||
| 20421 | ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF | ||||
| 20422 | ** OPFLAG_BULKCSR == BTREE_BULKLOAD | ||||
| 20423 | ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ | ||||
| 20424 | ** OPFLAG_FORDELETE == BTREE_FORDELETE | ||||
| 20425 | ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION | ||||
| 20426 | ** OPFLAG_AUXDELETE == BTREE_AUXDELETE | ||||
| 20427 | */ | ||||
| 20428 | #define OPFLAG_NCHANGE0x01 0x01 /* OP_Insert: Set to update db->nChange */ | ||||
| 20429 | /* Also used in P2 (not P5) of OP_Delete */ | ||||
| 20430 | #define OPFLAG_NOCHNG0x01 0x01 /* OP_VColumn nochange for UPDATE */ | ||||
| 20431 | #define OPFLAG_EPHEM0x01 0x01 /* OP_Column: Ephemeral output is ok */ | ||||
| 20432 | #define OPFLAG_LASTROWID0x20 0x20 /* Set to update db->lastRowid */ | ||||
| 20433 | #define OPFLAG_ISUPDATE0x04 0x04 /* This OP_Insert is an sql UPDATE */ | ||||
| 20434 | #define OPFLAG_APPEND0x08 0x08 /* This is likely to be an append */ | ||||
| 20435 | #define OPFLAG_USESEEKRESULT0x10 0x10 /* Try to avoid a seek in BtreeInsert() */ | ||||
| 20436 | #define OPFLAG_ISNOOP0x40 0x40 /* OP_Delete does pre-update-hook only */ | ||||
| 20437 | #define OPFLAG_LENGTHARG0x40 0x40 /* OP_Column only used for length() */ | ||||
| 20438 | #define OPFLAG_TYPEOFARG0x80 0x80 /* OP_Column only used for typeof() */ | ||||
| 20439 | #define OPFLAG_BYTELENARG0xc0 0xc0 /* OP_Column only for octet_length() */ | ||||
| 20440 | #define OPFLAG_BULKCSR0x01 0x01 /* OP_Open** used to open bulk cursor */ | ||||
| 20441 | #define OPFLAG_SEEKEQ0x02 0x02 /* OP_Open** cursor uses EQ seek only */ | ||||
| 20442 | #define OPFLAG_FORDELETE0x08 0x08 /* OP_Open should use BTREE_FORDELETE */ | ||||
| 20443 | #define OPFLAG_P2ISREG0x10 0x10 /* P2 to OP_Open** is a register number */ | ||||
| 20444 | #define OPFLAG_PERMUTE0x01 0x01 /* OP_Compare: use the permutation */ | ||||
| 20445 | #define OPFLAG_SAVEPOSITION0x02 0x02 /* OP_Delete/Insert: save cursor pos */ | ||||
| 20446 | #define OPFLAG_AUXDELETE0x04 0x04 /* OP_Delete: index in a DELETE op */ | ||||
| 20447 | #define OPFLAG_NOCHNG_MAGIC0x6d 0x6d /* OP_MakeRecord: serialtype 10 is ok */ | ||||
| 20448 | #define OPFLAG_PREFORMAT0x80 0x80 /* OP_Insert uses preformatted cell */ | ||||
| 20449 | |||||
| 20450 | /* | ||||
| 20451 | ** Each trigger present in the database schema is stored as an instance of | ||||
| 20452 | ** struct Trigger. | ||||
| 20453 | ** | ||||
| 20454 | ** Pointers to instances of struct Trigger are stored in two ways. | ||||
| 20455 | ** 1. In the "trigHash" hash table (part of the sqlite3* that represents the | ||||
| 20456 | ** database). This allows Trigger structures to be retrieved by name. | ||||
| 20457 | ** 2. All triggers associated with a single table form a linked list, using the | ||||
| 20458 | ** pNext member of struct Trigger. A pointer to the first element of the | ||||
| 20459 | ** linked list is stored as the "pTrigger" member of the associated | ||||
| 20460 | ** struct Table. | ||||
| 20461 | ** | ||||
| 20462 | ** The "step_list" member points to the first element of a linked list | ||||
| 20463 | ** containing the SQL statements specified as the trigger program. | ||||
| 20464 | */ | ||||
| 20465 | struct Trigger { | ||||
| 20466 | char *zName; /* The name of the trigger */ | ||||
| 20467 | char *table; /* The table or view to which the trigger applies */ | ||||
| 20468 | u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */ | ||||
| 20469 | u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ | ||||
| 20470 | u8 bReturning; /* This trigger implements a RETURNING clause */ | ||||
| 20471 | Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */ | ||||
| 20472 | IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger, | ||||
| 20473 | the <column-list> is stored here */ | ||||
| 20474 | Schema *pSchema; /* Schema containing the trigger */ | ||||
| 20475 | Schema *pTabSchema; /* Schema containing the table */ | ||||
| 20476 | TriggerStep *step_list; /* Link list of trigger program steps */ | ||||
| 20477 | Trigger *pNext; /* Next trigger associated with the table */ | ||||
| 20478 | }; | ||||
| 20479 | |||||
| 20480 | /* | ||||
| 20481 | ** A trigger is either a BEFORE or an AFTER trigger. The following constants | ||||
| 20482 | ** determine which. | ||||
| 20483 | ** | ||||
| 20484 | ** If there are multiple triggers, you might of some BEFORE and some AFTER. | ||||
| 20485 | ** In that cases, the constants below can be ORed together. | ||||
| 20486 | */ | ||||
| 20487 | #define TRIGGER_BEFORE1 1 | ||||
| 20488 | #define TRIGGER_AFTER2 2 | ||||
| 20489 | |||||
| 20490 | /* | ||||
| 20491 | ** An instance of struct TriggerStep is used to store a single SQL statement | ||||
| 20492 | ** that is a part of a trigger-program. | ||||
| 20493 | ** | ||||
| 20494 | ** Instances of struct TriggerStep are stored in a singly linked list (linked | ||||
| 20495 | ** using the "pNext" member) referenced by the "step_list" member of the | ||||
| 20496 | ** associated struct Trigger instance. The first element of the linked list is | ||||
| 20497 | ** the first step of the trigger-program. | ||||
| 20498 | ** | ||||
| 20499 | ** The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or | ||||
| 20500 | ** "SELECT" statement. The meanings of the other members is determined by the | ||||
| 20501 | ** value of "op" as follows: | ||||
| 20502 | ** | ||||
| 20503 | ** (op == TK_INSERT) | ||||
| 20504 | ** orconf -> stores the ON CONFLICT algorithm | ||||
| 20505 | ** pSelect -> The content to be inserted - either a SELECT statement or | ||||
| 20506 | ** a VALUES clause. | ||||
| 20507 | ** zTarget -> Dequoted name of the table to insert into. | ||||
| 20508 | ** pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ... | ||||
| 20509 | ** statement, then this stores the column-names to be | ||||
| 20510 | ** inserted into. | ||||
| 20511 | ** pUpsert -> The ON CONFLICT clauses for an Upsert | ||||
| 20512 | ** | ||||
| 20513 | ** (op == TK_DELETE) | ||||
| 20514 | ** zTarget -> Dequoted name of the table to delete from. | ||||
| 20515 | ** pWhere -> The WHERE clause of the DELETE statement if one is specified. | ||||
| 20516 | ** Otherwise NULL. | ||||
| 20517 | ** | ||||
| 20518 | ** (op == TK_UPDATE) | ||||
| 20519 | ** zTarget -> Dequoted name of the table to update. | ||||
| 20520 | ** pWhere -> The WHERE clause of the UPDATE statement if one is specified. | ||||
| 20521 | ** Otherwise NULL. | ||||
| 20522 | ** pExprList -> A list of the columns to update and the expressions to update | ||||
| 20523 | ** them to. See sqlite3Update() documentation of "pChanges" | ||||
| 20524 | ** argument. | ||||
| 20525 | ** | ||||
| 20526 | ** (op == TK_SELECT) | ||||
| 20527 | ** pSelect -> The SELECT statement | ||||
| 20528 | ** | ||||
| 20529 | ** (op == TK_RETURNING) | ||||
| 20530 | ** pExprList -> The list of expressions that follow the RETURNING keyword. | ||||
| 20531 | ** | ||||
| 20532 | */ | ||||
| 20533 | struct TriggerStep { | ||||
| 20534 | u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT, | ||||
| 20535 | ** or TK_RETURNING */ | ||||
| 20536 | u8 orconf; /* OE_Rollback etc. */ | ||||
| 20537 | Trigger *pTrig; /* The trigger that this step is a part of */ | ||||
| 20538 | Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */ | ||||
| 20539 | char *zTarget; /* Target table for DELETE, UPDATE, INSERT */ | ||||
| 20540 | SrcList *pFrom; /* FROM clause for UPDATE statement (if any) */ | ||||
| 20541 | Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ | ||||
| 20542 | ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */ | ||||
| 20543 | IdList *pIdList; /* Column names for INSERT */ | ||||
| 20544 | Upsert *pUpsert; /* Upsert clauses on an INSERT */ | ||||
| 20545 | char *zSpan; /* Original SQL text of this command */ | ||||
| 20546 | TriggerStep *pNext; /* Next in the link-list */ | ||||
| 20547 | TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */ | ||||
| 20548 | }; | ||||
| 20549 | |||||
| 20550 | /* | ||||
| 20551 | ** Information about a RETURNING clause | ||||
| 20552 | */ | ||||
| 20553 | struct Returning { | ||||
| 20554 | Parse *pParse; /* The parse that includes the RETURNING clause */ | ||||
| 20555 | ExprList *pReturnEL; /* List of expressions to return */ | ||||
| 20556 | Trigger retTrig; /* The transient trigger that implements RETURNING */ | ||||
| 20557 | TriggerStep retTStep; /* The trigger step */ | ||||
| 20558 | int iRetCur; /* Transient table holding RETURNING results */ | ||||
| 20559 | int nRetCol; /* Number of in pReturnEL after expansion */ | ||||
| 20560 | int iRetReg; /* Register array for holding a row of RETURNING */ | ||||
| 20561 | char zName[40]; /* Name of trigger: "sqlite_returning_%p" */ | ||||
| 20562 | }; | ||||
| 20563 | |||||
| 20564 | /* | ||||
| 20565 | ** An object used to accumulate the text of a string where we | ||||
| 20566 | ** do not necessarily know how big the string will be in the end. | ||||
| 20567 | */ | ||||
| 20568 | struct sqlite3_str { | ||||
| 20569 | sqlite3 *db; /* Optional database for lookaside. Can be NULL */ | ||||
| 20570 | char *zText; /* The string collected so far */ | ||||
| 20571 | u32 nAlloc; /* Amount of space allocated in zText */ | ||||
| 20572 | u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */ | ||||
| 20573 | u32 nChar; /* Length of the string so far */ | ||||
| 20574 | u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */ | ||||
| 20575 | u8 printfFlags; /* SQLITE_PRINTF flags below */ | ||||
| 20576 | }; | ||||
| 20577 | #define SQLITE_PRINTF_INTERNAL0x01 0x01 /* Internal-use-only converters allowed */ | ||||
| 20578 | #define SQLITE_PRINTF_SQLFUNC0x02 0x02 /* SQL function arguments to VXPrintf */ | ||||
| 20579 | #define SQLITE_PRINTF_MALLOCED0x04 0x04 /* True if zText is allocated space */ | ||||
| 20580 | |||||
| 20581 | #define isMalloced(X)(((X)->printfFlags & 0x04)!=0) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED0x04)!=0) | ||||
| 20582 | |||||
| 20583 | /* | ||||
| 20584 | ** The following object is the header for an "RCStr" or "reference-counted | ||||
| 20585 | ** string". An RCStr is passed around and used like any other char* | ||||
| 20586 | ** that has been dynamically allocated. The important interface | ||||
| 20587 | ** differences: | ||||
| 20588 | ** | ||||
| 20589 | ** 1. RCStr strings are reference counted. They are deallocated | ||||
| 20590 | ** when the reference count reaches zero. | ||||
| 20591 | ** | ||||
| 20592 | ** 2. Use sqlite3RCStrUnref() to free an RCStr string rather than | ||||
| 20593 | ** sqlite3_free() | ||||
| 20594 | ** | ||||
| 20595 | ** 3. Make a (read-only) copy of a read-only RCStr string using | ||||
| 20596 | ** sqlite3RCStrRef(). | ||||
| 20597 | ** | ||||
| 20598 | ** "String" is in the name, but an RCStr object can also be used to hold | ||||
| 20599 | ** binary data. | ||||
| 20600 | */ | ||||
| 20601 | struct RCStr { | ||||
| 20602 | u64 nRCRef; /* Number of references */ | ||||
| 20603 | /* Total structure size should be a multiple of 8 bytes for alignment */ | ||||
| 20604 | }; | ||||
| 20605 | |||||
| 20606 | /* | ||||
| 20607 | ** A pointer to this structure is used to communicate information | ||||
| 20608 | ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback. | ||||
| 20609 | */ | ||||
| 20610 | typedef struct { | ||||
| 20611 | sqlite3 *db; /* The database being initialized */ | ||||
| 20612 | char **pzErrMsg; /* Error message stored here */ | ||||
| 20613 | int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */ | ||||
| 20614 | int rc; /* Result code stored here */ | ||||
| 20615 | u32 mInitFlags; /* Flags controlling error messages */ | ||||
| 20616 | u32 nInitRow; /* Number of rows processed */ | ||||
| 20617 | Pgno mxPage; /* Maximum page number. 0 for no limit. */ | ||||
| 20618 | } InitData; | ||||
| 20619 | |||||
| 20620 | /* | ||||
| 20621 | ** Allowed values for mInitFlags | ||||
| 20622 | */ | ||||
| 20623 | #define INITFLAG_AlterMask0x0003 0x0003 /* Types of ALTER */ | ||||
| 20624 | #define INITFLAG_AlterRename0x0001 0x0001 /* Reparse after a RENAME */ | ||||
| 20625 | #define INITFLAG_AlterDrop0x0002 0x0002 /* Reparse after a DROP COLUMN */ | ||||
| 20626 | #define INITFLAG_AlterAdd0x0003 0x0003 /* Reparse after an ADD COLUMN */ | ||||
| 20627 | |||||
| 20628 | /* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled | ||||
| 20629 | ** on debug-builds of the CLI using ".testctrl tune ID VALUE". Tuning | ||||
| 20630 | ** parameters are for temporary use during development, to help find | ||||
| 20631 | ** optimal values for parameters in the query planner. The should not | ||||
| 20632 | ** be used on trunk check-ins. They are a temporary mechanism available | ||||
| 20633 | ** for transient development builds only. | ||||
| 20634 | ** | ||||
| 20635 | ** Tuning parameters are numbered starting with 1. | ||||
| 20636 | */ | ||||
| 20637 | #define SQLITE_NTUNE6 6 /* Should be zero for all trunk check-ins */ | ||||
| 20638 | #ifdef SQLITE_DEBUG | ||||
| 20639 | # define Tuning(X)0 (sqlite3Config.aTune[(X)-1]) | ||||
| 20640 | #else | ||||
| 20641 | # define Tuning(X)0 0 | ||||
| 20642 | #endif | ||||
| 20643 | |||||
| 20644 | /* | ||||
| 20645 | ** Structure containing global configuration data for the SQLite library. | ||||
| 20646 | ** | ||||
| 20647 | ** This structure also contains some state information. | ||||
| 20648 | */ | ||||
| 20649 | struct Sqlite3Config { | ||||
| 20650 | int bMemstat; /* True to enable memory status */ | ||||
| 20651 | u8 bCoreMutex; /* True to enable core mutexing */ | ||||
| 20652 | u8 bFullMutex; /* True to enable full mutexing */ | ||||
| 20653 | u8 bOpenUri; /* True to interpret filenames as URIs */ | ||||
| 20654 | u8 bUseCis; /* Use covering indices for full-scans */ | ||||
| 20655 | u8 bSmallMalloc; /* Avoid large memory allocations if true */ | ||||
| 20656 | u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */ | ||||
| 20657 | #ifdef SQLITE_DEBUG | ||||
| 20658 | u8 bJsonSelfcheck; /* Double-check JSON parsing */ | ||||
| 20659 | #endif | ||||
| 20660 | int mxStrlen; /* Maximum string length */ | ||||
| 20661 | int neverCorrupt; /* Database is always well-formed */ | ||||
| 20662 | int szLookaside; /* Default lookaside buffer size */ | ||||
| 20663 | int nLookaside; /* Default lookaside buffer count */ | ||||
| 20664 | int nStmtSpill; /* Stmt-journal spill-to-disk threshold */ | ||||
| 20665 | sqlite3_mem_methods m; /* Low-level memory allocation interface */ | ||||
| 20666 | sqlite3_mutex_methods mutex; /* Low-level mutex interface */ | ||||
| 20667 | sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ | ||||
| 20668 | void *pHeap; /* Heap storage space */ | ||||
| 20669 | int nHeap; /* Size of pHeap[] */ | ||||
| 20670 | int mnReq, mxReq; /* Min and max heap requests sizes */ | ||||
| 20671 | sqlite3_int64 szMmap; /* mmap() space per open file */ | ||||
| 20672 | sqlite3_int64 mxMmap; /* Maximum value for szMmap */ | ||||
| 20673 | void *pPage; /* Page cache memory */ | ||||
| 20674 | int szPage; /* Size of each page in pPage[] */ | ||||
| 20675 | int nPage; /* Number of pages in pPage[] */ | ||||
| 20676 | int mxParserStack; /* maximum depth of the parser stack */ | ||||
| 20677 | int sharedCacheEnabled; /* true if shared-cache mode enabled */ | ||||
| 20678 | u32 szPma; /* Maximum Sorter PMA size */ | ||||
| 20679 | /* The above might be initialized to non-zero. The following need to always | ||||
| 20680 | ** initially be zero, however. */ | ||||
| 20681 | int isInit; /* True after initialization has finished */ | ||||
| 20682 | int inProgress; /* True while initialization in progress */ | ||||
| 20683 | int isMutexInit; /* True after mutexes are initialized */ | ||||
| 20684 | int isMallocInit; /* True after malloc is initialized */ | ||||
| 20685 | int isPCacheInit; /* True after malloc is initialized */ | ||||
| 20686 | int nRefInitMutex; /* Number of users of pInitMutex */ | ||||
| 20687 | sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ | ||||
| 20688 | void (*xLog)(void*,int,const char*); /* Function for logging */ | ||||
| 20689 | void *pLogArg; /* First argument to xLog() */ | ||||
| 20690 | #ifdef SQLITE_ENABLE_SQLLOG | ||||
| 20691 | void(*xSqllog)(void*,sqlite3*,const char*, int); | ||||
| 20692 | void *pSqllogArg; | ||||
| 20693 | #endif | ||||
| 20694 | #ifdef SQLITE_VDBE_COVERAGE | ||||
| 20695 | /* The following callback (if not NULL) is invoked on every VDBE branch | ||||
| 20696 | ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE. | ||||
| 20697 | */ | ||||
| 20698 | void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */ | ||||
| 20699 | void *pVdbeBranchArg; /* 1st argument */ | ||||
| 20700 | #endif | ||||
| 20701 | #ifndef SQLITE_OMIT_DESERIALIZE | ||||
| 20702 | sqlite3_int64 mxMemdbSize; /* Default max memdb size */ | ||||
| 20703 | #endif | ||||
| 20704 | #ifndef SQLITE_UNTESTABLE | ||||
| 20705 | int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */ | ||||
| 20706 | #endif | ||||
| 20707 | #ifdef SQLITE_ALLOW_ROWID_IN_VIEW | ||||
| 20708 | u32 mNoVisibleRowid; /* TF_NoVisibleRowid if the ROWID_IN_VIEW | ||||
| 20709 | ** feature is disabled. 0 if rowids can | ||||
| 20710 | ** occur in views. */ | ||||
| 20711 | #endif | ||||
| 20712 | int bLocaltimeFault; /* True to fail localtime() calls */ | ||||
| 20713 | int (*xAltLocaltime)(const void*,void*); /* Alternative localtime() routine */ | ||||
| 20714 | int iOnceResetThreshold; /* When to reset OP_Once counters */ | ||||
| 20715 | u32 szSorterRef; /* Min size in bytes to use sorter-refs */ | ||||
| 20716 | unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */ | ||||
| 20717 | /* vvvv--- must be last ---vvv */ | ||||
| 20718 | #ifdef SQLITE_DEBUG | ||||
| 20719 | sqlite3_int64 aTune[SQLITE_NTUNE6]; /* Tuning parameters */ | ||||
| 20720 | #endif | ||||
| 20721 | }; | ||||
| 20722 | |||||
| 20723 | /* | ||||
| 20724 | ** This macro is used inside of assert() statements to indicate that | ||||
| 20725 | ** the assert is only valid on a well-formed database. Instead of: | ||||
| 20726 | ** | ||||
| 20727 | ** assert( X ); | ||||
| 20728 | ** | ||||
| 20729 | ** One writes: | ||||
| 20730 | ** | ||||
| 20731 | ** assert( X || CORRUPT_DB ); | ||||
| 20732 | ** | ||||
| 20733 | ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate | ||||
| 20734 | ** that the database is definitely corrupt, only that it might be corrupt. | ||||
| 20735 | ** For most test cases, CORRUPT_DB is set to false using a special | ||||
| 20736 | ** sqlite3_test_control(). This enables assert() statements to prove | ||||
| 20737 | ** things that are always true for well-formed databases. | ||||
| 20738 | */ | ||||
| 20739 | #define CORRUPT_DB(sqlite3Config.neverCorrupt==0) (sqlite3Config.neverCorrupt==0) | ||||
| 20740 | |||||
| 20741 | /* | ||||
| 20742 | ** Context pointer passed down through the tree-walk. | ||||
| 20743 | */ | ||||
| 20744 | struct Walker { | ||||
| 20745 | Parse *pParse; /* Parser context. */ | ||||
| 20746 | int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ | ||||
| 20747 | int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */ | ||||
| 20748 | void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */ | ||||
| 20749 | int walkerDepth; /* Number of subqueries */ | ||||
| 20750 | u16 eCode; /* A small processing code */ | ||||
| 20751 | u16 mWFlags; /* Use-dependent flags */ | ||||
| 20752 | union { /* Extra data for callback */ | ||||
| 20753 | NameContext *pNC; /* Naming context */ | ||||
| 20754 | int n; /* A counter */ | ||||
| 20755 | int iCur; /* A cursor number */ | ||||
| 20756 | SrcList *pSrcList; /* FROM clause */ | ||||
| 20757 | struct CCurHint *pCCurHint; /* Used by codeCursorHint() */ | ||||
| 20758 | struct RefSrcList *pRefSrcList; /* sqlite3ReferencesSrcList() */ | ||||
| 20759 | int *aiCol; /* array of column indexes */ | ||||
| 20760 | struct IdxCover *pIdxCover; /* Check for index coverage */ | ||||
| 20761 | ExprList *pGroupBy; /* GROUP BY clause */ | ||||
| 20762 | Select *pSelect; /* HAVING to WHERE clause ctx */ | ||||
| 20763 | struct WindowRewrite *pRewrite; /* Window rewrite context */ | ||||
| 20764 | struct WhereConst *pConst; /* WHERE clause constants */ | ||||
| 20765 | struct RenameCtx *pRename; /* RENAME COLUMN context */ | ||||
| 20766 | struct Table *pTab; /* Table of generated column */ | ||||
| 20767 | struct CoveringIndexCheck *pCovIdxCk; /* Check for covering index */ | ||||
| 20768 | SrcItem *pSrcItem; /* A single FROM clause item */ | ||||
| 20769 | DbFixer *pFix; /* See sqlite3FixSelect() */ | ||||
| 20770 | Mem *aMem; /* See sqlite3BtreeCursorHint() */ | ||||
| 20771 | } u; | ||||
| 20772 | }; | ||||
| 20773 | |||||
| 20774 | /* | ||||
| 20775 | ** The following structure contains information used by the sqliteFix... | ||||
| 20776 | ** routines as they walk the parse tree to make database references | ||||
| 20777 | ** explicit. | ||||
| 20778 | */ | ||||
| 20779 | struct DbFixer { | ||||
| 20780 | Parse *pParse; /* The parsing context. Error messages written here */ | ||||
| 20781 | Walker w; /* Walker object */ | ||||
| 20782 | Schema *pSchema; /* Fix items to this schema */ | ||||
| 20783 | u8 bTemp; /* True for TEMP schema entries */ | ||||
| 20784 | const char *zDb; /* Make sure all objects are contained in this database */ | ||||
| 20785 | const char *zType; /* Type of the container - used for error messages */ | ||||
| 20786 | const Token *pName; /* Name of the container - used for error messages */ | ||||
| 20787 | }; | ||||
| 20788 | |||||
| 20789 | /* Forward declarations */ | ||||
| 20790 | SQLITE_PRIVATEstatic int sqlite3WalkExpr(Walker*, Expr*); | ||||
| 20791 | SQLITE_PRIVATEstatic int sqlite3WalkExprNN(Walker*, Expr*); | ||||
| 20792 | SQLITE_PRIVATEstatic int sqlite3WalkExprList(Walker*, ExprList*); | ||||
| 20793 | SQLITE_PRIVATEstatic int sqlite3WalkSelect(Walker*, Select*); | ||||
| 20794 | SQLITE_PRIVATEstatic int sqlite3WalkSelectExpr(Walker*, Select*); | ||||
| 20795 | SQLITE_PRIVATEstatic int sqlite3WalkSelectFrom(Walker*, Select*); | ||||
| 20796 | SQLITE_PRIVATEstatic int sqlite3ExprWalkNoop(Walker*, Expr*); | ||||
| 20797 | SQLITE_PRIVATEstatic int sqlite3SelectWalkNoop(Walker*, Select*); | ||||
| 20798 | SQLITE_PRIVATEstatic int sqlite3SelectWalkFail(Walker*, Select*); | ||||
| 20799 | SQLITE_PRIVATEstatic int sqlite3WalkerDepthIncrease(Walker*,Select*); | ||||
| 20800 | SQLITE_PRIVATEstatic void sqlite3WalkerDepthDecrease(Walker*,Select*); | ||||
| 20801 | SQLITE_PRIVATEstatic void sqlite3WalkWinDefnDummyCallback(Walker*,Select*); | ||||
| 20802 | |||||
| 20803 | #ifdef SQLITE_DEBUG | ||||
| 20804 | SQLITE_PRIVATEstatic void sqlite3SelectWalkAssert2(Walker*, Select*); | ||||
| 20805 | #endif | ||||
| 20806 | |||||
| 20807 | #ifndef SQLITE_OMIT_CTE | ||||
| 20808 | SQLITE_PRIVATEstatic void sqlite3SelectPopWith(Walker*, Select*); | ||||
| 20809 | #else | ||||
| 20810 | # define sqlite3SelectPopWith 0 | ||||
| 20811 | #endif | ||||
| 20812 | |||||
| 20813 | /* | ||||
| 20814 | ** Return code from the parse-tree walking primitives and their | ||||
| 20815 | ** callbacks. | ||||
| 20816 | */ | ||||
| 20817 | #define WRC_Continue0 0 /* Continue down into children */ | ||||
| 20818 | #define WRC_Prune1 1 /* Omit children but continue walking siblings */ | ||||
| 20819 | #define WRC_Abort2 2 /* Abandon the tree walk */ | ||||
| 20820 | |||||
| 20821 | /* | ||||
| 20822 | ** A single common table expression | ||||
| 20823 | */ | ||||
| 20824 | struct Cte { | ||||
| 20825 | char *zName; /* Name of this CTE */ | ||||
| 20826 | ExprList *pCols; /* List of explicit column names, or NULL */ | ||||
| 20827 | Select *pSelect; /* The definition of this CTE */ | ||||
| 20828 | const char *zCteErr; /* Error message for circular references */ | ||||
| 20829 | CteUse *pUse; /* Usage information for this CTE */ | ||||
| 20830 | u8 eM10d; /* The MATERIALIZED flag */ | ||||
| 20831 | }; | ||||
| 20832 | |||||
| 20833 | /* | ||||
| 20834 | ** Allowed values for the materialized flag (eM10d): | ||||
| 20835 | */ | ||||
| 20836 | #define M10d_Yes0 0 /* AS MATERIALIZED */ | ||||
| 20837 | #define M10d_Any1 1 /* Not specified. Query planner's choice */ | ||||
| 20838 | #define M10d_No2 2 /* AS NOT MATERIALIZED */ | ||||
| 20839 | |||||
| 20840 | /* | ||||
| 20841 | ** An instance of the With object represents a WITH clause containing | ||||
| 20842 | ** one or more CTEs (common table expressions). | ||||
| 20843 | */ | ||||
| 20844 | struct With { | ||||
| 20845 | int nCte; /* Number of CTEs in the WITH clause */ | ||||
| 20846 | int bView; /* Belongs to the outermost Select of a view */ | ||||
| 20847 | With *pOuter; /* Containing WITH clause, or NULL */ | ||||
| 20848 | Cte a[FLEXARRAY]; /* For each CTE in the WITH clause.... */ | ||||
| 20849 | }; | ||||
| 20850 | |||||
| 20851 | /* The size (in bytes) of a With object that can hold as many | ||||
| 20852 | ** as N different CTEs. */ | ||||
| 20853 | #define SZ_WITH(N)(__builtin_offsetof(With, a) + (N)*sizeof(Cte)) (offsetof(With,a)__builtin_offsetof(With, a) + (N)*sizeof(Cte)) | ||||
| 20854 | |||||
| 20855 | /* | ||||
| 20856 | ** The Cte object is not guaranteed to persist for the entire duration | ||||
| 20857 | ** of code generation. (The query flattener or other parser tree | ||||
| 20858 | ** edits might delete it.) The following object records information | ||||
| 20859 | ** about each Common Table Expression that must be preserved for the | ||||
| 20860 | ** duration of the parse. | ||||
| 20861 | ** | ||||
| 20862 | ** The CteUse objects are freed using sqlite3ParserAddCleanup() rather | ||||
| 20863 | ** than sqlite3SelectDelete(), which is what enables them to persist | ||||
| 20864 | ** until the end of code generation. | ||||
| 20865 | */ | ||||
| 20866 | struct CteUse { | ||||
| 20867 | int nUse; /* Number of users of this CTE */ | ||||
| 20868 | int addrM9e; /* Start of subroutine to compute materialization */ | ||||
| 20869 | int regRtn; /* Return address register for addrM9e subroutine */ | ||||
| 20870 | int iCur; /* Ephemeral table holding the materialization */ | ||||
| 20871 | LogEst nRowEst; /* Estimated number of rows in the table */ | ||||
| 20872 | u8 eM10d; /* The MATERIALIZED flag */ | ||||
| 20873 | }; | ||||
| 20874 | |||||
| 20875 | |||||
| 20876 | /* Client data associated with sqlite3_set_clientdata() and | ||||
| 20877 | ** sqlite3_get_clientdata(). | ||||
| 20878 | */ | ||||
| 20879 | struct DbClientData { | ||||
| 20880 | DbClientData *pNext; /* Next in a linked list */ | ||||
| 20881 | void *pData; /* The data */ | ||||
| 20882 | void (*xDestructor)(void*); /* Destructor. Might be NULL */ | ||||
| 20883 | char zName[FLEXARRAY]; /* Name of this client data. MUST BE LAST */ | ||||
| 20884 | }; | ||||
| 20885 | |||||
| 20886 | /* The size (in bytes) of a DbClientData object that can has a name | ||||
| 20887 | ** that is N bytes long, including the zero-terminator. */ | ||||
| 20888 | #define SZ_DBCLIENTDATA(N)(__builtin_offsetof(DbClientData, zName)+(N)) (offsetof(DbClientData,zName)__builtin_offsetof(DbClientData, zName)+(N)) | ||||
| 20889 | |||||
| 20890 | #ifdef SQLITE_DEBUG | ||||
| 20891 | /* | ||||
| 20892 | ** An instance of the TreeView object is used for printing the content of | ||||
| 20893 | ** data structures on sqlite3DebugPrintf() using a tree-like view. | ||||
| 20894 | */ | ||||
| 20895 | struct TreeView { | ||||
| 20896 | int iLevel; /* Which level of the tree we are on */ | ||||
| 20897 | u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */ | ||||
| 20898 | }; | ||||
| 20899 | #endif /* SQLITE_DEBUG */ | ||||
| 20900 | |||||
| 20901 | /* | ||||
| 20902 | ** This object is used in various ways, most (but not all) related to window | ||||
| 20903 | ** functions. | ||||
| 20904 | ** | ||||
| 20905 | ** (1) A single instance of this structure is attached to the | ||||
| 20906 | ** the Expr.y.pWin field for each window function in an expression tree. | ||||
| 20907 | ** This object holds the information contained in the OVER clause, | ||||
| 20908 | ** plus additional fields used during code generation. | ||||
| 20909 | ** | ||||
| 20910 | ** (2) All window functions in a single SELECT form a linked-list | ||||
| 20911 | ** attached to Select.pWin. The Window.pFunc and Window.pExpr | ||||
| 20912 | ** fields point back to the expression that is the window function. | ||||
| 20913 | ** | ||||
| 20914 | ** (3) The terms of the WINDOW clause of a SELECT are instances of this | ||||
| 20915 | ** object on a linked list attached to Select.pWinDefn. | ||||
| 20916 | ** | ||||
| 20917 | ** (4) For an aggregate function with a FILTER clause, an instance | ||||
| 20918 | ** of this object is stored in Expr.y.pWin with eFrmType set to | ||||
| 20919 | ** TK_FILTER. In this case the only field used is Window.pFilter. | ||||
| 20920 | ** | ||||
| 20921 | ** The uses (1) and (2) are really the same Window object that just happens | ||||
| 20922 | ** to be accessible in two different ways. Use case (3) are separate objects. | ||||
| 20923 | */ | ||||
| 20924 | struct Window { | ||||
| 20925 | char *zName; /* Name of window (may be NULL) */ | ||||
| 20926 | char *zBase; /* Name of base window for chaining (may be NULL) */ | ||||
| 20927 | ExprList *pPartition; /* PARTITION BY clause */ | ||||
| 20928 | ExprList *pOrderBy; /* ORDER BY clause */ | ||||
| 20929 | u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */ | ||||
| 20930 | u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */ | ||||
| 20931 | u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */ | ||||
| 20932 | u8 bImplicitFrame; /* True if frame was implicitly specified */ | ||||
| 20933 | u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */ | ||||
| 20934 | Expr *pStart; /* Expression for "<expr> PRECEDING" */ | ||||
| 20935 | Expr *pEnd; /* Expression for "<expr> FOLLOWING" */ | ||||
| 20936 | Window **ppThis; /* Pointer to this object in Select.pWin list */ | ||||
| 20937 | Window *pNextWin; /* Next window function belonging to this SELECT */ | ||||
| 20938 | Expr *pFilter; /* The FILTER expression */ | ||||
| 20939 | FuncDef *pWFunc; /* The function */ | ||||
| 20940 | int iEphCsr; /* Partition buffer or Peer buffer */ | ||||
| 20941 | int regAccum; /* Accumulator */ | ||||
| 20942 | int regResult; /* Interim result */ | ||||
| 20943 | int csrApp; /* Function cursor (used by min/max) */ | ||||
| 20944 | int regApp; /* Function register (also used by min/max) */ | ||||
| 20945 | int regPart; /* Array of registers for PARTITION BY values */ | ||||
| 20946 | Expr *pOwner; /* Expression object this window is attached to */ | ||||
| 20947 | int nBufferCol; /* Number of columns in buffer table */ | ||||
| 20948 | int iArgCol; /* Offset of first argument for this function */ | ||||
| 20949 | int regOne; /* Register containing constant value 1 */ | ||||
| 20950 | int regStartRowid; | ||||
| 20951 | int regEndRowid; | ||||
| 20952 | u8 bExprArgs; /* Defer evaluation of window function arguments | ||||
| 20953 | ** due to the SQLITE_SUBTYPE flag */ | ||||
| 20954 | }; | ||||
| 20955 | |||||
| 20956 | SQLITE_PRIVATEstatic Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList *pRow); | ||||
| 20957 | SQLITE_PRIVATEstatic void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal); | ||||
| 20958 | |||||
| 20959 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 20960 | SQLITE_PRIVATEstatic void sqlite3WindowDelete(sqlite3*, Window*); | ||||
| 20961 | SQLITE_PRIVATEstatic void sqlite3WindowUnlinkFromSelect(Window*); | ||||
| 20962 | SQLITE_PRIVATEstatic void sqlite3WindowListDelete(sqlite3 *db, Window *p); | ||||
| 20963 | SQLITE_PRIVATEstatic Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8); | ||||
| 20964 | SQLITE_PRIVATEstatic void sqlite3WindowAttach(Parse*, Expr*, Window*); | ||||
| 20965 | SQLITE_PRIVATEstatic void sqlite3WindowLink(Select *pSel, Window *pWin); | ||||
| 20966 | SQLITE_PRIVATEstatic int sqlite3WindowCompare(const Parse*, const Window*, const Window*, int); | ||||
| 20967 | SQLITE_PRIVATEstatic void sqlite3WindowCodeInit(Parse*, Select*); | ||||
| 20968 | SQLITE_PRIVATEstatic void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int); | ||||
| 20969 | SQLITE_PRIVATEstatic int sqlite3WindowRewrite(Parse*, Select*); | ||||
| 20970 | SQLITE_PRIVATEstatic void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*); | ||||
| 20971 | SQLITE_PRIVATEstatic Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p); | ||||
| 20972 | SQLITE_PRIVATEstatic Window *sqlite3WindowListDup(sqlite3 *db, Window *p); | ||||
| 20973 | SQLITE_PRIVATEstatic void sqlite3WindowFunctions(void); | ||||
| 20974 | SQLITE_PRIVATEstatic void sqlite3WindowChain(Parse*, Window*, Window*); | ||||
| 20975 | SQLITE_PRIVATEstatic Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*); | ||||
| 20976 | #else | ||||
| 20977 | # define sqlite3WindowDelete(a,b) | ||||
| 20978 | # define sqlite3WindowFunctions() | ||||
| 20979 | # define sqlite3WindowAttach(a,b,c) | ||||
| 20980 | #endif | ||||
| 20981 | |||||
| 20982 | /* | ||||
| 20983 | ** Assuming zIn points to the first byte of a UTF-8 character, | ||||
| 20984 | ** advance zIn to point to the first byte of the next UTF-8 character. | ||||
| 20985 | */ | ||||
| 20986 | #define SQLITE_SKIP_UTF8(zIn){ if( (*(zIn++))>=0xc0 ){ while( (*zIn & 0xc0)==0x80 ) { zIn++; } } } { \ | ||||
| 20987 | if( (*(zIn++))>=0xc0 ){ \ | ||||
| 20988 | while( (*zIn & 0xc0)==0x80 ){ zIn++; } \ | ||||
| 20989 | } \ | ||||
| 20990 | } | ||||
| 20991 | |||||
| 20992 | /* | ||||
| 20993 | ** The SQLITE_*_BKPT macros are substitutes for the error codes with | ||||
| 20994 | ** the same name but without the _BKPT suffix. These macros invoke | ||||
| 20995 | ** routines that report the line-number on which the error originated | ||||
| 20996 | ** using sqlite3_log(). The routines also provide a convenient place | ||||
| 20997 | ** to set a debugger breakpoint. | ||||
| 20998 | */ | ||||
| 20999 | SQLITE_PRIVATEstatic int sqlite3ReportError(int iErr, int lineno, const char *zType); | ||||
| 21000 | SQLITE_PRIVATEstatic int sqlite3CorruptError(int); | ||||
| 21001 | SQLITE_PRIVATEstatic int sqlite3MisuseError(int); | ||||
| 21002 | SQLITE_PRIVATEstatic int sqlite3CantopenError(int); | ||||
| 21003 | #define SQLITE_CORRUPT_BKPTsqlite3CorruptError(21003) sqlite3CorruptError(__LINE__21003) | ||||
| 21004 | #define SQLITE_MISUSE_BKPTsqlite3MisuseError(21004) sqlite3MisuseError(__LINE__21004) | ||||
| 21005 | #define SQLITE_CANTOPEN_BKPTsqlite3CantopenError(21005) sqlite3CantopenError(__LINE__21005) | ||||
| 21006 | #ifdef SQLITE_DEBUG | ||||
| 21007 | SQLITE_PRIVATEstatic int sqlite3NomemError(int); | ||||
| 21008 | SQLITE_PRIVATEstatic int sqlite3IoerrnomemError(int); | ||||
| 21009 | # define SQLITE_NOMEM_BKPT7 sqlite3NomemError(__LINE__21009) | ||||
| 21010 | # define SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)) sqlite3IoerrnomemError(__LINE__21010) | ||||
| 21011 | #else | ||||
| 21012 | # define SQLITE_NOMEM_BKPT7 SQLITE_NOMEM7 | ||||
| 21013 | # define SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)) SQLITE_IOERR_NOMEM(10 | (12<<8)) | ||||
| 21014 | #endif | ||||
| 21015 | #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO) | ||||
| 21016 | SQLITE_PRIVATEstatic int sqlite3CorruptPgnoError(int,Pgno); | ||||
| 21017 | # define SQLITE_CORRUPT_PGNO(P)sqlite3CorruptError(21017) sqlite3CorruptPgnoError(__LINE__21017,(P)) | ||||
| 21018 | #else | ||||
| 21019 | # define SQLITE_CORRUPT_PGNO(P)sqlite3CorruptError(21019) sqlite3CorruptError(__LINE__21019) | ||||
| 21020 | #endif | ||||
| 21021 | |||||
| 21022 | /* | ||||
| 21023 | ** FTS3 and FTS4 both require virtual table support | ||||
| 21024 | */ | ||||
| 21025 | #if defined(SQLITE_OMIT_VIRTUALTABLE) | ||||
| 21026 | # undef SQLITE_ENABLE_FTS31 | ||||
| 21027 | # undef SQLITE_ENABLE_FTS41 | ||||
| 21028 | #endif | ||||
| 21029 | |||||
| 21030 | /* | ||||
| 21031 | ** FTS4 is really an extension for FTS3. It is enabled using the | ||||
| 21032 | ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call | ||||
| 21033 | ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3. | ||||
| 21034 | */ | ||||
| 21035 | #if defined(SQLITE_ENABLE_FTS41) && !defined(SQLITE_ENABLE_FTS31) | ||||
| 21036 | # define SQLITE_ENABLE_FTS31 1 | ||||
| 21037 | #endif | ||||
| 21038 | |||||
| 21039 | /* | ||||
| 21040 | ** The following macros mimic the standard library functions toupper(), | ||||
| 21041 | ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The | ||||
| 21042 | ** sqlite versions only work for ASCII characters, regardless of locale. | ||||
| 21043 | */ | ||||
| 21044 | #ifdef SQLITE_ASCII1 | ||||
| 21045 | # define sqlite3Toupper(x)((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) | ||||
| 21046 | # define sqlite3Isspace(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x01) (sqlite3CtypeMap[(unsigned char)(x)]&0x01) | ||||
| 21047 | # define sqlite3Isalnum(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x06) (sqlite3CtypeMap[(unsigned char)(x)]&0x06) | ||||
| 21048 | # define sqlite3Isalpha(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x02) (sqlite3CtypeMap[(unsigned char)(x)]&0x02) | ||||
| 21049 | # define sqlite3Isdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x04) (sqlite3CtypeMap[(unsigned char)(x)]&0x04) | ||||
| 21050 | # define sqlite3Isxdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x08) (sqlite3CtypeMap[(unsigned char)(x)]&0x08) | ||||
| 21051 | # define sqlite3Tolower(x)(sqlite3UpperToLower[(unsigned char)(x)]) (sqlite3UpperToLower[(unsigned char)(x)]) | ||||
| 21052 | # define sqlite3Isquote(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x80) (sqlite3CtypeMap[(unsigned char)(x)]&0x80) | ||||
| 21053 | # define sqlite3JsonId1(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x42) (sqlite3CtypeMap[(unsigned char)(x)]&0x42) | ||||
| 21054 | # define sqlite3JsonId2(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x46) (sqlite3CtypeMap[(unsigned char)(x)]&0x46) | ||||
| 21055 | #else | ||||
| 21056 | # define sqlite3Toupper(x)((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) toupper((unsigned char)(x))(__extension__ ({ int __res; if (sizeof ((unsigned char)(x)) > 1) { if (__builtin_constant_p ((unsigned char)(x))) { int __c = ((unsigned char)(x)); __res = __c < -128 || __c > 255 ? __c : (*__ctype_toupper_loc ())[__c]; } else __res = toupper ((unsigned char)(x)); } else __res = (*__ctype_toupper_loc ( ))[(int) ((unsigned char)(x))]; __res; })) | ||||
| 21057 | # define sqlite3Isspace(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x01) isspace((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned short int) _ISspace) | ||||
| 21058 | # define sqlite3Isalnum(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x06) isalnum((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned short int) _ISalnum) | ||||
| 21059 | # define sqlite3Isalpha(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x02) isalpha((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned short int) _ISalpha) | ||||
| 21060 | # define sqlite3Isdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x04) isdigit((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned short int) _ISdigit) | ||||
| 21061 | # define sqlite3Isxdigit(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x08) isxdigit((unsigned char)(x))((*__ctype_b_loc ())[(int) (((unsigned char)(x)))] & (unsigned short int) _ISxdigit) | ||||
| 21062 | # define sqlite3Tolower(x)(sqlite3UpperToLower[(unsigned char)(x)]) tolower((unsigned char)(x))(__extension__ ({ int __res; if (sizeof ((unsigned char)(x)) > 1) { if (__builtin_constant_p ((unsigned char)(x))) { int __c = ((unsigned char)(x)); __res = __c < -128 || __c > 255 ? __c : (*__ctype_tolower_loc ())[__c]; } else __res = tolower ((unsigned char)(x)); } else __res = (*__ctype_tolower_loc ( ))[(int) ((unsigned char)(x))]; __res; })) | ||||
| 21063 | # define sqlite3Isquote(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x80) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`') | ||||
| 21064 | # define sqlite3JsonId1(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x42) (sqlite3IsIdChar(x)&&(x)<'0') | ||||
| 21065 | # define sqlite3JsonId2(x)(sqlite3CtypeMap[(unsigned char)(x)]&0x46) sqlite3IsIdChar(x) | ||||
| 21066 | #endif | ||||
| 21067 | SQLITE_PRIVATEstatic int sqlite3IsIdChar(u8); | ||||
| 21068 | |||||
| 21069 | /* | ||||
| 21070 | ** Internal function prototypes | ||||
| 21071 | */ | ||||
| 21072 | SQLITE_PRIVATEstatic int sqlite3StrICmp(const char*,const char*); | ||||
| 21073 | SQLITE_PRIVATEstatic int sqlite3Strlen30(const char*); | ||||
| 21074 | #define sqlite3Strlen30NN(C)(strlen(C)&0x3fffffff) (strlen(C)&0x3fffffff) | ||||
| 21075 | SQLITE_PRIVATEstatic char *sqlite3ColumnType(Column*,char*); | ||||
| 21076 | #define sqlite3StrNICmpsqlite3_strnicmp sqlite3_strnicmp | ||||
| 21077 | |||||
| 21078 | SQLITE_PRIVATEstatic int sqlite3MallocInit(void); | ||||
| 21079 | SQLITE_PRIVATEstatic void sqlite3MallocEnd(void); | ||||
| 21080 | SQLITE_PRIVATEstatic void *sqlite3Malloc(u64); | ||||
| 21081 | SQLITE_PRIVATEstatic void *sqlite3MallocZero(u64); | ||||
| 21082 | SQLITE_PRIVATEstatic void *sqlite3DbMallocZero(sqlite3*, u64); | ||||
| 21083 | SQLITE_PRIVATEstatic void *sqlite3DbMallocRaw(sqlite3*, u64); | ||||
| 21084 | SQLITE_PRIVATEstatic void *sqlite3DbMallocRawNN(sqlite3*, u64); | ||||
| 21085 | SQLITE_PRIVATEstatic char *sqlite3DbStrDup(sqlite3*,const char*); | ||||
| 21086 | SQLITE_PRIVATEstatic char *sqlite3DbStrNDup(sqlite3*,const char*, u64); | ||||
| 21087 | SQLITE_PRIVATEstatic char *sqlite3DbSpanDup(sqlite3*,const char*,const char*); | ||||
| 21088 | SQLITE_PRIVATEstatic void *sqlite3Realloc(void*, u64); | ||||
| 21089 | SQLITE_PRIVATEstatic void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64); | ||||
| 21090 | SQLITE_PRIVATEstatic void *sqlite3DbRealloc(sqlite3 *, void *, u64); | ||||
| 21091 | SQLITE_PRIVATEstatic void sqlite3DbFree(sqlite3*, void*); | ||||
| 21092 | SQLITE_PRIVATEstatic void sqlite3DbFreeNN(sqlite3*, void*); | ||||
| 21093 | SQLITE_PRIVATEstatic void sqlite3DbNNFreeNN(sqlite3*, void*); | ||||
| 21094 | SQLITE_PRIVATEstatic int sqlite3MallocSize(const void*); | ||||
| 21095 | SQLITE_PRIVATEstatic int sqlite3DbMallocSize(sqlite3*, const void*); | ||||
| 21096 | SQLITE_PRIVATEstatic void *sqlite3PageMalloc(int); | ||||
| 21097 | SQLITE_PRIVATEstatic void sqlite3PageFree(void*); | ||||
| 21098 | SQLITE_PRIVATEstatic void sqlite3MemSetDefault(void); | ||||
| 21099 | #ifndef SQLITE_UNTESTABLE | ||||
| 21100 | SQLITE_PRIVATEstatic void sqlite3BenignMallocHooks(void (*)(void), void (*)(void)); | ||||
| 21101 | #endif | ||||
| 21102 | SQLITE_PRIVATEstatic int sqlite3HeapNearlyFull(void); | ||||
| 21103 | |||||
| 21104 | /* | ||||
| 21105 | ** On systems with ample stack space and that support alloca(), make | ||||
| 21106 | ** use of alloca() to obtain space for large automatic objects. By default, | ||||
| 21107 | ** obtain space from malloc(). | ||||
| 21108 | ** | ||||
| 21109 | ** The alloca() routine never returns NULL. This will cause code paths | ||||
| 21110 | ** that deal with sqlite3StackAlloc() failures to be unreachable. | ||||
| 21111 | */ | ||||
| 21112 | #ifdef SQLITE_USE_ALLOCA | ||||
| 21113 | # define sqlite3StackAllocRaw(D,N)sqlite3DbMallocRaw(D,N) alloca(N)__builtin_alloca (N) | ||||
| 21114 | # define sqlite3StackAllocRawNN(D,N)sqlite3DbMallocRawNN(D,N) alloca(N)__builtin_alloca (N) | ||||
| 21115 | # define sqlite3StackFree(D,P)sqlite3DbFree(D,P) | ||||
| 21116 | # define sqlite3StackFreeNN(D,P)sqlite3DbFreeNN(D,P) | ||||
| 21117 | #else | ||||
| 21118 | # define sqlite3StackAllocRaw(D,N)sqlite3DbMallocRaw(D,N) sqlite3DbMallocRaw(D,N) | ||||
| 21119 | # define sqlite3StackAllocRawNN(D,N)sqlite3DbMallocRawNN(D,N) sqlite3DbMallocRawNN(D,N) | ||||
| 21120 | # define sqlite3StackFree(D,P)sqlite3DbFree(D,P) sqlite3DbFree(D,P) | ||||
| 21121 | # define sqlite3StackFreeNN(D,P)sqlite3DbFreeNN(D,P) sqlite3DbFreeNN(D,P) | ||||
| 21122 | #endif | ||||
| 21123 | |||||
| 21124 | /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they | ||||
| 21125 | ** are, disable MEMSYS3 | ||||
| 21126 | */ | ||||
| 21127 | #ifdef SQLITE_ENABLE_MEMSYS5 | ||||
| 21128 | SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetMemsys5(void); | ||||
| 21129 | #undef SQLITE_ENABLE_MEMSYS3 | ||||
| 21130 | #endif | ||||
| 21131 | #ifdef SQLITE_ENABLE_MEMSYS3 | ||||
| 21132 | SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetMemsys3(void); | ||||
| 21133 | #endif | ||||
| 21134 | |||||
| 21135 | |||||
| 21136 | #ifndef SQLITE_MUTEX_OMIT | ||||
| 21137 | SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3DefaultMutex(void); | ||||
| 21138 | SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3NoopMutex(void); | ||||
| 21139 | SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3MutexAlloc(int); | ||||
| 21140 | SQLITE_PRIVATEstatic int sqlite3MutexInit(void); | ||||
| 21141 | SQLITE_PRIVATEstatic int sqlite3MutexEnd(void); | ||||
| 21142 | #endif | ||||
| 21143 | #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP) | ||||
| 21144 | SQLITE_PRIVATEstatic void sqlite3MemoryBarrier(void); | ||||
| 21145 | #else | ||||
| 21146 | # define sqlite3MemoryBarrier() | ||||
| 21147 | #endif | ||||
| 21148 | |||||
| 21149 | SQLITE_PRIVATEstatic sqlite3_int64 sqlite3StatusValue(int); | ||||
| 21150 | SQLITE_PRIVATEstatic void sqlite3StatusUp(int, int); | ||||
| 21151 | SQLITE_PRIVATEstatic void sqlite3StatusDown(int, int); | ||||
| 21152 | SQLITE_PRIVATEstatic void sqlite3StatusHighwater(int, int); | ||||
| 21153 | SQLITE_PRIVATEstatic int sqlite3LookasideUsed(sqlite3*,int*); | ||||
| 21154 | |||||
| 21155 | /* Access to mutexes used by sqlite3_status() */ | ||||
| 21156 | SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3Pcache1Mutex(void); | ||||
| 21157 | SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3MallocMutex(void); | ||||
| 21158 | |||||
| 21159 | #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT) | ||||
| 21160 | SQLITE_PRIVATEstatic void sqlite3MutexWarnOnContention(sqlite3_mutex*); | ||||
| 21161 | #else | ||||
| 21162 | # define sqlite3MutexWarnOnContention(x) | ||||
| 21163 | #endif | ||||
| 21164 | |||||
| 21165 | #ifndef SQLITE_OMIT_FLOATING_POINT | ||||
| 21166 | # define EXP754(((u64)0x7ff)<<52) (((u64)0x7ff)<<52) | ||||
| 21167 | # define MAN754((((u64)1)<<52)-1) ((((u64)1)<<52)-1) | ||||
| 21168 | # define IsNaN(X)(((X)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52) && ((X)&((((u64)1)<<52)-1))!=0) (((X)&EXP754(((u64)0x7ff)<<52))==EXP754(((u64)0x7ff)<<52) && ((X)&MAN754((((u64)1)<<52)-1))!=0) | ||||
| 21169 | # define IsOvfl(X)(((X)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52) ) (((X)&EXP754(((u64)0x7ff)<<52))==EXP754(((u64)0x7ff)<<52)) | ||||
| 21170 | SQLITE_PRIVATEstatic int sqlite3IsNaN(double); | ||||
| 21171 | SQLITE_PRIVATEstatic int sqlite3IsOverflow(double); | ||||
| 21172 | #else | ||||
| 21173 | # define IsNaN(X)(((X)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52) && ((X)&((((u64)1)<<52)-1))!=0) 0 | ||||
| 21174 | # define sqlite3IsNaN(X) 0 | ||||
| 21175 | # define sqlite3IsOVerflow(X) 0 | ||||
| 21176 | #endif | ||||
| 21177 | |||||
| 21178 | /* | ||||
| 21179 | ** An instance of the following structure holds information about SQL | ||||
| 21180 | ** functions arguments that are the parameters to the printf() function. | ||||
| 21181 | */ | ||||
| 21182 | struct PrintfArguments { | ||||
| 21183 | int nArg; /* Total number of arguments */ | ||||
| 21184 | int nUsed; /* Number of arguments used so far */ | ||||
| 21185 | sqlite3_value **apArg; /* The argument values */ | ||||
| 21186 | }; | ||||
| 21187 | |||||
| 21188 | /* | ||||
| 21189 | ** An instance of this object receives the decoding of a floating point | ||||
| 21190 | ** value into an approximate decimal representation. | ||||
| 21191 | */ | ||||
| 21192 | struct FpDecode { | ||||
| 21193 | char sign; /* '+' or '-' */ | ||||
| 21194 | char isSpecial; /* 1: Infinity 2: NaN */ | ||||
| 21195 | int n; /* Significant digits in the decode */ | ||||
| 21196 | int iDP; /* Location of the decimal point */ | ||||
| 21197 | char *z; /* Start of significant digits */ | ||||
| 21198 | char zBuf[24]; /* Storage for significant digits */ | ||||
| 21199 | }; | ||||
| 21200 | |||||
| 21201 | SQLITE_PRIVATEstatic void sqlite3FpDecode(FpDecode*,double,int,int); | ||||
| 21202 | SQLITE_PRIVATEstatic char *sqlite3MPrintf(sqlite3*,const char*, ...); | ||||
| 21203 | SQLITE_PRIVATEstatic char *sqlite3VMPrintf(sqlite3*,const char*, va_list); | ||||
| 21204 | #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) | ||||
| 21205 | SQLITE_PRIVATEstatic void sqlite3DebugPrintf(const char*, ...); | ||||
| 21206 | #endif | ||||
| 21207 | #if defined(SQLITE_TEST) | ||||
| 21208 | SQLITE_PRIVATEstatic void *sqlite3TestTextToPtr(const char*); | ||||
| 21209 | #endif | ||||
| 21210 | |||||
| 21211 | #if defined(SQLITE_DEBUG) | ||||
| 21212 | SQLITE_PRIVATEstatic void sqlite3TreeViewLine(TreeView*, const char *zFormat, ...); | ||||
| 21213 | SQLITE_PRIVATEstatic void sqlite3TreeViewExpr(TreeView*, const Expr*, u8); | ||||
| 21214 | SQLITE_PRIVATEstatic void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*); | ||||
| 21215 | SQLITE_PRIVATEstatic void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*); | ||||
| 21216 | SQLITE_PRIVATEstatic void sqlite3TreeViewBareIdList(TreeView*, const IdList*, const char*); | ||||
| 21217 | SQLITE_PRIVATEstatic void sqlite3TreeViewIdList(TreeView*, const IdList*, u8, const char*); | ||||
| 21218 | SQLITE_PRIVATEstatic void sqlite3TreeViewColumnList(TreeView*, const Column*, int, u8); | ||||
| 21219 | SQLITE_PRIVATEstatic void sqlite3TreeViewSrcList(TreeView*, const SrcList*); | ||||
| 21220 | SQLITE_PRIVATEstatic void sqlite3TreeViewSelect(TreeView*, const Select*, u8); | ||||
| 21221 | SQLITE_PRIVATEstatic void sqlite3TreeViewWith(TreeView*, const With*, u8); | ||||
| 21222 | SQLITE_PRIVATEstatic void sqlite3TreeViewUpsert(TreeView*, const Upsert*, u8); | ||||
| 21223 | #if TREETRACE_ENABLED0 | ||||
| 21224 | SQLITE_PRIVATEstatic void sqlite3TreeViewDelete(const With*, const SrcList*, const Expr*, | ||||
| 21225 | const ExprList*,const Expr*, const Trigger*); | ||||
| 21226 | SQLITE_PRIVATEstatic void sqlite3TreeViewInsert(const With*, const SrcList*, | ||||
| 21227 | const IdList*, const Select*, const ExprList*, | ||||
| 21228 | int, const Upsert*, const Trigger*); | ||||
| 21229 | SQLITE_PRIVATEstatic void sqlite3TreeViewUpdate(const With*, const SrcList*, const ExprList*, | ||||
| 21230 | const Expr*, int, const ExprList*, const Expr*, | ||||
| 21231 | const Upsert*, const Trigger*); | ||||
| 21232 | #endif | ||||
| 21233 | #ifndef SQLITE_OMIT_TRIGGER | ||||
| 21234 | SQLITE_PRIVATEstatic void sqlite3TreeViewTriggerStep(TreeView*, const TriggerStep*, u8, u8); | ||||
| 21235 | SQLITE_PRIVATEstatic void sqlite3TreeViewTrigger(TreeView*, const Trigger*, u8, u8); | ||||
| 21236 | #endif | ||||
| 21237 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 21238 | SQLITE_PRIVATEstatic void sqlite3TreeViewWindow(TreeView*, const Window*, u8); | ||||
| 21239 | SQLITE_PRIVATEstatic void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8); | ||||
| 21240 | #endif | ||||
| 21241 | SQLITE_PRIVATEstatic void sqlite3ShowExpr(const Expr*); | ||||
| 21242 | SQLITE_PRIVATEstatic void sqlite3ShowExprList(const ExprList*); | ||||
| 21243 | SQLITE_PRIVATEstatic void sqlite3ShowIdList(const IdList*); | ||||
| 21244 | SQLITE_PRIVATEstatic void sqlite3ShowSrcList(const SrcList*); | ||||
| 21245 | SQLITE_PRIVATEstatic void sqlite3ShowSelect(const Select*); | ||||
| 21246 | SQLITE_PRIVATEstatic void sqlite3ShowWith(const With*); | ||||
| 21247 | SQLITE_PRIVATEstatic void sqlite3ShowUpsert(const Upsert*); | ||||
| 21248 | #ifndef SQLITE_OMIT_TRIGGER | ||||
| 21249 | SQLITE_PRIVATEstatic void sqlite3ShowTriggerStep(const TriggerStep*); | ||||
| 21250 | SQLITE_PRIVATEstatic void sqlite3ShowTriggerStepList(const TriggerStep*); | ||||
| 21251 | SQLITE_PRIVATEstatic void sqlite3ShowTrigger(const Trigger*); | ||||
| 21252 | SQLITE_PRIVATEstatic void sqlite3ShowTriggerList(const Trigger*); | ||||
| 21253 | #endif | ||||
| 21254 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 21255 | SQLITE_PRIVATEstatic void sqlite3ShowWindow(const Window*); | ||||
| 21256 | SQLITE_PRIVATEstatic void sqlite3ShowWinFunc(const Window*); | ||||
| 21257 | #endif | ||||
| 21258 | #endif | ||||
| 21259 | |||||
| 21260 | SQLITE_PRIVATEstatic void sqlite3SetString(char **, sqlite3*, const char*); | ||||
| 21261 | SQLITE_PRIVATEstatic void sqlite3ProgressCheck(Parse*); | ||||
| 21262 | SQLITE_PRIVATEstatic void sqlite3ErrorMsg(Parse*, const char*, ...); | ||||
| 21263 | SQLITE_PRIVATEstatic int sqlite3ErrorToParser(sqlite3*,int); | ||||
| 21264 | SQLITE_PRIVATEstatic void sqlite3Dequote(char*); | ||||
| 21265 | SQLITE_PRIVATEstatic void sqlite3DequoteExpr(Expr*); | ||||
| 21266 | SQLITE_PRIVATEstatic void sqlite3DequoteToken(Token*); | ||||
| 21267 | SQLITE_PRIVATEstatic void sqlite3DequoteNumber(Parse*, Expr*); | ||||
| 21268 | SQLITE_PRIVATEstatic void sqlite3TokenInit(Token*,char*); | ||||
| 21269 | SQLITE_PRIVATEstatic int sqlite3KeywordCode(const unsigned char*, int); | ||||
| 21270 | SQLITE_PRIVATEstatic int sqlite3RunParser(Parse*, const char*); | ||||
| 21271 | SQLITE_PRIVATEstatic void sqlite3FinishCoding(Parse*); | ||||
| 21272 | SQLITE_PRIVATEstatic int sqlite3GetTempReg(Parse*); | ||||
| 21273 | SQLITE_PRIVATEstatic void sqlite3ReleaseTempReg(Parse*,int); | ||||
| 21274 | SQLITE_PRIVATEstatic int sqlite3GetTempRange(Parse*,int); | ||||
| 21275 | SQLITE_PRIVATEstatic void sqlite3ReleaseTempRange(Parse*,int,int); | ||||
| 21276 | SQLITE_PRIVATEstatic void sqlite3ClearTempRegCache(Parse*); | ||||
| 21277 | SQLITE_PRIVATEstatic void sqlite3TouchRegister(Parse*,int); | ||||
| 21278 | #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG) | ||||
| 21279 | SQLITE_PRIVATEstatic int sqlite3FirstAvailableRegister(Parse*,int); | ||||
| 21280 | #endif | ||||
| 21281 | #ifdef SQLITE_DEBUG | ||||
| 21282 | SQLITE_PRIVATEstatic int sqlite3NoTempsInRange(Parse*,int,int); | ||||
| 21283 | #endif | ||||
| 21284 | SQLITE_PRIVATEstatic Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int); | ||||
| 21285 | SQLITE_PRIVATEstatic Expr *sqlite3Expr(sqlite3*,int,const char*); | ||||
| 21286 | SQLITE_PRIVATEstatic void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*); | ||||
| 21287 | SQLITE_PRIVATEstatic Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*); | ||||
| 21288 | SQLITE_PRIVATEstatic void sqlite3PExprAddSelect(Parse*, Expr*, Select*); | ||||
| 21289 | SQLITE_PRIVATEstatic Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*); | ||||
| 21290 | SQLITE_PRIVATEstatic Expr *sqlite3ExprSimplifiedAndOr(Expr*); | ||||
| 21291 | SQLITE_PRIVATEstatic Expr *sqlite3ExprFunction(Parse*,ExprList*, const Token*, int); | ||||
| 21292 | SQLITE_PRIVATEstatic void sqlite3ExprAddFunctionOrderBy(Parse*,Expr*,ExprList*); | ||||
| 21293 | SQLITE_PRIVATEstatic void sqlite3ExprOrderByAggregateError(Parse*,Expr*); | ||||
| 21294 | SQLITE_PRIVATEstatic void sqlite3ExprFunctionUsable(Parse*,const Expr*,const FuncDef*); | ||||
| 21295 | SQLITE_PRIVATEstatic void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32); | ||||
| 21296 | SQLITE_PRIVATEstatic void sqlite3ExprDelete(sqlite3*, Expr*); | ||||
| 21297 | SQLITE_PRIVATEstatic void sqlite3ExprDeleteGeneric(sqlite3*,void*); | ||||
| 21298 | SQLITE_PRIVATEstatic int sqlite3ExprDeferredDelete(Parse*, Expr*); | ||||
| 21299 | SQLITE_PRIVATEstatic void sqlite3ExprUnmapAndDelete(Parse*, Expr*); | ||||
| 21300 | SQLITE_PRIVATEstatic ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*); | ||||
| 21301 | SQLITE_PRIVATEstatic ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*); | ||||
| 21302 | SQLITE_PRIVATEstatic Select *sqlite3ExprListToValues(Parse*, int, ExprList*); | ||||
| 21303 | SQLITE_PRIVATEstatic void sqlite3ExprListSetSortOrder(ExprList*,int,int); | ||||
| 21304 | SQLITE_PRIVATEstatic void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int); | ||||
| 21305 | SQLITE_PRIVATEstatic void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*); | ||||
| 21306 | SQLITE_PRIVATEstatic void sqlite3ExprListDelete(sqlite3*, ExprList*); | ||||
| 21307 | SQLITE_PRIVATEstatic void sqlite3ExprListDeleteGeneric(sqlite3*,void*); | ||||
| 21308 | SQLITE_PRIVATEstatic u32 sqlite3ExprListFlags(const ExprList*); | ||||
| 21309 | SQLITE_PRIVATEstatic int sqlite3IndexHasDuplicateRootPage(Index*); | ||||
| 21310 | SQLITE_PRIVATEstatic int sqlite3Init(sqlite3*, char**); | ||||
| 21311 | SQLITE_PRIVATEstatic int sqlite3InitCallback(void*, int, char**, char**); | ||||
| 21312 | SQLITE_PRIVATEstatic int sqlite3InitOne(sqlite3*, int, char**, u32); | ||||
| 21313 | SQLITE_PRIVATEstatic void sqlite3Pragma(Parse*,Token*,Token*,Token*,int); | ||||
| 21314 | #ifndef SQLITE_OMIT_VIRTUALTABLE | ||||
| 21315 | SQLITE_PRIVATEstatic Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName); | ||||
| 21316 | #endif | ||||
| 21317 | SQLITE_PRIVATEstatic void sqlite3ResetAllSchemasOfConnection(sqlite3*); | ||||
| 21318 | SQLITE_PRIVATEstatic void sqlite3ResetOneSchema(sqlite3*,int); | ||||
| 21319 | SQLITE_PRIVATEstatic void sqlite3CollapseDatabaseArray(sqlite3*); | ||||
| 21320 | SQLITE_PRIVATEstatic void sqlite3CommitInternalChanges(sqlite3*); | ||||
| 21321 | SQLITE_PRIVATEstatic void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*); | ||||
| 21322 | SQLITE_PRIVATEstatic Expr *sqlite3ColumnExpr(Table*,Column*); | ||||
| 21323 | SQLITE_PRIVATEstatic void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl); | ||||
| 21324 | SQLITE_PRIVATEstatic const char *sqlite3ColumnColl(Column*); | ||||
| 21325 | SQLITE_PRIVATEstatic void sqlite3DeleteColumnNames(sqlite3*,Table*); | ||||
| 21326 | SQLITE_PRIVATEstatic void sqlite3GenerateColumnNames(Parse *pParse, Select *pSelect); | ||||
| 21327 | SQLITE_PRIVATEstatic int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**); | ||||
| 21328 | SQLITE_PRIVATEstatic void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char); | ||||
| 21329 | SQLITE_PRIVATEstatic Table *sqlite3ResultSetOfSelect(Parse*,Select*,char); | ||||
| 21330 | SQLITE_PRIVATEstatic void sqlite3OpenSchemaTable(Parse *, int); | ||||
| 21331 | SQLITE_PRIVATEstatic Index *sqlite3PrimaryKeyIndex(Table*); | ||||
| 21332 | SQLITE_PRIVATEstatic int sqlite3TableColumnToIndex(Index*, int); | ||||
| 21333 | #ifdef SQLITE_OMIT_GENERATED_COLUMNS | ||||
| 21334 | # define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */ | ||||
| 21335 | # define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */ | ||||
| 21336 | #else | ||||
| 21337 | SQLITE_PRIVATEstatic i16 sqlite3TableColumnToStorage(Table*, i16); | ||||
| 21338 | SQLITE_PRIVATEstatic i16 sqlite3StorageColumnToTable(Table*, i16); | ||||
| 21339 | #endif | ||||
| 21340 | SQLITE_PRIVATEstatic void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); | ||||
| 21341 | #if SQLITE_ENABLE_HIDDEN_COLUMNS | ||||
| 21342 | SQLITE_PRIVATEstatic void sqlite3ColumnPropertiesFromName(Table*, Column*); | ||||
| 21343 | #else | ||||
| 21344 | # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */ | ||||
| 21345 | #endif | ||||
| 21346 | SQLITE_PRIVATEstatic void sqlite3AddColumn(Parse*,Token,Token); | ||||
| 21347 | SQLITE_PRIVATEstatic void sqlite3AddNotNull(Parse*, int); | ||||
| 21348 | SQLITE_PRIVATEstatic void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); | ||||
| 21349 | SQLITE_PRIVATEstatic void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*); | ||||
| 21350 | SQLITE_PRIVATEstatic void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*); | ||||
| 21351 | SQLITE_PRIVATEstatic void sqlite3AddCollateType(Parse*, Token*); | ||||
| 21352 | SQLITE_PRIVATEstatic void sqlite3AddGenerated(Parse*,Expr*,Token*); | ||||
| 21353 | SQLITE_PRIVATEstatic void sqlite3EndTable(Parse*,Token*,Token*,u32,Select*); | ||||
| 21354 | SQLITE_PRIVATEstatic void sqlite3AddReturning(Parse*,ExprList*); | ||||
| 21355 | SQLITE_PRIVATEstatic int sqlite3ParseUri(const char*,const char*,unsigned int*, | ||||
| 21356 | sqlite3_vfs**,char**,char **); | ||||
| 21357 | #define sqlite3CodecQueryParameters(A,B,C)0 0 | ||||
| 21358 | SQLITE_PRIVATEstatic Btree *sqlite3DbNameToBtree(sqlite3*,const char*); | ||||
| 21359 | |||||
| 21360 | #ifdef SQLITE_UNTESTABLE | ||||
| 21361 | # define sqlite3FaultSim(X) SQLITE_OK0 | ||||
| 21362 | #else | ||||
| 21363 | SQLITE_PRIVATEstatic int sqlite3FaultSim(int); | ||||
| 21364 | #endif | ||||
| 21365 | |||||
| 21366 | SQLITE_PRIVATEstatic Bitvec *sqlite3BitvecCreate(u32); | ||||
| 21367 | SQLITE_PRIVATEstatic int sqlite3BitvecTest(Bitvec*, u32); | ||||
| 21368 | SQLITE_PRIVATEstatic int sqlite3BitvecTestNotNull(Bitvec*, u32); | ||||
| 21369 | SQLITE_PRIVATEstatic int sqlite3BitvecSet(Bitvec*, u32); | ||||
| 21370 | SQLITE_PRIVATEstatic void sqlite3BitvecClear(Bitvec*, u32, void*); | ||||
| 21371 | SQLITE_PRIVATEstatic void sqlite3BitvecDestroy(Bitvec*); | ||||
| 21372 | SQLITE_PRIVATEstatic u32 sqlite3BitvecSize(Bitvec*); | ||||
| 21373 | #ifndef SQLITE_UNTESTABLE | ||||
| 21374 | SQLITE_PRIVATEstatic int sqlite3BitvecBuiltinTest(int,int*); | ||||
| 21375 | #endif | ||||
| 21376 | |||||
| 21377 | SQLITE_PRIVATEstatic RowSet *sqlite3RowSetInit(sqlite3*); | ||||
| 21378 | SQLITE_PRIVATEstatic void sqlite3RowSetDelete(void*); | ||||
| 21379 | SQLITE_PRIVATEstatic void sqlite3RowSetClear(void*); | ||||
| 21380 | SQLITE_PRIVATEstatic void sqlite3RowSetInsert(RowSet*, i64); | ||||
| 21381 | SQLITE_PRIVATEstatic int sqlite3RowSetTest(RowSet*, int iBatch, i64); | ||||
| 21382 | SQLITE_PRIVATEstatic int sqlite3RowSetNext(RowSet*, i64*); | ||||
| 21383 | |||||
| 21384 | SQLITE_PRIVATEstatic void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int); | ||||
| 21385 | |||||
| 21386 | #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) | ||||
| 21387 | SQLITE_PRIVATEstatic int sqlite3ViewGetColumnNames(Parse*,Table*); | ||||
| 21388 | #else | ||||
| 21389 | # define sqlite3ViewGetColumnNames(A,B) 0 | ||||
| 21390 | #endif | ||||
| 21391 | |||||
| 21392 | #if SQLITE_MAX_ATTACHED10>30 | ||||
| 21393 | SQLITE_PRIVATEstatic int sqlite3DbMaskAllZero(yDbMask); | ||||
| 21394 | #endif | ||||
| 21395 | SQLITE_PRIVATEstatic void sqlite3DropTable(Parse*, SrcList*, int, int); | ||||
| 21396 | SQLITE_PRIVATEstatic void sqlite3CodeDropTable(Parse*, Table*, int, int); | ||||
| 21397 | SQLITE_PRIVATEstatic void sqlite3DeleteTable(sqlite3*, Table*); | ||||
| 21398 | SQLITE_PRIVATEstatic void sqlite3DeleteTableGeneric(sqlite3*, void*); | ||||
| 21399 | SQLITE_PRIVATEstatic void sqlite3FreeIndex(sqlite3*, Index*); | ||||
| 21400 | #ifndef SQLITE_OMIT_AUTOINCREMENT | ||||
| 21401 | SQLITE_PRIVATEstatic void sqlite3AutoincrementBegin(Parse *pParse); | ||||
| 21402 | SQLITE_PRIVATEstatic void sqlite3AutoincrementEnd(Parse *pParse); | ||||
| 21403 | #else | ||||
| 21404 | # define sqlite3AutoincrementBegin(X) | ||||
| 21405 | # define sqlite3AutoincrementEnd(X) | ||||
| 21406 | #endif | ||||
| 21407 | SQLITE_PRIVATEstatic void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*); | ||||
| 21408 | #ifndef SQLITE_OMIT_GENERATED_COLUMNS | ||||
| 21409 | SQLITE_PRIVATEstatic void sqlite3ComputeGeneratedColumns(Parse*, int, Table*); | ||||
| 21410 | #endif | ||||
| 21411 | SQLITE_PRIVATEstatic void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*); | ||||
| 21412 | SQLITE_PRIVATEstatic IdList *sqlite3IdListAppend(Parse*, IdList*, Token*); | ||||
| 21413 | SQLITE_PRIVATEstatic int sqlite3IdListIndex(IdList*,const char*); | ||||
| 21414 | SQLITE_PRIVATEstatic SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int); | ||||
| 21415 | SQLITE_PRIVATEstatic SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2); | ||||
| 21416 | SQLITE_PRIVATEstatic SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*); | ||||
| 21417 | SQLITE_PRIVATEstatic void sqlite3SubqueryDelete(sqlite3*,Subquery*); | ||||
| 21418 | SQLITE_PRIVATEstatic Select *sqlite3SubqueryDetach(sqlite3*,SrcItem*); | ||||
| 21419 | SQLITE_PRIVATEstatic int sqlite3SrcItemAttachSubquery(Parse*, SrcItem*, Select*, int); | ||||
| 21420 | SQLITE_PRIVATEstatic SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*, | ||||
| 21421 | Token*, Select*, OnOrUsing*); | ||||
| 21422 | SQLITE_PRIVATEstatic void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *); | ||||
| 21423 | SQLITE_PRIVATEstatic void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*); | ||||
| 21424 | SQLITE_PRIVATEstatic int sqlite3IndexedByLookup(Parse *, SrcItem *); | ||||
| 21425 | SQLITE_PRIVATEstatic void sqlite3SrcListShiftJoinType(Parse*,SrcList*); | ||||
| 21426 | SQLITE_PRIVATEstatic void sqlite3SrcListAssignCursors(Parse*, SrcList*); | ||||
| 21427 | SQLITE_PRIVATEstatic void sqlite3IdListDelete(sqlite3*, IdList*); | ||||
| 21428 | SQLITE_PRIVATEstatic void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*); | ||||
| 21429 | SQLITE_PRIVATEstatic void sqlite3SrcListDelete(sqlite3*, SrcList*); | ||||
| 21430 | SQLITE_PRIVATEstatic Index *sqlite3AllocateIndexObject(sqlite3*,int,int,char**); | ||||
| 21431 | SQLITE_PRIVATEstatic void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, | ||||
| 21432 | Expr*, int, int, u8); | ||||
| 21433 | SQLITE_PRIVATEstatic void sqlite3DropIndex(Parse*, SrcList*, int); | ||||
| 21434 | SQLITE_PRIVATEstatic int sqlite3Select(Parse*, Select*, SelectDest*); | ||||
| 21435 | SQLITE_PRIVATEstatic Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, | ||||
| 21436 | Expr*,ExprList*,u32,Expr*); | ||||
| 21437 | SQLITE_PRIVATEstatic void sqlite3SelectDelete(sqlite3*, Select*); | ||||
| 21438 | SQLITE_PRIVATEstatic void sqlite3SelectDeleteGeneric(sqlite3*,void*); | ||||
| 21439 | SQLITE_PRIVATEstatic Table *sqlite3SrcListLookup(Parse*, SrcList*); | ||||
| 21440 | SQLITE_PRIVATEstatic int sqlite3IsReadOnly(Parse*, Table*, Trigger*); | ||||
| 21441 | SQLITE_PRIVATEstatic void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); | ||||
| 21442 | #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT1) && !defined(SQLITE_OMIT_SUBQUERY) | ||||
| 21443 | SQLITE_PRIVATEstatic Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*); | ||||
| 21444 | #endif | ||||
| 21445 | SQLITE_PRIVATEstatic void sqlite3CodeChangeCount(Vdbe*,int,const char*); | ||||
| 21446 | SQLITE_PRIVATEstatic void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*); | ||||
| 21447 | SQLITE_PRIVATEstatic void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*, | ||||
| 21448 | Upsert*); | ||||
| 21449 | SQLITE_PRIVATEstatic WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*, | ||||
| 21450 | ExprList*,Select*,u16,int); | ||||
| 21451 | SQLITE_PRIVATEstatic void sqlite3WhereEnd(WhereInfo*); | ||||
| 21452 | SQLITE_PRIVATEstatic LogEst sqlite3WhereOutputRowCount(WhereInfo*); | ||||
| 21453 | SQLITE_PRIVATEstatic int sqlite3WhereIsDistinct(WhereInfo*); | ||||
| 21454 | SQLITE_PRIVATEstatic int sqlite3WhereIsOrdered(WhereInfo*); | ||||
| 21455 | SQLITE_PRIVATEstatic int sqlite3WhereOrderByLimitOptLabel(WhereInfo*); | ||||
| 21456 | SQLITE_PRIVATEstatic void sqlite3WhereMinMaxOptEarlyOut(Vdbe*,WhereInfo*); | ||||
| 21457 | SQLITE_PRIVATEstatic int sqlite3WhereIsSorted(WhereInfo*); | ||||
| 21458 | SQLITE_PRIVATEstatic int sqlite3WhereContinueLabel(WhereInfo*); | ||||
| 21459 | SQLITE_PRIVATEstatic int sqlite3WhereBreakLabel(WhereInfo*); | ||||
| 21460 | SQLITE_PRIVATEstatic int sqlite3WhereOkOnePass(WhereInfo*, int*); | ||||
| 21461 | #define ONEPASS_OFF0 0 /* Use of ONEPASS not allowed */ | ||||
| 21462 | #define ONEPASS_SINGLE1 1 /* ONEPASS valid for a single row update */ | ||||
| 21463 | #define ONEPASS_MULTI2 2 /* ONEPASS is valid for multiple rows */ | ||||
| 21464 | SQLITE_PRIVATEstatic int sqlite3WhereUsesDeferredSeek(WhereInfo*); | ||||
| 21465 | SQLITE_PRIVATEstatic void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int); | ||||
| 21466 | SQLITE_PRIVATEstatic int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); | ||||
| 21467 | SQLITE_PRIVATEstatic void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); | ||||
| 21468 | SQLITE_PRIVATEstatic void sqlite3ExprCodeMove(Parse*, int, int, int); | ||||
| 21469 | SQLITE_PRIVATEstatic void sqlite3ExprToRegister(Expr *pExpr, int iReg); | ||||
| 21470 | SQLITE_PRIVATEstatic void sqlite3ExprCode(Parse*, Expr*, int); | ||||
| 21471 | #ifndef SQLITE_OMIT_GENERATED_COLUMNS | ||||
| 21472 | SQLITE_PRIVATEstatic void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int); | ||||
| 21473 | #endif | ||||
| 21474 | SQLITE_PRIVATEstatic void sqlite3ExprCodeCopy(Parse*, Expr*, int); | ||||
| 21475 | SQLITE_PRIVATEstatic void sqlite3ExprCodeFactorable(Parse*, Expr*, int); | ||||
| 21476 | SQLITE_PRIVATEstatic int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int); | ||||
| 21477 | SQLITE_PRIVATEstatic int sqlite3ExprCodeTemp(Parse*, Expr*, int*); | ||||
| 21478 | SQLITE_PRIVATEstatic int sqlite3ExprCodeTarget(Parse*, Expr*, int); | ||||
| 21479 | SQLITE_PRIVATEstatic int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8); | ||||
| 21480 | #define SQLITE_ECEL_DUP0x01 0x01 /* Deep, not shallow copies */ | ||||
| 21481 | #define SQLITE_ECEL_FACTOR0x02 0x02 /* Factor out constant terms */ | ||||
| 21482 | #define SQLITE_ECEL_REF0x04 0x04 /* Use ExprList.u.x.iOrderByCol */ | ||||
| 21483 | #define SQLITE_ECEL_OMITREF0x08 0x08 /* Omit if ExprList.u.x.iOrderByCol */ | ||||
| 21484 | SQLITE_PRIVATEstatic void sqlite3ExprIfTrue(Parse*, Expr*, int, int); | ||||
| 21485 | SQLITE_PRIVATEstatic void sqlite3ExprIfFalse(Parse*, Expr*, int, int); | ||||
| 21486 | SQLITE_PRIVATEstatic void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int); | ||||
| 21487 | SQLITE_PRIVATEstatic Table *sqlite3FindTable(sqlite3*,const char*, const char*); | ||||
| 21488 | #define LOCATE_VIEW0x01 0x01 | ||||
| 21489 | #define LOCATE_NOERR0x02 0x02 | ||||
| 21490 | SQLITE_PRIVATEstatic Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*); | ||||
| 21491 | SQLITE_PRIVATEstatic const char *sqlite3PreferredTableName(const char*); | ||||
| 21492 | SQLITE_PRIVATEstatic Table *sqlite3LocateTableItem(Parse*,u32 flags,SrcItem *); | ||||
| 21493 | SQLITE_PRIVATEstatic Index *sqlite3FindIndex(sqlite3*,const char*, const char*); | ||||
| 21494 | SQLITE_PRIVATEstatic void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); | ||||
| 21495 | SQLITE_PRIVATEstatic void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); | ||||
| 21496 | SQLITE_PRIVATEstatic void sqlite3Vacuum(Parse*,Token*,Expr*); | ||||
| 21497 | SQLITE_PRIVATEstatic int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*); | ||||
| 21498 | SQLITE_PRIVATEstatic char *sqlite3NameFromToken(sqlite3*, const Token*); | ||||
| 21499 | SQLITE_PRIVATEstatic int sqlite3ExprCompare(const Parse*,const Expr*,const Expr*, int); | ||||
| 21500 | SQLITE_PRIVATEstatic int sqlite3ExprCompareSkip(Expr*,Expr*,int); | ||||
| 21501 | SQLITE_PRIVATEstatic int sqlite3ExprListCompare(const ExprList*,const ExprList*, int); | ||||
| 21502 | SQLITE_PRIVATEstatic int sqlite3ExprImpliesExpr(const Parse*,const Expr*,const Expr*, int); | ||||
| 21503 | SQLITE_PRIVATEstatic int sqlite3ExprImpliesNonNullRow(Expr*,int,int); | ||||
| 21504 | SQLITE_PRIVATEstatic void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*); | ||||
| 21505 | SQLITE_PRIVATEstatic void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); | ||||
| 21506 | SQLITE_PRIVATEstatic void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); | ||||
| 21507 | SQLITE_PRIVATEstatic int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx); | ||||
| 21508 | SQLITE_PRIVATEstatic int sqlite3ReferencesSrcList(Parse*, Expr*, SrcList*); | ||||
| 21509 | SQLITE_PRIVATEstatic Vdbe *sqlite3GetVdbe(Parse*); | ||||
| 21510 | #ifndef SQLITE_UNTESTABLE | ||||
| 21511 | SQLITE_PRIVATEstatic void sqlite3PrngSaveState(void); | ||||
| 21512 | SQLITE_PRIVATEstatic void sqlite3PrngRestoreState(void); | ||||
| 21513 | #endif | ||||
| 21514 | SQLITE_PRIVATEstatic void sqlite3RollbackAll(sqlite3*,int); | ||||
| 21515 | SQLITE_PRIVATEstatic void sqlite3CodeVerifySchema(Parse*, int); | ||||
| 21516 | SQLITE_PRIVATEstatic void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); | ||||
| 21517 | SQLITE_PRIVATEstatic void sqlite3BeginTransaction(Parse*, int); | ||||
| 21518 | SQLITE_PRIVATEstatic void sqlite3EndTransaction(Parse*,int); | ||||
| 21519 | SQLITE_PRIVATEstatic void sqlite3Savepoint(Parse*, int, Token*); | ||||
| 21520 | SQLITE_PRIVATEstatic void sqlite3CloseSavepoints(sqlite3 *); | ||||
| 21521 | SQLITE_PRIVATEstatic void sqlite3LeaveMutexAndCloseZombie(sqlite3*); | ||||
| 21522 | SQLITE_PRIVATEstatic u32 sqlite3IsTrueOrFalse(const char*); | ||||
| 21523 | SQLITE_PRIVATEstatic int sqlite3ExprIdToTrueFalse(Expr*); | ||||
| 21524 | SQLITE_PRIVATEstatic int sqlite3ExprTruthValue(const Expr*); | ||||
| 21525 | SQLITE_PRIVATEstatic int sqlite3ExprIsConstant(Parse*,Expr*); | ||||
| 21526 | SQLITE_PRIVATEstatic int sqlite3ExprIsConstantOrFunction(Expr*, u8); | ||||
| 21527 | SQLITE_PRIVATEstatic int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*); | ||||
| 21528 | SQLITE_PRIVATEstatic int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int,int); | ||||
| 21529 | #ifdef SQLITE_ENABLE_CURSOR_HINTS | ||||
| 21530 | SQLITE_PRIVATEstatic int sqlite3ExprContainsSubquery(Expr*); | ||||
| 21531 | #endif | ||||
| 21532 | SQLITE_PRIVATEstatic int sqlite3ExprIsInteger(const Expr*, int*, Parse*); | ||||
| 21533 | SQLITE_PRIVATEstatic int sqlite3ExprCanBeNull(const Expr*); | ||||
| 21534 | SQLITE_PRIVATEstatic int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); | ||||
| 21535 | SQLITE_PRIVATEstatic int sqlite3IsRowid(const char*); | ||||
| 21536 | SQLITE_PRIVATEstatic const char *sqlite3RowidAlias(Table *pTab); | ||||
| 21537 | SQLITE_PRIVATEstatic void sqlite3GenerateRowDelete( | ||||
| 21538 | Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int); | ||||
| 21539 | SQLITE_PRIVATEstatic void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int); | ||||
| 21540 | SQLITE_PRIVATEstatic int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int); | ||||
| 21541 | SQLITE_PRIVATEstatic void sqlite3ResolvePartIdxLabel(Parse*,int); | ||||
| 21542 | SQLITE_PRIVATEstatic int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int); | ||||
| 21543 | SQLITE_PRIVATEstatic void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int, | ||||
| 21544 | u8,u8,int,int*,int*,Upsert*); | ||||
| 21545 | #ifdef SQLITE_ENABLE_NULL_TRIM | ||||
| 21546 | SQLITE_PRIVATEstatic void sqlite3SetMakeRecordP5(Vdbe*,Table*); | ||||
| 21547 | #else | ||||
| 21548 | # define sqlite3SetMakeRecordP5(A,B) | ||||
| 21549 | #endif | ||||
| 21550 | SQLITE_PRIVATEstatic void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int); | ||||
| 21551 | SQLITE_PRIVATEstatic int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*); | ||||
| 21552 | SQLITE_PRIVATEstatic void sqlite3BeginWriteOperation(Parse*, int, int); | ||||
| 21553 | SQLITE_PRIVATEstatic void sqlite3MultiWrite(Parse*); | ||||
| 21554 | SQLITE_PRIVATEstatic void sqlite3MayAbort(Parse*); | ||||
| 21555 | SQLITE_PRIVATEstatic void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8); | ||||
| 21556 | SQLITE_PRIVATEstatic void sqlite3UniqueConstraint(Parse*, int, Index*); | ||||
| 21557 | SQLITE_PRIVATEstatic void sqlite3RowidConstraint(Parse*, int, Table*); | ||||
| 21558 | SQLITE_PRIVATEstatic Expr *sqlite3ExprDup(sqlite3*,const Expr*,int); | ||||
| 21559 | SQLITE_PRIVATEstatic ExprList *sqlite3ExprListDup(sqlite3*,const ExprList*,int); | ||||
| 21560 | SQLITE_PRIVATEstatic SrcList *sqlite3SrcListDup(sqlite3*,const SrcList*,int); | ||||
| 21561 | SQLITE_PRIVATEstatic IdList *sqlite3IdListDup(sqlite3*,const IdList*); | ||||
| 21562 | SQLITE_PRIVATEstatic Select *sqlite3SelectDup(sqlite3*,const Select*,int); | ||||
| 21563 | SQLITE_PRIVATEstatic FuncDef *sqlite3FunctionSearch(int,const char*); | ||||
| 21564 | SQLITE_PRIVATEstatic void sqlite3InsertBuiltinFuncs(FuncDef*,int); | ||||
| 21565 | SQLITE_PRIVATEstatic FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8); | ||||
| 21566 | SQLITE_PRIVATEstatic void sqlite3QuoteValue(StrAccum*,sqlite3_value*,int); | ||||
| 21567 | SQLITE_PRIVATEstatic int sqlite3AppendOneUtf8Character(char*, u32); | ||||
| 21568 | SQLITE_PRIVATEstatic void sqlite3RegisterBuiltinFunctions(void); | ||||
| 21569 | SQLITE_PRIVATEstatic void sqlite3RegisterDateTimeFunctions(void); | ||||
| 21570 | SQLITE_PRIVATEstatic void sqlite3RegisterJsonFunctions(void); | ||||
| 21571 | SQLITE_PRIVATEstatic void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*); | ||||
| 21572 | #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) | ||||
| 21573 | SQLITE_PRIVATEstatic int sqlite3JsonTableFunctions(sqlite3*); | ||||
| 21574 | #endif | ||||
| 21575 | SQLITE_PRIVATEstatic int sqlite3SafetyCheckOk(sqlite3*); | ||||
| 21576 | SQLITE_PRIVATEstatic int sqlite3SafetyCheckSickOrOk(sqlite3*); | ||||
| 21577 | SQLITE_PRIVATEstatic void sqlite3ChangeCookie(Parse*, int); | ||||
| 21578 | SQLITE_PRIVATEstatic With *sqlite3WithDup(sqlite3 *db, With *p); | ||||
| 21579 | |||||
| 21580 | #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) | ||||
| 21581 | SQLITE_PRIVATEstatic void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int); | ||||
| 21582 | #endif | ||||
| 21583 | |||||
| 21584 | #ifndef SQLITE_OMIT_TRIGGER | ||||
| 21585 | SQLITE_PRIVATEstatic void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, | ||||
| 21586 | Expr*,int, int); | ||||
| 21587 | SQLITE_PRIVATEstatic void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*); | ||||
| 21588 | SQLITE_PRIVATEstatic void sqlite3DropTrigger(Parse*, SrcList*, int); | ||||
| 21589 | SQLITE_PRIVATEstatic void sqlite3DropTriggerPtr(Parse*, Trigger*); | ||||
| 21590 | SQLITE_PRIVATEstatic Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask); | ||||
| 21591 | SQLITE_PRIVATEstatic Trigger *sqlite3TriggerList(Parse *, Table *); | ||||
| 21592 | SQLITE_PRIVATEstatic void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *, | ||||
| 21593 | int, int, int); | ||||
| 21594 | SQLITE_PRIVATEstatic void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int); | ||||
| 21595 | void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*); | ||||
| 21596 | SQLITE_PRIVATEstatic void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*); | ||||
| 21597 | SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*, | ||||
| 21598 | const char*,const char*); | ||||
| 21599 | SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*, | ||||
| 21600 | Select*,u8,Upsert*, | ||||
| 21601 | const char*,const char*); | ||||
| 21602 | SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*, | ||||
| 21603 | Expr*, u8, const char*,const char*); | ||||
| 21604 | SQLITE_PRIVATEstatic TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*, | ||||
| 21605 | const char*,const char*); | ||||
| 21606 | SQLITE_PRIVATEstatic void sqlite3DeleteTrigger(sqlite3*, Trigger*); | ||||
| 21607 | SQLITE_PRIVATEstatic void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); | ||||
| 21608 | SQLITE_PRIVATEstatic u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); | ||||
| 21609 | SQLITE_PRIVATEstatic SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*); | ||||
| 21610 | # define sqlite3ParseToplevel(p)((p)->pToplevel ? (p)->pToplevel : (p)) ((p)->pToplevel ? (p)->pToplevel : (p)) | ||||
| 21611 | # define sqlite3IsToplevel(p)((p)->pToplevel==0) ((p)->pToplevel==0) | ||||
| 21612 | #else | ||||
| 21613 | # define sqlite3TriggersExist(B,C,D,E,F) 0 | ||||
| 21614 | # define sqlite3DeleteTrigger(A,B) | ||||
| 21615 | # define sqlite3DropTriggerPtr(A,B) | ||||
| 21616 | # define sqlite3UnlinkAndDeleteTrigger(A,B,C) | ||||
| 21617 | # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) | ||||
| 21618 | # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F) | ||||
| 21619 | # define sqlite3TriggerList(X, Y) 0 | ||||
| 21620 | # define sqlite3ParseToplevel(p)((p)->pToplevel ? (p)->pToplevel : (p)) p | ||||
| 21621 | # define sqlite3IsToplevel(p)((p)->pToplevel==0) 1 | ||||
| 21622 | # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 | ||||
| 21623 | # define sqlite3TriggerStepSrc(A,B) 0 | ||||
| 21624 | #endif | ||||
| 21625 | |||||
| 21626 | SQLITE_PRIVATEstatic int sqlite3JoinType(Parse*, Token*, Token*, Token*); | ||||
| 21627 | SQLITE_PRIVATEstatic int sqlite3ColumnIndex(Table *pTab, const char *zCol); | ||||
| 21628 | SQLITE_PRIVATEstatic void sqlite3SrcItemColumnUsed(SrcItem*,int); | ||||
| 21629 | SQLITE_PRIVATEstatic void sqlite3SetJoinExpr(Expr*,int,u32); | ||||
| 21630 | SQLITE_PRIVATEstatic void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); | ||||
| 21631 | SQLITE_PRIVATEstatic void sqlite3DeferForeignKey(Parse*, int); | ||||
| 21632 | #ifndef SQLITE_OMIT_AUTHORIZATION | ||||
| 21633 | SQLITE_PRIVATEstatic void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); | ||||
| 21634 | SQLITE_PRIVATEstatic int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); | ||||
| 21635 | SQLITE_PRIVATEstatic void sqlite3AuthContextPush(Parse*, AuthContext*, const char*); | ||||
| 21636 | SQLITE_PRIVATEstatic void sqlite3AuthContextPop(AuthContext*); | ||||
| 21637 | SQLITE_PRIVATEstatic int sqlite3AuthReadCol(Parse*, const char *, const char *, int); | ||||
| 21638 | #else | ||||
| 21639 | # define sqlite3AuthRead(a,b,c,d) | ||||
| 21640 | # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK0 | ||||
| 21641 | # define sqlite3AuthContextPush(a,b,c) | ||||
| 21642 | # define sqlite3AuthContextPop(a) ((void)(a)) | ||||
| 21643 | #endif | ||||
| 21644 | SQLITE_PRIVATEstatic int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName); | ||||
| 21645 | SQLITE_PRIVATEstatic void sqlite3Attach(Parse*, Expr*, Expr*, Expr*); | ||||
| 21646 | SQLITE_PRIVATEstatic void sqlite3Detach(Parse*, Expr*); | ||||
| 21647 | SQLITE_PRIVATEstatic void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); | ||||
| 21648 | SQLITE_PRIVATEstatic int sqlite3FixSrcList(DbFixer*, SrcList*); | ||||
| 21649 | SQLITE_PRIVATEstatic int sqlite3FixSelect(DbFixer*, Select*); | ||||
| 21650 | SQLITE_PRIVATEstatic int sqlite3FixExpr(DbFixer*, Expr*); | ||||
| 21651 | SQLITE_PRIVATEstatic int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); | ||||
| 21652 | |||||
| 21653 | SQLITE_PRIVATEstatic int sqlite3RealSameAsInt(double,sqlite3_int64); | ||||
| 21654 | SQLITE_PRIVATEstatic i64 sqlite3RealToI64(double); | ||||
| 21655 | SQLITE_PRIVATEstatic int sqlite3Int64ToText(i64,char*); | ||||
| 21656 | SQLITE_PRIVATEstatic int sqlite3AtoF(const char *z, double*, int, u8); | ||||
| 21657 | SQLITE_PRIVATEstatic int sqlite3GetInt32(const char *, int*); | ||||
| 21658 | SQLITE_PRIVATEstatic int sqlite3GetUInt32(const char*, u32*); | ||||
| 21659 | SQLITE_PRIVATEstatic int sqlite3Atoi(const char*); | ||||
| 21660 | #ifndef SQLITE_OMIT_UTF16 | ||||
| 21661 | SQLITE_PRIVATEstatic int sqlite3Utf16ByteLen(const void *pData, int nByte, int nChar); | ||||
| 21662 | #endif | ||||
| 21663 | SQLITE_PRIVATEstatic int sqlite3Utf8CharLen(const char *pData, int nByte); | ||||
| 21664 | SQLITE_PRIVATEstatic u32 sqlite3Utf8Read(const u8**); | ||||
| 21665 | SQLITE_PRIVATEstatic int sqlite3Utf8ReadLimited(const u8*, int, u32*); | ||||
| 21666 | SQLITE_PRIVATEstatic LogEst sqlite3LogEst(u64); | ||||
| 21667 | SQLITE_PRIVATEstatic LogEst sqlite3LogEstAdd(LogEst,LogEst); | ||||
| 21668 | SQLITE_PRIVATEstatic LogEst sqlite3LogEstFromDouble(double); | ||||
| 21669 | SQLITE_PRIVATEstatic u64 sqlite3LogEstToInt(LogEst); | ||||
| 21670 | SQLITE_PRIVATEstatic VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int); | ||||
| 21671 | SQLITE_PRIVATEstatic const char *sqlite3VListNumToName(VList*,int); | ||||
| 21672 | SQLITE_PRIVATEstatic int sqlite3VListNameToNum(VList*,const char*,int); | ||||
| 21673 | |||||
| 21674 | /* | ||||
| 21675 | ** Routines to read and write variable-length integers. These used to | ||||
| 21676 | ** be defined locally, but now we use the varint routines in the util.c | ||||
| 21677 | ** file. | ||||
| 21678 | */ | ||||
| 21679 | SQLITE_PRIVATEstatic int sqlite3PutVarint(unsigned char*, u64); | ||||
| 21680 | SQLITE_PRIVATEstatic u8 sqlite3GetVarint(const unsigned char *, u64 *); | ||||
| 21681 | SQLITE_PRIVATEstatic u8 sqlite3GetVarint32(const unsigned char *, u32 *); | ||||
| 21682 | SQLITE_PRIVATEstatic int sqlite3VarintLen(u64 v); | ||||
| 21683 | |||||
| 21684 | /* | ||||
| 21685 | ** The common case is for a varint to be a single byte. They following | ||||
| 21686 | ** macros handle the common case without a procedure call, but then call | ||||
| 21687 | ** the procedure for larger varints. | ||||
| 21688 | */ | ||||
| 21689 | #define getVarint32(A,B)(u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32( (A),(u32 *)&(B))) \ | ||||
| 21690 | (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B))) | ||||
| 21691 | #define getVarint32NR(A,B)B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&( B)) \ | ||||
| 21692 | B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B)) | ||||
| 21693 | #define putVarint32(A,B)(u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1: sqlite3PutVarint ((A),(B))) \ | ||||
| 21694 | (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ | ||||
| 21695 | sqlite3PutVarint((A),(B))) | ||||
| 21696 | #define getVarintsqlite3GetVarint sqlite3GetVarint | ||||
| 21697 | #define putVarintsqlite3PutVarint sqlite3PutVarint | ||||
| 21698 | |||||
| 21699 | |||||
| 21700 | SQLITE_PRIVATEstatic const char *sqlite3IndexAffinityStr(sqlite3*, Index*); | ||||
| 21701 | SQLITE_PRIVATEstatic char *sqlite3TableAffinityStr(sqlite3*,const Table*); | ||||
| 21702 | SQLITE_PRIVATEstatic void sqlite3TableAffinity(Vdbe*, Table*, int); | ||||
| 21703 | SQLITE_PRIVATEstatic char sqlite3CompareAffinity(const Expr *pExpr, char aff2); | ||||
| 21704 | SQLITE_PRIVATEstatic int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity); | ||||
| 21705 | SQLITE_PRIVATEstatic char sqlite3TableColumnAffinity(const Table*,int); | ||||
| 21706 | SQLITE_PRIVATEstatic char sqlite3ExprAffinity(const Expr *pExpr); | ||||
| 21707 | SQLITE_PRIVATEstatic int sqlite3ExprDataType(const Expr *pExpr); | ||||
| 21708 | SQLITE_PRIVATEstatic int sqlite3Atoi64(const char*, i64*, int, u8); | ||||
| 21709 | SQLITE_PRIVATEstatic int sqlite3DecOrHexToI64(const char*, i64*); | ||||
| 21710 | SQLITE_PRIVATEstatic void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...); | ||||
| 21711 | SQLITE_PRIVATEstatic void sqlite3Error(sqlite3*,int); | ||||
| 21712 | SQLITE_PRIVATEstatic void sqlite3ErrorClear(sqlite3*); | ||||
| 21713 | SQLITE_PRIVATEstatic void sqlite3SystemError(sqlite3*,int); | ||||
| 21714 | #if !defined(SQLITE_OMIT_BLOB_LITERAL) | ||||
| 21715 | SQLITE_PRIVATEstatic void *sqlite3HexToBlob(sqlite3*, const char *z, int n); | ||||
| 21716 | #endif | ||||
| 21717 | SQLITE_PRIVATEstatic u8 sqlite3HexToInt(int h); | ||||
| 21718 | SQLITE_PRIVATEstatic int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); | ||||
| 21719 | |||||
| 21720 | #if defined(SQLITE_NEED_ERR_NAME) | ||||
| 21721 | SQLITE_PRIVATEstatic const char *sqlite3ErrName(int); | ||||
| 21722 | #endif | ||||
| 21723 | |||||
| 21724 | #ifndef SQLITE_OMIT_DESERIALIZE | ||||
| 21725 | SQLITE_PRIVATEstatic int sqlite3MemdbInit(void); | ||||
| 21726 | SQLITE_PRIVATEstatic int sqlite3IsMemdb(const sqlite3_vfs*); | ||||
| 21727 | #else | ||||
| 21728 | # define sqlite3IsMemdb(X) 0 | ||||
| 21729 | #endif | ||||
| 21730 | |||||
| 21731 | SQLITE_PRIVATEstatic const char *sqlite3ErrStr(int); | ||||
| 21732 | SQLITE_PRIVATEstatic int sqlite3ReadSchema(Parse *pParse); | ||||
| 21733 | SQLITE_PRIVATEstatic CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); | ||||
| 21734 | SQLITE_PRIVATEstatic int sqlite3IsBinary(const CollSeq*); | ||||
| 21735 | SQLITE_PRIVATEstatic CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); | ||||
| 21736 | SQLITE_PRIVATEstatic void sqlite3SetTextEncoding(sqlite3 *db, u8); | ||||
| 21737 | SQLITE_PRIVATEstatic CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr); | ||||
| 21738 | SQLITE_PRIVATEstatic CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr); | ||||
| 21739 | SQLITE_PRIVATEstatic int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*); | ||||
| 21740 | SQLITE_PRIVATEstatic Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int); | ||||
| 21741 | SQLITE_PRIVATEstatic Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*); | ||||
| 21742 | SQLITE_PRIVATEstatic Expr *sqlite3ExprSkipCollate(Expr*); | ||||
| 21743 | SQLITE_PRIVATEstatic Expr *sqlite3ExprSkipCollateAndLikely(Expr*); | ||||
| 21744 | SQLITE_PRIVATEstatic int sqlite3CheckCollSeq(Parse *, CollSeq *); | ||||
| 21745 | SQLITE_PRIVATEstatic int sqlite3WritableSchema(sqlite3*); | ||||
| 21746 | SQLITE_PRIVATEstatic int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*); | ||||
| 21747 | SQLITE_PRIVATEstatic void sqlite3VdbeSetChanges(sqlite3 *, i64); | ||||
| 21748 | SQLITE_PRIVATEstatic int sqlite3AddInt64(i64*,i64); | ||||
| 21749 | SQLITE_PRIVATEstatic int sqlite3SubInt64(i64*,i64); | ||||
| 21750 | SQLITE_PRIVATEstatic int sqlite3MulInt64(i64*,i64); | ||||
| 21751 | SQLITE_PRIVATEstatic int sqlite3AbsInt32(int); | ||||
| 21752 | #ifdef SQLITE_ENABLE_8_3_NAMES | ||||
| 21753 | SQLITE_PRIVATEstatic void sqlite3FileSuffix3(const char*, char*); | ||||
| 21754 | #else | ||||
| 21755 | # define sqlite3FileSuffix3(X,Y) | ||||
| 21756 | #endif | ||||
| 21757 | SQLITE_PRIVATEstatic u8 sqlite3GetBoolean(const char *z,u8); | ||||
| 21758 | |||||
| 21759 | SQLITE_PRIVATEstatic const void *sqlite3ValueText(sqlite3_value*, u8); | ||||
| 21760 | SQLITE_PRIVATEstatic int sqlite3ValueIsOfClass(const sqlite3_value*, void(*)(void*)); | ||||
| 21761 | SQLITE_PRIVATEstatic int sqlite3ValueBytes(sqlite3_value*, u8); | ||||
| 21762 | SQLITE_PRIVATEstatic void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, | ||||
| 21763 | void(*)(void*)); | ||||
| 21764 | SQLITE_PRIVATEstatic void sqlite3ValueSetNull(sqlite3_value*); | ||||
| 21765 | SQLITE_PRIVATEstatic void sqlite3ValueFree(sqlite3_value*); | ||||
| 21766 | #ifndef SQLITE_UNTESTABLE | ||||
| 21767 | SQLITE_PRIVATEstatic void sqlite3ResultIntReal(sqlite3_context*); | ||||
| 21768 | #endif | ||||
| 21769 | SQLITE_PRIVATEstatic sqlite3_value *sqlite3ValueNew(sqlite3 *); | ||||
| 21770 | #ifndef SQLITE_OMIT_UTF16 | ||||
| 21771 | SQLITE_PRIVATEstatic char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); | ||||
| 21772 | #endif | ||||
| 21773 | SQLITE_PRIVATEstatic int sqlite3ValueFromExpr(sqlite3 *, const Expr *, u8, u8, sqlite3_value **); | ||||
| 21774 | SQLITE_PRIVATEstatic void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); | ||||
| 21775 | #ifndef SQLITE_AMALGAMATION1 | ||||
| 21776 | SQLITE_PRIVATEstatic const unsigned char sqlite3OpcodeProperty[]; | ||||
| 21777 | SQLITE_PRIVATEstatic const char sqlite3StrBINARY[]; | ||||
| 21778 | SQLITE_PRIVATEstatic const unsigned char sqlite3StdTypeLen[]; | ||||
| 21779 | SQLITE_PRIVATEstatic const char sqlite3StdTypeAffinity[]; | ||||
| 21780 | SQLITE_PRIVATEstatic const char *sqlite3StdType[]; | ||||
| 21781 | SQLITE_PRIVATEstatic const unsigned char sqlite3UpperToLower[]; | ||||
| 21782 | SQLITE_PRIVATEstatic const unsigned char *sqlite3aLTb; | ||||
| 21783 | SQLITE_PRIVATEstatic const unsigned char *sqlite3aEQb; | ||||
| 21784 | SQLITE_PRIVATEstatic const unsigned char *sqlite3aGTb; | ||||
| 21785 | SQLITE_PRIVATEstatic const unsigned char sqlite3CtypeMap[]; | ||||
| 21786 | SQLITE_PRIVATEstatic SQLITE_WSD struct Sqlite3Config sqlite3Config; | ||||
| 21787 | SQLITE_PRIVATEstatic FuncDefHash sqlite3BuiltinFunctions; | ||||
| 21788 | #ifndef SQLITE_OMIT_WSD | ||||
| 21789 | SQLITE_PRIVATEstatic int sqlite3PendingByte; | ||||
| 21790 | #endif | ||||
| 21791 | #endif /* SQLITE_AMALGAMATION */ | ||||
| 21792 | #ifdef VDBE_PROFILE | ||||
| 21793 | SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3NProfileCnt; | ||||
| 21794 | #endif | ||||
| 21795 | SQLITE_PRIVATEstatic void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno); | ||||
| 21796 | SQLITE_PRIVATEstatic void sqlite3Reindex(Parse*, Token*, Token*); | ||||
| 21797 | SQLITE_PRIVATEstatic void sqlite3AlterFunctions(void); | ||||
| 21798 | SQLITE_PRIVATEstatic void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); | ||||
| 21799 | SQLITE_PRIVATEstatic void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*); | ||||
| 21800 | SQLITE_PRIVATEstatic int sqlite3GetToken(const unsigned char *, int *); | ||||
| 21801 | SQLITE_PRIVATEstatic void sqlite3NestedParse(Parse*, const char*, ...); | ||||
| 21802 | SQLITE_PRIVATEstatic void sqlite3ExpirePreparedStatements(sqlite3*, int); | ||||
| 21803 | SQLITE_PRIVATEstatic void sqlite3CodeRhsOfIN(Parse*, Expr*, int); | ||||
| 21804 | SQLITE_PRIVATEstatic int sqlite3CodeSubselect(Parse*, Expr*); | ||||
| 21805 | SQLITE_PRIVATEstatic void sqlite3SelectPrep(Parse*, Select*, NameContext*); | ||||
| 21806 | SQLITE_PRIVATEstatic int sqlite3ExpandSubquery(Parse*, SrcItem*); | ||||
| 21807 | SQLITE_PRIVATEstatic void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p); | ||||
| 21808 | SQLITE_PRIVATEstatic int sqlite3MatchEName( | ||||
| 21809 | const struct ExprList_item*, | ||||
| 21810 | const char*, | ||||
| 21811 | const char*, | ||||
| 21812 | const char*, | ||||
| 21813 | int* | ||||
| 21814 | ); | ||||
| 21815 | SQLITE_PRIVATEstatic Bitmask sqlite3ExprColUsed(Expr*); | ||||
| 21816 | SQLITE_PRIVATEstatic u8 sqlite3StrIHash(const char*); | ||||
| 21817 | SQLITE_PRIVATEstatic int sqlite3ResolveExprNames(NameContext*, Expr*); | ||||
| 21818 | SQLITE_PRIVATEstatic int sqlite3ResolveExprListNames(NameContext*, ExprList*); | ||||
| 21819 | SQLITE_PRIVATEstatic void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*); | ||||
| 21820 | SQLITE_PRIVATEstatic int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*); | ||||
| 21821 | SQLITE_PRIVATEstatic int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*); | ||||
| 21822 | SQLITE_PRIVATEstatic void sqlite3ColumnDefault(Vdbe *, Table *, int, int); | ||||
| 21823 | SQLITE_PRIVATEstatic void sqlite3AlterFinishAddColumn(Parse *, Token *); | ||||
| 21824 | SQLITE_PRIVATEstatic void sqlite3AlterBeginAddColumn(Parse *, SrcList *); | ||||
| 21825 | SQLITE_PRIVATEstatic void sqlite3AlterDropColumn(Parse*, SrcList*, const Token*); | ||||
| 21826 | SQLITE_PRIVATEstatic const void *sqlite3RenameTokenMap(Parse*, const void*, const Token*); | ||||
| 21827 | SQLITE_PRIVATEstatic void sqlite3RenameTokenRemap(Parse*, const void *pTo, const void *pFrom); | ||||
| 21828 | SQLITE_PRIVATEstatic void sqlite3RenameExprUnmap(Parse*, Expr*); | ||||
| 21829 | SQLITE_PRIVATEstatic void sqlite3RenameExprlistUnmap(Parse*, ExprList*); | ||||
| 21830 | SQLITE_PRIVATEstatic CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); | ||||
| 21831 | SQLITE_PRIVATEstatic char sqlite3AffinityType(const char*, Column*); | ||||
| 21832 | SQLITE_PRIVATEstatic void sqlite3Analyze(Parse*, Token*, Token*); | ||||
| 21833 | SQLITE_PRIVATEstatic int sqlite3InvokeBusyHandler(BusyHandler*); | ||||
| 21834 | SQLITE_PRIVATEstatic int sqlite3FindDb(sqlite3*, Token*); | ||||
| 21835 | SQLITE_PRIVATEstatic int sqlite3FindDbName(sqlite3 *, const char *); | ||||
| 21836 | SQLITE_PRIVATEstatic int sqlite3AnalysisLoad(sqlite3*,int iDB); | ||||
| 21837 | SQLITE_PRIVATEstatic void sqlite3DeleteIndexSamples(sqlite3*,Index*); | ||||
| 21838 | SQLITE_PRIVATEstatic void sqlite3DefaultRowEst(Index*); | ||||
| 21839 | SQLITE_PRIVATEstatic void sqlite3RegisterLikeFunctions(sqlite3*, int); | ||||
| 21840 | SQLITE_PRIVATEstatic int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*); | ||||
| 21841 | SQLITE_PRIVATEstatic void sqlite3SchemaClear(void *); | ||||
| 21842 | SQLITE_PRIVATEstatic Schema *sqlite3SchemaGet(sqlite3 *, Btree *); | ||||
| 21843 | SQLITE_PRIVATEstatic int sqlite3SchemaToIndex(sqlite3 *db, Schema *); | ||||
| 21844 | SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int); | ||||
| 21845 | SQLITE_PRIVATEstatic void sqlite3KeyInfoUnref(KeyInfo*); | ||||
| 21846 | SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoRef(KeyInfo*); | ||||
| 21847 | SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*); | ||||
| 21848 | SQLITE_PRIVATEstatic KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int); | ||||
| 21849 | SQLITE_PRIVATEstatic const char *sqlite3SelectOpName(int); | ||||
| 21850 | SQLITE_PRIVATEstatic int sqlite3HasExplicitNulls(Parse*, ExprList*); | ||||
| 21851 | |||||
| 21852 | #ifdef SQLITE_DEBUG | ||||
| 21853 | SQLITE_PRIVATEstatic int sqlite3KeyInfoIsWriteable(KeyInfo*); | ||||
| 21854 | #endif | ||||
| 21855 | SQLITE_PRIVATEstatic int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, | ||||
| 21856 | void (*)(sqlite3_context*,int,sqlite3_value **), | ||||
| 21857 | void (*)(sqlite3_context*,int,sqlite3_value **), | ||||
| 21858 | void (*)(sqlite3_context*), | ||||
| 21859 | void (*)(sqlite3_context*), | ||||
| 21860 | void (*)(sqlite3_context*,int,sqlite3_value **), | ||||
| 21861 | FuncDestructor *pDestructor | ||||
| 21862 | ); | ||||
| 21863 | SQLITE_PRIVATEstatic void sqlite3NoopDestructor(void*); | ||||
| 21864 | SQLITE_PRIVATEstatic void *sqlite3OomFault(sqlite3*); | ||||
| 21865 | SQLITE_PRIVATEstatic void sqlite3OomClear(sqlite3*); | ||||
| 21866 | SQLITE_PRIVATEstatic int sqlite3ApiExit(sqlite3 *db, int); | ||||
| 21867 | SQLITE_PRIVATEstatic int sqlite3OpenTempDatabase(Parse *); | ||||
| 21868 | |||||
| 21869 | SQLITE_PRIVATEstatic char *sqlite3RCStrRef(char*); | ||||
| 21870 | SQLITE_PRIVATEstatic void sqlite3RCStrUnref(void*); | ||||
| 21871 | SQLITE_PRIVATEstatic char *sqlite3RCStrNew(u64); | ||||
| 21872 | SQLITE_PRIVATEstatic char *sqlite3RCStrResize(char*,u64); | ||||
| 21873 | |||||
| 21874 | SQLITE_PRIVATEstatic void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int); | ||||
| 21875 | SQLITE_PRIVATEstatic int sqlite3StrAccumEnlarge(StrAccum*, i64); | ||||
| 21876 | SQLITE_PRIVATEstatic char *sqlite3StrAccumFinish(StrAccum*); | ||||
| 21877 | SQLITE_PRIVATEstatic void sqlite3StrAccumSetError(StrAccum*, u8); | ||||
| 21878 | SQLITE_PRIVATEstatic void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*); | ||||
| 21879 | SQLITE_PRIVATEstatic void sqlite3SelectDestInit(SelectDest*,int,int); | ||||
| 21880 | SQLITE_PRIVATEstatic Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); | ||||
| 21881 | SQLITE_PRIVATEstatic void sqlite3RecordErrorByteOffset(sqlite3*,const char*); | ||||
| 21882 | SQLITE_PRIVATEstatic void sqlite3RecordErrorOffsetOfExpr(sqlite3*,const Expr*); | ||||
| 21883 | |||||
| 21884 | SQLITE_PRIVATEstatic void sqlite3BackupRestart(sqlite3_backup *); | ||||
| 21885 | SQLITE_PRIVATEstatic void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *); | ||||
| 21886 | |||||
| 21887 | #ifndef SQLITE_OMIT_SUBQUERY | ||||
| 21888 | SQLITE_PRIVATEstatic int sqlite3ExprCheckIN(Parse*, Expr*); | ||||
| 21889 | #else | ||||
| 21890 | # define sqlite3ExprCheckIN(x,y) SQLITE_OK0 | ||||
| 21891 | #endif | ||||
| 21892 | |||||
| 21893 | #ifdef SQLITE_ENABLE_STAT4 | ||||
| 21894 | SQLITE_PRIVATEstatic int sqlite3Stat4ProbeSetValue( | ||||
| 21895 | Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*); | ||||
| 21896 | SQLITE_PRIVATEstatic int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**); | ||||
| 21897 | SQLITE_PRIVATEstatic void sqlite3Stat4ProbeFree(UnpackedRecord*); | ||||
| 21898 | SQLITE_PRIVATEstatic int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**); | ||||
| 21899 | SQLITE_PRIVATEstatic char sqlite3IndexColumnAffinity(sqlite3*, Index*, int); | ||||
| 21900 | #endif | ||||
| 21901 | |||||
| 21902 | /* | ||||
| 21903 | ** The interface to the LEMON-generated parser | ||||
| 21904 | */ | ||||
| 21905 | #ifndef SQLITE_AMALGAMATION1 | ||||
| 21906 | SQLITE_PRIVATEstatic void *sqlite3ParserAlloc(void*(*)(u64), Parse*); | ||||
| 21907 | SQLITE_PRIVATEstatic void sqlite3ParserFree(void*, void(*)(void*)); | ||||
| 21908 | #endif | ||||
| 21909 | SQLITE_PRIVATEstatic void sqlite3Parser(void*, int, Token); | ||||
| 21910 | SQLITE_PRIVATEstatic int sqlite3ParserFallback(int); | ||||
| 21911 | #ifdef YYTRACKMAXSTACKDEPTH | ||||
| 21912 | SQLITE_PRIVATEstatic int sqlite3ParserStackPeak(void*); | ||||
| 21913 | #endif | ||||
| 21914 | |||||
| 21915 | SQLITE_PRIVATEstatic void sqlite3AutoLoadExtensions(sqlite3*); | ||||
| 21916 | #ifndef SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 21917 | SQLITE_PRIVATEstatic void sqlite3CloseExtensions(sqlite3*); | ||||
| 21918 | #else | ||||
| 21919 | # define sqlite3CloseExtensions(X) | ||||
| 21920 | #endif | ||||
| 21921 | |||||
| 21922 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 21923 | SQLITE_PRIVATEstatic void sqlite3TableLock(Parse *, int, Pgno, u8, const char *); | ||||
| 21924 | #else | ||||
| 21925 | #define sqlite3TableLock(v,w,x,y,z) | ||||
| 21926 | #endif | ||||
| 21927 | |||||
| 21928 | #ifdef SQLITE_TEST | ||||
| 21929 | SQLITE_PRIVATEstatic int sqlite3Utf8To8(unsigned char*); | ||||
| 21930 | #endif | ||||
| 21931 | |||||
| 21932 | #ifdef SQLITE_OMIT_VIRTUALTABLE | ||||
| 21933 | # define sqlite3VtabClear(D,T) | ||||
| 21934 | # define sqlite3VtabSync(X,Y) SQLITE_OK0 | ||||
| 21935 | # define sqlite3VtabRollback(X) | ||||
| 21936 | # define sqlite3VtabCommit(X) | ||||
| 21937 | # define sqlite3VtabInSync(db)((db)->nVTrans>0 && (db)->aVTrans==0) 0 | ||||
| 21938 | # define sqlite3VtabLock(X) | ||||
| 21939 | # define sqlite3VtabUnlock(X) | ||||
| 21940 | # define sqlite3VtabModuleUnref(D,X) | ||||
| 21941 | # define sqlite3VtabUnlockList(X) | ||||
| 21942 | # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK0 | ||||
| 21943 | # define sqlite3GetVTable(X,Y) ((VTable*)0) | ||||
| 21944 | #else | ||||
| 21945 | SQLITE_PRIVATEstatic void sqlite3VtabClear(sqlite3 *db, Table*); | ||||
| 21946 | SQLITE_PRIVATEstatic void sqlite3VtabDisconnect(sqlite3 *db, Table *p); | ||||
| 21947 | SQLITE_PRIVATEstatic int sqlite3VtabSync(sqlite3 *db, Vdbe*); | ||||
| 21948 | SQLITE_PRIVATEstatic int sqlite3VtabRollback(sqlite3 *db); | ||||
| 21949 | SQLITE_PRIVATEstatic int sqlite3VtabCommit(sqlite3 *db); | ||||
| 21950 | SQLITE_PRIVATEstatic void sqlite3VtabLock(VTable *); | ||||
| 21951 | SQLITE_PRIVATEstatic void sqlite3VtabUnlock(VTable *); | ||||
| 21952 | SQLITE_PRIVATEstatic void sqlite3VtabModuleUnref(sqlite3*,Module*); | ||||
| 21953 | SQLITE_PRIVATEstatic void sqlite3VtabUnlockList(sqlite3*); | ||||
| 21954 | SQLITE_PRIVATEstatic int sqlite3VtabSavepoint(sqlite3 *, int, int); | ||||
| 21955 | SQLITE_PRIVATEstatic void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*); | ||||
| 21956 | SQLITE_PRIVATEstatic VTable *sqlite3GetVTable(sqlite3*, Table*); | ||||
| 21957 | SQLITE_PRIVATEstatic Module *sqlite3VtabCreateModule( | ||||
| 21958 | sqlite3*, | ||||
| 21959 | const char*, | ||||
| 21960 | const sqlite3_module*, | ||||
| 21961 | void*, | ||||
| 21962 | void(*)(void*) | ||||
| 21963 | ); | ||||
| 21964 | # define sqlite3VtabInSync(db)((db)->nVTrans>0 && (db)->aVTrans==0) ((db)->nVTrans>0 && (db)->aVTrans==0) | ||||
| 21965 | #endif | ||||
| 21966 | SQLITE_PRIVATEstatic int sqlite3ReadOnlyShadowTables(sqlite3 *db); | ||||
| 21967 | #ifndef SQLITE_OMIT_VIRTUALTABLE | ||||
| 21968 | SQLITE_PRIVATEstatic int sqlite3ShadowTableName(sqlite3 *db, const char *zName); | ||||
| 21969 | SQLITE_PRIVATEstatic int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*); | ||||
| 21970 | SQLITE_PRIVATEstatic void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*); | ||||
| 21971 | #else | ||||
| 21972 | # define sqlite3ShadowTableName(A,B) 0 | ||||
| 21973 | # define sqlite3IsShadowTableOf(A,B,C) 0 | ||||
| 21974 | # define sqlite3MarkAllShadowTablesOf(A,B) | ||||
| 21975 | #endif | ||||
| 21976 | SQLITE_PRIVATEstatic int sqlite3VtabEponymousTableInit(Parse*,Module*); | ||||
| 21977 | SQLITE_PRIVATEstatic void sqlite3VtabEponymousTableClear(sqlite3*,Module*); | ||||
| 21978 | SQLITE_PRIVATEstatic void sqlite3VtabMakeWritable(Parse*,Table*); | ||||
| 21979 | SQLITE_PRIVATEstatic void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); | ||||
| 21980 | SQLITE_PRIVATEstatic void sqlite3VtabFinishParse(Parse*, Token*); | ||||
| 21981 | SQLITE_PRIVATEstatic void sqlite3VtabArgInit(Parse*); | ||||
| 21982 | SQLITE_PRIVATEstatic void sqlite3VtabArgExtend(Parse*, Token*); | ||||
| 21983 | SQLITE_PRIVATEstatic int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **); | ||||
| 21984 | SQLITE_PRIVATEstatic int sqlite3VtabCallConnect(Parse*, Table*); | ||||
| 21985 | SQLITE_PRIVATEstatic int sqlite3VtabCallDestroy(sqlite3*, int, const char *); | ||||
| 21986 | SQLITE_PRIVATEstatic int sqlite3VtabBegin(sqlite3 *, VTable *); | ||||
| 21987 | |||||
| 21988 | SQLITE_PRIVATEstatic FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); | ||||
| 21989 | SQLITE_PRIVATEstatic void sqlite3VtabUsesAllSchemas(Parse*); | ||||
| 21990 | SQLITE_PRIVATEstatic sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*); | ||||
| 21991 | SQLITE_PRIVATEstatic int sqlite3VdbeParameterIndex(Vdbe*, const char*, int); | ||||
| 21992 | SQLITE_PRIVATEstatic int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *); | ||||
| 21993 | SQLITE_PRIVATEstatic void sqlite3ParseObjectInit(Parse*,sqlite3*); | ||||
| 21994 | SQLITE_PRIVATEstatic void sqlite3ParseObjectReset(Parse*); | ||||
| 21995 | SQLITE_PRIVATEstatic void *sqlite3ParserAddCleanup(Parse*,void(*)(sqlite3*,void*),void*); | ||||
| 21996 | #ifdef SQLITE_ENABLE_NORMALIZE | ||||
| 21997 | SQLITE_PRIVATEstatic char *sqlite3Normalize(Vdbe*, const char*); | ||||
| 21998 | #endif | ||||
| 21999 | SQLITE_PRIVATEstatic int sqlite3Reprepare(Vdbe*); | ||||
| 22000 | SQLITE_PRIVATEstatic void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*); | ||||
| 22001 | SQLITE_PRIVATEstatic CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*); | ||||
| 22002 | SQLITE_PRIVATEstatic CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*); | ||||
| 22003 | SQLITE_PRIVATEstatic int sqlite3TempInMemory(const sqlite3*); | ||||
| 22004 | SQLITE_PRIVATEstatic const char *sqlite3JournalModename(int); | ||||
| 22005 | #ifndef SQLITE_OMIT_WAL | ||||
| 22006 | SQLITE_PRIVATEstatic int sqlite3Checkpoint(sqlite3*, int, int, int*, int*); | ||||
| 22007 | SQLITE_PRIVATEstatic int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int); | ||||
| 22008 | #endif | ||||
| 22009 | #ifndef SQLITE_OMIT_CTE | ||||
| 22010 | SQLITE_PRIVATEstatic Cte *sqlite3CteNew(Parse*,Token*,ExprList*,Select*,u8); | ||||
| 22011 | SQLITE_PRIVATEstatic void sqlite3CteDelete(sqlite3*,Cte*); | ||||
| 22012 | SQLITE_PRIVATEstatic With *sqlite3WithAdd(Parse*,With*,Cte*); | ||||
| 22013 | SQLITE_PRIVATEstatic void sqlite3WithDelete(sqlite3*,With*); | ||||
| 22014 | SQLITE_PRIVATEstatic void sqlite3WithDeleteGeneric(sqlite3*,void*); | ||||
| 22015 | SQLITE_PRIVATEstatic With *sqlite3WithPush(Parse*, With*, u8); | ||||
| 22016 | #else | ||||
| 22017 | # define sqlite3CteNew(P,T,E,S) ((void*)0) | ||||
| 22018 | # define sqlite3CteDelete(D,C) | ||||
| 22019 | # define sqlite3CteWithAdd(P,W,C) ((void*)0) | ||||
| 22020 | # define sqlite3WithDelete(x,y) | ||||
| 22021 | # define sqlite3WithPush(x,y,z) ((void*)0) | ||||
| 22022 | #endif | ||||
| 22023 | #ifndef SQLITE_OMIT_UPSERT | ||||
| 22024 | SQLITE_PRIVATEstatic Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*,Upsert*); | ||||
| 22025 | SQLITE_PRIVATEstatic void sqlite3UpsertDelete(sqlite3*,Upsert*); | ||||
| 22026 | SQLITE_PRIVATEstatic Upsert *sqlite3UpsertDup(sqlite3*,Upsert*); | ||||
| 22027 | SQLITE_PRIVATEstatic int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*,Upsert*); | ||||
| 22028 | SQLITE_PRIVATEstatic void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int); | ||||
| 22029 | SQLITE_PRIVATEstatic Upsert *sqlite3UpsertOfIndex(Upsert*,Index*); | ||||
| 22030 | SQLITE_PRIVATEstatic int sqlite3UpsertNextIsIPK(Upsert*); | ||||
| 22031 | #else | ||||
| 22032 | #define sqlite3UpsertNew(u,v,w,x,y,z) ((Upsert*)0) | ||||
| 22033 | #define sqlite3UpsertDelete(x,y) | ||||
| 22034 | #define sqlite3UpsertDup(x,y) ((Upsert*)0) | ||||
| 22035 | #define sqlite3UpsertOfIndex(x,y) ((Upsert*)0) | ||||
| 22036 | #define sqlite3UpsertNextIsIPK(x) 0 | ||||
| 22037 | #endif | ||||
| 22038 | |||||
| 22039 | |||||
| 22040 | /* Declarations for functions in fkey.c. All of these are replaced by | ||||
| 22041 | ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign | ||||
| 22042 | ** key functionality is available. If OMIT_TRIGGER is defined but | ||||
| 22043 | ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In | ||||
| 22044 | ** this case foreign keys are parsed, but no other functionality is | ||||
| 22045 | ** provided (enforcement of FK constraints requires the triggers sub-system). | ||||
| 22046 | */ | ||||
| 22047 | #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) | ||||
| 22048 | SQLITE_PRIVATEstatic void sqlite3FkCheck(Parse*, Table*, int, int, int*, int); | ||||
| 22049 | SQLITE_PRIVATEstatic void sqlite3FkDropTable(Parse*, SrcList *, Table*); | ||||
| 22050 | SQLITE_PRIVATEstatic void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int); | ||||
| 22051 | SQLITE_PRIVATEstatic int sqlite3FkRequired(Parse*, Table*, int*, int); | ||||
| 22052 | SQLITE_PRIVATEstatic u32 sqlite3FkOldmask(Parse*, Table*); | ||||
| 22053 | SQLITE_PRIVATEstatic FKey *sqlite3FkReferences(Table *); | ||||
| 22054 | SQLITE_PRIVATEstatic void sqlite3FkClearTriggerCache(sqlite3*,int); | ||||
| 22055 | #else | ||||
| 22056 | #define sqlite3FkActions(a,b,c,d,e,f) | ||||
| 22057 | #define sqlite3FkCheck(a,b,c,d,e,f) | ||||
| 22058 | #define sqlite3FkDropTable(a,b,c) | ||||
| 22059 | #define sqlite3FkOldmask(a,b) 0 | ||||
| 22060 | #define sqlite3FkRequired(a,b,c,d) 0 | ||||
| 22061 | #define sqlite3FkReferences(a) 0 | ||||
| 22062 | #define sqlite3FkClearTriggerCache(a,b) | ||||
| 22063 | #endif | ||||
| 22064 | #ifndef SQLITE_OMIT_FOREIGN_KEY | ||||
| 22065 | SQLITE_PRIVATEstatic void sqlite3FkDelete(sqlite3 *, Table*); | ||||
| 22066 | SQLITE_PRIVATEstatic int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**); | ||||
| 22067 | #else | ||||
| 22068 | #define sqlite3FkDelete(a,b) | ||||
| 22069 | #define sqlite3FkLocateIndex(a,b,c,d,e) | ||||
| 22070 | #endif | ||||
| 22071 | |||||
| 22072 | |||||
| 22073 | /* | ||||
| 22074 | ** Available fault injectors. Should be numbered beginning with 0. | ||||
| 22075 | */ | ||||
| 22076 | #define SQLITE_FAULTINJECTOR_MALLOC0 0 | ||||
| 22077 | #define SQLITE_FAULTINJECTOR_COUNT1 1 | ||||
| 22078 | |||||
| 22079 | /* | ||||
| 22080 | ** The interface to the code in fault.c used for identifying "benign" | ||||
| 22081 | ** malloc failures. This is only present if SQLITE_UNTESTABLE | ||||
| 22082 | ** is not defined. | ||||
| 22083 | */ | ||||
| 22084 | #ifndef SQLITE_UNTESTABLE | ||||
| 22085 | SQLITE_PRIVATEstatic void sqlite3BeginBenignMalloc(void); | ||||
| 22086 | SQLITE_PRIVATEstatic void sqlite3EndBenignMalloc(void); | ||||
| 22087 | #else | ||||
| 22088 | #define sqlite3BeginBenignMalloc() | ||||
| 22089 | #define sqlite3EndBenignMalloc() | ||||
| 22090 | #endif | ||||
| 22091 | |||||
| 22092 | /* | ||||
| 22093 | ** Allowed return values from sqlite3FindInIndex() | ||||
| 22094 | */ | ||||
| 22095 | #define IN_INDEX_ROWID1 1 /* Search the rowid of the table */ | ||||
| 22096 | #define IN_INDEX_EPH2 2 /* Search an ephemeral b-tree */ | ||||
| 22097 | #define IN_INDEX_INDEX_ASC3 3 /* Existing index ASCENDING */ | ||||
| 22098 | #define IN_INDEX_INDEX_DESC4 4 /* Existing index DESCENDING */ | ||||
| 22099 | #define IN_INDEX_NOOP5 5 /* No table available. Use comparisons */ | ||||
| 22100 | /* | ||||
| 22101 | ** Allowed flags for the 3rd parameter to sqlite3FindInIndex(). | ||||
| 22102 | */ | ||||
| 22103 | #define IN_INDEX_NOOP_OK0x0001 0x0001 /* OK to return IN_INDEX_NOOP */ | ||||
| 22104 | #define IN_INDEX_MEMBERSHIP0x0002 0x0002 /* IN operator used for membership test */ | ||||
| 22105 | #define IN_INDEX_LOOP0x0004 0x0004 /* IN operator used as a loop */ | ||||
| 22106 | SQLITE_PRIVATEstatic int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*); | ||||
| 22107 | |||||
| 22108 | SQLITE_PRIVATEstatic int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int); | ||||
| 22109 | SQLITE_PRIVATEstatic int sqlite3JournalSize(sqlite3_vfs *); | ||||
| 22110 | #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ | ||||
| 22111 | || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) | ||||
| 22112 | SQLITE_PRIVATEstatic int sqlite3JournalCreate(sqlite3_file *); | ||||
| 22113 | #endif | ||||
| 22114 | |||||
| 22115 | SQLITE_PRIVATEstatic int sqlite3JournalIsInMemory(sqlite3_file *p); | ||||
| 22116 | SQLITE_PRIVATEstatic void sqlite3MemJournalOpen(sqlite3_file *); | ||||
| 22117 | |||||
| 22118 | SQLITE_PRIVATEstatic void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p); | ||||
| 22119 | #if SQLITE_MAX_EXPR_DEPTH1000>0 | ||||
| 22120 | SQLITE_PRIVATEstatic int sqlite3SelectExprHeight(const Select *); | ||||
| 22121 | SQLITE_PRIVATEstatic int sqlite3ExprCheckHeight(Parse*, int); | ||||
| 22122 | #else | ||||
| 22123 | #define sqlite3SelectExprHeight(x) 0 | ||||
| 22124 | #define sqlite3ExprCheckHeight(x,y) | ||||
| 22125 | #endif | ||||
| 22126 | SQLITE_PRIVATEstatic void sqlite3ExprSetErrorOffset(Expr*,int); | ||||
| 22127 | |||||
| 22128 | SQLITE_PRIVATEstatic u32 sqlite3Get4byte(const u8*); | ||||
| 22129 | SQLITE_PRIVATEstatic void sqlite3Put4byte(u8*, u32); | ||||
| 22130 | |||||
| 22131 | #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY | ||||
| 22132 | SQLITE_PRIVATEstatic void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *); | ||||
| 22133 | SQLITE_PRIVATEstatic void sqlite3ConnectionUnlocked(sqlite3 *db); | ||||
| 22134 | SQLITE_PRIVATEstatic void sqlite3ConnectionClosed(sqlite3 *db); | ||||
| 22135 | #else | ||||
| 22136 | #define sqlite3ConnectionBlocked(x,y) | ||||
| 22137 | #define sqlite3ConnectionUnlocked(x) | ||||
| 22138 | #define sqlite3ConnectionClosed(x) | ||||
| 22139 | #endif | ||||
| 22140 | |||||
| 22141 | #ifdef SQLITE_DEBUG | ||||
| 22142 | SQLITE_PRIVATEstatic void sqlite3ParserTrace(FILE*, char *); | ||||
| 22143 | #endif | ||||
| 22144 | #if defined(YYCOVERAGE) | ||||
| 22145 | SQLITE_PRIVATEstatic int sqlite3ParserCoverage(FILE*); | ||||
| 22146 | #endif | ||||
| 22147 | |||||
| 22148 | /* | ||||
| 22149 | ** If the SQLITE_ENABLE IOTRACE exists then the global variable | ||||
| 22150 | ** sqlite3IoTrace is a pointer to a printf-like routine used to | ||||
| 22151 | ** print I/O tracing messages. | ||||
| 22152 | */ | ||||
| 22153 | #ifdef SQLITE_ENABLE_IOTRACE | ||||
| 22154 | # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; } | ||||
| 22155 | SQLITE_PRIVATEstatic void sqlite3VdbeIOTraceSql(Vdbe*); | ||||
| 22156 | SQLITE_API SQLITE_EXTERNextern void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...); | ||||
| 22157 | #else | ||||
| 22158 | # define IOTRACE(A) | ||||
| 22159 | # define sqlite3VdbeIOTraceSql(X) | ||||
| 22160 | #endif | ||||
| 22161 | |||||
| 22162 | /* | ||||
| 22163 | ** These routines are available for the mem2.c debugging memory allocator | ||||
| 22164 | ** only. They are used to verify that different "types" of memory | ||||
| 22165 | ** allocations are properly tracked by the system. | ||||
| 22166 | ** | ||||
| 22167 | ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of | ||||
| 22168 | ** the MEMTYPE_* macros defined below. The type must be a bitmask with | ||||
| 22169 | ** a single bit set. | ||||
| 22170 | ** | ||||
| 22171 | ** sqlite3MemdebugHasType() returns true if any of the bits in its second | ||||
| 22172 | ** argument match the type set by the previous sqlite3MemdebugSetType(). | ||||
| 22173 | ** sqlite3MemdebugHasType() is intended for use inside assert() statements. | ||||
| 22174 | ** | ||||
| 22175 | ** sqlite3MemdebugNoType() returns true if none of the bits in its second | ||||
| 22176 | ** argument match the type set by the previous sqlite3MemdebugSetType(). | ||||
| 22177 | ** | ||||
| 22178 | ** Perhaps the most important point is the difference between MEMTYPE_HEAP | ||||
| 22179 | ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means | ||||
| 22180 | ** it might have been allocated by lookaside, except the allocation was | ||||
| 22181 | ** too large or lookaside was already full. It is important to verify | ||||
| 22182 | ** that allocations that might have been satisfied by lookaside are not | ||||
| 22183 | ** passed back to non-lookaside free() routines. Asserts such as the | ||||
| 22184 | ** example above are placed on the non-lookaside free() routines to verify | ||||
| 22185 | ** this constraint. | ||||
| 22186 | ** | ||||
| 22187 | ** All of this is no-op for a production build. It only comes into | ||||
| 22188 | ** play when the SQLITE_MEMDEBUG compile-time option is used. | ||||
| 22189 | */ | ||||
| 22190 | #ifdef SQLITE_MEMDEBUG | ||||
| 22191 | SQLITE_PRIVATEstatic void sqlite3MemdebugSetType(void*,u8); | ||||
| 22192 | SQLITE_PRIVATEstatic int sqlite3MemdebugHasType(const void*,u8)1; | ||||
| 22193 | SQLITE_PRIVATEstatic int sqlite3MemdebugNoType(const void*,u8)1; | ||||
| 22194 | #else | ||||
| 22195 | # define sqlite3MemdebugSetType(X,Y) /* no-op */ | ||||
| 22196 | # define sqlite3MemdebugHasType(X,Y)1 1 | ||||
| 22197 | # define sqlite3MemdebugNoType(X,Y)1 1 | ||||
| 22198 | #endif | ||||
| 22199 | #define MEMTYPE_HEAP0x01 0x01 /* General heap allocations */ | ||||
| 22200 | #define MEMTYPE_LOOKASIDE0x02 0x02 /* Heap that might have been lookaside */ | ||||
| 22201 | #define MEMTYPE_PCACHE0x04 0x04 /* Page cache allocations */ | ||||
| 22202 | |||||
| 22203 | /* | ||||
| 22204 | ** Threading interface | ||||
| 22205 | */ | ||||
| 22206 | #if SQLITE_MAX_WORKER_THREADS8>0 | ||||
| 22207 | SQLITE_PRIVATEstatic int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*); | ||||
| 22208 | SQLITE_PRIVATEstatic int sqlite3ThreadJoin(SQLiteThread*, void**); | ||||
| 22209 | #endif | ||||
| 22210 | |||||
| 22211 | #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST) | ||||
| 22212 | SQLITE_PRIVATEstatic int sqlite3DbpageRegister(sqlite3*); | ||||
| 22213 | #endif | ||||
| 22214 | #if defined(SQLITE_ENABLE_DBSTAT_VTAB1) || defined(SQLITE_TEST) | ||||
| 22215 | SQLITE_PRIVATEstatic int sqlite3DbstatRegister(sqlite3*); | ||||
| 22216 | #endif | ||||
| 22217 | |||||
| 22218 | SQLITE_PRIVATEstatic int sqlite3ExprVectorSize(const Expr *pExpr); | ||||
| 22219 | SQLITE_PRIVATEstatic int sqlite3ExprIsVector(const Expr *pExpr); | ||||
| 22220 | SQLITE_PRIVATEstatic Expr *sqlite3VectorFieldSubexpr(Expr*, int); | ||||
| 22221 | SQLITE_PRIVATEstatic Expr *sqlite3ExprForVectorField(Parse*,Expr*,int,int); | ||||
| 22222 | SQLITE_PRIVATEstatic void sqlite3VectorErrorMsg(Parse*, Expr*); | ||||
| 22223 | |||||
| 22224 | #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS | ||||
| 22225 | SQLITE_PRIVATEstatic const char **sqlite3CompileOptions(int *pnOpt); | ||||
| 22226 | #endif | ||||
| 22227 | |||||
| 22228 | #if SQLITE_OS_UNIX1 && defined(SQLITE_OS_KV_OPTIONAL) | ||||
| 22229 | SQLITE_PRIVATEstatic int sqlite3KvvfsInit(void); | ||||
| 22230 | #endif | ||||
| 22231 | |||||
| 22232 | #if defined(VDBE_PROFILE) \ | ||||
| 22233 | || defined(SQLITE_PERFORMANCE_TRACE) \ | ||||
| 22234 | || defined(SQLITE_ENABLE_STMT_SCANSTATUS1) | ||||
| 22235 | SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3Hwtime(void); | ||||
| 22236 | #endif | ||||
| 22237 | |||||
| 22238 | #ifdef SQLITE_ENABLE_STMT_SCANSTATUS1 | ||||
| 22239 | # define IS_STMT_SCANSTATUS(db)(db->flags & 0x00000400) (db->flags & SQLITE_StmtScanStatus0x00000400) | ||||
| 22240 | #else | ||||
| 22241 | # define IS_STMT_SCANSTATUS(db)(db->flags & 0x00000400) 0 | ||||
| 22242 | #endif | ||||
| 22243 | |||||
| 22244 | #endif /* SQLITEINT_H */ | ||||
| 22245 | |||||
| 22246 | /************** End of sqliteInt.h *******************************************/ | ||||
| 22247 | /************** Begin file os_common.h ***************************************/ | ||||
| 22248 | /* | ||||
| 22249 | ** 2004 May 22 | ||||
| 22250 | ** | ||||
| 22251 | ** The author disclaims copyright to this source code. In place of | ||||
| 22252 | ** a legal notice, here is a blessing: | ||||
| 22253 | ** | ||||
| 22254 | ** May you do good and not evil. | ||||
| 22255 | ** May you find forgiveness for yourself and forgive others. | ||||
| 22256 | ** May you share freely, never taking more than you give. | ||||
| 22257 | ** | ||||
| 22258 | ****************************************************************************** | ||||
| 22259 | ** | ||||
| 22260 | ** This file contains macros and a little bit of code that is common to | ||||
| 22261 | ** all of the platform-specific files (os_*.c) and is #included into those | ||||
| 22262 | ** files. | ||||
| 22263 | ** | ||||
| 22264 | ** This file should be #included by the os_*.c files only. It is not a | ||||
| 22265 | ** general purpose header file. | ||||
| 22266 | */ | ||||
| 22267 | #ifndef _OS_COMMON_H_ | ||||
| 22268 | #define _OS_COMMON_H_ | ||||
| 22269 | |||||
| 22270 | /* | ||||
| 22271 | ** At least two bugs have slipped in because we changed the MEMORY_DEBUG | ||||
| 22272 | ** macro to SQLITE_DEBUG and some older makefiles have not yet made the | ||||
| 22273 | ** switch. The following code should catch this problem at compile-time. | ||||
| 22274 | */ | ||||
| 22275 | #ifdef MEMORY_DEBUG | ||||
| 22276 | # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." | ||||
| 22277 | #endif | ||||
| 22278 | |||||
| 22279 | /* | ||||
| 22280 | ** Macros for performance tracing. Normally turned off. Only works | ||||
| 22281 | ** on i486 hardware. | ||||
| 22282 | */ | ||||
| 22283 | #ifdef SQLITE_PERFORMANCE_TRACE | ||||
| 22284 | |||||
| 22285 | static sqlite_uint64 g_start; | ||||
| 22286 | static sqlite_uint64 g_elapsed; | ||||
| 22287 | #define TIMER_START g_start=sqlite3Hwtime() | ||||
| 22288 | #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start | ||||
| 22289 | #define TIMER_ELAPSED((sqlite_uint64)0) g_elapsed | ||||
| 22290 | #else | ||||
| 22291 | #define TIMER_START | ||||
| 22292 | #define TIMER_END | ||||
| 22293 | #define TIMER_ELAPSED((sqlite_uint64)0) ((sqlite_uint64)0) | ||||
| 22294 | #endif | ||||
| 22295 | |||||
| 22296 | /* | ||||
| 22297 | ** If we compile with the SQLITE_TEST macro set, then the following block | ||||
| 22298 | ** of code will give us the ability to simulate a disk I/O error. This | ||||
| 22299 | ** is used for testing the I/O recovery logic. | ||||
| 22300 | */ | ||||
| 22301 | #if defined(SQLITE_TEST) | ||||
| 22302 | SQLITE_API extern int sqlite3_io_error_hit; | ||||
| 22303 | SQLITE_API extern int sqlite3_io_error_hardhit; | ||||
| 22304 | SQLITE_API extern int sqlite3_io_error_pending; | ||||
| 22305 | SQLITE_API extern int sqlite3_io_error_persist; | ||||
| 22306 | SQLITE_API extern int sqlite3_io_error_benign; | ||||
| 22307 | SQLITE_API extern int sqlite3_diskfull_pending; | ||||
| 22308 | SQLITE_API extern int sqlite3_diskfull; | ||||
| 22309 | #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) | ||||
| 22310 | #define SimulateIOError(CODE) \ | ||||
| 22311 | if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ | ||||
| 22312 | || sqlite3_io_error_pending-- == 1 ) \ | ||||
| 22313 | { local_ioerr(); CODE; } | ||||
| 22314 | static void local_ioerr(){ | ||||
| 22315 | IOTRACE(("IOERR\n")); | ||||
| 22316 | sqlite3_io_error_hit++; | ||||
| 22317 | if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; | ||||
| 22318 | } | ||||
| 22319 | #define SimulateDiskfullError(CODE) \ | ||||
| 22320 | if( sqlite3_diskfull_pending ){ \ | ||||
| 22321 | if( sqlite3_diskfull_pending == 1 ){ \ | ||||
| 22322 | local_ioerr(); \ | ||||
| 22323 | sqlite3_diskfull = 1; \ | ||||
| 22324 | sqlite3_io_error_hit = 1; \ | ||||
| 22325 | CODE; \ | ||||
| 22326 | }else{ \ | ||||
| 22327 | sqlite3_diskfull_pending--; \ | ||||
| 22328 | } \ | ||||
| 22329 | } | ||||
| 22330 | #else | ||||
| 22331 | #define SimulateIOErrorBenign(X) | ||||
| 22332 | #define SimulateIOError(A) | ||||
| 22333 | #define SimulateDiskfullError(A) | ||||
| 22334 | #endif /* defined(SQLITE_TEST) */ | ||||
| 22335 | |||||
| 22336 | /* | ||||
| 22337 | ** When testing, keep a count of the number of open files. | ||||
| 22338 | */ | ||||
| 22339 | #if defined(SQLITE_TEST) | ||||
| 22340 | SQLITE_API extern int sqlite3_open_file_count; | ||||
| 22341 | #define OpenCounter(X) sqlite3_open_file_count+=(X) | ||||
| 22342 | #else | ||||
| 22343 | #define OpenCounter(X) | ||||
| 22344 | #endif /* defined(SQLITE_TEST) */ | ||||
| 22345 | |||||
| 22346 | #endif /* !defined(_OS_COMMON_H_) */ | ||||
| 22347 | |||||
| 22348 | /************** End of os_common.h *******************************************/ | ||||
| 22349 | /************** Begin file ctime.c *******************************************/ | ||||
| 22350 | /* DO NOT EDIT! | ||||
| 22351 | ** This file is automatically generated by the script in the canonical | ||||
| 22352 | ** SQLite source tree at tool/mkctimec.tcl. | ||||
| 22353 | ** | ||||
| 22354 | ** To modify this header, edit any of the various lists in that script | ||||
| 22355 | ** which specify categories of generated conditionals in this file. | ||||
| 22356 | */ | ||||
| 22357 | |||||
| 22358 | /* | ||||
| 22359 | ** 2010 February 23 | ||||
| 22360 | ** | ||||
| 22361 | ** The author disclaims copyright to this source code. In place of | ||||
| 22362 | ** a legal notice, here is a blessing: | ||||
| 22363 | ** | ||||
| 22364 | ** May you do good and not evil. | ||||
| 22365 | ** May you find forgiveness for yourself and forgive others. | ||||
| 22366 | ** May you share freely, never taking more than you give. | ||||
| 22367 | ** | ||||
| 22368 | ************************************************************************* | ||||
| 22369 | ** | ||||
| 22370 | ** This file implements routines used to report what compile-time options | ||||
| 22371 | ** SQLite was built with. | ||||
| 22372 | */ | ||||
| 22373 | #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */ | ||||
| 22374 | |||||
| 22375 | /* | ||||
| 22376 | ** Include the configuration header output by 'configure' if we're using the | ||||
| 22377 | ** autoconf-based build | ||||
| 22378 | */ | ||||
| 22379 | #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) | ||||
| 22380 | /* #include "sqlite_cfg.h" */ | ||||
| 22381 | #define SQLITECONFIG_H 1 | ||||
| 22382 | #endif | ||||
| 22383 | |||||
| 22384 | /* These macros are provided to "stringify" the value of the define | ||||
| 22385 | ** for those options in which the value is meaningful. */ | ||||
| 22386 | #define CTIMEOPT_VAL_(opt)"opt" #opt | ||||
| 22387 | #define CTIMEOPT_VAL(opt)"opt" CTIMEOPT_VAL_(opt)"opt" | ||||
| 22388 | |||||
| 22389 | /* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This | ||||
| 22390 | ** option requires a separate macro because legal values contain a single | ||||
| 22391 | ** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */ | ||||
| 22392 | #define CTIMEOPT_VAL2_(opt1,opt2)"opt1" "," "opt2" #opt1 "," #opt2 | ||||
| 22393 | #define CTIMEOPT_VAL2(opt)CTIMEOPT_VAL2_ CTIMEOPT_VAL2_(opt) | ||||
| 22394 | /* #include "sqliteInt.h" */ | ||||
| 22395 | |||||
| 22396 | /* | ||||
| 22397 | ** An array of names of all compile-time options. This array should | ||||
| 22398 | ** be sorted A-Z. | ||||
| 22399 | ** | ||||
| 22400 | ** This array looks large, but in a typical installation actually uses | ||||
| 22401 | ** only a handful of compile-time options, so most times this array is usually | ||||
| 22402 | ** rather short and uses little memory space. | ||||
| 22403 | */ | ||||
| 22404 | static const char * const sqlite3azCompileOpt[] = { | ||||
| 22405 | |||||
| 22406 | #ifdef SQLITE_32BIT_ROWID | ||||
| 22407 | "32BIT_ROWID", | ||||
| 22408 | #endif | ||||
| 22409 | #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC | ||||
| 22410 | "4_BYTE_ALIGNED_MALLOC", | ||||
| 22411 | #endif | ||||
| 22412 | #ifdef SQLITE_ALLOW_COVERING_INDEX_SCAN1 | ||||
| 22413 | # if SQLITE_ALLOW_COVERING_INDEX_SCAN1 != 1 | ||||
| 22414 | "ALLOW_COVERING_INDEX_SCAN=" CTIMEOPT_VAL(SQLITE_ALLOW_COVERING_INDEX_SCAN)"1", | ||||
| 22415 | # endif | ||||
| 22416 | #endif | ||||
| 22417 | #ifdef SQLITE_ALLOW_ROWID_IN_VIEW | ||||
| 22418 | "ALLOW_ROWID_IN_VIEW", | ||||
| 22419 | #endif | ||||
| 22420 | #ifdef SQLITE_ALLOW_URI_AUTHORITY | ||||
| 22421 | "ALLOW_URI_AUTHORITY", | ||||
| 22422 | #endif | ||||
| 22423 | #ifdef SQLITE_ATOMIC_INTRINSICS1 | ||||
| 22424 | "ATOMIC_INTRINSICS=" CTIMEOPT_VAL(SQLITE_ATOMIC_INTRINSICS)"1", | ||||
| 22425 | #endif | ||||
| 22426 | #ifdef SQLITE_BITMASK_TYPE | ||||
| 22427 | "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE)"SQLITE_BITMASK_TYPE", | ||||
| 22428 | #endif | ||||
| 22429 | #ifdef SQLITE_BUG_COMPATIBLE_20160819 | ||||
| 22430 | "BUG_COMPATIBLE_20160819", | ||||
| 22431 | #endif | ||||
| 22432 | #ifdef SQLITE_BUG_COMPATIBLE_20250510 | ||||
| 22433 | "BUG_COMPATIBLE_20250510", | ||||
| 22434 | #endif | ||||
| 22435 | #ifdef SQLITE_CASE_SENSITIVE_LIKE | ||||
| 22436 | "CASE_SENSITIVE_LIKE", | ||||
| 22437 | #endif | ||||
| 22438 | #ifdef SQLITE_CHECK_PAGES | ||||
| 22439 | "CHECK_PAGES", | ||||
| 22440 | #endif | ||||
| 22441 | #if defined(__clang__1) && defined(__clang_major__19) | ||||
| 22442 | "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__)"19" "." | ||||
| 22443 | CTIMEOPT_VAL(__clang_minor__)"1" "." | ||||
| 22444 | CTIMEOPT_VAL(__clang_patchlevel__)"2", | ||||
| 22445 | #elif defined(_MSC_VER) | ||||
| 22446 | "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER)"_MSC_VER", | ||||
| 22447 | #elif defined(__GNUC__4) && defined(__VERSION__"Clang 19.1.2") | ||||
| 22448 | "COMPILER=gcc-" __VERSION__"Clang 19.1.2", | ||||
| 22449 | #endif | ||||
| 22450 | #ifdef SQLITE_COVERAGE_TEST | ||||
| 22451 | "COVERAGE_TEST", | ||||
| 22452 | #endif | ||||
| 22453 | #ifdef SQLITE_DEBUG | ||||
| 22454 | "DEBUG", | ||||
| 22455 | #endif | ||||
| 22456 | #ifdef SQLITE_DEFAULT_AUTOMATIC_INDEX | ||||
| 22457 | "DEFAULT_AUTOMATIC_INDEX", | ||||
| 22458 | #endif | ||||
| 22459 | #ifdef SQLITE_DEFAULT_AUTOVACUUM0 | ||||
| 22460 | "DEFAULT_AUTOVACUUM", | ||||
| 22461 | #endif | ||||
| 22462 | #ifdef SQLITE_DEFAULT_CACHE_SIZE128 | ||||
| 22463 | "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE)"128", | ||||
| 22464 | #endif | ||||
| 22465 | #ifdef SQLITE_DEFAULT_CKPTFULLFSYNC1 | ||||
| 22466 | "DEFAULT_CKPTFULLFSYNC", | ||||
| 22467 | #endif | ||||
| 22468 | #ifdef SQLITE_DEFAULT_FILE_FORMAT4 | ||||
| 22469 | "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT)"4", | ||||
| 22470 | #endif | ||||
| 22471 | #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS0644 | ||||
| 22472 | "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS)"0644", | ||||
| 22473 | #endif | ||||
| 22474 | #ifdef SQLITE_DEFAULT_FOREIGN_KEYS | ||||
| 22475 | "DEFAULT_FOREIGN_KEYS", | ||||
| 22476 | #endif | ||||
| 22477 | #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT32768 | ||||
| 22478 | "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT)"32768", | ||||
| 22479 | #endif | ||||
| 22480 | #ifdef SQLITE_DEFAULT_LOCKING_MODE | ||||
| 22481 | "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE)"SQLITE_DEFAULT_LOCKING_MODE", | ||||
| 22482 | #endif | ||||
| 22483 | #ifdef SQLITE_DEFAULT_LOOKASIDE1200,40 | ||||
| 22484 | "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE)"1200" "," "40", | ||||
| 22485 | #endif | ||||
| 22486 | #ifdef SQLITE_DEFAULT_MEMSTATUS1 | ||||
| 22487 | # if SQLITE_DEFAULT_MEMSTATUS1 != 1 | ||||
| 22488 | "DEFAULT_MEMSTATUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_MEMSTATUS)"1", | ||||
| 22489 | # endif | ||||
| 22490 | #endif | ||||
| 22491 | #ifdef SQLITE_DEFAULT_MMAP_SIZE0 | ||||
| 22492 | "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE)"0", | ||||
| 22493 | #endif | ||||
| 22494 | #ifdef SQLITE_DEFAULT_PAGE_SIZE4096 | ||||
| 22495 | "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE)"4096", | ||||
| 22496 | #endif | ||||
| 22497 | #ifdef SQLITE_DEFAULT_PCACHE_INITSZ20 | ||||
| 22498 | "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ)"20", | ||||
| 22499 | #endif | ||||
| 22500 | #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS0755 | ||||
| 22501 | "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS)"0755", | ||||
| 22502 | #endif | ||||
| 22503 | #ifdef SQLITE_DEFAULT_RECURSIVE_TRIGGERS0 | ||||
| 22504 | "DEFAULT_RECURSIVE_TRIGGERS", | ||||
| 22505 | #endif | ||||
| 22506 | #ifdef SQLITE_DEFAULT_ROWEST | ||||
| 22507 | "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST)"SQLITE_DEFAULT_ROWEST", | ||||
| 22508 | #endif | ||||
| 22509 | #ifdef SQLITE_DEFAULT_SECTOR_SIZE4096 | ||||
| 22510 | "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE)"4096", | ||||
| 22511 | #endif | ||||
| 22512 | #ifdef SQLITE_DEFAULT_SYNCHRONOUS2 | ||||
| 22513 | "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS)"2", | ||||
| 22514 | #endif | ||||
| 22515 | #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT1000 | ||||
| 22516 | "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT)"1000", | ||||
| 22517 | #endif | ||||
| 22518 | #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS1 | ||||
| 22519 | "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS)"1", | ||||
| 22520 | #endif | ||||
| 22521 | #ifdef SQLITE_DEFAULT_WORKER_THREADS0 | ||||
| 22522 | "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS)"0", | ||||
| 22523 | #endif | ||||
| 22524 | #ifdef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 22525 | "DIRECT_OVERFLOW_READ", | ||||
| 22526 | #endif | ||||
| 22527 | #ifdef SQLITE_DISABLE_DIRSYNC | ||||
| 22528 | "DISABLE_DIRSYNC", | ||||
| 22529 | #endif | ||||
| 22530 | #ifdef SQLITE_DISABLE_FTS3_UNICODE | ||||
| 22531 | "DISABLE_FTS3_UNICODE", | ||||
| 22532 | #endif | ||||
| 22533 | #ifdef SQLITE_DISABLE_FTS4_DEFERRED | ||||
| 22534 | "DISABLE_FTS4_DEFERRED", | ||||
| 22535 | #endif | ||||
| 22536 | #ifdef SQLITE_DISABLE_INTRINSIC | ||||
| 22537 | "DISABLE_INTRINSIC", | ||||
| 22538 | #endif | ||||
| 22539 | #ifdef SQLITE_DISABLE_LFS | ||||
| 22540 | "DISABLE_LFS", | ||||
| 22541 | #endif | ||||
| 22542 | #ifdef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS | ||||
| 22543 | "DISABLE_PAGECACHE_OVERFLOW_STATS", | ||||
| 22544 | #endif | ||||
| 22545 | #ifdef SQLITE_DISABLE_SKIPAHEAD_DISTINCT | ||||
| 22546 | "DISABLE_SKIPAHEAD_DISTINCT", | ||||
| 22547 | #endif | ||||
| 22548 | #ifdef SQLITE_DQS0 | ||||
| 22549 | "DQS=" CTIMEOPT_VAL(SQLITE_DQS)"0", | ||||
| 22550 | #endif | ||||
| 22551 | #ifdef SQLITE_ENABLE_8_3_NAMES | ||||
| 22552 | "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES)"SQLITE_ENABLE_8_3_NAMES", | ||||
| 22553 | #endif | ||||
| 22554 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 22555 | "ENABLE_API_ARMOR", | ||||
| 22556 | #endif | ||||
| 22557 | #ifdef SQLITE_ENABLE_ATOMIC_WRITE | ||||
| 22558 | "ENABLE_ATOMIC_WRITE", | ||||
| 22559 | #endif | ||||
| 22560 | #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE | ||||
| 22561 | "ENABLE_BATCH_ATOMIC_WRITE", | ||||
| 22562 | #endif | ||||
| 22563 | #ifdef SQLITE_ENABLE_BYTECODE_VTAB | ||||
| 22564 | "ENABLE_BYTECODE_VTAB", | ||||
| 22565 | #endif | ||||
| 22566 | #ifdef SQLITE_ENABLE_CEROD | ||||
| 22567 | "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD)"SQLITE_ENABLE_CEROD", | ||||
| 22568 | #endif | ||||
| 22569 | #ifdef SQLITE_ENABLE_COLUMN_METADATA1 | ||||
| 22570 | "ENABLE_COLUMN_METADATA", | ||||
| 22571 | #endif | ||||
| 22572 | #ifdef SQLITE_ENABLE_COLUMN_USED_MASK | ||||
| 22573 | "ENABLE_COLUMN_USED_MASK", | ||||
| 22574 | #endif | ||||
| 22575 | #ifdef SQLITE_ENABLE_COSTMULT | ||||
| 22576 | "ENABLE_COSTMULT", | ||||
| 22577 | #endif | ||||
| 22578 | #ifdef SQLITE_ENABLE_CURSOR_HINTS | ||||
| 22579 | "ENABLE_CURSOR_HINTS", | ||||
| 22580 | #endif | ||||
| 22581 | #ifdef SQLITE_ENABLE_DBPAGE_VTAB | ||||
| 22582 | "ENABLE_DBPAGE_VTAB", | ||||
| 22583 | #endif | ||||
| 22584 | #ifdef SQLITE_ENABLE_DBSTAT_VTAB1 | ||||
| 22585 | "ENABLE_DBSTAT_VTAB", | ||||
| 22586 | #endif | ||||
| 22587 | #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT | ||||
| 22588 | "ENABLE_EXPENSIVE_ASSERT", | ||||
| 22589 | #endif | ||||
| 22590 | #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS | ||||
| 22591 | "ENABLE_EXPLAIN_COMMENTS", | ||||
| 22592 | #endif | ||||
| 22593 | #ifdef SQLITE_ENABLE_FTS31 | ||||
| 22594 | "ENABLE_FTS3", | ||||
| 22595 | #endif | ||||
| 22596 | #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS1 | ||||
| 22597 | "ENABLE_FTS3_PARENTHESIS", | ||||
| 22598 | #endif | ||||
| 22599 | #ifdef SQLITE_ENABLE_FTS3_TOKENIZER1 | ||||
| 22600 | "ENABLE_FTS3_TOKENIZER", | ||||
| 22601 | #endif | ||||
| 22602 | #ifdef SQLITE_ENABLE_FTS41 | ||||
| 22603 | "ENABLE_FTS4", | ||||
| 22604 | #endif | ||||
| 22605 | #ifdef SQLITE_ENABLE_FTS51 | ||||
| 22606 | "ENABLE_FTS5", | ||||
| 22607 | #endif | ||||
| 22608 | #ifdef SQLITE_ENABLE_GEOPOLY | ||||
| 22609 | "ENABLE_GEOPOLY", | ||||
| 22610 | #endif | ||||
| 22611 | #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS | ||||
| 22612 | "ENABLE_HIDDEN_COLUMNS", | ||||
| 22613 | #endif | ||||
| 22614 | #ifdef SQLITE_ENABLE_ICU | ||||
| 22615 | "ENABLE_ICU", | ||||
| 22616 | #endif | ||||
| 22617 | #ifdef SQLITE_ENABLE_IOTRACE | ||||
| 22618 | "ENABLE_IOTRACE", | ||||
| 22619 | #endif | ||||
| 22620 | #ifdef SQLITE_ENABLE_LOAD_EXTENSION | ||||
| 22621 | "ENABLE_LOAD_EXTENSION", | ||||
| 22622 | #endif | ||||
| 22623 | #ifdef SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 22624 | "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE)"0", | ||||
| 22625 | #endif | ||||
| 22626 | #ifdef SQLITE_ENABLE_MATH_FUNCTIONS1 | ||||
| 22627 | "ENABLE_MATH_FUNCTIONS", | ||||
| 22628 | #endif | ||||
| 22629 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 22630 | "ENABLE_MEMORY_MANAGEMENT", | ||||
| 22631 | #endif | ||||
| 22632 | #ifdef SQLITE_ENABLE_MEMSYS3 | ||||
| 22633 | "ENABLE_MEMSYS3", | ||||
| 22634 | #endif | ||||
| 22635 | #ifdef SQLITE_ENABLE_MEMSYS5 | ||||
| 22636 | "ENABLE_MEMSYS5", | ||||
| 22637 | #endif | ||||
| 22638 | #ifdef SQLITE_ENABLE_MULTIPLEX | ||||
| 22639 | "ENABLE_MULTIPLEX", | ||||
| 22640 | #endif | ||||
| 22641 | #ifdef SQLITE_ENABLE_NORMALIZE | ||||
| 22642 | "ENABLE_NORMALIZE", | ||||
| 22643 | #endif | ||||
| 22644 | #ifdef SQLITE_ENABLE_NULL_TRIM | ||||
| 22645 | "ENABLE_NULL_TRIM", | ||||
| 22646 | #endif | ||||
| 22647 | #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC | ||||
| 22648 | "ENABLE_OFFSET_SQL_FUNC", | ||||
| 22649 | #endif | ||||
| 22650 | #ifdef SQLITE_ENABLE_ORDERED_SET_AGGREGATES | ||||
| 22651 | "ENABLE_ORDERED_SET_AGGREGATES", | ||||
| 22652 | #endif | ||||
| 22653 | #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK | ||||
| 22654 | "ENABLE_OVERSIZE_CELL_CHECK", | ||||
| 22655 | #endif | ||||
| 22656 | #ifdef SQLITE_ENABLE_PREUPDATE_HOOK1 | ||||
| 22657 | "ENABLE_PREUPDATE_HOOK", | ||||
| 22658 | #endif | ||||
| 22659 | #ifdef SQLITE_ENABLE_QPSG | ||||
| 22660 | "ENABLE_QPSG", | ||||
| 22661 | #endif | ||||
| 22662 | #ifdef SQLITE_ENABLE_RBU | ||||
| 22663 | "ENABLE_RBU", | ||||
| 22664 | #endif | ||||
| 22665 | #ifdef SQLITE_ENABLE_RTREE1 | ||||
| 22666 | "ENABLE_RTREE", | ||||
| 22667 | #endif | ||||
| 22668 | #ifdef SQLITE_ENABLE_SESSION1 | ||||
| 22669 | "ENABLE_SESSION", | ||||
| 22670 | #endif | ||||
| 22671 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 22672 | "ENABLE_SETLK_TIMEOUT", | ||||
| 22673 | #endif | ||||
| 22674 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 22675 | "ENABLE_SNAPSHOT", | ||||
| 22676 | #endif | ||||
| 22677 | #ifdef SQLITE_ENABLE_SORTER_REFERENCES | ||||
| 22678 | "ENABLE_SORTER_REFERENCES", | ||||
| 22679 | #endif | ||||
| 22680 | #ifdef SQLITE_ENABLE_SQLLOG | ||||
| 22681 | "ENABLE_SQLLOG", | ||||
| 22682 | #endif | ||||
| 22683 | #ifdef SQLITE_ENABLE_STAT4 | ||||
| 22684 | "ENABLE_STAT4", | ||||
| 22685 | #endif | ||||
| 22686 | #ifdef SQLITE_ENABLE_STMTVTAB | ||||
| 22687 | "ENABLE_STMTVTAB", | ||||
| 22688 | #endif | ||||
| 22689 | #ifdef SQLITE_ENABLE_STMT_SCANSTATUS1 | ||||
| 22690 | "ENABLE_STMT_SCANSTATUS", | ||||
| 22691 | #endif | ||||
| 22692 | #ifdef SQLITE_ENABLE_TREETRACE | ||||
| 22693 | "ENABLE_TREETRACE", | ||||
| 22694 | #endif | ||||
| 22695 | #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION1 | ||||
| 22696 | "ENABLE_UNKNOWN_SQL_FUNCTION", | ||||
| 22697 | #endif | ||||
| 22698 | #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY | ||||
| 22699 | "ENABLE_UNLOCK_NOTIFY", | ||||
| 22700 | #endif | ||||
| 22701 | #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT1 | ||||
| 22702 | "ENABLE_UPDATE_DELETE_LIMIT", | ||||
| 22703 | #endif | ||||
| 22704 | #ifdef SQLITE_ENABLE_URI_00_ERROR | ||||
| 22705 | "ENABLE_URI_00_ERROR", | ||||
| 22706 | #endif | ||||
| 22707 | #ifdef SQLITE_ENABLE_VFSTRACE | ||||
| 22708 | "ENABLE_VFSTRACE", | ||||
| 22709 | #endif | ||||
| 22710 | #ifdef SQLITE_ENABLE_WHERETRACE | ||||
| 22711 | "ENABLE_WHERETRACE", | ||||
| 22712 | #endif | ||||
| 22713 | #ifdef SQLITE_ENABLE_ZIPVFS | ||||
| 22714 | "ENABLE_ZIPVFS", | ||||
| 22715 | #endif | ||||
| 22716 | #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS | ||||
| 22717 | "EXPLAIN_ESTIMATED_ROWS", | ||||
| 22718 | #endif | ||||
| 22719 | #ifdef SQLITE_EXTRA_AUTOEXT | ||||
| 22720 | "EXTRA_AUTOEXT=" CTIMEOPT_VAL(SQLITE_EXTRA_AUTOEXT)"SQLITE_EXTRA_AUTOEXT", | ||||
| 22721 | #endif | ||||
| 22722 | #ifdef SQLITE_EXTRA_IFNULLROW | ||||
| 22723 | "EXTRA_IFNULLROW", | ||||
| 22724 | #endif | ||||
| 22725 | #ifdef SQLITE_EXTRA_INIT | ||||
| 22726 | "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT)"SQLITE_EXTRA_INIT", | ||||
| 22727 | #endif | ||||
| 22728 | #ifdef SQLITE_EXTRA_INIT_MUTEXED | ||||
| 22729 | "EXTRA_INIT_MUTEXED=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT_MUTEXED)"SQLITE_EXTRA_INIT_MUTEXED", | ||||
| 22730 | #endif | ||||
| 22731 | #ifdef SQLITE_EXTRA_SHUTDOWN | ||||
| 22732 | "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN)"SQLITE_EXTRA_SHUTDOWN", | ||||
| 22733 | #endif | ||||
| 22734 | #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH12 | ||||
| 22735 | "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH)"12", | ||||
| 22736 | #endif | ||||
| 22737 | #ifdef SQLITE_FTS5_ENABLE_TEST_MI | ||||
| 22738 | "FTS5_ENABLE_TEST_MI", | ||||
| 22739 | #endif | ||||
| 22740 | #ifdef SQLITE_FTS5_NO_WITHOUT_ROWID | ||||
| 22741 | "FTS5_NO_WITHOUT_ROWID", | ||||
| 22742 | #endif | ||||
| 22743 | #if HAVE_ISNAN || SQLITE_HAVE_ISNAN1 | ||||
| 22744 | "HAVE_ISNAN", | ||||
| 22745 | #endif | ||||
| 22746 | #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX | ||||
| 22747 | # if SQLITE_HOMEGROWN_RECURSIVE_MUTEX != 1 | ||||
| 22748 | "HOMEGROWN_RECURSIVE_MUTEX=" CTIMEOPT_VAL(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)"SQLITE_HOMEGROWN_RECURSIVE_MUTEX", | ||||
| 22749 | # endif | ||||
| 22750 | #endif | ||||
| 22751 | #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS | ||||
| 22752 | "IGNORE_AFP_LOCK_ERRORS", | ||||
| 22753 | #endif | ||||
| 22754 | #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS | ||||
| 22755 | "IGNORE_FLOCK_LOCK_ERRORS", | ||||
| 22756 | #endif | ||||
| 22757 | #ifdef SQLITE_INLINE_MEMCPY | ||||
| 22758 | "INLINE_MEMCPY", | ||||
| 22759 | #endif | ||||
| 22760 | #ifdef SQLITE_INT64_TYPE | ||||
| 22761 | "INT64_TYPE", | ||||
| 22762 | #endif | ||||
| 22763 | #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX100 | ||||
| 22764 | "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX)"100", | ||||
| 22765 | #endif | ||||
| 22766 | #ifdef SQLITE_LEGACY_JSON_VALID | ||||
| 22767 | "LEGACY_JSON_VALID", | ||||
| 22768 | #endif | ||||
| 22769 | #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS | ||||
| 22770 | "LIKE_DOESNT_MATCH_BLOBS", | ||||
| 22771 | #endif | ||||
| 22772 | #ifdef SQLITE_LOCK_TRACE | ||||
| 22773 | "LOCK_TRACE", | ||||
| 22774 | #endif | ||||
| 22775 | #ifdef SQLITE_LOG_CACHE_SPILL | ||||
| 22776 | "LOG_CACHE_SPILL", | ||||
| 22777 | #endif | ||||
| 22778 | #ifdef SQLITE_MALLOC_SOFT_LIMIT1024 | ||||
| 22779 | "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT)"1024", | ||||
| 22780 | #endif | ||||
| 22781 | #ifdef SQLITE_MAX_ATTACHED10 | ||||
| 22782 | "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED)"10", | ||||
| 22783 | #endif | ||||
| 22784 | #ifdef SQLITE_MAX_COLUMN2000 | ||||
| 22785 | "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN)"2000", | ||||
| 22786 | #endif | ||||
| 22787 | #ifdef SQLITE_MAX_COMPOUND_SELECT500 | ||||
| 22788 | "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT)"500", | ||||
| 22789 | #endif | ||||
| 22790 | #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE8192 | ||||
| 22791 | "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE)"8192", | ||||
| 22792 | #endif | ||||
| 22793 | #ifdef SQLITE_MAX_EXPR_DEPTH1000 | ||||
| 22794 | "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH)"1000", | ||||
| 22795 | #endif | ||||
| 22796 | #ifdef SQLITE_MAX_FUNCTION_ARG1000 | ||||
| 22797 | "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG)"1000", | ||||
| 22798 | #endif | ||||
| 22799 | #ifdef SQLITE_MAX_LENGTH2147483645 | ||||
| 22800 | "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH)"2147483645", | ||||
| 22801 | #endif | ||||
| 22802 | #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH50000 | ||||
| 22803 | "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH)"50000", | ||||
| 22804 | #endif | ||||
| 22805 | #ifdef SQLITE_MAX_MEMORY0 | ||||
| 22806 | "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY)"0", | ||||
| 22807 | #endif | ||||
| 22808 | #ifdef SQLITE_MAX_MMAP_SIZE20971520 | ||||
| 22809 | "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE)"20971520", | ||||
| 22810 | #endif | ||||
| 22811 | #ifdef SQLITE_MAX_MMAP_SIZE_ | ||||
| 22812 | "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_)"SQLITE_MAX_MMAP_SIZE_", | ||||
| 22813 | #endif | ||||
| 22814 | #ifdef SQLITE_MAX_PAGE_COUNT0xfffffffe | ||||
| 22815 | "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT)"0xfffffffe", | ||||
| 22816 | #endif | ||||
| 22817 | #ifdef SQLITE_MAX_PAGE_SIZE65536 | ||||
| 22818 | "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE)"65536", | ||||
| 22819 | #endif | ||||
| 22820 | #ifdef SQLITE_MAX_SCHEMA_RETRY50 | ||||
| 22821 | "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY)"50", | ||||
| 22822 | #endif | ||||
| 22823 | #ifdef SQLITE_MAX_SQL_LENGTH1000000000 | ||||
| 22824 | "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH)"1000000000", | ||||
| 22825 | #endif | ||||
| 22826 | #ifdef SQLITE_MAX_TRIGGER_DEPTH1000 | ||||
| 22827 | "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH)"1000", | ||||
| 22828 | #endif | ||||
| 22829 | #ifdef SQLITE_MAX_VARIABLE_NUMBER500000 | ||||
| 22830 | "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER)"500000", | ||||
| 22831 | #endif | ||||
| 22832 | #ifdef SQLITE_MAX_VDBE_OP250000000 | ||||
| 22833 | "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP)"250000000", | ||||
| 22834 | #endif | ||||
| 22835 | #ifdef SQLITE_MAX_WORKER_THREADS8 | ||||
| 22836 | "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS)"8", | ||||
| 22837 | #endif | ||||
| 22838 | #ifdef SQLITE_MEMDEBUG | ||||
| 22839 | "MEMDEBUG", | ||||
| 22840 | #endif | ||||
| 22841 | #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT | ||||
| 22842 | "MIXED_ENDIAN_64BIT_FLOAT", | ||||
| 22843 | #endif | ||||
| 22844 | #ifdef SQLITE_MMAP_READWRITE | ||||
| 22845 | "MMAP_READWRITE", | ||||
| 22846 | #endif | ||||
| 22847 | #ifdef SQLITE_MUTEX_NOOP | ||||
| 22848 | "MUTEX_NOOP", | ||||
| 22849 | #endif | ||||
| 22850 | #ifdef SQLITE_MUTEX_OMIT | ||||
| 22851 | "MUTEX_OMIT", | ||||
| 22852 | #endif | ||||
| 22853 | #ifdef SQLITE_MUTEX_PTHREADS | ||||
| 22854 | "MUTEX_PTHREADS", | ||||
| 22855 | #endif | ||||
| 22856 | #ifdef SQLITE_MUTEX_W32 | ||||
| 22857 | "MUTEX_W32", | ||||
| 22858 | #endif | ||||
| 22859 | #ifdef SQLITE_NEED_ERR_NAME | ||||
| 22860 | "NEED_ERR_NAME", | ||||
| 22861 | #endif | ||||
| 22862 | #ifdef SQLITE_NO_SYNC | ||||
| 22863 | "NO_SYNC", | ||||
| 22864 | #endif | ||||
| 22865 | #ifdef SQLITE_OMIT_ALTERTABLE | ||||
| 22866 | "OMIT_ALTERTABLE", | ||||
| 22867 | #endif | ||||
| 22868 | #ifdef SQLITE_OMIT_ANALYZE | ||||
| 22869 | "OMIT_ANALYZE", | ||||
| 22870 | #endif | ||||
| 22871 | #ifdef SQLITE_OMIT_ATTACH | ||||
| 22872 | "OMIT_ATTACH", | ||||
| 22873 | #endif | ||||
| 22874 | #ifdef SQLITE_OMIT_AUTHORIZATION | ||||
| 22875 | "OMIT_AUTHORIZATION", | ||||
| 22876 | #endif | ||||
| 22877 | #ifdef SQLITE_OMIT_AUTOINCREMENT | ||||
| 22878 | "OMIT_AUTOINCREMENT", | ||||
| 22879 | #endif | ||||
| 22880 | #ifdef SQLITE_OMIT_AUTOINIT | ||||
| 22881 | "OMIT_AUTOINIT", | ||||
| 22882 | #endif | ||||
| 22883 | #ifdef SQLITE_OMIT_AUTOMATIC_INDEX | ||||
| 22884 | "OMIT_AUTOMATIC_INDEX", | ||||
| 22885 | #endif | ||||
| 22886 | #ifdef SQLITE_OMIT_AUTORESET1 | ||||
| 22887 | "OMIT_AUTORESET", | ||||
| 22888 | #endif | ||||
| 22889 | #ifdef SQLITE_OMIT_AUTOVACUUM | ||||
| 22890 | "OMIT_AUTOVACUUM", | ||||
| 22891 | #endif | ||||
| 22892 | #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION | ||||
| 22893 | "OMIT_BETWEEN_OPTIMIZATION", | ||||
| 22894 | #endif | ||||
| 22895 | #ifdef SQLITE_OMIT_BLOB_LITERAL | ||||
| 22896 | "OMIT_BLOB_LITERAL", | ||||
| 22897 | #endif | ||||
| 22898 | #ifdef SQLITE_OMIT_CAST | ||||
| 22899 | "OMIT_CAST", | ||||
| 22900 | #endif | ||||
| 22901 | #ifdef SQLITE_OMIT_CHECK | ||||
| 22902 | "OMIT_CHECK", | ||||
| 22903 | #endif | ||||
| 22904 | #ifdef SQLITE_OMIT_COMPLETE | ||||
| 22905 | "OMIT_COMPLETE", | ||||
| 22906 | #endif | ||||
| 22907 | #ifdef SQLITE_OMIT_COMPOUND_SELECT | ||||
| 22908 | "OMIT_COMPOUND_SELECT", | ||||
| 22909 | #endif | ||||
| 22910 | #ifdef SQLITE_OMIT_CONFLICT_CLAUSE | ||||
| 22911 | "OMIT_CONFLICT_CLAUSE", | ||||
| 22912 | #endif | ||||
| 22913 | #ifdef SQLITE_OMIT_CTE | ||||
| 22914 | "OMIT_CTE", | ||||
| 22915 | #endif | ||||
| 22916 | #if defined(SQLITE_OMIT_DATETIME_FUNCS) || defined(SQLITE_OMIT_FLOATING_POINT) | ||||
| 22917 | "OMIT_DATETIME_FUNCS", | ||||
| 22918 | #endif | ||||
| 22919 | #ifdef SQLITE_OMIT_DECLTYPE | ||||
| 22920 | "OMIT_DECLTYPE", | ||||
| 22921 | #endif | ||||
| 22922 | #ifdef SQLITE_OMIT_DEPRECATED1 | ||||
| 22923 | "OMIT_DEPRECATED", | ||||
| 22924 | #endif | ||||
| 22925 | #ifdef SQLITE_OMIT_DESERIALIZE | ||||
| 22926 | "OMIT_DESERIALIZE", | ||||
| 22927 | #endif | ||||
| 22928 | #ifdef SQLITE_OMIT_DISKIO | ||||
| 22929 | "OMIT_DISKIO", | ||||
| 22930 | #endif | ||||
| 22931 | #ifdef SQLITE_OMIT_EXPLAIN | ||||
| 22932 | "OMIT_EXPLAIN", | ||||
| 22933 | #endif | ||||
| 22934 | #ifdef SQLITE_OMIT_FLAG_PRAGMAS | ||||
| 22935 | "OMIT_FLAG_PRAGMAS", | ||||
| 22936 | #endif | ||||
| 22937 | #ifdef SQLITE_OMIT_FLOATING_POINT | ||||
| 22938 | "OMIT_FLOATING_POINT", | ||||
| 22939 | #endif | ||||
| 22940 | #ifdef SQLITE_OMIT_FOREIGN_KEY | ||||
| 22941 | "OMIT_FOREIGN_KEY", | ||||
| 22942 | #endif | ||||
| 22943 | #ifdef SQLITE_OMIT_GET_TABLE | ||||
| 22944 | "OMIT_GET_TABLE", | ||||
| 22945 | #endif | ||||
| 22946 | #ifdef SQLITE_OMIT_HEX_INTEGER | ||||
| 22947 | "OMIT_HEX_INTEGER", | ||||
| 22948 | #endif | ||||
| 22949 | #ifdef SQLITE_OMIT_INCRBLOB | ||||
| 22950 | "OMIT_INCRBLOB", | ||||
| 22951 | #endif | ||||
| 22952 | #ifdef SQLITE_OMIT_INTEGRITY_CHECK | ||||
| 22953 | "OMIT_INTEGRITY_CHECK", | ||||
| 22954 | #endif | ||||
| 22955 | #ifdef SQLITE_OMIT_INTROSPECTION_PRAGMAS | ||||
| 22956 | "OMIT_INTROSPECTION_PRAGMAS", | ||||
| 22957 | #endif | ||||
| 22958 | #ifdef SQLITE_OMIT_JSON | ||||
| 22959 | "OMIT_JSON", | ||||
| 22960 | #endif | ||||
| 22961 | #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION | ||||
| 22962 | "OMIT_LIKE_OPTIMIZATION", | ||||
| 22963 | #endif | ||||
| 22964 | #ifdef SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 22965 | "OMIT_LOAD_EXTENSION", | ||||
| 22966 | #endif | ||||
| 22967 | #ifdef SQLITE_OMIT_LOCALTIME | ||||
| 22968 | "OMIT_LOCALTIME", | ||||
| 22969 | #endif | ||||
| 22970 | #ifdef SQLITE_OMIT_LOOKASIDE | ||||
| 22971 | "OMIT_LOOKASIDE", | ||||
| 22972 | #endif | ||||
| 22973 | #ifdef SQLITE_OMIT_MEMORYDB | ||||
| 22974 | "OMIT_MEMORYDB", | ||||
| 22975 | #endif | ||||
| 22976 | #ifdef SQLITE_OMIT_OR_OPTIMIZATION | ||||
| 22977 | "OMIT_OR_OPTIMIZATION", | ||||
| 22978 | #endif | ||||
| 22979 | #ifdef SQLITE_OMIT_PAGER_PRAGMAS | ||||
| 22980 | "OMIT_PAGER_PRAGMAS", | ||||
| 22981 | #endif | ||||
| 22982 | #ifdef SQLITE_OMIT_PARSER_TRACE | ||||
| 22983 | "OMIT_PARSER_TRACE", | ||||
| 22984 | #endif | ||||
| 22985 | #ifdef SQLITE_OMIT_POPEN | ||||
| 22986 | "OMIT_POPEN", | ||||
| 22987 | #endif | ||||
| 22988 | #ifdef SQLITE_OMIT_PRAGMA | ||||
| 22989 | "OMIT_PRAGMA", | ||||
| 22990 | #endif | ||||
| 22991 | #ifdef SQLITE_OMIT_PROGRESS_CALLBACK1 | ||||
| 22992 | "OMIT_PROGRESS_CALLBACK", | ||||
| 22993 | #endif | ||||
| 22994 | #ifdef SQLITE_OMIT_QUICKBALANCE | ||||
| 22995 | "OMIT_QUICKBALANCE", | ||||
| 22996 | #endif | ||||
| 22997 | #ifdef SQLITE_OMIT_REINDEX | ||||
| 22998 | "OMIT_REINDEX", | ||||
| 22999 | #endif | ||||
| 23000 | #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS | ||||
| 23001 | "OMIT_SCHEMA_PRAGMAS", | ||||
| 23002 | #endif | ||||
| 23003 | #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS | ||||
| 23004 | "OMIT_SCHEMA_VERSION_PRAGMAS", | ||||
| 23005 | #endif | ||||
| 23006 | #ifdef SQLITE_OMIT_SEH | ||||
| 23007 | "OMIT_SEH", | ||||
| 23008 | #endif | ||||
| 23009 | #ifdef SQLITE_OMIT_SHARED_CACHE | ||||
| 23010 | "OMIT_SHARED_CACHE", | ||||
| 23011 | #endif | ||||
| 23012 | #ifdef SQLITE_OMIT_SHUTDOWN_DIRECTORIES | ||||
| 23013 | "OMIT_SHUTDOWN_DIRECTORIES", | ||||
| 23014 | #endif | ||||
| 23015 | #ifdef SQLITE_OMIT_SUBQUERY | ||||
| 23016 | "OMIT_SUBQUERY", | ||||
| 23017 | #endif | ||||
| 23018 | #ifdef SQLITE_OMIT_TCL_VARIABLE | ||||
| 23019 | "OMIT_TCL_VARIABLE", | ||||
| 23020 | #endif | ||||
| 23021 | #ifdef SQLITE_OMIT_TEMPDB | ||||
| 23022 | "OMIT_TEMPDB", | ||||
| 23023 | #endif | ||||
| 23024 | #ifdef SQLITE_OMIT_TEST_CONTROL | ||||
| 23025 | "OMIT_TEST_CONTROL", | ||||
| 23026 | #endif | ||||
| 23027 | #ifdef SQLITE_OMIT_TRACE | ||||
| 23028 | # if SQLITE_OMIT_TRACE != 1 | ||||
| 23029 | "OMIT_TRACE=" CTIMEOPT_VAL(SQLITE_OMIT_TRACE)"SQLITE_OMIT_TRACE", | ||||
| 23030 | # endif | ||||
| 23031 | #endif | ||||
| 23032 | #ifdef SQLITE_OMIT_TRIGGER | ||||
| 23033 | "OMIT_TRIGGER", | ||||
| 23034 | #endif | ||||
| 23035 | #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION | ||||
| 23036 | "OMIT_TRUNCATE_OPTIMIZATION", | ||||
| 23037 | #endif | ||||
| 23038 | #ifdef SQLITE_OMIT_UTF16 | ||||
| 23039 | "OMIT_UTF16", | ||||
| 23040 | #endif | ||||
| 23041 | #ifdef SQLITE_OMIT_VACUUM | ||||
| 23042 | "OMIT_VACUUM", | ||||
| 23043 | #endif | ||||
| 23044 | #ifdef SQLITE_OMIT_VIEW | ||||
| 23045 | "OMIT_VIEW", | ||||
| 23046 | #endif | ||||
| 23047 | #ifdef SQLITE_OMIT_VIRTUALTABLE | ||||
| 23048 | "OMIT_VIRTUALTABLE", | ||||
| 23049 | #endif | ||||
| 23050 | #ifdef SQLITE_OMIT_WAL | ||||
| 23051 | "OMIT_WAL", | ||||
| 23052 | #endif | ||||
| 23053 | #ifdef SQLITE_OMIT_WSD | ||||
| 23054 | "OMIT_WSD", | ||||
| 23055 | #endif | ||||
| 23056 | #ifdef SQLITE_OMIT_XFER_OPT | ||||
| 23057 | "OMIT_XFER_OPT", | ||||
| 23058 | #endif | ||||
| 23059 | #ifdef SQLITE_PERFORMANCE_TRACE | ||||
| 23060 | "PERFORMANCE_TRACE", | ||||
| 23061 | #endif | ||||
| 23062 | #ifdef SQLITE_POWERSAFE_OVERWRITE1 | ||||
| 23063 | # if SQLITE_POWERSAFE_OVERWRITE1 != 1 | ||||
| 23064 | "POWERSAFE_OVERWRITE=" CTIMEOPT_VAL(SQLITE_POWERSAFE_OVERWRITE)"1", | ||||
| 23065 | # endif | ||||
| 23066 | #endif | ||||
| 23067 | #ifdef SQLITE_PREFER_PROXY_LOCKING | ||||
| 23068 | "PREFER_PROXY_LOCKING", | ||||
| 23069 | #endif | ||||
| 23070 | #ifdef SQLITE_PROXY_DEBUG | ||||
| 23071 | "PROXY_DEBUG", | ||||
| 23072 | #endif | ||||
| 23073 | #ifdef SQLITE_REVERSE_UNORDERED_SELECTS | ||||
| 23074 | "REVERSE_UNORDERED_SELECTS", | ||||
| 23075 | #endif | ||||
| 23076 | #ifdef SQLITE_RTREE_INT_ONLY | ||||
| 23077 | "RTREE_INT_ONLY", | ||||
| 23078 | #endif | ||||
| 23079 | #ifdef SQLITE_SECURE_DELETE | ||||
| 23080 | "SECURE_DELETE", | ||||
| 23081 | #endif | ||||
| 23082 | #ifdef SQLITE_SMALL_STACK | ||||
| 23083 | "SMALL_STACK", | ||||
| 23084 | #endif | ||||
| 23085 | #ifdef SQLITE_SORTER_PMASZ250 | ||||
| 23086 | "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ)"250", | ||||
| 23087 | #endif | ||||
| 23088 | #ifdef SQLITE_SOUNDEX | ||||
| 23089 | "SOUNDEX", | ||||
| 23090 | #endif | ||||
| 23091 | #ifdef SQLITE_STAT4_SAMPLES1 | ||||
| 23092 | "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES)"1", | ||||
| 23093 | #endif | ||||
| 23094 | #ifdef SQLITE_STMTJRNL_SPILL131072 | ||||
| 23095 | "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL)"131072", | ||||
| 23096 | #endif | ||||
| 23097 | #ifdef SQLITE_SUBSTR_COMPATIBILITY1 | ||||
| 23098 | "SUBSTR_COMPATIBILITY", | ||||
| 23099 | #endif | ||||
| 23100 | #if (!defined(SQLITE_WIN32_MALLOC) \ | ||||
| 23101 | && !defined(SQLITE_ZERO_MALLOC) \ | ||||
| 23102 | && !defined(SQLITE_MEMDEBUG) \ | ||||
| 23103 | ) || defined(SQLITE_SYSTEM_MALLOC1) | ||||
| 23104 | "SYSTEM_MALLOC", | ||||
| 23105 | #endif | ||||
| 23106 | #ifdef SQLITE_TCL | ||||
| 23107 | "TCL", | ||||
| 23108 | #endif | ||||
| 23109 | #ifdef SQLITE_TEMP_STORE1 | ||||
| 23110 | "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE)"1", | ||||
| 23111 | #endif | ||||
| 23112 | #ifdef SQLITE_TEST | ||||
| 23113 | "TEST", | ||||
| 23114 | #endif | ||||
| 23115 | #if defined(SQLITE_THREADSAFE2) | ||||
| 23116 | "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE)"2", | ||||
| 23117 | #elif defined(THREADSAFE) | ||||
| 23118 | "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE)"THREADSAFE", | ||||
| 23119 | #else | ||||
| 23120 | "THREADSAFE=1", | ||||
| 23121 | #endif | ||||
| 23122 | #ifdef SQLITE_UNLINK_AFTER_CLOSE | ||||
| 23123 | "UNLINK_AFTER_CLOSE", | ||||
| 23124 | #endif | ||||
| 23125 | #ifdef SQLITE_UNTESTABLE | ||||
| 23126 | "UNTESTABLE", | ||||
| 23127 | #endif | ||||
| 23128 | #ifdef SQLITE_USE_ALLOCA | ||||
| 23129 | "USE_ALLOCA", | ||||
| 23130 | #endif | ||||
| 23131 | #ifdef SQLITE_USE_FCNTL_TRACE | ||||
| 23132 | "USE_FCNTL_TRACE", | ||||
| 23133 | #endif | ||||
| 23134 | #ifdef SQLITE_USE_URI1 | ||||
| 23135 | "USE_URI", | ||||
| 23136 | #endif | ||||
| 23137 | #ifdef SQLITE_VDBE_COVERAGE | ||||
| 23138 | "VDBE_COVERAGE", | ||||
| 23139 | #endif | ||||
| 23140 | #ifdef SQLITE_WIN32_MALLOC | ||||
| 23141 | "WIN32_MALLOC", | ||||
| 23142 | #endif | ||||
| 23143 | #ifdef SQLITE_ZERO_MALLOC | ||||
| 23144 | "ZERO_MALLOC", | ||||
| 23145 | #endif | ||||
| 23146 | |||||
| 23147 | } ; | ||||
| 23148 | |||||
| 23149 | SQLITE_PRIVATEstatic const char **sqlite3CompileOptions(int *pnOpt){ | ||||
| 23150 | *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]); | ||||
| 23151 | return (const char**)sqlite3azCompileOpt; | ||||
| 23152 | } | ||||
| 23153 | |||||
| 23154 | #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ | ||||
| 23155 | |||||
| 23156 | /************** End of ctime.c ***********************************************/ | ||||
| 23157 | /************** Begin file global.c ******************************************/ | ||||
| 23158 | /* | ||||
| 23159 | ** 2008 June 13 | ||||
| 23160 | ** | ||||
| 23161 | ** The author disclaims copyright to this source code. In place of | ||||
| 23162 | ** a legal notice, here is a blessing: | ||||
| 23163 | ** | ||||
| 23164 | ** May you do good and not evil. | ||||
| 23165 | ** May you find forgiveness for yourself and forgive others. | ||||
| 23166 | ** May you share freely, never taking more than you give. | ||||
| 23167 | ** | ||||
| 23168 | ************************************************************************* | ||||
| 23169 | ** | ||||
| 23170 | ** This file contains definitions of global variables and constants. | ||||
| 23171 | */ | ||||
| 23172 | /* #include "sqliteInt.h" */ | ||||
| 23173 | |||||
| 23174 | /* An array to map all upper-case characters into their corresponding | ||||
| 23175 | ** lower-case character. | ||||
| 23176 | ** | ||||
| 23177 | ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not | ||||
| 23178 | ** handle case conversions for the UTF character set since the tables | ||||
| 23179 | ** involved are nearly as big or bigger than SQLite itself. | ||||
| 23180 | */ | ||||
| 23181 | SQLITE_PRIVATEstatic const unsigned char sqlite3UpperToLower[] = { | ||||
| 23182 | #ifdef SQLITE_ASCII1 | ||||
| 23183 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, | ||||
| 23184 | 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, | ||||
| 23185 | 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, | ||||
| 23186 | 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, | ||||
| 23187 | 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, | ||||
| 23188 | 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, | ||||
| 23189 | 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, | ||||
| 23190 | 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, | ||||
| 23191 | 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, | ||||
| 23192 | 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, | ||||
| 23193 | 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, | ||||
| 23194 | 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, | ||||
| 23195 | 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, | ||||
| 23196 | 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, | ||||
| 23197 | 252,253,254,255, | ||||
| 23198 | #endif | ||||
| 23199 | #ifdef SQLITE_EBCDIC | ||||
| 23200 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */ | ||||
| 23201 | 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */ | ||||
| 23202 | 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */ | ||||
| 23203 | 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */ | ||||
| 23204 | 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */ | ||||
| 23205 | 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */ | ||||
| 23206 | 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */ | ||||
| 23207 | 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */ | ||||
| 23208 | 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */ | ||||
| 23209 | 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */ | ||||
| 23210 | 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */ | ||||
| 23211 | 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */ | ||||
| 23212 | 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */ | ||||
| 23213 | 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */ | ||||
| 23214 | 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */ | ||||
| 23215 | 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */ | ||||
| 23216 | #endif | ||||
| 23217 | /* All of the upper-to-lower conversion data is above. The following | ||||
| 23218 | ** 18 integers are completely unrelated. They are appended to the | ||||
| 23219 | ** sqlite3UpperToLower[] array to avoid UBSAN warnings. Here's what is | ||||
| 23220 | ** going on: | ||||
| 23221 | ** | ||||
| 23222 | ** The SQL comparison operators (<>, =, >, <=, <, and >=) are implemented | ||||
| 23223 | ** by invoking sqlite3MemCompare(A,B) which compares values A and B and | ||||
| 23224 | ** returns negative, zero, or positive if A is less then, equal to, or | ||||
| 23225 | ** greater than B, respectively. Then the true false results is found by | ||||
| 23226 | ** consulting sqlite3aLTb[opcode], sqlite3aEQb[opcode], or | ||||
| 23227 | ** sqlite3aGTb[opcode] depending on whether the result of compare(A,B) | ||||
| 23228 | ** is negative, zero, or positive, where opcode is the specific opcode. | ||||
| 23229 | ** The only works because the comparison opcodes are consecutive and in | ||||
| 23230 | ** this order: NE EQ GT LE LT GE. Various assert()s throughout the code | ||||
| 23231 | ** ensure that is the case. | ||||
| 23232 | ** | ||||
| 23233 | ** These elements must be appended to another array. Otherwise the | ||||
| 23234 | ** index (here shown as [256-OP_Ne]) would be out-of-bounds and thus | ||||
| 23235 | ** be undefined behavior. That's goofy, but the C-standards people thought | ||||
| 23236 | ** it was a good idea, so here we are. | ||||
| 23237 | */ | ||||
| 23238 | /* NE EQ GT LE LT GE */ | ||||
| 23239 | 1, 0, 0, 1, 1, 0, /* aLTb[]: Use when compare(A,B) less than zero */ | ||||
| 23240 | 0, 1, 0, 1, 0, 1, /* aEQb[]: Use when compare(A,B) equals zero */ | ||||
| 23241 | 1, 0, 1, 0, 0, 1 /* aGTb[]: Use when compare(A,B) greater than zero*/ | ||||
| 23242 | }; | ||||
| 23243 | SQLITE_PRIVATEstatic const unsigned char *sqlite3aLTb = &sqlite3UpperToLower[256-OP_Ne53]; | ||||
| 23244 | SQLITE_PRIVATEstatic const unsigned char *sqlite3aEQb = &sqlite3UpperToLower[256+6-OP_Ne53]; | ||||
| 23245 | SQLITE_PRIVATEstatic const unsigned char *sqlite3aGTb = &sqlite3UpperToLower[256+12-OP_Ne53]; | ||||
| 23246 | |||||
| 23247 | /* | ||||
| 23248 | ** The following 256 byte lookup table is used to support SQLites built-in | ||||
| 23249 | ** equivalents to the following standard library functions: | ||||
| 23250 | ** | ||||
| 23251 | ** isspace() 0x01 | ||||
| 23252 | ** isalpha() 0x02 | ||||
| 23253 | ** isdigit() 0x04 | ||||
| 23254 | ** isalnum() 0x06 | ||||
| 23255 | ** isxdigit() 0x08 | ||||
| 23256 | ** toupper() 0x20 | ||||
| 23257 | ** SQLite identifier character 0x40 $, _, or non-ascii | ||||
| 23258 | ** Quote character 0x80 | ||||
| 23259 | ** | ||||
| 23260 | ** Bit 0x20 is set if the mapped character requires translation to upper | ||||
| 23261 | ** case. i.e. if the character is a lower-case ASCII character. | ||||
| 23262 | ** If x is a lower-case ASCII character, then its upper-case equivalent | ||||
| 23263 | ** is (x - 0x20). Therefore toupper() can be implemented as: | ||||
| 23264 | ** | ||||
| 23265 | ** (x & ~(map[x]&0x20)) | ||||
| 23266 | ** | ||||
| 23267 | ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[] | ||||
| 23268 | ** array. tolower() is used more often than toupper() by SQLite. | ||||
| 23269 | ** | ||||
| 23270 | ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an | ||||
| 23271 | ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any | ||||
| 23272 | ** non-ASCII UTF character. Hence the test for whether or not a character is | ||||
| 23273 | ** part of an identifier is 0x46. | ||||
| 23274 | */ | ||||
| 23275 | SQLITE_PRIVATEstatic const unsigned char sqlite3CtypeMap[256] = { | ||||
| 23276 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ | ||||
| 23277 | 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ | ||||
| 23278 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ | ||||
| 23279 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */ | ||||
| 23280 | 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */ | ||||
| 23281 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */ | ||||
| 23282 | 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */ | ||||
| 23283 | 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */ | ||||
| 23284 | |||||
| 23285 | 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ | ||||
| 23286 | 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ | ||||
| 23287 | 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ | ||||
| 23288 | 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */ | ||||
| 23289 | 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ | ||||
| 23290 | 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ | ||||
| 23291 | 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ | ||||
| 23292 | 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ | ||||
| 23293 | |||||
| 23294 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */ | ||||
| 23295 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */ | ||||
| 23296 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */ | ||||
| 23297 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */ | ||||
| 23298 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */ | ||||
| 23299 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */ | ||||
| 23300 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */ | ||||
| 23301 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */ | ||||
| 23302 | |||||
| 23303 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */ | ||||
| 23304 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */ | ||||
| 23305 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */ | ||||
| 23306 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */ | ||||
| 23307 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */ | ||||
| 23308 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */ | ||||
| 23309 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ | ||||
| 23310 | 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ | ||||
| 23311 | }; | ||||
| 23312 | |||||
| 23313 | /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards | ||||
| 23314 | ** compatibility for legacy applications, the URI filename capability is | ||||
| 23315 | ** disabled by default. | ||||
| 23316 | ** | ||||
| 23317 | ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled | ||||
| 23318 | ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options. | ||||
| 23319 | ** | ||||
| 23320 | ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally | ||||
| 23321 | ** disabled. The default value may be changed by compiling with the | ||||
| 23322 | ** SQLITE_USE_URI symbol defined. | ||||
| 23323 | */ | ||||
| 23324 | #ifndef SQLITE_USE_URI1 | ||||
| 23325 | # define SQLITE_USE_URI1 0 | ||||
| 23326 | #endif | ||||
| 23327 | |||||
| 23328 | /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the | ||||
| 23329 | ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if | ||||
| 23330 | ** that compile-time option is omitted. | ||||
| 23331 | */ | ||||
| 23332 | #if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN1) | ||||
| 23333 | # define SQLITE_ALLOW_COVERING_INDEX_SCAN1 1 | ||||
| 23334 | #else | ||||
| 23335 | # if !SQLITE_ALLOW_COVERING_INDEX_SCAN1 | ||||
| 23336 | # error "Compile-time disabling of covering index scan using the\ | ||||
| 23337 | -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\ | ||||
| 23338 | Contact SQLite developers if this is a problem for you, and\ | ||||
| 23339 | delete this #error macro to continue with your build." | ||||
| 23340 | # endif | ||||
| 23341 | #endif | ||||
| 23342 | |||||
| 23343 | /* The minimum PMA size is set to this value multiplied by the database | ||||
| 23344 | ** page size in bytes. | ||||
| 23345 | */ | ||||
| 23346 | #ifndef SQLITE_SORTER_PMASZ250 | ||||
| 23347 | # define SQLITE_SORTER_PMASZ250 250 | ||||
| 23348 | #endif | ||||
| 23349 | |||||
| 23350 | /* Statement journals spill to disk when their size exceeds the following | ||||
| 23351 | ** threshold (in bytes). 0 means that statement journals are created and | ||||
| 23352 | ** written to disk immediately (the default behavior for SQLite versions | ||||
| 23353 | ** before 3.12.0). -1 means always keep the entire statement journal in | ||||
| 23354 | ** memory. (The statement journal is also always held entirely in memory | ||||
| 23355 | ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this | ||||
| 23356 | ** setting.) | ||||
| 23357 | */ | ||||
| 23358 | #ifndef SQLITE_STMTJRNL_SPILL131072 | ||||
| 23359 | # define SQLITE_STMTJRNL_SPILL131072 (64*1024) | ||||
| 23360 | #endif | ||||
| 23361 | |||||
| 23362 | /* | ||||
| 23363 | ** The default lookaside-configuration, the format "SZ,N". SZ is the | ||||
| 23364 | ** number of bytes in each lookaside slot (should be a multiple of 8) | ||||
| 23365 | ** and N is the number of slots. The lookaside-configuration can be | ||||
| 23366 | ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE) | ||||
| 23367 | ** or at run-time for an individual database connection using | ||||
| 23368 | ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE); | ||||
| 23369 | ** | ||||
| 23370 | ** With the two-size-lookaside enhancement, less lookaside is required. | ||||
| 23371 | ** The default configuration of 1200,40 actually provides 30 1200-byte slots | ||||
| 23372 | ** and 93 128-byte slots, which is more lookaside than is available | ||||
| 23373 | ** using the older 1200,100 configuration without two-size-lookaside. | ||||
| 23374 | */ | ||||
| 23375 | #ifndef SQLITE_DEFAULT_LOOKASIDE1200,40 | ||||
| 23376 | # ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 23377 | # define SQLITE_DEFAULT_LOOKASIDE1200,40 1200,100 /* 120KB of memory */ | ||||
| 23378 | # else | ||||
| 23379 | # define SQLITE_DEFAULT_LOOKASIDE1200,40 1200,40 /* 48KB of memory */ | ||||
| 23380 | # endif | ||||
| 23381 | #endif | ||||
| 23382 | |||||
| 23383 | |||||
| 23384 | /* The default maximum size of an in-memory database created using | ||||
| 23385 | ** sqlite3_deserialize() | ||||
| 23386 | */ | ||||
| 23387 | #ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE1073741824 | ||||
| 23388 | # define SQLITE_MEMDB_DEFAULT_MAXSIZE1073741824 1073741824 | ||||
| 23389 | #endif | ||||
| 23390 | |||||
| 23391 | /* | ||||
| 23392 | ** The following singleton contains the global configuration for | ||||
| 23393 | ** the SQLite library. | ||||
| 23394 | */ | ||||
| 23395 | SQLITE_PRIVATEstatic SQLITE_WSD struct Sqlite3Config sqlite3Config = { | ||||
| 23396 | SQLITE_DEFAULT_MEMSTATUS1, /* bMemstat */ | ||||
| 23397 | 1, /* bCoreMutex */ | ||||
| 23398 | SQLITE_THREADSAFE2==1, /* bFullMutex */ | ||||
| 23399 | SQLITE_USE_URI1, /* bOpenUri */ | ||||
| 23400 | SQLITE_ALLOW_COVERING_INDEX_SCAN1, /* bUseCis */ | ||||
| 23401 | 0, /* bSmallMalloc */ | ||||
| 23402 | 1, /* bExtraSchemaChecks */ | ||||
| 23403 | #ifdef SQLITE_DEBUG | ||||
| 23404 | 0, /* bJsonSelfcheck */ | ||||
| 23405 | #endif | ||||
| 23406 | 0x7ffffffe, /* mxStrlen */ | ||||
| 23407 | 0, /* neverCorrupt */ | ||||
| 23408 | SQLITE_DEFAULT_LOOKASIDE1200,40, /* szLookaside, nLookaside */ | ||||
| 23409 | SQLITE_STMTJRNL_SPILL131072, /* nStmtSpill */ | ||||
| 23410 | {0,0,0,0,0,0,0,0}, /* m */ | ||||
| 23411 | {0,0,0,0,0,0,0,0,0}, /* mutex */ | ||||
| 23412 | {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */ | ||||
| 23413 | (void*)0, /* pHeap */ | ||||
| 23414 | 0, /* nHeap */ | ||||
| 23415 | 0, 0, /* mnHeap, mxHeap */ | ||||
| 23416 | SQLITE_DEFAULT_MMAP_SIZE0, /* szMmap */ | ||||
| 23417 | SQLITE_MAX_MMAP_SIZE20971520, /* mxMmap */ | ||||
| 23418 | (void*)0, /* pPage */ | ||||
| 23419 | 0, /* szPage */ | ||||
| 23420 | SQLITE_DEFAULT_PCACHE_INITSZ20, /* nPage */ | ||||
| 23421 | 0, /* mxParserStack */ | ||||
| 23422 | 0, /* sharedCacheEnabled */ | ||||
| 23423 | SQLITE_SORTER_PMASZ250, /* szPma */ | ||||
| 23424 | /* All the rest should always be initialized to zero */ | ||||
| 23425 | 0, /* isInit */ | ||||
| 23426 | 0, /* inProgress */ | ||||
| 23427 | 0, /* isMutexInit */ | ||||
| 23428 | 0, /* isMallocInit */ | ||||
| 23429 | 0, /* isPCacheInit */ | ||||
| 23430 | 0, /* nRefInitMutex */ | ||||
| 23431 | 0, /* pInitMutex */ | ||||
| 23432 | 0, /* xLog */ | ||||
| 23433 | 0, /* pLogArg */ | ||||
| 23434 | #ifdef SQLITE_ENABLE_SQLLOG | ||||
| 23435 | 0, /* xSqllog */ | ||||
| 23436 | 0, /* pSqllogArg */ | ||||
| 23437 | #endif | ||||
| 23438 | #ifdef SQLITE_VDBE_COVERAGE | ||||
| 23439 | 0, /* xVdbeBranch */ | ||||
| 23440 | 0, /* pVbeBranchArg */ | ||||
| 23441 | #endif | ||||
| 23442 | #ifndef SQLITE_OMIT_DESERIALIZE | ||||
| 23443 | SQLITE_MEMDB_DEFAULT_MAXSIZE1073741824, /* mxMemdbSize */ | ||||
| 23444 | #endif | ||||
| 23445 | #ifndef SQLITE_UNTESTABLE | ||||
| 23446 | 0, /* xTestCallback */ | ||||
| 23447 | #endif | ||||
| 23448 | #ifdef SQLITE_ALLOW_ROWID_IN_VIEW | ||||
| 23449 | 0, /* mNoVisibleRowid. 0 == allow rowid-in-view */ | ||||
| 23450 | #endif | ||||
| 23451 | 0, /* bLocaltimeFault */ | ||||
| 23452 | 0, /* xAltLocaltime */ | ||||
| 23453 | 0x7ffffffe, /* iOnceResetThreshold */ | ||||
| 23454 | SQLITE_DEFAULT_SORTERREF_SIZE0x7fffffff, /* szSorterRef */ | ||||
| 23455 | 0, /* iPrngSeed */ | ||||
| 23456 | #ifdef SQLITE_DEBUG | ||||
| 23457 | {0,0,0,0,0,0}, /* aTune */ | ||||
| 23458 | #endif | ||||
| 23459 | }; | ||||
| 23460 | |||||
| 23461 | /* | ||||
| 23462 | ** Hash table for global functions - functions common to all | ||||
| 23463 | ** database connections. After initialization, this table is | ||||
| 23464 | ** read-only. | ||||
| 23465 | */ | ||||
| 23466 | SQLITE_PRIVATEstatic FuncDefHash sqlite3BuiltinFunctions; | ||||
| 23467 | |||||
| 23468 | #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG) | ||||
| 23469 | /* | ||||
| 23470 | ** Counter used for coverage testing. Does not come into play for | ||||
| 23471 | ** release builds. | ||||
| 23472 | ** | ||||
| 23473 | ** Access to this global variable is not mutex protected. This might | ||||
| 23474 | ** result in TSAN warnings. But as the variable does not exist in | ||||
| 23475 | ** release builds, that should not be a concern. | ||||
| 23476 | */ | ||||
| 23477 | SQLITE_PRIVATEstatic unsigned int sqlite3CoverageCounter; | ||||
| 23478 | #endif /* SQLITE_COVERAGE_TEST || SQLITE_DEBUG */ | ||||
| 23479 | |||||
| 23480 | #ifdef VDBE_PROFILE | ||||
| 23481 | /* | ||||
| 23482 | ** The following performance counter can be used in place of | ||||
| 23483 | ** sqlite3Hwtime() for profiling. This is a no-op on standard builds. | ||||
| 23484 | */ | ||||
| 23485 | SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3NProfileCnt = 0; | ||||
| 23486 | #endif | ||||
| 23487 | |||||
| 23488 | /* | ||||
| 23489 | ** The value of the "pending" byte must be 0x40000000 (1 byte past the | ||||
| 23490 | ** 1-gibabyte boundary) in a compatible database. SQLite never uses | ||||
| 23491 | ** the database page that contains the pending byte. It never attempts | ||||
| 23492 | ** to read or write that page. The pending byte page is set aside | ||||
| 23493 | ** for use by the VFS layers as space for managing file locks. | ||||
| 23494 | ** | ||||
| 23495 | ** During testing, it is often desirable to move the pending byte to | ||||
| 23496 | ** a different position in the file. This allows code that has to | ||||
| 23497 | ** deal with the pending byte to run on files that are much smaller | ||||
| 23498 | ** than 1 GiB. The sqlite3_test_control() interface can be used to | ||||
| 23499 | ** move the pending byte. | ||||
| 23500 | ** | ||||
| 23501 | ** IMPORTANT: Changing the pending byte to any value other than | ||||
| 23502 | ** 0x40000000 results in an incompatible database file format! | ||||
| 23503 | ** Changing the pending byte during operation will result in undefined | ||||
| 23504 | ** and incorrect behavior. | ||||
| 23505 | */ | ||||
| 23506 | #ifndef SQLITE_OMIT_WSD | ||||
| 23507 | SQLITE_PRIVATEstatic int sqlite3PendingByte = 0x40000000; | ||||
| 23508 | #endif | ||||
| 23509 | |||||
| 23510 | /* | ||||
| 23511 | ** Tracing flags set by SQLITE_TESTCTRL_TRACEFLAGS. | ||||
| 23512 | */ | ||||
| 23513 | SQLITE_PRIVATEstatic u32 sqlite3TreeTrace = 0; | ||||
| 23514 | SQLITE_PRIVATEstatic u32 sqlite3WhereTrace = 0; | ||||
| 23515 | |||||
| 23516 | /* #include "opcodes.h" */ | ||||
| 23517 | /* | ||||
| 23518 | ** Properties of opcodes. The OPFLG_INITIALIZER macro is | ||||
| 23519 | ** created by mkopcodeh.awk during compilation. Data is obtained | ||||
| 23520 | ** from the comments following the "case OP_xxxx:" statements in | ||||
| 23521 | ** the vdbe.c file. | ||||
| 23522 | */ | ||||
| 23523 | SQLITE_PRIVATEstatic const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER{ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00, 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01, 0x03, 0x03, 0x01, 0x12, 0x01 , 0xc9, 0xc9, 0xc9, 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49, 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41, 0x41, 0x41 , 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b, 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01 , 0x41, 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00 , 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26, 0x26 , 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40 , 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40, 0x10, 0x00, 0x00 , 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50, 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 , 0x00,}; | ||||
| 23524 | |||||
| 23525 | /* | ||||
| 23526 | ** Name of the default collating sequence | ||||
| 23527 | */ | ||||
| 23528 | SQLITE_PRIVATEstatic const char sqlite3StrBINARY[] = "BINARY"; | ||||
| 23529 | |||||
| 23530 | /* | ||||
| 23531 | ** Standard typenames. These names must match the COLTYPE_* definitions. | ||||
| 23532 | ** Adjust the SQLITE_N_STDTYPE value if adding or removing entries. | ||||
| 23533 | ** | ||||
| 23534 | ** sqlite3StdType[] The actual names of the datatypes. | ||||
| 23535 | ** | ||||
| 23536 | ** sqlite3StdTypeLen[] The length (in bytes) of each entry | ||||
| 23537 | ** in sqlite3StdType[]. | ||||
| 23538 | ** | ||||
| 23539 | ** sqlite3StdTypeAffinity[] The affinity associated with each entry | ||||
| 23540 | ** in sqlite3StdType[]. | ||||
| 23541 | */ | ||||
| 23542 | SQLITE_PRIVATEstatic const unsigned char sqlite3StdTypeLen[] = { 3, 4, 3, 7, 4, 4 }; | ||||
| 23543 | SQLITE_PRIVATEstatic const char sqlite3StdTypeAffinity[] = { | ||||
| 23544 | SQLITE_AFF_NUMERIC0x43, | ||||
| 23545 | SQLITE_AFF_BLOB0x41, | ||||
| 23546 | SQLITE_AFF_INTEGER0x44, | ||||
| 23547 | SQLITE_AFF_INTEGER0x44, | ||||
| 23548 | SQLITE_AFF_REAL0x45, | ||||
| 23549 | SQLITE_AFF_TEXT0x42 | ||||
| 23550 | }; | ||||
| 23551 | SQLITE_PRIVATEstatic const char *sqlite3StdType[] = { | ||||
| 23552 | "ANY", | ||||
| 23553 | "BLOB", | ||||
| 23554 | "INT", | ||||
| 23555 | "INTEGER", | ||||
| 23556 | "REAL", | ||||
| 23557 | "TEXT" | ||||
| 23558 | }; | ||||
| 23559 | |||||
| 23560 | /************** End of global.c **********************************************/ | ||||
| 23561 | /************** Begin file status.c ******************************************/ | ||||
| 23562 | /* | ||||
| 23563 | ** 2008 June 18 | ||||
| 23564 | ** | ||||
| 23565 | ** The author disclaims copyright to this source code. In place of | ||||
| 23566 | ** a legal notice, here is a blessing: | ||||
| 23567 | ** | ||||
| 23568 | ** May you do good and not evil. | ||||
| 23569 | ** May you find forgiveness for yourself and forgive others. | ||||
| 23570 | ** May you share freely, never taking more than you give. | ||||
| 23571 | ** | ||||
| 23572 | ************************************************************************* | ||||
| 23573 | ** | ||||
| 23574 | ** This module implements the sqlite3_status() interface and related | ||||
| 23575 | ** functionality. | ||||
| 23576 | */ | ||||
| 23577 | /* #include "sqliteInt.h" */ | ||||
| 23578 | /************** Include vdbeInt.h in the middle of status.c ******************/ | ||||
| 23579 | /************** Begin file vdbeInt.h *****************************************/ | ||||
| 23580 | /* | ||||
| 23581 | ** 2003 September 6 | ||||
| 23582 | ** | ||||
| 23583 | ** The author disclaims copyright to this source code. In place of | ||||
| 23584 | ** a legal notice, here is a blessing: | ||||
| 23585 | ** | ||||
| 23586 | ** May you do good and not evil. | ||||
| 23587 | ** May you find forgiveness for yourself and forgive others. | ||||
| 23588 | ** May you share freely, never taking more than you give. | ||||
| 23589 | ** | ||||
| 23590 | ************************************************************************* | ||||
| 23591 | ** This is the header file for information that is private to the | ||||
| 23592 | ** VDBE. This information used to all be at the top of the single | ||||
| 23593 | ** source code file "vdbe.c". When that file became too big (over | ||||
| 23594 | ** 6000 lines long) it was split up into several smaller files and | ||||
| 23595 | ** this header information was factored out. | ||||
| 23596 | */ | ||||
| 23597 | #ifndef SQLITE_VDBEINT_H | ||||
| 23598 | #define SQLITE_VDBEINT_H | ||||
| 23599 | |||||
| 23600 | /* | ||||
| 23601 | ** The maximum number of times that a statement will try to reparse | ||||
| 23602 | ** itself before giving up and returning SQLITE_SCHEMA. | ||||
| 23603 | */ | ||||
| 23604 | #ifndef SQLITE_MAX_SCHEMA_RETRY50 | ||||
| 23605 | # define SQLITE_MAX_SCHEMA_RETRY50 50 | ||||
| 23606 | #endif | ||||
| 23607 | |||||
| 23608 | /* | ||||
| 23609 | ** VDBE_DISPLAY_P4 is true or false depending on whether or not the | ||||
| 23610 | ** "explain" P4 display logic is enabled. | ||||
| 23611 | */ | ||||
| 23612 | #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG1) \ | ||||
| 23613 | || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \ | ||||
| 23614 | || defined(SQLITE_ENABLE_BYTECODE_VTAB) | ||||
| 23615 | # define VDBE_DISPLAY_P41 1 | ||||
| 23616 | #else | ||||
| 23617 | # define VDBE_DISPLAY_P41 0 | ||||
| 23618 | #endif | ||||
| 23619 | |||||
| 23620 | /* | ||||
| 23621 | ** SQL is translated into a sequence of instructions to be | ||||
| 23622 | ** executed by a virtual machine. Each instruction is an instance | ||||
| 23623 | ** of the following structure. | ||||
| 23624 | */ | ||||
| 23625 | typedef struct VdbeOp Op; | ||||
| 23626 | |||||
| 23627 | /* | ||||
| 23628 | ** Boolean values | ||||
| 23629 | */ | ||||
| 23630 | typedef unsigned Bool; | ||||
| 23631 | |||||
| 23632 | /* Opaque type used by code in vdbesort.c */ | ||||
| 23633 | typedef struct VdbeSorter VdbeSorter; | ||||
| 23634 | |||||
| 23635 | /* Elements of the linked list at Vdbe.pAuxData */ | ||||
| 23636 | typedef struct AuxData AuxData; | ||||
| 23637 | |||||
| 23638 | /* A cache of large TEXT or BLOB values in a VdbeCursor */ | ||||
| 23639 | typedef struct VdbeTxtBlbCache VdbeTxtBlbCache; | ||||
| 23640 | |||||
| 23641 | /* Types of VDBE cursors */ | ||||
| 23642 | #define CURTYPE_BTREE0 0 | ||||
| 23643 | #define CURTYPE_SORTER1 1 | ||||
| 23644 | #define CURTYPE_VTAB2 2 | ||||
| 23645 | #define CURTYPE_PSEUDO3 3 | ||||
| 23646 | |||||
| 23647 | /* | ||||
| 23648 | ** A VdbeCursor is an superclass (a wrapper) for various cursor objects: | ||||
| 23649 | ** | ||||
| 23650 | ** * A b-tree cursor | ||||
| 23651 | ** - In the main database or in an ephemeral database | ||||
| 23652 | ** - On either an index or a table | ||||
| 23653 | ** * A sorter | ||||
| 23654 | ** * A virtual table | ||||
| 23655 | ** * A one-row "pseudotable" stored in a single register | ||||
| 23656 | */ | ||||
| 23657 | typedef struct VdbeCursor VdbeCursor; | ||||
| 23658 | struct VdbeCursor { | ||||
| 23659 | u8 eCurType; /* One of the CURTYPE_* values above */ | ||||
| 23660 | i8 iDb; /* Index of cursor database in db->aDb[] */ | ||||
| 23661 | u8 nullRow; /* True if pointing to a row with no data */ | ||||
| 23662 | u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ | ||||
| 23663 | u8 isTable; /* True for rowid tables. False for indexes */ | ||||
| 23664 | #ifdef SQLITE_DEBUG | ||||
| 23665 | u8 seekOp; /* Most recent seek operation on this cursor */ | ||||
| 23666 | u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */ | ||||
| 23667 | #endif | ||||
| 23668 | Bool isEphemeral:1; /* True for an ephemeral table */ | ||||
| 23669 | Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */ | ||||
| 23670 | Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */ | ||||
| 23671 | Bool noReuse:1; /* OpenEphemeral may not reuse this cursor */ | ||||
| 23672 | Bool colCache:1; /* pCache pointer is initialized and non-NULL */ | ||||
| 23673 | u16 seekHit; /* See the OP_SeekHit and OP_IfNoHope opcodes */ | ||||
| 23674 | union { /* pBtx for isEphermeral. pAltMap otherwise */ | ||||
| 23675 | Btree *pBtx; /* Separate file holding temporary table */ | ||||
| 23676 | u32 *aAltMap; /* Mapping from table to index column numbers */ | ||||
| 23677 | } ub; | ||||
| 23678 | i64 seqCount; /* Sequence counter */ | ||||
| 23679 | |||||
| 23680 | /* Cached OP_Column parse information is only valid if cacheStatus matches | ||||
| 23681 | ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of | ||||
| 23682 | ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that | ||||
| 23683 | ** the cache is out of date. */ | ||||
| 23684 | u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ | ||||
| 23685 | int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0 | ||||
| 23686 | ** if there have been no prior seeks on the cursor. */ | ||||
| 23687 | /* seekResult does not distinguish between "no seeks have ever occurred | ||||
| 23688 | ** on this cursor" and "the most recent seek was an exact match". | ||||
| 23689 | ** For CURTYPE_PSEUDO, seekResult is the register holding the record */ | ||||
| 23690 | |||||
| 23691 | /* When a new VdbeCursor is allocated, only the fields above are zeroed. | ||||
| 23692 | ** The fields that follow are uninitialized, and must be individually | ||||
| 23693 | ** initialized prior to first use. */ | ||||
| 23694 | VdbeCursor *pAltCursor; /* Associated index cursor from which to read */ | ||||
| 23695 | union { | ||||
| 23696 | BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */ | ||||
| 23697 | sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */ | ||||
| 23698 | VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */ | ||||
| 23699 | } uc; | ||||
| 23700 | KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */ | ||||
| 23701 | u32 iHdrOffset; /* Offset to next unparsed byte of the header */ | ||||
| 23702 | Pgno pgnoRoot; /* Root page of the open btree cursor */ | ||||
| 23703 | i16 nField; /* Number of fields in the header */ | ||||
| 23704 | u16 nHdrParsed; /* Number of header fields parsed so far */ | ||||
| 23705 | i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ | ||||
| 23706 | u32 *aOffset; /* Pointer to aType[nField] */ | ||||
| 23707 | const u8 *aRow; /* Data for the current row, if all on one page */ | ||||
| 23708 | u32 payloadSize; /* Total number of bytes in the record */ | ||||
| 23709 | u32 szRow; /* Byte available in aRow */ | ||||
| 23710 | #ifdef SQLITE_ENABLE_COLUMN_USED_MASK | ||||
| 23711 | u64 maskUsed; /* Mask of columns used by this cursor */ | ||||
| 23712 | #endif | ||||
| 23713 | VdbeTxtBlbCache *pCache; /* Cache of large TEXT or BLOB values */ | ||||
| 23714 | |||||
| 23715 | /* Space is allocated for aType to hold at least 2*nField+1 entries: | ||||
| 23716 | ** nField slots for aType[] and nField+1 array slots for aOffset[] */ | ||||
| 23717 | u32 aType[FLEXARRAY]; /* Type values record decode. MUST BE LAST */ | ||||
| 23718 | }; | ||||
| 23719 | |||||
| 23720 | /* | ||||
| 23721 | ** The size (in bytes) of a VdbeCursor object that has an nField value of N | ||||
| 23722 | ** or less. The value of SZ_VDBECURSOR(n) is guaranteed to be a multiple | ||||
| 23723 | ** of 8. | ||||
| 23724 | */ | ||||
| 23725 | #define SZ_VDBECURSOR(N)((((__builtin_offsetof(VdbeCursor, aType))+7)&~7) + ((N)+ 1)*sizeof(u64)) \ | ||||
| 23726 | (ROUND8(offsetof(VdbeCursor,aType))(((__builtin_offsetof(VdbeCursor, aType))+7)&~7) + ((N)+1)*sizeof(u64)) | ||||
| 23727 | |||||
| 23728 | /* Return true if P is a null-only cursor | ||||
| 23729 | */ | ||||
| 23730 | #define IsNullCursor(P)((P)->eCurType==3 && (P)->nullRow && (P )->seekResult==0) \ | ||||
| 23731 | ((P)->eCurType==CURTYPE_PSEUDO3 && (P)->nullRow && (P)->seekResult==0) | ||||
| 23732 | |||||
| 23733 | /* | ||||
| 23734 | ** A value for VdbeCursor.cacheStatus that means the cache is always invalid. | ||||
| 23735 | */ | ||||
| 23736 | #define CACHE_STALE0 0 | ||||
| 23737 | |||||
| 23738 | /* | ||||
| 23739 | ** Large TEXT or BLOB values can be slow to load, so we want to avoid | ||||
| 23740 | ** loading them more than once. For that reason, large TEXT and BLOB values | ||||
| 23741 | ** can be stored in a cache defined by this object, and attached to the | ||||
| 23742 | ** VdbeCursor using the pCache field. | ||||
| 23743 | */ | ||||
| 23744 | struct VdbeTxtBlbCache { | ||||
| 23745 | char *pCValue; /* A RCStr buffer to hold the value */ | ||||
| 23746 | i64 iOffset; /* File offset of the row being cached */ | ||||
| 23747 | int iCol; /* Column for which the cache is valid */ | ||||
| 23748 | u32 cacheStatus; /* Vdbe.cacheCtr value */ | ||||
| 23749 | u32 colCacheCtr; /* Column cache counter */ | ||||
| 23750 | }; | ||||
| 23751 | |||||
| 23752 | /* | ||||
| 23753 | ** When a sub-program is executed (OP_Program), a structure of this type | ||||
| 23754 | ** is allocated to store the current value of the program counter, as | ||||
| 23755 | ** well as the current memory cell array and various other frame specific | ||||
| 23756 | ** values stored in the Vdbe struct. When the sub-program is finished, | ||||
| 23757 | ** these values are copied back to the Vdbe from the VdbeFrame structure, | ||||
| 23758 | ** restoring the state of the VM to as it was before the sub-program | ||||
| 23759 | ** began executing. | ||||
| 23760 | ** | ||||
| 23761 | ** The memory for a VdbeFrame object is allocated and managed by a memory | ||||
| 23762 | ** cell in the parent (calling) frame. When the memory cell is deleted or | ||||
| 23763 | ** overwritten, the VdbeFrame object is not freed immediately. Instead, it | ||||
| 23764 | ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame | ||||
| 23765 | ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing | ||||
| 23766 | ** this instead of deleting the VdbeFrame immediately is to avoid recursive | ||||
| 23767 | ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the | ||||
| 23768 | ** child frame are released. | ||||
| 23769 | ** | ||||
| 23770 | ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is | ||||
| 23771 | ** set to NULL if the currently executing frame is the main program. | ||||
| 23772 | */ | ||||
| 23773 | typedef struct VdbeFrame VdbeFrame; | ||||
| 23774 | struct VdbeFrame { | ||||
| 23775 | Vdbe *v; /* VM this frame belongs to */ | ||||
| 23776 | VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */ | ||||
| 23777 | Op *aOp; /* Program instructions for parent frame */ | ||||
| 23778 | Mem *aMem; /* Array of memory cells for parent frame */ | ||||
| 23779 | VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */ | ||||
| 23780 | u8 *aOnce; /* Bitmask used by OP_Once */ | ||||
| 23781 | void *token; /* Copy of SubProgram.token */ | ||||
| 23782 | i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ | ||||
| 23783 | AuxData *pAuxData; /* Linked list of auxdata allocations */ | ||||
| 23784 | #if SQLITE_DEBUG | ||||
| 23785 | u32 iFrameMagic; /* magic number for sanity checking */ | ||||
| 23786 | #endif | ||||
| 23787 | int nCursor; /* Number of entries in apCsr */ | ||||
| 23788 | int pc; /* Program Counter in parent (calling) frame */ | ||||
| 23789 | int nOp; /* Size of aOp array */ | ||||
| 23790 | int nMem; /* Number of entries in aMem */ | ||||
| 23791 | int nChildMem; /* Number of memory cells for child frame */ | ||||
| 23792 | int nChildCsr; /* Number of cursors for child frame */ | ||||
| 23793 | i64 nChange; /* Statement changes (Vdbe.nChange) */ | ||||
| 23794 | i64 nDbChange; /* Value of db->nChange */ | ||||
| 23795 | }; | ||||
| 23796 | |||||
| 23797 | /* Magic number for sanity checking on VdbeFrame objects */ | ||||
| 23798 | #define SQLITE_FRAME_MAGIC0x879fb71e 0x879fb71e | ||||
| 23799 | |||||
| 23800 | /* | ||||
| 23801 | ** Return a pointer to the array of registers allocated for use | ||||
| 23802 | ** by a VdbeFrame. | ||||
| 23803 | */ | ||||
| 23804 | #define VdbeFrameMem(p)((Mem *)&((u8 *)p)[(((sizeof(VdbeFrame))+7)&~7)]) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))(((sizeof(VdbeFrame))+7)&~7)]) | ||||
| 23805 | |||||
| 23806 | /* | ||||
| 23807 | ** Internally, the vdbe manipulates nearly all SQL values as Mem | ||||
| 23808 | ** structures. Each Mem struct may cache multiple representations (string, | ||||
| 23809 | ** integer etc.) of the same value. | ||||
| 23810 | */ | ||||
| 23811 | struct sqlite3_value { | ||||
| 23812 | union MemValue { | ||||
| 23813 | double r; /* Real value used when MEM_Real is set in flags */ | ||||
| 23814 | i64 i; /* Integer value used when MEM_Int is set in flags */ | ||||
| 23815 | int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */ | ||||
| 23816 | const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */ | ||||
| 23817 | FuncDef *pDef; /* Used only when flags==MEM_Agg */ | ||||
| 23818 | } u; | ||||
| 23819 | char *z; /* String or BLOB value */ | ||||
| 23820 | int n; /* Number of characters in string value, excluding '\0' */ | ||||
| 23821 | u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ | ||||
| 23822 | u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ | ||||
| 23823 | u8 eSubtype; /* Subtype for this value */ | ||||
| 23824 | /* ShallowCopy only needs to copy the information above */ | ||||
| 23825 | sqlite3 *db; /* The associated database connection */ | ||||
| 23826 | int szMalloc; /* Size of the zMalloc allocation */ | ||||
| 23827 | u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */ | ||||
| 23828 | char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */ | ||||
| 23829 | void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */ | ||||
| 23830 | #ifdef SQLITE_DEBUG | ||||
| 23831 | Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ | ||||
| 23832 | u16 mScopyFlags; /* flags value immediately after the shallow copy */ | ||||
| 23833 | u8 bScopy; /* The pScopyFrom of some other Mem *might* point here */ | ||||
| 23834 | #endif | ||||
| 23835 | }; | ||||
| 23836 | |||||
| 23837 | /* | ||||
| 23838 | ** Size of struct Mem not including the Mem.zMalloc member or anything that | ||||
| 23839 | ** follows. | ||||
| 23840 | */ | ||||
| 23841 | #define MEMCELLSIZE__builtin_offsetof(Mem, db) offsetof(Mem,db)__builtin_offsetof(Mem, db) | ||||
| 23842 | |||||
| 23843 | /* One or more of the following flags are set to indicate the | ||||
| 23844 | ** representations of the value stored in the Mem struct. | ||||
| 23845 | ** | ||||
| 23846 | ** * MEM_Null An SQL NULL value | ||||
| 23847 | ** | ||||
| 23848 | ** * MEM_Null|MEM_Zero An SQL NULL with the virtual table | ||||
| 23849 | ** UPDATE no-change flag set | ||||
| 23850 | ** | ||||
| 23851 | ** * MEM_Null|MEM_Term| An SQL NULL, but also contains a | ||||
| 23852 | ** MEM_Subtype pointer accessible using | ||||
| 23853 | ** sqlite3_value_pointer(). | ||||
| 23854 | ** | ||||
| 23855 | ** * MEM_Null|MEM_Cleared Special SQL NULL that compares non-equal | ||||
| 23856 | ** to other NULLs even using the IS operator. | ||||
| 23857 | ** | ||||
| 23858 | ** * MEM_Str A string, stored in Mem.z with | ||||
| 23859 | ** length Mem.n. Zero-terminated if | ||||
| 23860 | ** MEM_Term is set. This flag is | ||||
| 23861 | ** incompatible with MEM_Blob and | ||||
| 23862 | ** MEM_Null, but can appear with MEM_Int, | ||||
| 23863 | ** MEM_Real, and MEM_IntReal. | ||||
| 23864 | ** | ||||
| 23865 | ** * MEM_Blob A blob, stored in Mem.z length Mem.n. | ||||
| 23866 | ** Incompatible with MEM_Str, MEM_Null, | ||||
| 23867 | ** MEM_Int, MEM_Real, and MEM_IntReal. | ||||
| 23868 | ** | ||||
| 23869 | ** * MEM_Blob|MEM_Zero A blob in Mem.z of length Mem.n plus | ||||
| 23870 | ** MEM.u.i extra 0x00 bytes at the end. | ||||
| 23871 | ** | ||||
| 23872 | ** * MEM_Int Integer stored in Mem.u.i. | ||||
| 23873 | ** | ||||
| 23874 | ** * MEM_Real Real stored in Mem.u.r. | ||||
| 23875 | ** | ||||
| 23876 | ** * MEM_IntReal Real stored as an integer in Mem.u.i. | ||||
| 23877 | ** | ||||
| 23878 | ** If the MEM_Null flag is set, then the value is an SQL NULL value. | ||||
| 23879 | ** For a pointer type created using sqlite3_bind_pointer() or | ||||
| 23880 | ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set. | ||||
| 23881 | ** | ||||
| 23882 | ** If the MEM_Str flag is set then Mem.z points at a string representation. | ||||
| 23883 | ** Usually this is encoded in the same unicode encoding as the main | ||||
| 23884 | ** database (see below for exceptions). If the MEM_Term flag is also | ||||
| 23885 | ** set, then the string is nul terminated. The MEM_Int and MEM_Real | ||||
| 23886 | ** flags may coexist with the MEM_Str flag. | ||||
| 23887 | */ | ||||
| 23888 | #define MEM_Undefined0x0000 0x0000 /* Value is undefined */ | ||||
| 23889 | #define MEM_Null0x0001 0x0001 /* Value is NULL (or a pointer) */ | ||||
| 23890 | #define MEM_Str0x0002 0x0002 /* Value is a string */ | ||||
| 23891 | #define MEM_Int0x0004 0x0004 /* Value is an integer */ | ||||
| 23892 | #define MEM_Real0x0008 0x0008 /* Value is a real number */ | ||||
| 23893 | #define MEM_Blob0x0010 0x0010 /* Value is a BLOB */ | ||||
| 23894 | #define MEM_IntReal0x0020 0x0020 /* MEM_Int that stringifies like MEM_Real */ | ||||
| 23895 | #define MEM_AffMask0x003f 0x003f /* Mask of affinity bits */ | ||||
| 23896 | |||||
| 23897 | /* Extra bits that modify the meanings of the core datatypes above | ||||
| 23898 | */ | ||||
| 23899 | #define MEM_FromBind0x0040 0x0040 /* Value originates from sqlite3_bind() */ | ||||
| 23900 | /* 0x0080 // Available */ | ||||
| 23901 | #define MEM_Cleared0x0100 0x0100 /* NULL set by OP_Null, not from data */ | ||||
| 23902 | #define MEM_Term0x0200 0x0200 /* String in Mem.z is zero terminated */ | ||||
| 23903 | #define MEM_Zero0x0400 0x0400 /* Mem.i contains count of 0s appended to blob */ | ||||
| 23904 | #define MEM_Subtype0x0800 0x0800 /* Mem.eSubtype is valid */ | ||||
| 23905 | #define MEM_TypeMask0x0dbf 0x0dbf /* Mask of type bits */ | ||||
| 23906 | |||||
| 23907 | /* Bits that determine the storage for Mem.z for a string or blob or | ||||
| 23908 | ** aggregate accumulator. | ||||
| 23909 | */ | ||||
| 23910 | #define MEM_Dyn0x1000 0x1000 /* Need to call Mem.xDel() on Mem.z */ | ||||
| 23911 | #define MEM_Static0x2000 0x2000 /* Mem.z points to a static string */ | ||||
| 23912 | #define MEM_Ephem0x4000 0x4000 /* Mem.z points to an ephemeral string */ | ||||
| 23913 | #define MEM_Agg0x8000 0x8000 /* Mem.z points to an agg function context */ | ||||
| 23914 | |||||
| 23915 | /* Return TRUE if Mem X contains dynamically allocated content - anything | ||||
| 23916 | ** that needs to be deallocated to avoid a leak. | ||||
| 23917 | */ | ||||
| 23918 | #define VdbeMemDynamic(X)(((X)->flags&(0x8000|0x1000))!=0) \ | ||||
| 23919 | (((X)->flags&(MEM_Agg0x8000|MEM_Dyn0x1000))!=0) | ||||
| 23920 | |||||
| 23921 | /* | ||||
| 23922 | ** Clear any existing type flags from a Mem and replace them with f | ||||
| 23923 | */ | ||||
| 23924 | #define MemSetTypeFlag(p, f)((p)->flags = ((p)->flags&~(0x0dbf|0x0400))|f) \ | ||||
| 23925 | ((p)->flags = ((p)->flags&~(MEM_TypeMask0x0dbf|MEM_Zero0x0400))|f) | ||||
| 23926 | |||||
| 23927 | /* | ||||
| 23928 | ** True if Mem X is a NULL-nochng type. | ||||
| 23929 | */ | ||||
| 23930 | #define MemNullNochng(X)(((X)->flags&0x0dbf)==(0x0001|0x0400) && (X)-> n==0 && (X)->u.nZero==0) \ | ||||
| 23931 | (((X)->flags&MEM_TypeMask0x0dbf)==(MEM_Null0x0001|MEM_Zero0x0400) \ | ||||
| 23932 | && (X)->n==0 && (X)->u.nZero==0) | ||||
| 23933 | |||||
| 23934 | /* | ||||
| 23935 | ** Return true if a memory cell has been initialized and is valid. | ||||
| 23936 | ** is for use inside assert() statements only. | ||||
| 23937 | ** | ||||
| 23938 | ** A Memory cell is initialized if at least one of the | ||||
| 23939 | ** MEM_Null, MEM_Str, MEM_Int, MEM_Real, MEM_Blob, or MEM_IntReal bits | ||||
| 23940 | ** is set. It is "undefined" if all those bits are zero. | ||||
| 23941 | */ | ||||
| 23942 | #ifdef SQLITE_DEBUG | ||||
| 23943 | #define memIsValid(M) ((M)->flags & MEM_AffMask0x003f)!=0 | ||||
| 23944 | #endif | ||||
| 23945 | |||||
| 23946 | /* | ||||
| 23947 | ** Each auxiliary data pointer stored by a user defined function | ||||
| 23948 | ** implementation calling sqlite3_set_auxdata() is stored in an instance | ||||
| 23949 | ** of this structure. All such structures associated with a single VM | ||||
| 23950 | ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed | ||||
| 23951 | ** when the VM is halted (if not before). | ||||
| 23952 | */ | ||||
| 23953 | struct AuxData { | ||||
| 23954 | int iAuxOp; /* Instruction number of OP_Function opcode */ | ||||
| 23955 | int iAuxArg; /* Index of function argument. */ | ||||
| 23956 | void *pAux; /* Aux data pointer */ | ||||
| 23957 | void (*xDeleteAux)(void*); /* Destructor for the aux data */ | ||||
| 23958 | AuxData *pNextAux; /* Next element in list */ | ||||
| 23959 | }; | ||||
| 23960 | |||||
| 23961 | /* | ||||
| 23962 | ** The "context" argument for an installable function. A pointer to an | ||||
| 23963 | ** instance of this structure is the first argument to the routines used | ||||
| 23964 | ** implement the SQL functions. | ||||
| 23965 | ** | ||||
| 23966 | ** There is a typedef for this structure in sqlite.h. So all routines, | ||||
| 23967 | ** even the public interface to SQLite, can use a pointer to this structure. | ||||
| 23968 | ** But this file is the only place where the internal details of this | ||||
| 23969 | ** structure are known. | ||||
| 23970 | ** | ||||
| 23971 | ** This structure is defined inside of vdbeInt.h because it uses substructures | ||||
| 23972 | ** (Mem) which are only defined there. | ||||
| 23973 | */ | ||||
| 23974 | struct sqlite3_context { | ||||
| 23975 | Mem *pOut; /* The return value is stored here */ | ||||
| 23976 | FuncDef *pFunc; /* Pointer to function information */ | ||||
| 23977 | Mem *pMem; /* Memory cell used to store aggregate context */ | ||||
| 23978 | Vdbe *pVdbe; /* The VM that owns this context */ | ||||
| 23979 | int iOp; /* Instruction number of OP_Function */ | ||||
| 23980 | int isError; /* Error code returned by the function. */ | ||||
| 23981 | u8 enc; /* Encoding to use for results */ | ||||
| 23982 | u8 skipFlag; /* Skip accumulator loading if true */ | ||||
| 23983 | u16 argc; /* Number of arguments */ | ||||
| 23984 | sqlite3_value *argv[FLEXARRAY]; /* Argument set */ | ||||
| 23985 | }; | ||||
| 23986 | |||||
| 23987 | /* | ||||
| 23988 | ** The size (in bytes) of an sqlite3_context object that holds N | ||||
| 23989 | ** argv[] arguments. | ||||
| 23990 | */ | ||||
| 23991 | #define SZ_CONTEXT(N)(__builtin_offsetof(sqlite3_context, argv)+(N)*sizeof(sqlite3_value *)) \ | ||||
| 23992 | (offsetof(sqlite3_context,argv)__builtin_offsetof(sqlite3_context, argv)+(N)*sizeof(sqlite3_value*)) | ||||
| 23993 | |||||
| 23994 | |||||
| 23995 | /* The ScanStatus object holds a single value for the | ||||
| 23996 | ** sqlite3_stmt_scanstatus() interface. | ||||
| 23997 | ** | ||||
| 23998 | ** aAddrRange[]: | ||||
| 23999 | ** This array is used by ScanStatus elements associated with EQP | ||||
| 24000 | ** notes that make an SQLITE_SCANSTAT_NCYCLE value available. It is | ||||
| 24001 | ** an array of up to 3 ranges of VM addresses for which the Vdbe.anCycle[] | ||||
| 24002 | ** values should be summed to calculate the NCYCLE value. Each pair of | ||||
| 24003 | ** integer addresses is a start and end address (both inclusive) for a range | ||||
| 24004 | ** instructions. A start value of 0 indicates an empty range. | ||||
| 24005 | */ | ||||
| 24006 | typedef struct ScanStatus ScanStatus; | ||||
| 24007 | struct ScanStatus { | ||||
| 24008 | int addrExplain; /* OP_Explain for loop */ | ||||
| 24009 | int aAddrRange[6]; | ||||
| 24010 | int addrLoop; /* Address of "loops" counter */ | ||||
| 24011 | int addrVisit; /* Address of "rows visited" counter */ | ||||
| 24012 | int iSelectID; /* The "Select-ID" for this loop */ | ||||
| 24013 | LogEst nEst; /* Estimated output rows per loop */ | ||||
| 24014 | char *zName; /* Name of table or index */ | ||||
| 24015 | }; | ||||
| 24016 | |||||
| 24017 | /* The DblquoteStr object holds the text of a double-quoted | ||||
| 24018 | ** string for a prepared statement. A linked list of these objects | ||||
| 24019 | ** is constructed during statement parsing and is held on Vdbe.pDblStr. | ||||
| 24020 | ** When computing a normalized SQL statement for an SQL statement, that | ||||
| 24021 | ** list is consulted for each double-quoted identifier to see if the | ||||
| 24022 | ** identifier should really be a string literal. | ||||
| 24023 | */ | ||||
| 24024 | typedef struct DblquoteStr DblquoteStr; | ||||
| 24025 | struct DblquoteStr { | ||||
| 24026 | DblquoteStr *pNextStr; /* Next string literal in the list */ | ||||
| 24027 | char z[8]; /* Dequoted value for the string */ | ||||
| 24028 | }; | ||||
| 24029 | |||||
| 24030 | /* | ||||
| 24031 | ** An instance of the virtual machine. This structure contains the complete | ||||
| 24032 | ** state of the virtual machine. | ||||
| 24033 | ** | ||||
| 24034 | ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare() | ||||
| 24035 | ** is really a pointer to an instance of this structure. | ||||
| 24036 | */ | ||||
| 24037 | struct Vdbe { | ||||
| 24038 | sqlite3 *db; /* The database connection that owns this statement */ | ||||
| 24039 | Vdbe **ppVPrev,*pVNext; /* Linked list of VDBEs with the same Vdbe.db */ | ||||
| 24040 | Parse *pParse; /* Parsing context used to create this Vdbe */ | ||||
| 24041 | ynVar nVar; /* Number of entries in aVar[] */ | ||||
| 24042 | int nMem; /* Number of memory locations currently allocated */ | ||||
| 24043 | int nCursor; /* Number of slots in apCsr[] */ | ||||
| 24044 | u32 cacheCtr; /* VdbeCursor row cache generation counter */ | ||||
| 24045 | int pc; /* The program counter */ | ||||
| 24046 | int rc; /* Value to return */ | ||||
| 24047 | i64 nChange; /* Number of db changes made since last reset */ | ||||
| 24048 | int iStatement; /* Statement number (or 0 if has no opened stmt) */ | ||||
| 24049 | i64 iCurrentTime; /* Value of julianday('now') for this statement */ | ||||
| 24050 | i64 nFkConstraint; /* Number of imm. FK constraints this VM */ | ||||
| 24051 | i64 nStmtDefCons; /* Number of def. constraints when stmt started */ | ||||
| 24052 | i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */ | ||||
| 24053 | Mem *aMem; /* The memory locations */ | ||||
| 24054 | Mem **apArg; /* Arguments xUpdate and xFilter vtab methods */ | ||||
| 24055 | VdbeCursor **apCsr; /* One element of this array for each open cursor */ | ||||
| 24056 | Mem *aVar; /* Values for the OP_Variable opcode. */ | ||||
| 24057 | |||||
| 24058 | /* When allocating a new Vdbe object, all of the fields below should be | ||||
| 24059 | ** initialized to zero or NULL */ | ||||
| 24060 | |||||
| 24061 | Op *aOp; /* Space to hold the virtual machine's program */ | ||||
| 24062 | int nOp; /* Number of instructions in the program */ | ||||
| 24063 | int nOpAlloc; /* Slots allocated for aOp[] */ | ||||
| 24064 | Mem *aColName; /* Column names to return */ | ||||
| 24065 | Mem *pResultRow; /* Current output row */ | ||||
| 24066 | char *zErrMsg; /* Error message written here */ | ||||
| 24067 | VList *pVList; /* Name of variables */ | ||||
| 24068 | #ifndef SQLITE_OMIT_TRACE | ||||
| 24069 | i64 startTime; /* Time when query started - used for profiling */ | ||||
| 24070 | #endif | ||||
| 24071 | #ifdef SQLITE_DEBUG | ||||
| 24072 | int rcApp; /* errcode set by sqlite3_result_error_code() */ | ||||
| 24073 | u32 nWrite; /* Number of write operations that have occurred */ | ||||
| 24074 | int napArg; /* Size of the apArg[] array */ | ||||
| 24075 | #endif | ||||
| 24076 | u16 nResColumn; /* Number of columns in one row of the result set */ | ||||
| 24077 | u16 nResAlloc; /* Column slots allocated to aColName[] */ | ||||
| 24078 | u8 errorAction; /* Recovery action to do in case of an error */ | ||||
| 24079 | u8 minWriteFileFormat; /* Minimum file format for writable database files */ | ||||
| 24080 | u8 prepFlags; /* SQLITE_PREPARE_* flags */ | ||||
| 24081 | u8 eVdbeState; /* On of the VDBE_*_STATE values */ | ||||
| 24082 | bft expired:2; /* 1: recompile VM immediately 2: when convenient */ | ||||
| 24083 | bft explain:2; /* 0: normal, 1: EXPLAIN, 2: EXPLAIN QUERY PLAN */ | ||||
| 24084 | bft changeCntOn:1; /* True to update the change-counter */ | ||||
| 24085 | bft usesStmtJournal:1; /* True if uses a statement journal */ | ||||
| 24086 | bft readOnly:1; /* True for statements that do not write */ | ||||
| 24087 | bft bIsReader:1; /* True for statements that read */ | ||||
| 24088 | bft haveEqpOps:1; /* Bytecode supports EXPLAIN QUERY PLAN */ | ||||
| 24089 | yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */ | ||||
| 24090 | yDbMask lockMask; /* Subset of btreeMask that requires a lock */ | ||||
| 24091 | u32 aCounter[9]; /* Counters used by sqlite3_stmt_status() */ | ||||
| 24092 | char *zSql; /* Text of the SQL statement that generated this */ | ||||
| 24093 | #ifdef SQLITE_ENABLE_NORMALIZE | ||||
| 24094 | char *zNormSql; /* Normalization of the associated SQL statement */ | ||||
| 24095 | DblquoteStr *pDblStr; /* List of double-quoted string literals */ | ||||
| 24096 | #endif | ||||
| 24097 | void *pFree; /* Free this when deleting the vdbe */ | ||||
| 24098 | VdbeFrame *pFrame; /* Parent frame */ | ||||
| 24099 | VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ | ||||
| 24100 | int nFrame; /* Number of frames in pFrame list */ | ||||
| 24101 | u32 expmask; /* Binding to these vars invalidates VM */ | ||||
| 24102 | SubProgram *pProgram; /* Linked list of all sub-programs used by VM */ | ||||
| 24103 | AuxData *pAuxData; /* Linked list of auxdata allocations */ | ||||
| 24104 | #ifdef SQLITE_ENABLE_STMT_SCANSTATUS1 | ||||
| 24105 | int nScan; /* Entries in aScan[] */ | ||||
| 24106 | ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */ | ||||
| 24107 | #endif | ||||
| 24108 | }; | ||||
| 24109 | |||||
| 24110 | /* | ||||
| 24111 | ** The following are allowed values for Vdbe.eVdbeState | ||||
| 24112 | */ | ||||
| 24113 | #define VDBE_INIT_STATE0 0 /* Prepared statement under construction */ | ||||
| 24114 | #define VDBE_READY_STATE1 1 /* Ready to run but not yet started */ | ||||
| 24115 | #define VDBE_RUN_STATE2 2 /* Run in progress */ | ||||
| 24116 | #define VDBE_HALT_STATE3 3 /* Finished. Need reset() or finalize() */ | ||||
| 24117 | |||||
| 24118 | /* | ||||
| 24119 | ** Structure used to store the context required by the | ||||
| 24120 | ** sqlite3_preupdate_*() API functions. | ||||
| 24121 | */ | ||||
| 24122 | struct PreUpdate { | ||||
| 24123 | Vdbe *v; | ||||
| 24124 | VdbeCursor *pCsr; /* Cursor to read old values from */ | ||||
| 24125 | int op; /* One of SQLITE_INSERT, UPDATE, DELETE */ | ||||
| 24126 | u8 *aRecord; /* old.* database record */ | ||||
| 24127 | KeyInfo *pKeyinfo; /* Key information */ | ||||
| 24128 | UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */ | ||||
| 24129 | UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */ | ||||
| 24130 | int iNewReg; /* Register for new.* values */ | ||||
| 24131 | int iBlobWrite; /* Value returned by preupdate_blobwrite() */ | ||||
| 24132 | i64 iKey1; /* First key value passed to hook */ | ||||
| 24133 | i64 iKey2; /* Second key value passed to hook */ | ||||
| 24134 | Mem oldipk; /* Memory cell holding "old" IPK value */ | ||||
| 24135 | Mem *aNew; /* Array of new.* values */ | ||||
| 24136 | Table *pTab; /* Schema object being updated */ | ||||
| 24137 | Index *pPk; /* PK index if pTab is WITHOUT ROWID */ | ||||
| 24138 | sqlite3_value **apDflt; /* Array of default values, if required */ | ||||
| 24139 | u8 keyinfoSpace[SZ_KEYINFO(0)(__builtin_offsetof(KeyInfo, aColl) + (0)*sizeof(CollSeq*))]; /* Space to hold pKeyinfo[0] content */ | ||||
| 24140 | }; | ||||
| 24141 | |||||
| 24142 | /* | ||||
| 24143 | ** An instance of this object is used to pass an vector of values into | ||||
| 24144 | ** OP_VFilter, the xFilter method of a virtual table. The vector is the | ||||
| 24145 | ** set of values on the right-hand side of an IN constraint. | ||||
| 24146 | ** | ||||
| 24147 | ** The value as passed into xFilter is an sqlite3_value with a "pointer" | ||||
| 24148 | ** type, such as is generated by sqlite3_result_pointer() and read by | ||||
| 24149 | ** sqlite3_value_pointer. Such values have MEM_Term|MEM_Subtype|MEM_Null | ||||
| 24150 | ** and a subtype of 'p'. The sqlite3_vtab_in_first() and _next() interfaces | ||||
| 24151 | ** know how to use this object to step through all the values in the | ||||
| 24152 | ** right operand of the IN constraint. | ||||
| 24153 | */ | ||||
| 24154 | typedef struct ValueList ValueList; | ||||
| 24155 | struct ValueList { | ||||
| 24156 | BtCursor *pCsr; /* An ephemeral table holding all values */ | ||||
| 24157 | sqlite3_value *pOut; /* Register to hold each decoded output value */ | ||||
| 24158 | }; | ||||
| 24159 | |||||
| 24160 | /* Size of content associated with serial types that fit into a | ||||
| 24161 | ** single-byte varint. | ||||
| 24162 | */ | ||||
| 24163 | #ifndef SQLITE_AMALGAMATION1 | ||||
| 24164 | SQLITE_PRIVATEstatic const u8 sqlite3SmallTypeSizes[]; | ||||
| 24165 | #endif | ||||
| 24166 | |||||
| 24167 | /* | ||||
| 24168 | ** Function prototypes | ||||
| 24169 | */ | ||||
| 24170 | SQLITE_PRIVATEstatic void sqlite3VdbeError(Vdbe*, const char *, ...); | ||||
| 24171 | SQLITE_PRIVATEstatic void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); | ||||
| 24172 | SQLITE_PRIVATEstatic void sqlite3VdbeFreeCursorNN(Vdbe*,VdbeCursor*); | ||||
| 24173 | void sqliteVdbePopStack(Vdbe*,int); | ||||
| 24174 | SQLITE_PRIVATEstatic int SQLITE_NOINLINE__attribute__((noinline)) sqlite3VdbeHandleMovedCursor(VdbeCursor *p); | ||||
| 24175 | SQLITE_PRIVATEstatic int SQLITE_NOINLINE__attribute__((noinline)) sqlite3VdbeFinishMoveto(VdbeCursor*); | ||||
| 24176 | SQLITE_PRIVATEstatic int sqlite3VdbeCursorRestore(VdbeCursor*); | ||||
| 24177 | SQLITE_PRIVATEstatic u32 sqlite3VdbeSerialTypeLen(u32); | ||||
| 24178 | SQLITE_PRIVATEstatic u8 sqlite3VdbeOneByteSerialTypeLen(u8); | ||||
| 24179 | #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT | ||||
| 24180 | SQLITE_PRIVATEstatic u64 sqlite3FloatSwap(u64 in); | ||||
| 24181 | # define swapMixedEndianFloat(X) X = sqlite3FloatSwap(X) | ||||
| 24182 | #else | ||||
| 24183 | # define swapMixedEndianFloat(X) | ||||
| 24184 | #endif | ||||
| 24185 | SQLITE_PRIVATEstatic void sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); | ||||
| 24186 | SQLITE_PRIVATEstatic void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int); | ||||
| 24187 | |||||
| 24188 | int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); | ||||
| 24189 | SQLITE_PRIVATEstatic int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*); | ||||
| 24190 | SQLITE_PRIVATEstatic int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*); | ||||
| 24191 | SQLITE_PRIVATEstatic int sqlite3VdbeExec(Vdbe*); | ||||
| 24192 | #if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB) | ||||
| 24193 | SQLITE_PRIVATEstatic int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**); | ||||
| 24194 | SQLITE_PRIVATEstatic char *sqlite3VdbeDisplayP4(sqlite3*,Op*); | ||||
| 24195 | #endif | ||||
| 24196 | #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) | ||||
| 24197 | SQLITE_PRIVATEstatic char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*); | ||||
| 24198 | #endif | ||||
| 24199 | #if !defined(SQLITE_OMIT_EXPLAIN) | ||||
| 24200 | SQLITE_PRIVATEstatic int sqlite3VdbeList(Vdbe*); | ||||
| 24201 | #endif | ||||
| 24202 | SQLITE_PRIVATEstatic int sqlite3VdbeHalt(Vdbe*); | ||||
| 24203 | SQLITE_PRIVATEstatic int sqlite3VdbeChangeEncoding(Mem *, int); | ||||
| 24204 | SQLITE_PRIVATEstatic int sqlite3VdbeMemTooBig(Mem*); | ||||
| 24205 | SQLITE_PRIVATEstatic int sqlite3VdbeMemCopy(Mem*, const Mem*); | ||||
| 24206 | SQLITE_PRIVATEstatic void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); | ||||
| 24207 | SQLITE_PRIVATEstatic void sqlite3VdbeMemMove(Mem*, Mem*); | ||||
| 24208 | SQLITE_PRIVATEstatic int sqlite3VdbeMemNulTerminate(Mem*); | ||||
| 24209 | SQLITE_PRIVATEstatic int sqlite3VdbeMemSetStr(Mem*, const char*, i64, u8, void(*)(void*)); | ||||
| 24210 | SQLITE_PRIVATEstatic void sqlite3VdbeMemSetInt64(Mem*, i64); | ||||
| 24211 | #ifdef SQLITE_OMIT_FLOATING_POINT | ||||
| 24212 | # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 | ||||
| 24213 | #else | ||||
| 24214 | SQLITE_PRIVATEstatic void sqlite3VdbeMemSetDouble(Mem*, double); | ||||
| 24215 | #endif | ||||
| 24216 | SQLITE_PRIVATEstatic void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*)); | ||||
| 24217 | SQLITE_PRIVATEstatic void sqlite3VdbeMemInit(Mem*,sqlite3*,u16); | ||||
| 24218 | SQLITE_PRIVATEstatic void sqlite3VdbeMemSetNull(Mem*); | ||||
| 24219 | #ifndef SQLITE_OMIT_INCRBLOB | ||||
| 24220 | SQLITE_PRIVATEstatic void sqlite3VdbeMemSetZeroBlob(Mem*,int); | ||||
| 24221 | #else | ||||
| 24222 | SQLITE_PRIVATEstatic int sqlite3VdbeMemSetZeroBlob(Mem*,int); | ||||
| 24223 | #endif | ||||
| 24224 | #ifdef SQLITE_DEBUG | ||||
| 24225 | SQLITE_PRIVATEstatic int sqlite3VdbeMemIsRowSet(const Mem*); | ||||
| 24226 | #endif | ||||
| 24227 | SQLITE_PRIVATEstatic int sqlite3VdbeMemSetRowSet(Mem*); | ||||
| 24228 | SQLITE_PRIVATEstatic void sqlite3VdbeMemZeroTerminateIfAble(Mem*); | ||||
| 24229 | SQLITE_PRIVATEstatic int sqlite3VdbeMemMakeWriteable(Mem*); | ||||
| 24230 | SQLITE_PRIVATEstatic int sqlite3VdbeMemStringify(Mem*, u8, u8); | ||||
| 24231 | SQLITE_PRIVATEstatic int sqlite3IntFloatCompare(i64,double); | ||||
| 24232 | SQLITE_PRIVATEstatic i64 sqlite3VdbeIntValue(const Mem*); | ||||
| 24233 | SQLITE_PRIVATEstatic int sqlite3VdbeMemIntegerify(Mem*); | ||||
| 24234 | SQLITE_PRIVATEstatic double sqlite3VdbeRealValue(Mem*); | ||||
| 24235 | SQLITE_PRIVATEstatic int sqlite3VdbeBooleanValue(Mem*, int ifNull); | ||||
| 24236 | SQLITE_PRIVATEstatic void sqlite3VdbeIntegerAffinity(Mem*); | ||||
| 24237 | SQLITE_PRIVATEstatic int sqlite3VdbeMemRealify(Mem*); | ||||
| 24238 | SQLITE_PRIVATEstatic int sqlite3VdbeMemNumerify(Mem*); | ||||
| 24239 | SQLITE_PRIVATEstatic int sqlite3VdbeMemCast(Mem*,u8,u8); | ||||
| 24240 | SQLITE_PRIVATEstatic int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*); | ||||
| 24241 | SQLITE_PRIVATEstatic int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*); | ||||
| 24242 | SQLITE_PRIVATEstatic void sqlite3VdbeMemRelease(Mem *p); | ||||
| 24243 | SQLITE_PRIVATEstatic void sqlite3VdbeMemReleaseMalloc(Mem*p); | ||||
| 24244 | SQLITE_PRIVATEstatic int sqlite3VdbeMemFinalize(Mem*, FuncDef*); | ||||
| 24245 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 24246 | SQLITE_PRIVATEstatic int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*); | ||||
| 24247 | #endif | ||||
| 24248 | #if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB) | ||||
| 24249 | SQLITE_PRIVATEstatic const char *sqlite3OpcodeName(int); | ||||
| 24250 | #endif | ||||
| 24251 | SQLITE_PRIVATEstatic int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); | ||||
| 24252 | SQLITE_PRIVATEstatic int sqlite3VdbeMemClearAndResize(Mem *pMem, int n); | ||||
| 24253 | SQLITE_PRIVATEstatic int sqlite3VdbeCloseStatement(Vdbe *, int); | ||||
| 24254 | #ifdef SQLITE_DEBUG | ||||
| 24255 | SQLITE_PRIVATEstatic int sqlite3VdbeFrameIsValid(VdbeFrame*); | ||||
| 24256 | #endif | ||||
| 24257 | SQLITE_PRIVATEstatic void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */ | ||||
| 24258 | SQLITE_PRIVATEstatic void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */ | ||||
| 24259 | SQLITE_PRIVATEstatic int sqlite3VdbeFrameRestore(VdbeFrame *); | ||||
| 24260 | #ifdef SQLITE_ENABLE_PREUPDATE_HOOK1 | ||||
| 24261 | SQLITE_PRIVATEstatic void sqlite3VdbePreUpdateHook( | ||||
| 24262 | Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int,int); | ||||
| 24263 | #endif | ||||
| 24264 | SQLITE_PRIVATEstatic int sqlite3VdbeTransferError(Vdbe *p); | ||||
| 24265 | |||||
| 24266 | SQLITE_PRIVATEstatic int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *); | ||||
| 24267 | SQLITE_PRIVATEstatic void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *); | ||||
| 24268 | SQLITE_PRIVATEstatic void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *); | ||||
| 24269 | SQLITE_PRIVATEstatic int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *); | ||||
| 24270 | SQLITE_PRIVATEstatic int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *); | ||||
| 24271 | SQLITE_PRIVATEstatic int sqlite3VdbeSorterRewind(const VdbeCursor *, int *); | ||||
| 24272 | SQLITE_PRIVATEstatic int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *); | ||||
| 24273 | SQLITE_PRIVATEstatic int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *); | ||||
| 24274 | |||||
| 24275 | SQLITE_PRIVATEstatic void sqlite3VdbeValueListFree(void*); | ||||
| 24276 | |||||
| 24277 | #ifdef SQLITE_DEBUG | ||||
| 24278 | SQLITE_PRIVATEstatic void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*); | ||||
| 24279 | SQLITE_PRIVATEstatic void sqlite3VdbeAssertAbortable(Vdbe*); | ||||
| 24280 | #else | ||||
| 24281 | # define sqlite3VdbeIncrWriteCounter(V,C) | ||||
| 24282 | # define sqlite3VdbeAssertAbortable(V) | ||||
| 24283 | #endif | ||||
| 24284 | |||||
| 24285 | #if !defined(SQLITE_OMIT_SHARED_CACHE) | ||||
| 24286 | SQLITE_PRIVATEstatic void sqlite3VdbeEnter(Vdbe*); | ||||
| 24287 | #else | ||||
| 24288 | # define sqlite3VdbeEnter(X) | ||||
| 24289 | #endif | ||||
| 24290 | |||||
| 24291 | #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE2>0 | ||||
| 24292 | SQLITE_PRIVATEstatic void sqlite3VdbeLeave(Vdbe*); | ||||
| 24293 | #else | ||||
| 24294 | # define sqlite3VdbeLeave(X) | ||||
| 24295 | #endif | ||||
| 24296 | |||||
| 24297 | #ifdef SQLITE_DEBUG | ||||
| 24298 | SQLITE_PRIVATEstatic void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*); | ||||
| 24299 | SQLITE_PRIVATEstatic int sqlite3VdbeCheckMemInvariants(Mem*); | ||||
| 24300 | #endif | ||||
| 24301 | |||||
| 24302 | #ifndef SQLITE_OMIT_FOREIGN_KEY | ||||
| 24303 | SQLITE_PRIVATEstatic int sqlite3VdbeCheckFk(Vdbe *, int); | ||||
| 24304 | #else | ||||
| 24305 | # define sqlite3VdbeCheckFk(p,i) 0 | ||||
| 24306 | #endif | ||||
| 24307 | |||||
| 24308 | #ifdef SQLITE_DEBUG | ||||
| 24309 | SQLITE_PRIVATEstatic void sqlite3VdbePrintSql(Vdbe*); | ||||
| 24310 | SQLITE_PRIVATEstatic void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr); | ||||
| 24311 | #endif | ||||
| 24312 | #ifndef SQLITE_OMIT_UTF16 | ||||
| 24313 | SQLITE_PRIVATEstatic int sqlite3VdbeMemTranslate(Mem*, u8); | ||||
| 24314 | SQLITE_PRIVATEstatic int sqlite3VdbeMemHandleBom(Mem *pMem); | ||||
| 24315 | #endif | ||||
| 24316 | |||||
| 24317 | #ifndef SQLITE_OMIT_INCRBLOB | ||||
| 24318 | SQLITE_PRIVATEstatic int sqlite3VdbeMemExpandBlob(Mem *); | ||||
| 24319 | #define ExpandBlob(P)(((P)->flags&0x0400)?sqlite3VdbeMemExpandBlob(P):0) (((P)->flags&MEM_Zero0x0400)?sqlite3VdbeMemExpandBlob(P):0) | ||||
| 24320 | #else | ||||
| 24321 | #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK0 | ||||
| 24322 | #define ExpandBlob(P)(((P)->flags&0x0400)?sqlite3VdbeMemExpandBlob(P):0) SQLITE_OK0 | ||||
| 24323 | #endif | ||||
| 24324 | |||||
| 24325 | #endif /* !defined(SQLITE_VDBEINT_H) */ | ||||
| 24326 | |||||
| 24327 | /************** End of vdbeInt.h *********************************************/ | ||||
| 24328 | /************** Continuing where we left off in status.c *********************/ | ||||
| 24329 | |||||
| 24330 | /* | ||||
| 24331 | ** Variables in which to record status information. | ||||
| 24332 | */ | ||||
| 24333 | #if SQLITE_PTRSIZE8>4 | ||||
| 24334 | typedef sqlite3_int64 sqlite3StatValueType; | ||||
| 24335 | #else | ||||
| 24336 | typedef u32 sqlite3StatValueType; | ||||
| 24337 | #endif | ||||
| 24338 | typedef struct sqlite3StatType sqlite3StatType; | ||||
| 24339 | static SQLITE_WSD struct sqlite3StatType { | ||||
| 24340 | sqlite3StatValueType nowValue[10]; /* Current value */ | ||||
| 24341 | sqlite3StatValueType mxValue[10]; /* Maximum value */ | ||||
| 24342 | } sqlite3Stat = { {0,}, {0,} }; | ||||
| 24343 | |||||
| 24344 | /* | ||||
| 24345 | ** Elements of sqlite3Stat[] are protected by either the memory allocator | ||||
| 24346 | ** mutex, or by the pcache1 mutex. The following array determines which. | ||||
| 24347 | */ | ||||
| 24348 | static const char statMutex[] = { | ||||
| 24349 | 0, /* SQLITE_STATUS_MEMORY_USED */ | ||||
| 24350 | 1, /* SQLITE_STATUS_PAGECACHE_USED */ | ||||
| 24351 | 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */ | ||||
| 24352 | 0, /* SQLITE_STATUS_SCRATCH_USED */ | ||||
| 24353 | 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */ | ||||
| 24354 | 0, /* SQLITE_STATUS_MALLOC_SIZE */ | ||||
| 24355 | 0, /* SQLITE_STATUS_PARSER_STACK */ | ||||
| 24356 | 1, /* SQLITE_STATUS_PAGECACHE_SIZE */ | ||||
| 24357 | 0, /* SQLITE_STATUS_SCRATCH_SIZE */ | ||||
| 24358 | 0, /* SQLITE_STATUS_MALLOC_COUNT */ | ||||
| 24359 | }; | ||||
| 24360 | |||||
| 24361 | |||||
| 24362 | /* The "wsdStat" macro will resolve to the status information | ||||
| 24363 | ** state vector. If writable static data is unsupported on the target, | ||||
| 24364 | ** we have to locate the state vector at run-time. In the more common | ||||
| 24365 | ** case where writable static data is supported, wsdStat can refer directly | ||||
| 24366 | ** to the "sqlite3Stat" state vector declared above. | ||||
| 24367 | */ | ||||
| 24368 | #ifdef SQLITE_OMIT_WSD | ||||
| 24369 | # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)sqlite3Stat | ||||
| 24370 | # define wsdStatsqlite3Stat x[0] | ||||
| 24371 | #else | ||||
| 24372 | # define wsdStatInit | ||||
| 24373 | # define wsdStatsqlite3Stat sqlite3Stat | ||||
| 24374 | #endif | ||||
| 24375 | |||||
| 24376 | /* | ||||
| 24377 | ** Return the current value of a status parameter. The caller must | ||||
| 24378 | ** be holding the appropriate mutex. | ||||
| 24379 | */ | ||||
| 24380 | SQLITE_PRIVATEstatic sqlite3_int64 sqlite3StatusValue(int op){ | ||||
| 24381 | wsdStatInit; | ||||
| 24382 | assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0)); | ||||
| 24383 | assert( op>=0 && op<ArraySize(statMutex) )((void) (0)); | ||||
| 24384 | assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0)) | ||||
| 24385 | : sqlite3MallocMutex()) )((void) (0)); | ||||
| 24386 | return wsdStatsqlite3Stat.nowValue[op]; | ||||
| 24387 | } | ||||
| 24388 | |||||
| 24389 | /* | ||||
| 24390 | ** Add N to the value of a status record. The caller must hold the | ||||
| 24391 | ** appropriate mutex. (Locking is checked by assert()). | ||||
| 24392 | ** | ||||
| 24393 | ** The StatusUp() routine can accept positive or negative values for N. | ||||
| 24394 | ** The value of N is added to the current status value and the high-water | ||||
| 24395 | ** mark is adjusted if necessary. | ||||
| 24396 | ** | ||||
| 24397 | ** The StatusDown() routine lowers the current value by N. The highwater | ||||
| 24398 | ** mark is unchanged. N must be non-negative for StatusDown(). | ||||
| 24399 | */ | ||||
| 24400 | SQLITE_PRIVATEstatic void sqlite3StatusUp(int op, int N){ | ||||
| 24401 | wsdStatInit; | ||||
| 24402 | assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0)); | ||||
| 24403 | assert( op>=0 && op<ArraySize(statMutex) )((void) (0)); | ||||
| 24404 | assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0)) | ||||
| 24405 | : sqlite3MallocMutex()) )((void) (0)); | ||||
| 24406 | wsdStatsqlite3Stat.nowValue[op] += N; | ||||
| 24407 | if( wsdStatsqlite3Stat.nowValue[op]>wsdStatsqlite3Stat.mxValue[op] ){ | ||||
| 24408 | wsdStatsqlite3Stat.mxValue[op] = wsdStatsqlite3Stat.nowValue[op]; | ||||
| 24409 | } | ||||
| 24410 | } | ||||
| 24411 | SQLITE_PRIVATEstatic void sqlite3StatusDown(int op, int N){ | ||||
| 24412 | wsdStatInit; | ||||
| 24413 | assert( N>=0 )((void) (0)); | ||||
| 24414 | assert( op>=0 && op<ArraySize(statMutex) )((void) (0)); | ||||
| 24415 | assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0)) | ||||
| 24416 | : sqlite3MallocMutex()) )((void) (0)); | ||||
| 24417 | assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0)); | ||||
| 24418 | wsdStatsqlite3Stat.nowValue[op] -= N; | ||||
| 24419 | } | ||||
| 24420 | |||||
| 24421 | /* | ||||
| 24422 | ** Adjust the highwater mark if necessary. | ||||
| 24423 | ** The caller must hold the appropriate mutex. | ||||
| 24424 | */ | ||||
| 24425 | SQLITE_PRIVATEstatic void sqlite3StatusHighwater(int op, int X){ | ||||
| 24426 | sqlite3StatValueType newValue; | ||||
| 24427 | wsdStatInit; | ||||
| 24428 | assert( X>=0 )((void) (0)); | ||||
| 24429 | newValue = (sqlite3StatValueType)X; | ||||
| 24430 | assert( op>=0 && op<ArraySize(wsdStat.nowValue) )((void) (0)); | ||||
| 24431 | assert( op>=0 && op<ArraySize(statMutex) )((void) (0)); | ||||
| 24432 | assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()((void) (0)) | ||||
| 24433 | : sqlite3MallocMutex()) )((void) (0)); | ||||
| 24434 | assert( op==SQLITE_STATUS_MALLOC_SIZE((void) (0)) | ||||
| 24435 | || op==SQLITE_STATUS_PAGECACHE_SIZE((void) (0)) | ||||
| 24436 | || op==SQLITE_STATUS_PARSER_STACK )((void) (0)); | ||||
| 24437 | if( newValue>wsdStatsqlite3Stat.mxValue[op] ){ | ||||
| 24438 | wsdStatsqlite3Stat.mxValue[op] = newValue; | ||||
| 24439 | } | ||||
| 24440 | } | ||||
| 24441 | |||||
| 24442 | /* | ||||
| 24443 | ** Query status information. | ||||
| 24444 | */ | ||||
| 24445 | SQLITE_API int sqlite3_status64( | ||||
| 24446 | int op, | ||||
| 24447 | sqlite3_int64 *pCurrent, | ||||
| 24448 | sqlite3_int64 *pHighwater, | ||||
| 24449 | int resetFlag | ||||
| 24450 | ){ | ||||
| 24451 | sqlite3_mutex *pMutex; | ||||
| 24452 | wsdStatInit; | ||||
| 24453 | if( op<0 || op>=ArraySize(wsdStat.nowValue)((int)(sizeof(sqlite3Stat.nowValue)/sizeof(sqlite3Stat.nowValue [0]))) ){ | ||||
| 24454 | return SQLITE_MISUSE_BKPTsqlite3MisuseError(24454); | ||||
| 24455 | } | ||||
| 24456 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 24457 | if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPTsqlite3MisuseError(24457); | ||||
| 24458 | #endif | ||||
| 24459 | pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex(); | ||||
| 24460 | sqlite3_mutex_enter(pMutex); | ||||
| 24461 | *pCurrent = wsdStatsqlite3Stat.nowValue[op]; | ||||
| 24462 | *pHighwater = wsdStatsqlite3Stat.mxValue[op]; | ||||
| 24463 | if( resetFlag ){ | ||||
| 24464 | wsdStatsqlite3Stat.mxValue[op] = wsdStatsqlite3Stat.nowValue[op]; | ||||
| 24465 | } | ||||
| 24466 | sqlite3_mutex_leave(pMutex); | ||||
| 24467 | (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */ | ||||
| 24468 | return SQLITE_OK0; | ||||
| 24469 | } | ||||
| 24470 | SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ | ||||
| 24471 | sqlite3_int64 iCur = 0, iHwtr = 0; | ||||
| 24472 | int rc; | ||||
| 24473 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 24474 | if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPTsqlite3MisuseError(24474); | ||||
| 24475 | #endif | ||||
| 24476 | rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag); | ||||
| 24477 | if( rc==0 ){ | ||||
| 24478 | *pCurrent = (int)iCur; | ||||
| 24479 | *pHighwater = (int)iHwtr; | ||||
| 24480 | } | ||||
| 24481 | return rc; | ||||
| 24482 | } | ||||
| 24483 | |||||
| 24484 | /* | ||||
| 24485 | ** Return the number of LookasideSlot elements on the linked list | ||||
| 24486 | */ | ||||
| 24487 | static u32 countLookasideSlots(LookasideSlot *p){ | ||||
| 24488 | u32 cnt = 0; | ||||
| 24489 | while( p ){ | ||||
| 24490 | p = p->pNext; | ||||
| 24491 | cnt++; | ||||
| 24492 | } | ||||
| 24493 | return cnt; | ||||
| 24494 | } | ||||
| 24495 | |||||
| 24496 | /* | ||||
| 24497 | ** Count the number of slots of lookaside memory that are outstanding | ||||
| 24498 | */ | ||||
| 24499 | SQLITE_PRIVATEstatic int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){ | ||||
| 24500 | u32 nInit = countLookasideSlots(db->lookaside.pInit); | ||||
| 24501 | u32 nFree = countLookasideSlots(db->lookaside.pFree); | ||||
| 24502 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 24503 | nInit += countLookasideSlots(db->lookaside.pSmallInit); | ||||
| 24504 | nFree += countLookasideSlots(db->lookaside.pSmallFree); | ||||
| 24505 | #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ | ||||
| 24506 | assert( db->lookaside.nSlot >= nInit+nFree )((void) (0)); | ||||
| 24507 | if( pHighwater ) *pHighwater = (int)(db->lookaside.nSlot - nInit); | ||||
| 24508 | return (int)(db->lookaside.nSlot - (nInit+nFree)); | ||||
| 24509 | } | ||||
| 24510 | |||||
| 24511 | /* | ||||
| 24512 | ** Query status information for a single database connection | ||||
| 24513 | */ | ||||
| 24514 | SQLITE_API int sqlite3_db_status( | ||||
| 24515 | sqlite3 *db, /* The database connection whose status is desired */ | ||||
| 24516 | int op, /* Status verb */ | ||||
| 24517 | int *pCurrent, /* Write current value here */ | ||||
| 24518 | int *pHighwater, /* Write high-water mark here */ | ||||
| 24519 | int resetFlag /* Reset high-water mark if true */ | ||||
| 24520 | ){ | ||||
| 24521 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 24522 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 24523 | if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){ | ||||
| 24524 | return SQLITE_MISUSE_BKPTsqlite3MisuseError(24524); | ||||
| 24525 | } | ||||
| 24526 | #endif | ||||
| 24527 | sqlite3_mutex_enter(db->mutex); | ||||
| 24528 | switch( op ){ | ||||
| 24529 | case SQLITE_DBSTATUS_LOOKASIDE_USED0: { | ||||
| 24530 | *pCurrent = sqlite3LookasideUsed(db, pHighwater); | ||||
| 24531 | if( resetFlag ){ | ||||
| 24532 | LookasideSlot *p = db->lookaside.pFree; | ||||
| 24533 | if( p ){ | ||||
| 24534 | while( p->pNext ) p = p->pNext; | ||||
| 24535 | p->pNext = db->lookaside.pInit; | ||||
| 24536 | db->lookaside.pInit = db->lookaside.pFree; | ||||
| 24537 | db->lookaside.pFree = 0; | ||||
| 24538 | } | ||||
| 24539 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 24540 | p = db->lookaside.pSmallFree; | ||||
| 24541 | if( p ){ | ||||
| 24542 | while( p->pNext ) p = p->pNext; | ||||
| 24543 | p->pNext = db->lookaside.pSmallInit; | ||||
| 24544 | db->lookaside.pSmallInit = db->lookaside.pSmallFree; | ||||
| 24545 | db->lookaside.pSmallFree = 0; | ||||
| 24546 | } | ||||
| 24547 | #endif | ||||
| 24548 | } | ||||
| 24549 | break; | ||||
| 24550 | } | ||||
| 24551 | |||||
| 24552 | case SQLITE_DBSTATUS_LOOKASIDE_HIT4: | ||||
| 24553 | case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE5: | ||||
| 24554 | case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL6: { | ||||
| 24555 | testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT ); | ||||
| 24556 | testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE ); | ||||
| 24557 | testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL ); | ||||
| 24558 | assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 )((void) (0)); | ||||
| 24559 | assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 )((void) (0)); | ||||
| 24560 | *pCurrent = 0; | ||||
| 24561 | *pHighwater = (int)db->lookaside.anStat[op-SQLITE_DBSTATUS_LOOKASIDE_HIT4]; | ||||
| 24562 | if( resetFlag ){ | ||||
| 24563 | db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT4] = 0; | ||||
| 24564 | } | ||||
| 24565 | break; | ||||
| 24566 | } | ||||
| 24567 | |||||
| 24568 | /* | ||||
| 24569 | ** Return an approximation for the amount of memory currently used | ||||
| 24570 | ** by all pagers associated with the given database connection. The | ||||
| 24571 | ** highwater mark is meaningless and is returned as zero. | ||||
| 24572 | */ | ||||
| 24573 | case SQLITE_DBSTATUS_CACHE_USED_SHARED11: | ||||
| 24574 | case SQLITE_DBSTATUS_CACHE_USED1: { | ||||
| 24575 | int totalUsed = 0; | ||||
| 24576 | int i; | ||||
| 24577 | sqlite3BtreeEnterAll(db); | ||||
| 24578 | for(i=0; i<db->nDb; i++){ | ||||
| 24579 | Btree *pBt = db->aDb[i].pBt; | ||||
| 24580 | if( pBt ){ | ||||
| 24581 | Pager *pPager = sqlite3BtreePager(pBt); | ||||
| 24582 | int nByte = sqlite3PagerMemUsed(pPager); | ||||
| 24583 | if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED11 ){ | ||||
| 24584 | nByte = nByte / sqlite3BtreeConnectionCount(pBt); | ||||
| 24585 | } | ||||
| 24586 | totalUsed += nByte; | ||||
| 24587 | } | ||||
| 24588 | } | ||||
| 24589 | sqlite3BtreeLeaveAll(db); | ||||
| 24590 | *pCurrent = totalUsed; | ||||
| 24591 | *pHighwater = 0; | ||||
| 24592 | break; | ||||
| 24593 | } | ||||
| 24594 | |||||
| 24595 | /* | ||||
| 24596 | ** *pCurrent gets an accurate estimate of the amount of memory used | ||||
| 24597 | ** to store the schema for all databases (main, temp, and any ATTACHed | ||||
| 24598 | ** databases. *pHighwater is set to zero. | ||||
| 24599 | */ | ||||
| 24600 | case SQLITE_DBSTATUS_SCHEMA_USED2: { | ||||
| 24601 | int i; /* Used to iterate through schemas */ | ||||
| 24602 | int nByte = 0; /* Used to accumulate return value */ | ||||
| 24603 | |||||
| 24604 | sqlite3BtreeEnterAll(db); | ||||
| 24605 | db->pnBytesFreed = &nByte; | ||||
| 24606 | assert( db->lookaside.pEnd==db->lookaside.pTrueEnd )((void) (0)); | ||||
| 24607 | db->lookaside.pEnd = db->lookaside.pStart; | ||||
| 24608 | for(i=0; i<db->nDb; i++){ | ||||
| 24609 | Schema *pSchema = db->aDb[i].pSchema; | ||||
| 24610 | if( ALWAYS(pSchema!=0)(pSchema!=0) ){ | ||||
| 24611 | HashElem *p; | ||||
| 24612 | |||||
| 24613 | nByte += sqlite3GlobalConfigsqlite3Config.m.xRoundup(sizeof(HashElem)) * ( | ||||
| 24614 | pSchema->tblHash.count | ||||
| 24615 | + pSchema->trigHash.count | ||||
| 24616 | + pSchema->idxHash.count | ||||
| 24617 | + pSchema->fkeyHash.count | ||||
| 24618 | ); | ||||
| 24619 | nByte += sqlite3_msize(pSchema->tblHash.ht); | ||||
| 24620 | nByte += sqlite3_msize(pSchema->trigHash.ht); | ||||
| 24621 | nByte += sqlite3_msize(pSchema->idxHash.ht); | ||||
| 24622 | nByte += sqlite3_msize(pSchema->fkeyHash.ht); | ||||
| 24623 | |||||
| 24624 | for(p=sqliteHashFirst(&pSchema->trigHash)((&pSchema->trigHash)->first); p; p=sqliteHashNext(p)((p)->next)){ | ||||
| 24625 | sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)((p)->data)); | ||||
| 24626 | } | ||||
| 24627 | for(p=sqliteHashFirst(&pSchema->tblHash)((&pSchema->tblHash)->first); p; p=sqliteHashNext(p)((p)->next)){ | ||||
| 24628 | sqlite3DeleteTable(db, (Table *)sqliteHashData(p)((p)->data)); | ||||
| 24629 | } | ||||
| 24630 | } | ||||
| 24631 | } | ||||
| 24632 | db->pnBytesFreed = 0; | ||||
| 24633 | db->lookaside.pEnd = db->lookaside.pTrueEnd; | ||||
| 24634 | sqlite3BtreeLeaveAll(db); | ||||
| 24635 | |||||
| 24636 | *pHighwater = 0; | ||||
| 24637 | *pCurrent = nByte; | ||||
| 24638 | break; | ||||
| 24639 | } | ||||
| 24640 | |||||
| 24641 | /* | ||||
| 24642 | ** *pCurrent gets an accurate estimate of the amount of memory used | ||||
| 24643 | ** to store all prepared statements. | ||||
| 24644 | ** *pHighwater is set to zero. | ||||
| 24645 | */ | ||||
| 24646 | case SQLITE_DBSTATUS_STMT_USED3: { | ||||
| 24647 | struct Vdbe *pVdbe; /* Used to iterate through VMs */ | ||||
| 24648 | int nByte = 0; /* Used to accumulate return value */ | ||||
| 24649 | |||||
| 24650 | db->pnBytesFreed = &nByte; | ||||
| 24651 | assert( db->lookaside.pEnd==db->lookaside.pTrueEnd )((void) (0)); | ||||
| 24652 | db->lookaside.pEnd = db->lookaside.pStart; | ||||
| 24653 | for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pVNext){ | ||||
| 24654 | sqlite3VdbeDelete(pVdbe); | ||||
| 24655 | } | ||||
| 24656 | db->lookaside.pEnd = db->lookaside.pTrueEnd; | ||||
| 24657 | db->pnBytesFreed = 0; | ||||
| 24658 | |||||
| 24659 | *pHighwater = 0; /* IMP: R-64479-57858 */ | ||||
| 24660 | *pCurrent = nByte; | ||||
| 24661 | |||||
| 24662 | break; | ||||
| 24663 | } | ||||
| 24664 | |||||
| 24665 | /* | ||||
| 24666 | ** Set *pCurrent to the total cache hits or misses encountered by all | ||||
| 24667 | ** pagers the database handle is connected to. *pHighwater is always set | ||||
| 24668 | ** to zero. | ||||
| 24669 | */ | ||||
| 24670 | case SQLITE_DBSTATUS_CACHE_SPILL12: | ||||
| 24671 | op = SQLITE_DBSTATUS_CACHE_WRITE9+1; | ||||
| 24672 | /* no break */ deliberate_fall_through__attribute__((fallthrough)); | ||||
| 24673 | case SQLITE_DBSTATUS_CACHE_HIT7: | ||||
| 24674 | case SQLITE_DBSTATUS_CACHE_MISS8: | ||||
| 24675 | case SQLITE_DBSTATUS_CACHE_WRITE9:{ | ||||
| 24676 | int i; | ||||
| 24677 | u64 nRet = 0; | ||||
| 24678 | assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 )((void) (0)); | ||||
| 24679 | assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 )((void) (0)); | ||||
| 24680 | |||||
| 24681 | for(i=0; i<db->nDb; i++){ | ||||
| 24682 | if( db->aDb[i].pBt ){ | ||||
| 24683 | Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt); | ||||
| 24684 | sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); | ||||
| 24685 | } | ||||
| 24686 | } | ||||
| 24687 | *pHighwater = 0; /* IMP: R-42420-56072 */ | ||||
| 24688 | /* IMP: R-54100-20147 */ | ||||
| 24689 | /* IMP: R-29431-39229 */ | ||||
| 24690 | *pCurrent = (int)nRet & 0x7fffffff; | ||||
| 24691 | break; | ||||
| 24692 | } | ||||
| 24693 | |||||
| 24694 | /* Set *pCurrent to non-zero if there are unresolved deferred foreign | ||||
| 24695 | ** key constraints. Set *pCurrent to zero if all foreign key constraints | ||||
| 24696 | ** have been satisfied. The *pHighwater is always set to zero. | ||||
| 24697 | */ | ||||
| 24698 | case SQLITE_DBSTATUS_DEFERRED_FKS10: { | ||||
| 24699 | *pHighwater = 0; /* IMP: R-11967-56545 */ | ||||
| 24700 | *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0; | ||||
| 24701 | break; | ||||
| 24702 | } | ||||
| 24703 | |||||
| 24704 | default: { | ||||
| 24705 | rc = SQLITE_ERROR1; | ||||
| 24706 | } | ||||
| 24707 | } | ||||
| 24708 | sqlite3_mutex_leave(db->mutex); | ||||
| 24709 | return rc; | ||||
| 24710 | } | ||||
| 24711 | |||||
| 24712 | /************** End of status.c **********************************************/ | ||||
| 24713 | /************** Begin file date.c ********************************************/ | ||||
| 24714 | /* | ||||
| 24715 | ** 2003 October 31 | ||||
| 24716 | ** | ||||
| 24717 | ** The author disclaims copyright to this source code. In place of | ||||
| 24718 | ** a legal notice, here is a blessing: | ||||
| 24719 | ** | ||||
| 24720 | ** May you do good and not evil. | ||||
| 24721 | ** May you find forgiveness for yourself and forgive others. | ||||
| 24722 | ** May you share freely, never taking more than you give. | ||||
| 24723 | ** | ||||
| 24724 | ************************************************************************* | ||||
| 24725 | ** This file contains the C functions that implement date and time | ||||
| 24726 | ** functions for SQLite. | ||||
| 24727 | ** | ||||
| 24728 | ** There is only one exported symbol in this file - the function | ||||
| 24729 | ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. | ||||
| 24730 | ** All other code has file scope. | ||||
| 24731 | ** | ||||
| 24732 | ** SQLite processes all times and dates as julian day numbers. The | ||||
| 24733 | ** dates and times are stored as the number of days since noon | ||||
| 24734 | ** in Greenwich on November 24, 4714 B.C. according to the Gregorian | ||||
| 24735 | ** calendar system. | ||||
| 24736 | ** | ||||
| 24737 | ** 1970-01-01 00:00:00 is JD 2440587.5 | ||||
| 24738 | ** 2000-01-01 00:00:00 is JD 2451544.5 | ||||
| 24739 | ** | ||||
| 24740 | ** This implementation requires years to be expressed as a 4-digit number | ||||
| 24741 | ** which means that only dates between 0000-01-01 and 9999-12-31 can | ||||
| 24742 | ** be represented, even though julian day numbers allow a much wider | ||||
| 24743 | ** range of dates. | ||||
| 24744 | ** | ||||
| 24745 | ** The Gregorian calendar system is used for all dates and times, | ||||
| 24746 | ** even those that predate the Gregorian calendar. Historians usually | ||||
| 24747 | ** use the julian calendar for dates prior to 1582-10-15 and for some | ||||
| 24748 | ** dates afterwards, depending on locale. Beware of this difference. | ||||
| 24749 | ** | ||||
| 24750 | ** The conversion algorithms are implemented based on descriptions | ||||
| 24751 | ** in the following text: | ||||
| 24752 | ** | ||||
| 24753 | ** Jean Meeus | ||||
| 24754 | ** Astronomical Algorithms, 2nd Edition, 1998 | ||||
| 24755 | ** ISBN 0-943396-61-1 | ||||
| 24756 | ** Willmann-Bell, Inc | ||||
| 24757 | ** Richmond, Virginia (USA) | ||||
| 24758 | */ | ||||
| 24759 | /* #include "sqliteInt.h" */ | ||||
| 24760 | /* #include <stdlib.h> */ | ||||
| 24761 | /* #include <assert.h> */ | ||||
| 24762 | #include <time.h> | ||||
| 24763 | |||||
| 24764 | #ifndef SQLITE_OMIT_DATETIME_FUNCS | ||||
| 24765 | |||||
| 24766 | /* | ||||
| 24767 | ** The MSVC CRT on Windows CE may not have a localtime() function. | ||||
| 24768 | ** So declare a substitute. The substitute function itself is | ||||
| 24769 | ** defined in "os_win.c". | ||||
| 24770 | */ | ||||
| 24771 | #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \ | ||||
| 24772 | (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API) | ||||
| 24773 | struct tm *__cdecl localtime(const time_t *); | ||||
| 24774 | #endif | ||||
| 24775 | |||||
| 24776 | /* | ||||
| 24777 | ** A structure for holding a single date and time. | ||||
| 24778 | */ | ||||
| 24779 | typedef struct DateTime DateTime; | ||||
| 24780 | struct DateTime { | ||||
| 24781 | sqlite3_int64 iJD; /* The julian day number times 86400000 */ | ||||
| 24782 | int Y, M, D; /* Year, month, and day */ | ||||
| 24783 | int h, m; /* Hour and minutes */ | ||||
| 24784 | int tz; /* Timezone offset in minutes */ | ||||
| 24785 | double s; /* Seconds */ | ||||
| 24786 | char validJD; /* True (1) if iJD is valid */ | ||||
| 24787 | char validYMD; /* True (1) if Y,M,D are valid */ | ||||
| 24788 | char validHMS; /* True (1) if h,m,s are valid */ | ||||
| 24789 | char nFloor; /* Days to implement "floor" */ | ||||
| 24790 | unsigned rawS : 1; /* Raw numeric value stored in s */ | ||||
| 24791 | unsigned isError : 1; /* An overflow has occurred */ | ||||
| 24792 | unsigned useSubsec : 1; /* Display subsecond precision */ | ||||
| 24793 | unsigned isUtc : 1; /* Time is known to be UTC */ | ||||
| 24794 | unsigned isLocal : 1; /* Time is known to be localtime */ | ||||
| 24795 | }; | ||||
| 24796 | |||||
| 24797 | |||||
| 24798 | /* | ||||
| 24799 | ** Convert zDate into one or more integers according to the conversion | ||||
| 24800 | ** specifier zFormat. | ||||
| 24801 | ** | ||||
| 24802 | ** zFormat[] contains 4 characters for each integer converted, except for | ||||
| 24803 | ** the last integer which is specified by three characters. The meaning | ||||
| 24804 | ** of a four-character format specifiers ABCD is: | ||||
| 24805 | ** | ||||
| 24806 | ** A: number of digits to convert. Always "2" or "4". | ||||
| 24807 | ** B: minimum value. Always "0" or "1". | ||||
| 24808 | ** C: maximum value, decoded as: | ||||
| 24809 | ** a: 12 | ||||
| 24810 | ** b: 14 | ||||
| 24811 | ** c: 24 | ||||
| 24812 | ** d: 31 | ||||
| 24813 | ** e: 59 | ||||
| 24814 | ** f: 9999 | ||||
| 24815 | ** D: the separator character, or \000 to indicate this is the | ||||
| 24816 | ** last number to convert. | ||||
| 24817 | ** | ||||
| 24818 | ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would | ||||
| 24819 | ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-". | ||||
| 24820 | ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates | ||||
| 24821 | ** the 2-digit day which is the last integer in the set. | ||||
| 24822 | ** | ||||
| 24823 | ** The function returns the number of successful conversions. | ||||
| 24824 | */ | ||||
| 24825 | static int getDigits(const char *zDate, const char *zFormat, ...){ | ||||
| 24826 | /* The aMx[] array translates the 3rd character of each format | ||||
| 24827 | ** spec into a max size: a b c d e f */ | ||||
| 24828 | static const u16 aMx[] = { 12, 14, 24, 31, 59, 14712 }; | ||||
| 24829 | va_list ap; | ||||
| 24830 | int cnt = 0; | ||||
| 24831 | char nextC; | ||||
| 24832 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 24833 | do{ | ||||
| 24834 | char N = zFormat[0] - '0'; | ||||
| 24835 | char min = zFormat[1] - '0'; | ||||
| 24836 | int val = 0; | ||||
| 24837 | u16 max; | ||||
| 24838 | |||||
| 24839 | assert( zFormat[2]>='a' && zFormat[2]<='f' )((void) (0)); | ||||
| 24840 | max = aMx[zFormat[2] - 'a']; | ||||
| 24841 | nextC = zFormat[3]; | ||||
| 24842 | val = 0; | ||||
| 24843 | while( N-- ){ | ||||
| 24844 | if( !sqlite3Isdigit(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x04) ){ | ||||
| 24845 | goto end_getDigits; | ||||
| 24846 | } | ||||
| 24847 | val = val*10 + *zDate - '0'; | ||||
| 24848 | zDate++; | ||||
| 24849 | } | ||||
| 24850 | if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){ | ||||
| 24851 | goto end_getDigits; | ||||
| 24852 | } | ||||
| 24853 | *va_arg(ap,int*)__builtin_va_arg(ap, int*) = val; | ||||
| 24854 | zDate++; | ||||
| 24855 | cnt++; | ||||
| 24856 | zFormat += 4; | ||||
| 24857 | }while( nextC ); | ||||
| 24858 | end_getDigits: | ||||
| 24859 | va_end(ap)__builtin_va_end(ap); | ||||
| 24860 | return cnt; | ||||
| 24861 | } | ||||
| 24862 | |||||
| 24863 | /* | ||||
| 24864 | ** Parse a timezone extension on the end of a date-time. | ||||
| 24865 | ** The extension is of the form: | ||||
| 24866 | ** | ||||
| 24867 | ** (+/-)HH:MM | ||||
| 24868 | ** | ||||
| 24869 | ** Or the "zulu" notation: | ||||
| 24870 | ** | ||||
| 24871 | ** Z | ||||
| 24872 | ** | ||||
| 24873 | ** If the parse is successful, write the number of minutes | ||||
| 24874 | ** of change in p->tz and return 0. If a parser error occurs, | ||||
| 24875 | ** return non-zero. | ||||
| 24876 | ** | ||||
| 24877 | ** A missing specifier is not considered an error. | ||||
| 24878 | */ | ||||
| 24879 | static int parseTimezone(const char *zDate, DateTime *p){ | ||||
| 24880 | int sgn = 0; | ||||
| 24881 | int nHr, nMn; | ||||
| 24882 | int c; | ||||
| 24883 | while( sqlite3Isspace(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x01) ){ zDate++; } | ||||
| 24884 | p->tz = 0; | ||||
| 24885 | c = *zDate; | ||||
| 24886 | if( c=='-' ){ | ||||
| 24887 | sgn = -1; | ||||
| 24888 | }else if( c=='+' ){ | ||||
| 24889 | sgn = +1; | ||||
| 24890 | }else if( c=='Z' || c=='z' ){ | ||||
| 24891 | zDate++; | ||||
| 24892 | p->isLocal = 0; | ||||
| 24893 | p->isUtc = 1; | ||||
| 24894 | goto zulu_time; | ||||
| 24895 | }else{ | ||||
| 24896 | return c!=0; | ||||
| 24897 | } | ||||
| 24898 | zDate++; | ||||
| 24899 | if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){ | ||||
| 24900 | return 1; | ||||
| 24901 | } | ||||
| 24902 | zDate += 5; | ||||
| 24903 | p->tz = sgn*(nMn + nHr*60); | ||||
| 24904 | zulu_time: | ||||
| 24905 | while( sqlite3Isspace(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x01) ){ zDate++; } | ||||
| 24906 | return *zDate!=0; | ||||
| 24907 | } | ||||
| 24908 | |||||
| 24909 | /* | ||||
| 24910 | ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF. | ||||
| 24911 | ** The HH, MM, and SS must each be exactly 2 digits. The | ||||
| 24912 | ** fractional seconds FFFF can be one or more digits. | ||||
| 24913 | ** | ||||
| 24914 | ** Return 1 if there is a parsing error and 0 on success. | ||||
| 24915 | */ | ||||
| 24916 | static int parseHhMmSs(const char *zDate, DateTime *p){ | ||||
| 24917 | int h, m, s; | ||||
| 24918 | double ms = 0.0; | ||||
| 24919 | if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){ | ||||
| 24920 | return 1; | ||||
| 24921 | } | ||||
| 24922 | zDate += 5; | ||||
| 24923 | if( *zDate==':' ){ | ||||
| 24924 | zDate++; | ||||
| 24925 | if( getDigits(zDate, "20e", &s)!=1 ){ | ||||
| 24926 | return 1; | ||||
| 24927 | } | ||||
| 24928 | zDate += 2; | ||||
| 24929 | if( *zDate=='.' && sqlite3Isdigit(zDate[1])(sqlite3CtypeMap[(unsigned char)(zDate[1])]&0x04) ){ | ||||
| 24930 | double rScale = 1.0; | ||||
| 24931 | zDate++; | ||||
| 24932 | while( sqlite3Isdigit(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x04) ){ | ||||
| 24933 | ms = ms*10.0 + *zDate - '0'; | ||||
| 24934 | rScale *= 10.0; | ||||
| 24935 | zDate++; | ||||
| 24936 | } | ||||
| 24937 | ms /= rScale; | ||||
| 24938 | /* Truncate to avoid problems with sub-milliseconds | ||||
| 24939 | ** rounding. https://sqlite.org/forum/forumpost/766a2c9231 */ | ||||
| 24940 | if( ms>0.999 ) ms = 0.999; | ||||
| 24941 | } | ||||
| 24942 | }else{ | ||||
| 24943 | s = 0; | ||||
| 24944 | } | ||||
| 24945 | p->validJD = 0; | ||||
| 24946 | p->rawS = 0; | ||||
| 24947 | p->validHMS = 1; | ||||
| 24948 | p->h = h; | ||||
| 24949 | p->m = m; | ||||
| 24950 | p->s = s + ms; | ||||
| 24951 | if( parseTimezone(zDate, p) ) return 1; | ||||
| 24952 | return 0; | ||||
| 24953 | } | ||||
| 24954 | |||||
| 24955 | /* | ||||
| 24956 | ** Put the DateTime object into its error state. | ||||
| 24957 | */ | ||||
| 24958 | static void datetimeError(DateTime *p){ | ||||
| 24959 | memset(p, 0, sizeof(*p)); | ||||
| 24960 | p->isError = 1; | ||||
| 24961 | } | ||||
| 24962 | |||||
| 24963 | /* | ||||
| 24964 | ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume | ||||
| 24965 | ** that the YYYY-MM-DD is according to the Gregorian calendar. | ||||
| 24966 | ** | ||||
| 24967 | ** Reference: Meeus page 61 | ||||
| 24968 | */ | ||||
| 24969 | static void computeJD(DateTime *p){ | ||||
| 24970 | int Y, M, D, A, B, X1, X2; | ||||
| 24971 | |||||
| 24972 | if( p->validJD ) return; | ||||
| 24973 | if( p->validYMD ){ | ||||
| 24974 | Y = p->Y; | ||||
| 24975 | M = p->M; | ||||
| 24976 | D = p->D; | ||||
| 24977 | }else{ | ||||
| 24978 | Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ | ||||
| 24979 | M = 1; | ||||
| 24980 | D = 1; | ||||
| 24981 | } | ||||
| 24982 | if( Y<-4713 || Y>9999 || p->rawS ){ | ||||
| 24983 | datetimeError(p); | ||||
| 24984 | return; | ||||
| 24985 | } | ||||
| 24986 | if( M<=2 ){ | ||||
| 24987 | Y--; | ||||
| 24988 | M += 12; | ||||
| 24989 | } | ||||
| 24990 | A = (Y+4800)/100; | ||||
| 24991 | B = 38 - A + (A/4); | ||||
| 24992 | X1 = 36525*(Y+4716)/100; | ||||
| 24993 | X2 = 306001*(M+1)/10000; | ||||
| 24994 | p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); | ||||
| 24995 | p->validJD = 1; | ||||
| 24996 | if( p->validHMS ){ | ||||
| 24997 | p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000 + 0.5); | ||||
| 24998 | if( p->tz ){ | ||||
| 24999 | p->iJD -= p->tz*60000; | ||||
| 25000 | p->validYMD = 0; | ||||
| 25001 | p->validHMS = 0; | ||||
| 25002 | p->tz = 0; | ||||
| 25003 | p->isUtc = 1; | ||||
| 25004 | p->isLocal = 0; | ||||
| 25005 | } | ||||
| 25006 | } | ||||
| 25007 | } | ||||
| 25008 | |||||
| 25009 | /* | ||||
| 25010 | ** Given the YYYY-MM-DD information current in p, determine if there | ||||
| 25011 | ** is day-of-month overflow and set nFloor to the number of days that | ||||
| 25012 | ** would need to be subtracted from the date in order to bring the | ||||
| 25013 | ** date back to the end of the month. | ||||
| 25014 | */ | ||||
| 25015 | static void computeFloor(DateTime *p){ | ||||
| 25016 | assert( p->validYMD || p->isError )((void) (0)); | ||||
| 25017 | assert( p->D>=0 && p->D<=31 )((void) (0)); | ||||
| 25018 | assert( p->M>=0 && p->M<=12 )((void) (0)); | ||||
| 25019 | if( p->D<=28 ){ | ||||
| 25020 | p->nFloor = 0; | ||||
| 25021 | }else if( (1<<p->M) & 0x15aa ){ | ||||
| 25022 | p->nFloor = 0; | ||||
| 25023 | }else if( p->M!=2 ){ | ||||
| 25024 | p->nFloor = (p->D==31); | ||||
| 25025 | }else if( p->Y%4!=0 || (p->Y%100==0 && p->Y%400!=0) ){ | ||||
| 25026 | p->nFloor = p->D - 28; | ||||
| 25027 | }else{ | ||||
| 25028 | p->nFloor = p->D - 29; | ||||
| 25029 | } | ||||
| 25030 | } | ||||
| 25031 | |||||
| 25032 | /* | ||||
| 25033 | ** Parse dates of the form | ||||
| 25034 | ** | ||||
| 25035 | ** YYYY-MM-DD HH:MM:SS.FFF | ||||
| 25036 | ** YYYY-MM-DD HH:MM:SS | ||||
| 25037 | ** YYYY-MM-DD HH:MM | ||||
| 25038 | ** YYYY-MM-DD | ||||
| 25039 | ** | ||||
| 25040 | ** Write the result into the DateTime structure and return 0 | ||||
| 25041 | ** on success and 1 if the input string is not a well-formed | ||||
| 25042 | ** date. | ||||
| 25043 | */ | ||||
| 25044 | static int parseYyyyMmDd(const char *zDate, DateTime *p){ | ||||
| 25045 | int Y, M, D, neg; | ||||
| 25046 | |||||
| 25047 | if( zDate[0]=='-' ){ | ||||
| 25048 | zDate++; | ||||
| 25049 | neg = 1; | ||||
| 25050 | }else{ | ||||
| 25051 | neg = 0; | ||||
| 25052 | } | ||||
| 25053 | if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){ | ||||
| 25054 | return 1; | ||||
| 25055 | } | ||||
| 25056 | zDate += 10; | ||||
| 25057 | while( sqlite3Isspace(*zDate)(sqlite3CtypeMap[(unsigned char)(*zDate)]&0x01) || 'T'==*(u8*)zDate ){ zDate++; } | ||||
| 25058 | if( parseHhMmSs(zDate, p)==0 ){ | ||||
| 25059 | /* We got the time */ | ||||
| 25060 | }else if( *zDate==0 ){ | ||||
| 25061 | p->validHMS = 0; | ||||
| 25062 | }else{ | ||||
| 25063 | return 1; | ||||
| 25064 | } | ||||
| 25065 | p->validJD = 0; | ||||
| 25066 | p->validYMD = 1; | ||||
| 25067 | p->Y = neg ? -Y : Y; | ||||
| 25068 | p->M = M; | ||||
| 25069 | p->D = D; | ||||
| 25070 | computeFloor(p); | ||||
| 25071 | if( p->tz ){ | ||||
| 25072 | computeJD(p); | ||||
| 25073 | } | ||||
| 25074 | return 0; | ||||
| 25075 | } | ||||
| 25076 | |||||
| 25077 | |||||
| 25078 | static void clearYMD_HMS_TZ(DateTime *p); /* Forward declaration */ | ||||
| 25079 | |||||
| 25080 | /* | ||||
| 25081 | ** Set the time to the current time reported by the VFS. | ||||
| 25082 | ** | ||||
| 25083 | ** Return the number of errors. | ||||
| 25084 | */ | ||||
| 25085 | static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){ | ||||
| 25086 | p->iJD = sqlite3StmtCurrentTime(context); | ||||
| 25087 | if( p->iJD>0 ){ | ||||
| 25088 | p->validJD = 1; | ||||
| 25089 | p->isUtc = 1; | ||||
| 25090 | p->isLocal = 0; | ||||
| 25091 | clearYMD_HMS_TZ(p); | ||||
| 25092 | return 0; | ||||
| 25093 | }else{ | ||||
| 25094 | return 1; | ||||
| 25095 | } | ||||
| 25096 | } | ||||
| 25097 | |||||
| 25098 | /* | ||||
| 25099 | ** Input "r" is a numeric quantity which might be a julian day number, | ||||
| 25100 | ** or the number of seconds since 1970. If the value if r is within | ||||
| 25101 | ** range of a julian day number, install it as such and set validJD. | ||||
| 25102 | ** If the value is a valid unix timestamp, put it in p->s and set p->rawS. | ||||
| 25103 | */ | ||||
| 25104 | static void setRawDateNumber(DateTime *p, double r){ | ||||
| 25105 | p->s = r; | ||||
| 25106 | p->rawS = 1; | ||||
| 25107 | if( r>=0.0 && r<5373484.5 ){ | ||||
| 25108 | p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5); | ||||
| 25109 | p->validJD = 1; | ||||
| 25110 | } | ||||
| 25111 | } | ||||
| 25112 | |||||
| 25113 | /* | ||||
| 25114 | ** Attempt to parse the given string into a julian day number. Return | ||||
| 25115 | ** the number of errors. | ||||
| 25116 | ** | ||||
| 25117 | ** The following are acceptable forms for the input string: | ||||
| 25118 | ** | ||||
| 25119 | ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM | ||||
| 25120 | ** DDDD.DD | ||||
| 25121 | ** now | ||||
| 25122 | ** | ||||
| 25123 | ** In the first form, the +/-HH:MM is always optional. The fractional | ||||
| 25124 | ** seconds extension (the ".FFF") is optional. The seconds portion | ||||
| 25125 | ** (":SS.FFF") is option. The year and date can be omitted as long | ||||
| 25126 | ** as there is a time string. The time string can be omitted as long | ||||
| 25127 | ** as there is a year and date. | ||||
| 25128 | */ | ||||
| 25129 | static int parseDateOrTime( | ||||
| 25130 | sqlite3_context *context, | ||||
| 25131 | const char *zDate, | ||||
| 25132 | DateTime *p | ||||
| 25133 | ){ | ||||
| 25134 | double r; | ||||
| 25135 | if( parseYyyyMmDd(zDate,p)==0 ){ | ||||
| 25136 | return 0; | ||||
| 25137 | }else if( parseHhMmSs(zDate, p)==0 ){ | ||||
| 25138 | return 0; | ||||
| 25139 | }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){ | ||||
| 25140 | return setDateTimeToCurrent(context, p); | ||||
| 25141 | }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF81)>0 ){ | ||||
| 25142 | setRawDateNumber(p, r); | ||||
| 25143 | return 0; | ||||
| 25144 | }else if( (sqlite3StrICmp(zDate,"subsec")==0 | ||||
| 25145 | || sqlite3StrICmp(zDate,"subsecond")==0) | ||||
| 25146 | && sqlite3NotPureFunc(context) ){ | ||||
| 25147 | p->useSubsec = 1; | ||||
| 25148 | return setDateTimeToCurrent(context, p); | ||||
| 25149 | } | ||||
| 25150 | return 1; | ||||
| 25151 | } | ||||
| 25152 | |||||
| 25153 | /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999. | ||||
| 25154 | ** Multiplying this by 86400000 gives 464269060799999 as the maximum value | ||||
| 25155 | ** for DateTime.iJD. | ||||
| 25156 | ** | ||||
| 25157 | ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with | ||||
| 25158 | ** such a large integer literal, so we have to encode it. | ||||
| 25159 | */ | ||||
| 25160 | #define INT_464269060799999((((i64)0x1a640)<<32)|0x1072fdff) ((((i64)0x1a640)<<32)|0x1072fdff) | ||||
| 25161 | |||||
| 25162 | /* | ||||
| 25163 | ** Return TRUE if the given julian day number is within range. | ||||
| 25164 | ** | ||||
| 25165 | ** The input is the JulianDay times 86400000. | ||||
| 25166 | */ | ||||
| 25167 | static int validJulianDay(sqlite3_int64 iJD){ | ||||
| 25168 | return iJD>=0 && iJD<=INT_464269060799999((((i64)0x1a640)<<32)|0x1072fdff); | ||||
| 25169 | } | ||||
| 25170 | |||||
| 25171 | /* | ||||
| 25172 | ** Compute the Year, Month, and Day from the julian day number. | ||||
| 25173 | */ | ||||
| 25174 | static void computeYMD(DateTime *p){ | ||||
| 25175 | int Z, alpha, A, B, C, D, E, X1; | ||||
| 25176 | if( p->validYMD ) return; | ||||
| 25177 | if( !p->validJD ){ | ||||
| 25178 | p->Y = 2000; | ||||
| 25179 | p->M = 1; | ||||
| 25180 | p->D = 1; | ||||
| 25181 | }else if( !validJulianDay(p->iJD) ){ | ||||
| 25182 | datetimeError(p); | ||||
| 25183 | return; | ||||
| 25184 | }else{ | ||||
| 25185 | Z = (int)((p->iJD + 43200000)/86400000); | ||||
| 25186 | alpha = (int)((Z + 32044.75)/36524.25) - 52; | ||||
| 25187 | A = Z + 1 + alpha - ((alpha+100)/4) + 25; | ||||
| 25188 | B = A + 1524; | ||||
| 25189 | C = (int)((B - 122.1)/365.25); | ||||
| 25190 | D = (36525*(C&32767))/100; | ||||
| 25191 | E = (int)((B-D)/30.6001); | ||||
| 25192 | X1 = (int)(30.6001*E); | ||||
| 25193 | p->D = B - D - X1; | ||||
| 25194 | p->M = E<14 ? E-1 : E-13; | ||||
| 25195 | p->Y = p->M>2 ? C - 4716 : C - 4715; | ||||
| 25196 | } | ||||
| 25197 | p->validYMD = 1; | ||||
| 25198 | } | ||||
| 25199 | |||||
| 25200 | /* | ||||
| 25201 | ** Compute the Hour, Minute, and Seconds from the julian day number. | ||||
| 25202 | */ | ||||
| 25203 | static void computeHMS(DateTime *p){ | ||||
| 25204 | int day_ms, day_min; /* milliseconds, minutes into the day */ | ||||
| 25205 | if( p->validHMS ) return; | ||||
| 25206 | computeJD(p); | ||||
| 25207 | day_ms = (int)((p->iJD + 43200000) % 86400000); | ||||
| 25208 | p->s = (day_ms % 60000)/1000.0; | ||||
| 25209 | day_min = day_ms/60000; | ||||
| 25210 | p->m = day_min % 60; | ||||
| 25211 | p->h = day_min / 60; | ||||
| 25212 | p->rawS = 0; | ||||
| 25213 | p->validHMS = 1; | ||||
| 25214 | } | ||||
| 25215 | |||||
| 25216 | /* | ||||
| 25217 | ** Compute both YMD and HMS | ||||
| 25218 | */ | ||||
| 25219 | static void computeYMD_HMS(DateTime *p){ | ||||
| 25220 | computeYMD(p); | ||||
| 25221 | computeHMS(p); | ||||
| 25222 | } | ||||
| 25223 | |||||
| 25224 | /* | ||||
| 25225 | ** Clear the YMD and HMS and the TZ | ||||
| 25226 | */ | ||||
| 25227 | static void clearYMD_HMS_TZ(DateTime *p){ | ||||
| 25228 | p->validYMD = 0; | ||||
| 25229 | p->validHMS = 0; | ||||
| 25230 | p->tz = 0; | ||||
| 25231 | } | ||||
| 25232 | |||||
| 25233 | #ifndef SQLITE_OMIT_LOCALTIME | ||||
| 25234 | /* | ||||
| 25235 | ** On recent Windows platforms, the localtime_s() function is available | ||||
| 25236 | ** as part of the "Secure CRT". It is essentially equivalent to | ||||
| 25237 | ** localtime_r() available under most POSIX platforms, except that the | ||||
| 25238 | ** order of the parameters is reversed. | ||||
| 25239 | ** | ||||
| 25240 | ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. | ||||
| 25241 | ** | ||||
| 25242 | ** If the user has not indicated to use localtime_r() or localtime_s() | ||||
| 25243 | ** already, check for an MSVC build environment that provides | ||||
| 25244 | ** localtime_s(). | ||||
| 25245 | */ | ||||
| 25246 | #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \ | ||||
| 25247 | && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE) | ||||
| 25248 | #undef HAVE_LOCALTIME_S | ||||
| 25249 | #define HAVE_LOCALTIME_S 1 | ||||
| 25250 | #endif | ||||
| 25251 | |||||
| 25252 | /* | ||||
| 25253 | ** The following routine implements the rough equivalent of localtime_r() | ||||
| 25254 | ** using whatever operating-system specific localtime facility that | ||||
| 25255 | ** is available. This routine returns 0 on success and | ||||
| 25256 | ** non-zero on any kind of error. | ||||
| 25257 | ** | ||||
| 25258 | ** If the sqlite3GlobalConfig.bLocaltimeFault variable is non-zero then this | ||||
| 25259 | ** routine will always fail. If bLocaltimeFault is nonzero and | ||||
| 25260 | ** sqlite3GlobalConfig.xAltLocaltime is not NULL, then xAltLocaltime() is | ||||
| 25261 | ** invoked in place of the OS-defined localtime() function. | ||||
| 25262 | ** | ||||
| 25263 | ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C | ||||
| 25264 | ** library function localtime_r() is used to assist in the calculation of | ||||
| 25265 | ** local time. | ||||
| 25266 | */ | ||||
| 25267 | static int osLocaltime(time_t *t, struct tm *pTm){ | ||||
| 25268 | int rc; | ||||
| 25269 | #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S | ||||
| 25270 | struct tm *pX; | ||||
| 25271 | #if SQLITE_THREADSAFE2>0 | ||||
| 25272 | sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2); | ||||
| 25273 | #endif | ||||
| 25274 | sqlite3_mutex_enter(mutex); | ||||
| 25275 | pX = localtime(t); | ||||
| 25276 | #ifndef SQLITE_UNTESTABLE | ||||
| 25277 | if( sqlite3GlobalConfigsqlite3Config.bLocaltimeFault ){ | ||||
| 25278 | if( sqlite3GlobalConfigsqlite3Config.xAltLocaltime!=0 | ||||
| 25279 | && 0==sqlite3GlobalConfigsqlite3Config.xAltLocaltime((const void*)t,(void*)pTm) | ||||
| 25280 | ){ | ||||
| 25281 | pX = pTm; | ||||
| 25282 | }else{ | ||||
| 25283 | pX = 0; | ||||
| 25284 | } | ||||
| 25285 | } | ||||
| 25286 | #endif | ||||
| 25287 | if( pX ) *pTm = *pX; | ||||
| 25288 | #if SQLITE_THREADSAFE2>0 | ||||
| 25289 | sqlite3_mutex_leave(mutex); | ||||
| 25290 | #endif | ||||
| 25291 | rc = pX==0; | ||||
| 25292 | #else | ||||
| 25293 | #ifndef SQLITE_UNTESTABLE | ||||
| 25294 | if( sqlite3GlobalConfigsqlite3Config.bLocaltimeFault ){ | ||||
| 25295 | if( sqlite3GlobalConfigsqlite3Config.xAltLocaltime!=0 ){ | ||||
| 25296 | return sqlite3GlobalConfigsqlite3Config.xAltLocaltime((const void*)t,(void*)pTm); | ||||
| 25297 | }else{ | ||||
| 25298 | return 1; | ||||
| 25299 | } | ||||
| 25300 | } | ||||
| 25301 | #endif | ||||
| 25302 | #if HAVE_LOCALTIME_R | ||||
| 25303 | rc = localtime_r(t, pTm)==0; | ||||
| 25304 | #else | ||||
| 25305 | rc = localtime_s(pTm, t); | ||||
| 25306 | #endif /* HAVE_LOCALTIME_R */ | ||||
| 25307 | #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */ | ||||
| 25308 | return rc; | ||||
| 25309 | } | ||||
| 25310 | #endif /* SQLITE_OMIT_LOCALTIME */ | ||||
| 25311 | |||||
| 25312 | |||||
| 25313 | #ifndef SQLITE_OMIT_LOCALTIME | ||||
| 25314 | /* | ||||
| 25315 | ** Assuming the input DateTime is UTC, move it to its localtime equivalent. | ||||
| 25316 | */ | ||||
| 25317 | static int toLocaltime( | ||||
| 25318 | DateTime *p, /* Date at which to calculate offset */ | ||||
| 25319 | sqlite3_context *pCtx /* Write error here if one occurs */ | ||||
| 25320 | ){ | ||||
| 25321 | time_t t; | ||||
| 25322 | struct tm sLocal; | ||||
| 25323 | int iYearDiff; | ||||
| 25324 | |||||
| 25325 | /* Initialize the contents of sLocal to avoid a compiler warning. */ | ||||
| 25326 | memset(&sLocal, 0, sizeof(sLocal)); | ||||
| 25327 | |||||
| 25328 | computeJD(p); | ||||
| 25329 | if( p->iJD<2108667600*(i64)100000 /* 1970-01-01 */ | ||||
| 25330 | || p->iJD>2130141456*(i64)100000 /* 2038-01-18 */ | ||||
| 25331 | ){ | ||||
| 25332 | /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only | ||||
| 25333 | ** works for years between 1970 and 2037. For dates outside this range, | ||||
| 25334 | ** SQLite attempts to map the year into an equivalent year within this | ||||
| 25335 | ** range, do the calculation, then map the year back. | ||||
| 25336 | */ | ||||
| 25337 | DateTime x = *p; | ||||
| 25338 | computeYMD_HMS(&x); | ||||
| 25339 | iYearDiff = (2000 + x.Y%4) - x.Y; | ||||
| 25340 | x.Y += iYearDiff; | ||||
| 25341 | x.validJD = 0; | ||||
| 25342 | computeJD(&x); | ||||
| 25343 | t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); | ||||
| 25344 | }else{ | ||||
| 25345 | iYearDiff = 0; | ||||
| 25346 | t = (time_t)(p->iJD/1000 - 21086676*(i64)10000); | ||||
| 25347 | } | ||||
| 25348 | if( osLocaltime(&t, &sLocal) ){ | ||||
| 25349 | sqlite3_result_error(pCtx, "local time unavailable", -1); | ||||
| 25350 | return SQLITE_ERROR1; | ||||
| 25351 | } | ||||
| 25352 | p->Y = sLocal.tm_year + 1900 - iYearDiff; | ||||
| 25353 | p->M = sLocal.tm_mon + 1; | ||||
| 25354 | p->D = sLocal.tm_mday; | ||||
| 25355 | p->h = sLocal.tm_hour; | ||||
| 25356 | p->m = sLocal.tm_min; | ||||
| 25357 | p->s = sLocal.tm_sec + (p->iJD%1000)*0.001; | ||||
| 25358 | p->validYMD = 1; | ||||
| 25359 | p->validHMS = 1; | ||||
| 25360 | p->validJD = 0; | ||||
| 25361 | p->rawS = 0; | ||||
| 25362 | p->tz = 0; | ||||
| 25363 | p->isError = 0; | ||||
| 25364 | return SQLITE_OK0; | ||||
| 25365 | } | ||||
| 25366 | #endif /* SQLITE_OMIT_LOCALTIME */ | ||||
| 25367 | |||||
| 25368 | /* | ||||
| 25369 | ** The following table defines various date transformations of the form | ||||
| 25370 | ** | ||||
| 25371 | ** 'NNN days' | ||||
| 25372 | ** | ||||
| 25373 | ** Where NNN is an arbitrary floating-point number and "days" can be one | ||||
| 25374 | ** of several units of time. | ||||
| 25375 | */ | ||||
| 25376 | static const struct { | ||||
| 25377 | u8 nName; /* Length of the name */ | ||||
| 25378 | char zName[7]; /* Name of the transformation */ | ||||
| 25379 | float rLimit; /* Maximum NNN value for this transform */ | ||||
| 25380 | float rXform; /* Constant used for this transform */ | ||||
| 25381 | } aXformType[] = { | ||||
| 25382 | /* 0 */ { 6, "second", 4.6427e+14, 1.0 }, | ||||
| 25383 | /* 1 */ { 6, "minute", 7.7379e+12, 60.0 }, | ||||
| 25384 | /* 2 */ { 4, "hour", 1.2897e+11, 3600.0 }, | ||||
| 25385 | /* 3 */ { 3, "day", 5373485.0, 86400.0 }, | ||||
| 25386 | /* 4 */ { 5, "month", 176546.0, 2592000.0 }, | ||||
| 25387 | /* 5 */ { 4, "year", 14713.0, 31536000.0 }, | ||||
| 25388 | }; | ||||
| 25389 | |||||
| 25390 | /* | ||||
| 25391 | ** If the DateTime p is raw number, try to figure out if it is | ||||
| 25392 | ** a julian day number of a unix timestamp. Set the p value | ||||
| 25393 | ** appropriately. | ||||
| 25394 | */ | ||||
| 25395 | static void autoAdjustDate(DateTime *p){ | ||||
| 25396 | if( !p->rawS || p->validJD ){ | ||||
| 25397 | p->rawS = 0; | ||||
| 25398 | }else if( p->s>=-21086676*(i64)10000 /* -4713-11-24 12:00:00 */ | ||||
| 25399 | && p->s<=(25340230*(i64)10000)+799 /* 9999-12-31 23:59:59 */ | ||||
| 25400 | ){ | ||||
| 25401 | double r = p->s*1000.0 + 210866760000000.0; | ||||
| 25402 | clearYMD_HMS_TZ(p); | ||||
| 25403 | p->iJD = (sqlite3_int64)(r + 0.5); | ||||
| 25404 | p->validJD = 1; | ||||
| 25405 | p->rawS = 0; | ||||
| 25406 | } | ||||
| 25407 | } | ||||
| 25408 | |||||
| 25409 | /* | ||||
| 25410 | ** Process a modifier to a date-time stamp. The modifiers are | ||||
| 25411 | ** as follows: | ||||
| 25412 | ** | ||||
| 25413 | ** NNN days | ||||
| 25414 | ** NNN hours | ||||
| 25415 | ** NNN minutes | ||||
| 25416 | ** NNN.NNNN seconds | ||||
| 25417 | ** NNN months | ||||
| 25418 | ** NNN years | ||||
| 25419 | ** +/-YYYY-MM-DD HH:MM:SS.SSS | ||||
| 25420 | ** ceiling | ||||
| 25421 | ** floor | ||||
| 25422 | ** start of month | ||||
| 25423 | ** start of year | ||||
| 25424 | ** start of week | ||||
| 25425 | ** start of day | ||||
| 25426 | ** weekday N | ||||
| 25427 | ** unixepoch | ||||
| 25428 | ** auto | ||||
| 25429 | ** localtime | ||||
| 25430 | ** utc | ||||
| 25431 | ** subsec | ||||
| 25432 | ** subsecond | ||||
| 25433 | ** | ||||
| 25434 | ** Return 0 on success and 1 if there is any kind of error. If the error | ||||
| 25435 | ** is in a system call (i.e. localtime()), then an error message is written | ||||
| 25436 | ** to context pCtx. If the error is an unrecognized modifier, no error is | ||||
| 25437 | ** written to pCtx. | ||||
| 25438 | */ | ||||
| 25439 | static int parseModifier( | ||||
| 25440 | sqlite3_context *pCtx, /* Function context */ | ||||
| 25441 | const char *z, /* The text of the modifier */ | ||||
| 25442 | int n, /* Length of zMod in bytes */ | ||||
| 25443 | DateTime *p, /* The date/time value to be modified */ | ||||
| 25444 | int idx /* Parameter index of the modifier */ | ||||
| 25445 | ){ | ||||
| 25446 | int rc = 1; | ||||
| 25447 | double r; | ||||
| 25448 | switch(sqlite3UpperToLower[(u8)z[0]] ){ | ||||
| 25449 | case 'a': { | ||||
| 25450 | /* | ||||
| 25451 | ** auto | ||||
| 25452 | ** | ||||
| 25453 | ** If rawS is available, then interpret as a julian day number, or | ||||
| 25454 | ** a unix timestamp, depending on its magnitude. | ||||
| 25455 | */ | ||||
| 25456 | if( sqlite3_stricmp(z, "auto")==0 ){ | ||||
| 25457 | if( idx>1 ) return 1; /* IMP: R-33611-57934 */ | ||||
| 25458 | autoAdjustDate(p); | ||||
| 25459 | rc = 0; | ||||
| 25460 | } | ||||
| 25461 | break; | ||||
| 25462 | } | ||||
| 25463 | case 'c': { | ||||
| 25464 | /* | ||||
| 25465 | ** ceiling | ||||
| 25466 | ** | ||||
| 25467 | ** Resolve day-of-month overflow by rolling forward into the next | ||||
| 25468 | ** month. As this is the default action, this modifier is really | ||||
| 25469 | ** a no-op that is only included for symmetry. See "floor". | ||||
| 25470 | */ | ||||
| 25471 | if( sqlite3_stricmp(z, "ceiling")==0 ){ | ||||
| 25472 | computeJD(p); | ||||
| 25473 | clearYMD_HMS_TZ(p); | ||||
| 25474 | rc = 0; | ||||
| 25475 | p->nFloor = 0; | ||||
| 25476 | } | ||||
| 25477 | break; | ||||
| 25478 | } | ||||
| 25479 | case 'f': { | ||||
| 25480 | /* | ||||
| 25481 | ** floor | ||||
| 25482 | ** | ||||
| 25483 | ** Resolve day-of-month overflow by rolling back to the end of the | ||||
| 25484 | ** previous month. | ||||
| 25485 | */ | ||||
| 25486 | if( sqlite3_stricmp(z, "floor")==0 ){ | ||||
| 25487 | computeJD(p); | ||||
| 25488 | p->iJD -= p->nFloor*86400000; | ||||
| 25489 | clearYMD_HMS_TZ(p); | ||||
| 25490 | rc = 0; | ||||
| 25491 | } | ||||
| 25492 | break; | ||||
| 25493 | } | ||||
| 25494 | case 'j': { | ||||
| 25495 | /* | ||||
| 25496 | ** julianday | ||||
| 25497 | ** | ||||
| 25498 | ** Always interpret the prior number as a julian-day value. If this | ||||
| 25499 | ** is not the first modifier, or if the prior argument is not a numeric | ||||
| 25500 | ** value in the allowed range of julian day numbers understood by | ||||
| 25501 | ** SQLite (0..5373484.5) then the result will be NULL. | ||||
| 25502 | */ | ||||
| 25503 | if( sqlite3_stricmp(z, "julianday")==0 ){ | ||||
| 25504 | if( idx>1 ) return 1; /* IMP: R-31176-64601 */ | ||||
| 25505 | if( p->validJD && p->rawS ){ | ||||
| 25506 | rc = 0; | ||||
| 25507 | p->rawS = 0; | ||||
| 25508 | } | ||||
| 25509 | } | ||||
| 25510 | break; | ||||
| 25511 | } | ||||
| 25512 | #ifndef SQLITE_OMIT_LOCALTIME | ||||
| 25513 | case 'l': { | ||||
| 25514 | /* localtime | ||||
| 25515 | ** | ||||
| 25516 | ** Assuming the current time value is UTC (a.k.a. GMT), shift it to | ||||
| 25517 | ** show local time. | ||||
| 25518 | */ | ||||
| 25519 | if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){ | ||||
| 25520 | rc = p->isLocal ? SQLITE_OK0 : toLocaltime(p, pCtx); | ||||
| 25521 | p->isUtc = 0; | ||||
| 25522 | p->isLocal = 1; | ||||
| 25523 | } | ||||
| 25524 | break; | ||||
| 25525 | } | ||||
| 25526 | #endif | ||||
| 25527 | case 'u': { | ||||
| 25528 | /* | ||||
| 25529 | ** unixepoch | ||||
| 25530 | ** | ||||
| 25531 | ** Treat the current value of p->s as the number of | ||||
| 25532 | ** seconds since 1970. Convert to a real julian day number. | ||||
| 25533 | */ | ||||
| 25534 | if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){ | ||||
| 25535 | if( idx>1 ) return 1; /* IMP: R-49255-55373 */ | ||||
| 25536 | r = p->s*1000.0 + 210866760000000.0; | ||||
| 25537 | if( r>=0.0 && r<464269060800000.0 ){ | ||||
| 25538 | clearYMD_HMS_TZ(p); | ||||
| 25539 | p->iJD = (sqlite3_int64)(r + 0.5); | ||||
| 25540 | p->validJD = 1; | ||||
| 25541 | p->rawS = 0; | ||||
| 25542 | rc = 0; | ||||
| 25543 | } | ||||
| 25544 | } | ||||
| 25545 | #ifndef SQLITE_OMIT_LOCALTIME | ||||
| 25546 | else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){ | ||||
| 25547 | if( p->isUtc==0 ){ | ||||
| 25548 | i64 iOrigJD; /* Original localtime */ | ||||
| 25549 | i64 iGuess; /* Guess at the corresponding utc time */ | ||||
| 25550 | int cnt = 0; /* Safety to prevent infinite loop */ | ||||
| 25551 | i64 iErr; /* Guess is off by this much */ | ||||
| 25552 | |||||
| 25553 | computeJD(p); | ||||
| 25554 | iGuess = iOrigJD = p->iJD; | ||||
| 25555 | iErr = 0; | ||||
| 25556 | do{ | ||||
| 25557 | DateTime new; | ||||
| 25558 | memset(&new, 0, sizeof(new)); | ||||
| 25559 | iGuess -= iErr; | ||||
| 25560 | new.iJD = iGuess; | ||||
| 25561 | new.validJD = 1; | ||||
| 25562 | rc = toLocaltime(&new, pCtx); | ||||
| 25563 | if( rc ) return rc; | ||||
| 25564 | computeJD(&new); | ||||
| 25565 | iErr = new.iJD - iOrigJD; | ||||
| 25566 | }while( iErr && cnt++<3 ); | ||||
| 25567 | memset(p, 0, sizeof(*p)); | ||||
| 25568 | p->iJD = iGuess; | ||||
| 25569 | p->validJD = 1; | ||||
| 25570 | p->isUtc = 1; | ||||
| 25571 | p->isLocal = 0; | ||||
| 25572 | } | ||||
| 25573 | rc = SQLITE_OK0; | ||||
| 25574 | } | ||||
| 25575 | #endif | ||||
| 25576 | break; | ||||
| 25577 | } | ||||
| 25578 | case 'w': { | ||||
| 25579 | /* | ||||
| 25580 | ** weekday N | ||||
| 25581 | ** | ||||
| 25582 | ** Move the date to the same time on the next occurrence of | ||||
| 25583 | ** weekday N where 0==Sunday, 1==Monday, and so forth. If the | ||||
| 25584 | ** date is already on the appropriate weekday, this is a no-op. | ||||
| 25585 | */ | ||||
| 25586 | if( sqlite3_strnicmp(z, "weekday ", 8)==0 | ||||
| 25587 | && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF81)>0 | ||||
| 25588 | && r>=0.0 && r<7.0 && (n=(int)r)==r ){ | ||||
| 25589 | sqlite3_int64 Z; | ||||
| 25590 | computeYMD_HMS(p); | ||||
| 25591 | p->tz = 0; | ||||
| 25592 | p->validJD = 0; | ||||
| 25593 | computeJD(p); | ||||
| 25594 | Z = ((p->iJD + 129600000)/86400000) % 7; | ||||
| 25595 | if( Z>n ) Z -= 7; | ||||
| 25596 | p->iJD += (n - Z)*86400000; | ||||
| 25597 | clearYMD_HMS_TZ(p); | ||||
| 25598 | rc = 0; | ||||
| 25599 | } | ||||
| 25600 | break; | ||||
| 25601 | } | ||||
| 25602 | case 's': { | ||||
| 25603 | /* | ||||
| 25604 | ** start of TTTTT | ||||
| 25605 | ** | ||||
| 25606 | ** Move the date backwards to the beginning of the current day, | ||||
| 25607 | ** or month or year. | ||||
| 25608 | ** | ||||
| 25609 | ** subsecond | ||||
| 25610 | ** subsec | ||||
| 25611 | ** | ||||
| 25612 | ** Show subsecond precision in the output of datetime() and | ||||
| 25613 | ** unixepoch() and strftime('%s'). | ||||
| 25614 | */ | ||||
| 25615 | if( sqlite3_strnicmp(z, "start of ", 9)!=0 ){ | ||||
| 25616 | if( sqlite3_stricmp(z, "subsec")==0 | ||||
| 25617 | || sqlite3_stricmp(z, "subsecond")==0 | ||||
| 25618 | ){ | ||||
| 25619 | p->useSubsec = 1; | ||||
| 25620 | rc = 0; | ||||
| 25621 | } | ||||
| 25622 | break; | ||||
| 25623 | } | ||||
| 25624 | if( !p->validJD && !p->validYMD && !p->validHMS ) break; | ||||
| 25625 | z += 9; | ||||
| 25626 | computeYMD(p); | ||||
| 25627 | p->validHMS = 1; | ||||
| 25628 | p->h = p->m = 0; | ||||
| 25629 | p->s = 0.0; | ||||
| 25630 | p->rawS = 0; | ||||
| 25631 | p->tz = 0; | ||||
| 25632 | p->validJD = 0; | ||||
| 25633 | if( sqlite3_stricmp(z,"month")==0 ){ | ||||
| 25634 | p->D = 1; | ||||
| 25635 | rc = 0; | ||||
| 25636 | }else if( sqlite3_stricmp(z,"year")==0 ){ | ||||
| 25637 | p->M = 1; | ||||
| 25638 | p->D = 1; | ||||
| 25639 | rc = 0; | ||||
| 25640 | }else if( sqlite3_stricmp(z,"day")==0 ){ | ||||
| 25641 | rc = 0; | ||||
| 25642 | } | ||||
| 25643 | break; | ||||
| 25644 | } | ||||
| 25645 | case '+': | ||||
| 25646 | case '-': | ||||
| 25647 | case '0': | ||||
| 25648 | case '1': | ||||
| 25649 | case '2': | ||||
| 25650 | case '3': | ||||
| 25651 | case '4': | ||||
| 25652 | case '5': | ||||
| 25653 | case '6': | ||||
| 25654 | case '7': | ||||
| 25655 | case '8': | ||||
| 25656 | case '9': { | ||||
| 25657 | double rRounder; | ||||
| 25658 | int i; | ||||
| 25659 | int Y,M,D,h,m,x; | ||||
| 25660 | const char *z2 = z; | ||||
| 25661 | char z0 = z[0]; | ||||
| 25662 | for(n=1; z[n]; n++){ | ||||
| 25663 | if( z[n]==':' ) break; | ||||
| 25664 | if( sqlite3Isspace(z[n])(sqlite3CtypeMap[(unsigned char)(z[n])]&0x01) ) break; | ||||
| 25665 | if( z[n]=='-' ){ | ||||
| 25666 | if( n==5 && getDigits(&z[1], "40f", &Y)==1 ) break; | ||||
| 25667 | if( n==6 && getDigits(&z[1], "50f", &Y)==1 ) break; | ||||
| 25668 | } | ||||
| 25669 | } | ||||
| 25670 | if( sqlite3AtoF(z, &r, n, SQLITE_UTF81)<=0 ){ | ||||
| 25671 | assert( rc==1 )((void) (0)); | ||||
| 25672 | break; | ||||
| 25673 | } | ||||
| 25674 | if( z[n]=='-' ){ | ||||
| 25675 | /* A modifier of the form (+|-)YYYY-MM-DD adds or subtracts the | ||||
| 25676 | ** specified number of years, months, and days. MM is limited to | ||||
| 25677 | ** the range 0-11 and DD is limited to 0-30. | ||||
| 25678 | */ | ||||
| 25679 | if( z0!='+' && z0!='-' ) break; /* Must start with +/- */ | ||||
| 25680 | if( n==5 ){ | ||||
| 25681 | if( getDigits(&z[1], "40f-20a-20d", &Y, &M, &D)!=3 ) break; | ||||
| 25682 | }else{ | ||||
| 25683 | assert( n==6 )((void) (0)); | ||||
| 25684 | if( getDigits(&z[1], "50f-20a-20d", &Y, &M, &D)!=3 ) break; | ||||
| 25685 | z++; | ||||
| 25686 | } | ||||
| 25687 | if( M>=12 ) break; /* M range 0..11 */ | ||||
| 25688 | if( D>=31 ) break; /* D range 0..30 */ | ||||
| 25689 | computeYMD_HMS(p); | ||||
| 25690 | p->validJD = 0; | ||||
| 25691 | if( z0=='-' ){ | ||||
| 25692 | p->Y -= Y; | ||||
| 25693 | p->M -= M; | ||||
| 25694 | D = -D; | ||||
| 25695 | }else{ | ||||
| 25696 | p->Y += Y; | ||||
| 25697 | p->M += M; | ||||
| 25698 | } | ||||
| 25699 | x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; | ||||
| 25700 | p->Y += x; | ||||
| 25701 | p->M -= x*12; | ||||
| 25702 | computeFloor(p); | ||||
| 25703 | computeJD(p); | ||||
| 25704 | p->validHMS = 0; | ||||
| 25705 | p->validYMD = 0; | ||||
| 25706 | p->iJD += (i64)D*86400000; | ||||
| 25707 | if( z[11]==0 ){ | ||||
| 25708 | rc = 0; | ||||
| 25709 | break; | ||||
| 25710 | } | ||||
| 25711 | if( sqlite3Isspace(z[11])(sqlite3CtypeMap[(unsigned char)(z[11])]&0x01) | ||||
| 25712 | && getDigits(&z[12], "20c:20e", &h, &m)==2 | ||||
| 25713 | ){ | ||||
| 25714 | z2 = &z[12]; | ||||
| 25715 | n = 2; | ||||
| 25716 | }else{ | ||||
| 25717 | break; | ||||
| 25718 | } | ||||
| 25719 | } | ||||
| 25720 | if( z2[n]==':' ){ | ||||
| 25721 | /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the | ||||
| 25722 | ** specified number of hours, minutes, seconds, and fractional seconds | ||||
| 25723 | ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be | ||||
| 25724 | ** omitted. | ||||
| 25725 | */ | ||||
| 25726 | |||||
| 25727 | DateTime tx; | ||||
| 25728 | sqlite3_int64 day; | ||||
| 25729 | if( !sqlite3Isdigit(*z2)(sqlite3CtypeMap[(unsigned char)(*z2)]&0x04) ) z2++; | ||||
| 25730 | memset(&tx, 0, sizeof(tx)); | ||||
| 25731 | if( parseHhMmSs(z2, &tx) ) break; | ||||
| 25732 | computeJD(&tx); | ||||
| 25733 | tx.iJD -= 43200000; | ||||
| 25734 | day = tx.iJD/86400000; | ||||
| 25735 | tx.iJD -= day*86400000; | ||||
| 25736 | if( z0=='-' ) tx.iJD = -tx.iJD; | ||||
| 25737 | computeJD(p); | ||||
| 25738 | clearYMD_HMS_TZ(p); | ||||
| 25739 | p->iJD += tx.iJD; | ||||
| 25740 | rc = 0; | ||||
| 25741 | break; | ||||
| 25742 | } | ||||
| 25743 | |||||
| 25744 | /* If control reaches this point, it means the transformation is | ||||
| 25745 | ** one of the forms like "+NNN days". */ | ||||
| 25746 | z += n; | ||||
| 25747 | while( sqlite3Isspace(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x01) ) z++; | ||||
| 25748 | n = sqlite3Strlen30(z); | ||||
| 25749 | if( n<3 || n>10 ) break; | ||||
| 25750 | if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--; | ||||
| 25751 | computeJD(p); | ||||
| 25752 | assert( rc==1 )((void) (0)); | ||||
| 25753 | rRounder = r<0 ? -0.5 : +0.5; | ||||
| 25754 | p->nFloor = 0; | ||||
| 25755 | for(i=0; i<ArraySize(aXformType)((int)(sizeof(aXformType)/sizeof(aXformType[0]))); i++){ | ||||
| 25756 | if( aXformType[i].nName==n | ||||
| 25757 | && sqlite3_strnicmp(aXformType[i].zName, z, n)==0 | ||||
| 25758 | && r>-aXformType[i].rLimit && r<aXformType[i].rLimit | ||||
| 25759 | ){ | ||||
| 25760 | switch( i ){ | ||||
| 25761 | case 4: { /* Special processing to add months */ | ||||
| 25762 | assert( strcmp(aXformType[4].zName,"month")==0 )((void) (0)); | ||||
| 25763 | computeYMD_HMS(p); | ||||
| 25764 | p->M += (int)r; | ||||
| 25765 | x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; | ||||
| 25766 | p->Y += x; | ||||
| 25767 | p->M -= x*12; | ||||
| 25768 | computeFloor(p); | ||||
| 25769 | p->validJD = 0; | ||||
| 25770 | r -= (int)r; | ||||
| 25771 | break; | ||||
| 25772 | } | ||||
| 25773 | case 5: { /* Special processing to add years */ | ||||
| 25774 | int y = (int)r; | ||||
| 25775 | assert( strcmp(aXformType[5].zName,"year")==0 )((void) (0)); | ||||
| 25776 | computeYMD_HMS(p); | ||||
| 25777 | assert( p->M>=0 && p->M<=12 )((void) (0)); | ||||
| 25778 | p->Y += y; | ||||
| 25779 | computeFloor(p); | ||||
| 25780 | p->validJD = 0; | ||||
| 25781 | r -= (int)r; | ||||
| 25782 | break; | ||||
| 25783 | } | ||||
| 25784 | } | ||||
| 25785 | computeJD(p); | ||||
| 25786 | p->iJD += (sqlite3_int64)(r*1000.0*aXformType[i].rXform + rRounder); | ||||
| 25787 | rc = 0; | ||||
| 25788 | break; | ||||
| 25789 | } | ||||
| 25790 | } | ||||
| 25791 | clearYMD_HMS_TZ(p); | ||||
| 25792 | break; | ||||
| 25793 | } | ||||
| 25794 | default: { | ||||
| 25795 | break; | ||||
| 25796 | } | ||||
| 25797 | } | ||||
| 25798 | return rc; | ||||
| 25799 | } | ||||
| 25800 | |||||
| 25801 | /* | ||||
| 25802 | ** Process time function arguments. argv[0] is a date-time stamp. | ||||
| 25803 | ** argv[1] and following are modifiers. Parse them all and write | ||||
| 25804 | ** the resulting time into the DateTime structure p. Return 0 | ||||
| 25805 | ** on success and 1 if there are any errors. | ||||
| 25806 | ** | ||||
| 25807 | ** If there are zero parameters (if even argv[0] is undefined) | ||||
| 25808 | ** then assume a default value of "now" for argv[0]. | ||||
| 25809 | */ | ||||
| 25810 | static int isDate( | ||||
| 25811 | sqlite3_context *context, | ||||
| 25812 | int argc, | ||||
| 25813 | sqlite3_value **argv, | ||||
| 25814 | DateTime *p | ||||
| 25815 | ){ | ||||
| 25816 | int i, n; | ||||
| 25817 | const unsigned char *z; | ||||
| 25818 | int eType; | ||||
| 25819 | memset(p, 0, sizeof(*p)); | ||||
| 25820 | if( argc==0 ){ | ||||
| 25821 | if( !sqlite3NotPureFunc(context) ) return 1; | ||||
| 25822 | return setDateTimeToCurrent(context, p); | ||||
| 25823 | } | ||||
| 25824 | if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT2 | ||||
| 25825 | || eType==SQLITE_INTEGER1 ){ | ||||
| 25826 | setRawDateNumber(p, sqlite3_value_double(argv[0])); | ||||
| 25827 | }else{ | ||||
| 25828 | z = sqlite3_value_text(argv[0]); | ||||
| 25829 | if( !z || parseDateOrTime(context, (char*)z, p) ){ | ||||
| 25830 | return 1; | ||||
| 25831 | } | ||||
| 25832 | } | ||||
| 25833 | for(i=1; i<argc; i++){ | ||||
| 25834 | z = sqlite3_value_text(argv[i]); | ||||
| 25835 | n = sqlite3_value_bytes(argv[i]); | ||||
| 25836 | if( z==0 || parseModifier(context, (char*)z, n, p, i) ) return 1; | ||||
| 25837 | } | ||||
| 25838 | computeJD(p); | ||||
| 25839 | if( p->isError || !validJulianDay(p->iJD) ) return 1; | ||||
| 25840 | if( argc==1 && p->validYMD && p->D>28 ){ | ||||
| 25841 | /* Make sure a YYYY-MM-DD is normalized. | ||||
| 25842 | ** Example: 2023-02-31 -> 2023-03-03 */ | ||||
| 25843 | assert( p->validJD )((void) (0)); | ||||
| 25844 | p->validYMD = 0; | ||||
| 25845 | } | ||||
| 25846 | return 0; | ||||
| 25847 | } | ||||
| 25848 | |||||
| 25849 | |||||
| 25850 | /* | ||||
| 25851 | ** The following routines implement the various date and time functions | ||||
| 25852 | ** of SQLite. | ||||
| 25853 | */ | ||||
| 25854 | |||||
| 25855 | /* | ||||
| 25856 | ** julianday( TIMESTRING, MOD, MOD, ...) | ||||
| 25857 | ** | ||||
| 25858 | ** Return the julian day number of the date specified in the arguments | ||||
| 25859 | */ | ||||
| 25860 | static void juliandayFunc( | ||||
| 25861 | sqlite3_context *context, | ||||
| 25862 | int argc, | ||||
| 25863 | sqlite3_value **argv | ||||
| 25864 | ){ | ||||
| 25865 | DateTime x; | ||||
| 25866 | if( isDate(context, argc, argv, &x)==0 ){ | ||||
| 25867 | computeJD(&x); | ||||
| 25868 | sqlite3_result_double(context, x.iJD/86400000.0); | ||||
| 25869 | } | ||||
| 25870 | } | ||||
| 25871 | |||||
| 25872 | /* | ||||
| 25873 | ** unixepoch( TIMESTRING, MOD, MOD, ...) | ||||
| 25874 | ** | ||||
| 25875 | ** Return the number of seconds (including fractional seconds) since | ||||
| 25876 | ** the unix epoch of 1970-01-01 00:00:00 GMT. | ||||
| 25877 | */ | ||||
| 25878 | static void unixepochFunc( | ||||
| 25879 | sqlite3_context *context, | ||||
| 25880 | int argc, | ||||
| 25881 | sqlite3_value **argv | ||||
| 25882 | ){ | ||||
| 25883 | DateTime x; | ||||
| 25884 | if( isDate(context, argc, argv, &x)==0 ){ | ||||
| 25885 | computeJD(&x); | ||||
| 25886 | if( x.useSubsec ){ | ||||
| 25887 | sqlite3_result_double(context, (x.iJD - 21086676*(i64)10000000)/1000.0); | ||||
| 25888 | }else{ | ||||
| 25889 | sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000); | ||||
| 25890 | } | ||||
| 25891 | } | ||||
| 25892 | } | ||||
| 25893 | |||||
| 25894 | /* | ||||
| 25895 | ** datetime( TIMESTRING, MOD, MOD, ...) | ||||
| 25896 | ** | ||||
| 25897 | ** Return YYYY-MM-DD HH:MM:SS | ||||
| 25898 | */ | ||||
| 25899 | static void datetimeFunc( | ||||
| 25900 | sqlite3_context *context, | ||||
| 25901 | int argc, | ||||
| 25902 | sqlite3_value **argv | ||||
| 25903 | ){ | ||||
| 25904 | DateTime x; | ||||
| 25905 | if( isDate(context, argc, argv, &x)==0 ){ | ||||
| 25906 | int Y, s, n; | ||||
| 25907 | char zBuf[32]; | ||||
| 25908 | computeYMD_HMS(&x); | ||||
| 25909 | Y = x.Y; | ||||
| 25910 | if( Y<0 ) Y = -Y; | ||||
| 25911 | zBuf[1] = '0' + (Y/1000)%10; | ||||
| 25912 | zBuf[2] = '0' + (Y/100)%10; | ||||
| 25913 | zBuf[3] = '0' + (Y/10)%10; | ||||
| 25914 | zBuf[4] = '0' + (Y)%10; | ||||
| 25915 | zBuf[5] = '-'; | ||||
| 25916 | zBuf[6] = '0' + (x.M/10)%10; | ||||
| 25917 | zBuf[7] = '0' + (x.M)%10; | ||||
| 25918 | zBuf[8] = '-'; | ||||
| 25919 | zBuf[9] = '0' + (x.D/10)%10; | ||||
| 25920 | zBuf[10] = '0' + (x.D)%10; | ||||
| 25921 | zBuf[11] = ' '; | ||||
| 25922 | zBuf[12] = '0' + (x.h/10)%10; | ||||
| 25923 | zBuf[13] = '0' + (x.h)%10; | ||||
| 25924 | zBuf[14] = ':'; | ||||
| 25925 | zBuf[15] = '0' + (x.m/10)%10; | ||||
| 25926 | zBuf[16] = '0' + (x.m)%10; | ||||
| 25927 | zBuf[17] = ':'; | ||||
| 25928 | if( x.useSubsec ){ | ||||
| 25929 | s = (int)(1000.0*x.s + 0.5); | ||||
| 25930 | zBuf[18] = '0' + (s/10000)%10; | ||||
| 25931 | zBuf[19] = '0' + (s/1000)%10; | ||||
| 25932 | zBuf[20] = '.'; | ||||
| 25933 | zBuf[21] = '0' + (s/100)%10; | ||||
| 25934 | zBuf[22] = '0' + (s/10)%10; | ||||
| 25935 | zBuf[23] = '0' + (s)%10; | ||||
| 25936 | zBuf[24] = 0; | ||||
| 25937 | n = 24; | ||||
| 25938 | }else{ | ||||
| 25939 | s = (int)x.s; | ||||
| 25940 | zBuf[18] = '0' + (s/10)%10; | ||||
| 25941 | zBuf[19] = '0' + (s)%10; | ||||
| 25942 | zBuf[20] = 0; | ||||
| 25943 | n = 20; | ||||
| 25944 | } | ||||
| 25945 | if( x.Y<0 ){ | ||||
| 25946 | zBuf[0] = '-'; | ||||
| 25947 | sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT((sqlite3_destructor_type)-1)); | ||||
| 25948 | }else{ | ||||
| 25949 | sqlite3_result_text(context, &zBuf[1], n-1, SQLITE_TRANSIENT((sqlite3_destructor_type)-1)); | ||||
| 25950 | } | ||||
| 25951 | } | ||||
| 25952 | } | ||||
| 25953 | |||||
| 25954 | /* | ||||
| 25955 | ** time( TIMESTRING, MOD, MOD, ...) | ||||
| 25956 | ** | ||||
| 25957 | ** Return HH:MM:SS | ||||
| 25958 | */ | ||||
| 25959 | static void timeFunc( | ||||
| 25960 | sqlite3_context *context, | ||||
| 25961 | int argc, | ||||
| 25962 | sqlite3_value **argv | ||||
| 25963 | ){ | ||||
| 25964 | DateTime x; | ||||
| 25965 | if( isDate(context, argc, argv, &x)==0 ){ | ||||
| 25966 | int s, n; | ||||
| 25967 | char zBuf[16]; | ||||
| 25968 | computeHMS(&x); | ||||
| 25969 | zBuf[0] = '0' + (x.h/10)%10; | ||||
| 25970 | zBuf[1] = '0' + (x.h)%10; | ||||
| 25971 | zBuf[2] = ':'; | ||||
| 25972 | zBuf[3] = '0' + (x.m/10)%10; | ||||
| 25973 | zBuf[4] = '0' + (x.m)%10; | ||||
| 25974 | zBuf[5] = ':'; | ||||
| 25975 | if( x.useSubsec ){ | ||||
| 25976 | s = (int)(1000.0*x.s + 0.5); | ||||
| 25977 | zBuf[6] = '0' + (s/10000)%10; | ||||
| 25978 | zBuf[7] = '0' + (s/1000)%10; | ||||
| 25979 | zBuf[8] = '.'; | ||||
| 25980 | zBuf[9] = '0' + (s/100)%10; | ||||
| 25981 | zBuf[10] = '0' + (s/10)%10; | ||||
| 25982 | zBuf[11] = '0' + (s)%10; | ||||
| 25983 | zBuf[12] = 0; | ||||
| 25984 | n = 12; | ||||
| 25985 | }else{ | ||||
| 25986 | s = (int)x.s; | ||||
| 25987 | zBuf[6] = '0' + (s/10)%10; | ||||
| 25988 | zBuf[7] = '0' + (s)%10; | ||||
| 25989 | zBuf[8] = 0; | ||||
| 25990 | n = 8; | ||||
| 25991 | } | ||||
| 25992 | sqlite3_result_text(context, zBuf, n, SQLITE_TRANSIENT((sqlite3_destructor_type)-1)); | ||||
| 25993 | } | ||||
| 25994 | } | ||||
| 25995 | |||||
| 25996 | /* | ||||
| 25997 | ** date( TIMESTRING, MOD, MOD, ...) | ||||
| 25998 | ** | ||||
| 25999 | ** Return YYYY-MM-DD | ||||
| 26000 | */ | ||||
| 26001 | static void dateFunc( | ||||
| 26002 | sqlite3_context *context, | ||||
| 26003 | int argc, | ||||
| 26004 | sqlite3_value **argv | ||||
| 26005 | ){ | ||||
| 26006 | DateTime x; | ||||
| 26007 | if( isDate(context, argc, argv, &x)==0 ){ | ||||
| 26008 | int Y; | ||||
| 26009 | char zBuf[16]; | ||||
| 26010 | computeYMD(&x); | ||||
| 26011 | Y = x.Y; | ||||
| 26012 | if( Y<0 ) Y = -Y; | ||||
| 26013 | zBuf[1] = '0' + (Y/1000)%10; | ||||
| 26014 | zBuf[2] = '0' + (Y/100)%10; | ||||
| 26015 | zBuf[3] = '0' + (Y/10)%10; | ||||
| 26016 | zBuf[4] = '0' + (Y)%10; | ||||
| 26017 | zBuf[5] = '-'; | ||||
| 26018 | zBuf[6] = '0' + (x.M/10)%10; | ||||
| 26019 | zBuf[7] = '0' + (x.M)%10; | ||||
| 26020 | zBuf[8] = '-'; | ||||
| 26021 | zBuf[9] = '0' + (x.D/10)%10; | ||||
| 26022 | zBuf[10] = '0' + (x.D)%10; | ||||
| 26023 | zBuf[11] = 0; | ||||
| 26024 | if( x.Y<0 ){ | ||||
| 26025 | zBuf[0] = '-'; | ||||
| 26026 | sqlite3_result_text(context, zBuf, 11, SQLITE_TRANSIENT((sqlite3_destructor_type)-1)); | ||||
| 26027 | }else{ | ||||
| 26028 | sqlite3_result_text(context, &zBuf[1], 10, SQLITE_TRANSIENT((sqlite3_destructor_type)-1)); | ||||
| 26029 | } | ||||
| 26030 | } | ||||
| 26031 | } | ||||
| 26032 | |||||
| 26033 | /* | ||||
| 26034 | ** Compute the number of days after the most recent January 1. | ||||
| 26035 | ** | ||||
| 26036 | ** In other words, compute the zero-based day number for the | ||||
| 26037 | ** current year: | ||||
| 26038 | ** | ||||
| 26039 | ** Jan01 = 0, Jan02 = 1, ..., Jan31 = 30, Feb01 = 31, ... | ||||
| 26040 | ** Dec31 = 364 or 365. | ||||
| 26041 | */ | ||||
| 26042 | static int daysAfterJan01(DateTime *pDate){ | ||||
| 26043 | DateTime jan01 = *pDate; | ||||
| 26044 | assert( jan01.validYMD )((void) (0)); | ||||
| 26045 | assert( jan01.validHMS )((void) (0)); | ||||
| 26046 | assert( pDate->validJD )((void) (0)); | ||||
| 26047 | jan01.validJD = 0; | ||||
| 26048 | jan01.M = 1; | ||||
| 26049 | jan01.D = 1; | ||||
| 26050 | computeJD(&jan01); | ||||
| 26051 | return (int)((pDate->iJD-jan01.iJD+43200000)/86400000); | ||||
| 26052 | } | ||||
| 26053 | |||||
| 26054 | /* | ||||
| 26055 | ** Return the number of days after the most recent Monday. | ||||
| 26056 | ** | ||||
| 26057 | ** In other words, return the day of the week according | ||||
| 26058 | ** to this code: | ||||
| 26059 | ** | ||||
| 26060 | ** 0=Monday, 1=Tuesday, 2=Wednesday, ..., 6=Sunday. | ||||
| 26061 | */ | ||||
| 26062 | static int daysAfterMonday(DateTime *pDate){ | ||||
| 26063 | assert( pDate->validJD )((void) (0)); | ||||
| 26064 | return (int)((pDate->iJD+43200000)/86400000) % 7; | ||||
| 26065 | } | ||||
| 26066 | |||||
| 26067 | /* | ||||
| 26068 | ** Return the number of days after the most recent Sunday. | ||||
| 26069 | ** | ||||
| 26070 | ** In other words, return the day of the week according | ||||
| 26071 | ** to this code: | ||||
| 26072 | ** | ||||
| 26073 | ** 0=Sunday, 1=Monday, 2=Tuesday, ..., 6=Saturday | ||||
| 26074 | */ | ||||
| 26075 | static int daysAfterSunday(DateTime *pDate){ | ||||
| 26076 | assert( pDate->validJD )((void) (0)); | ||||
| 26077 | return (int)((pDate->iJD+129600000)/86400000) % 7; | ||||
| 26078 | } | ||||
| 26079 | |||||
| 26080 | /* | ||||
| 26081 | ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...) | ||||
| 26082 | ** | ||||
| 26083 | ** Return a string described by FORMAT. Conversions as follows: | ||||
| 26084 | ** | ||||
| 26085 | ** %d day of month 01-31 | ||||
| 26086 | ** %e day of month 1-31 | ||||
| 26087 | ** %f ** fractional seconds SS.SSS | ||||
| 26088 | ** %F ISO date. YYYY-MM-DD | ||||
| 26089 | ** %G ISO year corresponding to %V 0000-9999. | ||||
| 26090 | ** %g 2-digit ISO year corresponding to %V 00-99 | ||||
| 26091 | ** %H hour 00-24 | ||||
| 26092 | ** %k hour 0-24 (leading zero converted to space) | ||||
| 26093 | ** %I hour 01-12 | ||||
| 26094 | ** %j day of year 001-366 | ||||
| 26095 | ** %J ** julian day number | ||||
| 26096 | ** %l hour 1-12 (leading zero converted to space) | ||||
| 26097 | ** %m month 01-12 | ||||
| 26098 | ** %M minute 00-59 | ||||
| 26099 | ** %p "am" or "pm" | ||||
| 26100 | ** %P "AM" or "PM" | ||||
| 26101 | ** %R time as HH:MM | ||||
| 26102 | ** %s seconds since 1970-01-01 | ||||
| 26103 | ** %S seconds 00-59 | ||||
| 26104 | ** %T time as HH:MM:SS | ||||
| 26105 | ** %u day of week 1-7 Monday==1, Sunday==7 | ||||
| 26106 | ** %w day of week 0-6 Sunday==0, Monday==1 | ||||
| 26107 | ** %U week of year 00-53 (First Sunday is start of week 01) | ||||
| 26108 | ** %V week of year 01-53 (First week containing Thursday is week 01) | ||||
| 26109 | ** %W week of year 00-53 (First Monday is start of week 01) | ||||
| 26110 | ** %Y year 0000-9999 | ||||
| 26111 | ** %% % | ||||
| 26112 | */ | ||||
| 26113 | static void strftimeFunc( | ||||
| 26114 | sqlite3_context *context, | ||||
| 26115 | int argc, | ||||
| 26116 | sqlite3_value **argv | ||||
| 26117 | ){ | ||||
| 26118 | DateTime x; | ||||
| 26119 | size_t i,j; | ||||
| 26120 | sqlite3 *db; | ||||
| 26121 | const char *zFmt; | ||||
| 26122 | sqlite3_str sRes; | ||||
| 26123 | |||||
| 26124 | |||||
| 26125 | if( argc==0 ) return; | ||||
| 26126 | zFmt = (const char*)sqlite3_value_text(argv[0]); | ||||
| 26127 | if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return; | ||||
| 26128 | db = sqlite3_context_db_handle(context); | ||||
| 26129 | sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH0]); | ||||
| 26130 | |||||
| 26131 | computeJD(&x); | ||||
| 26132 | computeYMD_HMS(&x); | ||||
| 26133 | for(i=j=0; zFmt[i]; i++){ | ||||
| 26134 | char cf; | ||||
| 26135 | if( zFmt[i]!='%' ) continue; | ||||
| 26136 | if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j)); | ||||
| 26137 | i++; | ||||
| 26138 | j = i + 1; | ||||
| 26139 | cf = zFmt[i]; | ||||
| 26140 | switch( cf ){ | ||||
| 26141 | case 'd': /* Fall thru */ | ||||
| 26142 | case 'e': { | ||||
| 26143 | sqlite3_str_appendf(&sRes, cf=='d' ? "%02d" : "%2d", x.D); | ||||
| 26144 | break; | ||||
| 26145 | } | ||||
| 26146 | case 'f': { /* Fractional seconds. (Non-standard) */ | ||||
| 26147 | double s = x.s; | ||||
| 26148 | if( NEVER(s>59.999)(s>59.999) ) s = 59.999; | ||||
| 26149 | sqlite3_str_appendf(&sRes, "%06.3f", s); | ||||
| 26150 | break; | ||||
| 26151 | } | ||||
| 26152 | case 'F': { | ||||
| 26153 | sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D); | ||||
| 26154 | break; | ||||
| 26155 | } | ||||
| 26156 | case 'G': /* Fall thru */ | ||||
| 26157 | case 'g': { | ||||
| 26158 | DateTime y = x; | ||||
| 26159 | assert( y.validJD )((void) (0)); | ||||
| 26160 | /* Move y so that it is the Thursday in the same week as x */ | ||||
| 26161 | y.iJD += (3 - daysAfterMonday(&x))*86400000; | ||||
| 26162 | y.validYMD = 0; | ||||
| 26163 | computeYMD(&y); | ||||
| 26164 | if( cf=='g' ){ | ||||
| 26165 | sqlite3_str_appendf(&sRes, "%02d", y.Y%100); | ||||
| 26166 | }else{ | ||||
| 26167 | sqlite3_str_appendf(&sRes, "%04d", y.Y); | ||||
| 26168 | } | ||||
| 26169 | break; | ||||
| 26170 | } | ||||
| 26171 | case 'H': | ||||
| 26172 | case 'k': { | ||||
| 26173 | sqlite3_str_appendf(&sRes, cf=='H' ? "%02d" : "%2d", x.h); | ||||
| 26174 | break; | ||||
| 26175 | } | ||||
| 26176 | case 'I': /* Fall thru */ | ||||
| 26177 | case 'l': { | ||||
| 26178 | int h = x.h; | ||||
| 26179 | if( h>12 ) h -= 12; | ||||
| 26180 | if( h==0 ) h = 12; | ||||
| 26181 | sqlite3_str_appendf(&sRes, cf=='I' ? "%02d" : "%2d", h); | ||||
| 26182 | break; | ||||
| 26183 | } | ||||
| 26184 | case 'j': { /* Day of year. Jan01==1, Jan02==2, and so forth */ | ||||
| 26185 | sqlite3_str_appendf(&sRes,"%03d",daysAfterJan01(&x)+1); | ||||
| 26186 | break; | ||||
| 26187 | } | ||||
| 26188 | case 'J': { /* Julian day number. (Non-standard) */ | ||||
| 26189 | sqlite3_str_appendf(&sRes,"%.16g",x.iJD/86400000.0); | ||||
| 26190 | break; | ||||
| 26191 | } | ||||
| 26192 | case 'm': { | ||||
| 26193 | sqlite3_str_appendf(&sRes,"%02d",x.M); | ||||
| 26194 | break; | ||||
| 26195 | } | ||||
| 26196 | case 'M': { | ||||
| 26197 | sqlite3_str_appendf(&sRes,"%02d",x.m); | ||||
| 26198 | break; | ||||
| 26199 | } | ||||
| 26200 | case 'p': /* Fall thru */ | ||||
| 26201 | case 'P': { | ||||
| 26202 | if( x.h>=12 ){ | ||||
| 26203 | sqlite3_str_append(&sRes, cf=='p' ? "PM" : "pm", 2); | ||||
| 26204 | }else{ | ||||
| 26205 | sqlite3_str_append(&sRes, cf=='p' ? "AM" : "am", 2); | ||||
| 26206 | } | ||||
| 26207 | break; | ||||
| 26208 | } | ||||
| 26209 | case 'R': { | ||||
| 26210 | sqlite3_str_appendf(&sRes, "%02d:%02d", x.h, x.m); | ||||
| 26211 | break; | ||||
| 26212 | } | ||||
| 26213 | case 's': { | ||||
| 26214 | if( x.useSubsec ){ | ||||
| 26215 | sqlite3_str_appendf(&sRes,"%.3f", | ||||
| 26216 | (x.iJD - 21086676*(i64)10000000)/1000.0); | ||||
| 26217 | }else{ | ||||
| 26218 | i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000); | ||||
| 26219 | sqlite3_str_appendf(&sRes,"%lld",iS); | ||||
| 26220 | } | ||||
| 26221 | break; | ||||
| 26222 | } | ||||
| 26223 | case 'S': { | ||||
| 26224 | sqlite3_str_appendf(&sRes,"%02d",(int)x.s); | ||||
| 26225 | break; | ||||
| 26226 | } | ||||
| 26227 | case 'T': { | ||||
| 26228 | sqlite3_str_appendf(&sRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s); | ||||
| 26229 | break; | ||||
| 26230 | } | ||||
| 26231 | case 'u': /* Day of week. 1 to 7. Monday==1, Sunday==7 */ | ||||
| 26232 | case 'w': { /* Day of week. 0 to 6. Sunday==0, Monday==1 */ | ||||
| 26233 | char c = (char)daysAfterSunday(&x) + '0'; | ||||
| 26234 | if( c=='0' && cf=='u' ) c = '7'; | ||||
| 26235 | sqlite3_str_appendchar(&sRes, 1, c); | ||||
| 26236 | break; | ||||
| 26237 | } | ||||
| 26238 | case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */ | ||||
| 26239 | sqlite3_str_appendf(&sRes,"%02d", | ||||
| 26240 | (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7); | ||||
| 26241 | break; | ||||
| 26242 | } | ||||
| 26243 | case 'V': { /* Week num. 01-53. First week with a Thur is week 01 */ | ||||
| 26244 | DateTime y = x; | ||||
| 26245 | /* Adjust y so that is the Thursday in the same week as x */ | ||||
| 26246 | assert( y.validJD )((void) (0)); | ||||
| 26247 | y.iJD += (3 - daysAfterMonday(&x))*86400000; | ||||
| 26248 | y.validYMD = 0; | ||||
| 26249 | computeYMD(&y); | ||||
| 26250 | sqlite3_str_appendf(&sRes,"%02d", daysAfterJan01(&y)/7+1); | ||||
| 26251 | break; | ||||
| 26252 | } | ||||
| 26253 | case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */ | ||||
| 26254 | sqlite3_str_appendf(&sRes,"%02d", | ||||
| 26255 | (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7); | ||||
| 26256 | break; | ||||
| 26257 | } | ||||
| 26258 | case 'Y': { | ||||
| 26259 | sqlite3_str_appendf(&sRes,"%04d",x.Y); | ||||
| 26260 | break; | ||||
| 26261 | } | ||||
| 26262 | case '%': { | ||||
| 26263 | sqlite3_str_appendchar(&sRes, 1, '%'); | ||||
| 26264 | break; | ||||
| 26265 | } | ||||
| 26266 | default: { | ||||
| 26267 | sqlite3_str_reset(&sRes); | ||||
| 26268 | return; | ||||
| 26269 | } | ||||
| 26270 | } | ||||
| 26271 | } | ||||
| 26272 | if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j)); | ||||
| 26273 | sqlite3ResultStrAccum(context, &sRes); | ||||
| 26274 | } | ||||
| 26275 | |||||
| 26276 | /* | ||||
| 26277 | ** current_time() | ||||
| 26278 | ** | ||||
| 26279 | ** This function returns the same value as time('now'). | ||||
| 26280 | */ | ||||
| 26281 | static void ctimeFunc( | ||||
| 26282 | sqlite3_context *context, | ||||
| 26283 | int NotUsed, | ||||
| 26284 | sqlite3_value **NotUsed2 | ||||
| 26285 | ){ | ||||
| 26286 | UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2); | ||||
| 26287 | timeFunc(context, 0, 0); | ||||
| 26288 | } | ||||
| 26289 | |||||
| 26290 | /* | ||||
| 26291 | ** current_date() | ||||
| 26292 | ** | ||||
| 26293 | ** This function returns the same value as date('now'). | ||||
| 26294 | */ | ||||
| 26295 | static void cdateFunc( | ||||
| 26296 | sqlite3_context *context, | ||||
| 26297 | int NotUsed, | ||||
| 26298 | sqlite3_value **NotUsed2 | ||||
| 26299 | ){ | ||||
| 26300 | UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2); | ||||
| 26301 | dateFunc(context, 0, 0); | ||||
| 26302 | } | ||||
| 26303 | |||||
| 26304 | /* | ||||
| 26305 | ** timediff(DATE1, DATE2) | ||||
| 26306 | ** | ||||
| 26307 | ** Return the amount of time that must be added to DATE2 in order to | ||||
| 26308 | ** convert it into DATE2. The time difference format is: | ||||
| 26309 | ** | ||||
| 26310 | ** +YYYY-MM-DD HH:MM:SS.SSS | ||||
| 26311 | ** | ||||
| 26312 | ** The initial "+" becomes "-" if DATE1 occurs before DATE2. For | ||||
| 26313 | ** date/time values A and B, the following invariant should hold: | ||||
| 26314 | ** | ||||
| 26315 | ** datetime(A) == (datetime(B, timediff(A,B)) | ||||
| 26316 | ** | ||||
| 26317 | ** Both DATE arguments must be either a julian day number, or an | ||||
| 26318 | ** ISO-8601 string. The unix timestamps are not supported by this | ||||
| 26319 | ** routine. | ||||
| 26320 | */ | ||||
| 26321 | static void timediffFunc( | ||||
| 26322 | sqlite3_context *context, | ||||
| 26323 | int NotUsed1, | ||||
| 26324 | sqlite3_value **argv | ||||
| 26325 | ){ | ||||
| 26326 | char sign; | ||||
| 26327 | int Y, M; | ||||
| 26328 | DateTime d1, d2; | ||||
| 26329 | sqlite3_str sRes; | ||||
| 26330 | UNUSED_PARAMETER(NotUsed1)(void)(NotUsed1); | ||||
| 26331 | if( isDate(context, 1, &argv[0], &d1) ) return; | ||||
| 26332 | if( isDate(context, 1, &argv[1], &d2) ) return; | ||||
| 26333 | computeYMD_HMS(&d1); | ||||
| 26334 | computeYMD_HMS(&d2); | ||||
| 26335 | if( d1.iJD>=d2.iJD ){ | ||||
| 26336 | sign = '+'; | ||||
| 26337 | Y = d1.Y - d2.Y; | ||||
| 26338 | if( Y ){ | ||||
| 26339 | d2.Y = d1.Y; | ||||
| 26340 | d2.validJD = 0; | ||||
| 26341 | computeJD(&d2); | ||||
| 26342 | } | ||||
| 26343 | M = d1.M - d2.M; | ||||
| 26344 | if( M<0 ){ | ||||
| 26345 | Y--; | ||||
| 26346 | M += 12; | ||||
| 26347 | } | ||||
| 26348 | if( M!=0 ){ | ||||
| 26349 | d2.M = d1.M; | ||||
| 26350 | d2.validJD = 0; | ||||
| 26351 | computeJD(&d2); | ||||
| 26352 | } | ||||
| 26353 | while( d1.iJD<d2.iJD ){ | ||||
| 26354 | M--; | ||||
| 26355 | if( M<0 ){ | ||||
| 26356 | M = 11; | ||||
| 26357 | Y--; | ||||
| 26358 | } | ||||
| 26359 | d2.M--; | ||||
| 26360 | if( d2.M<1 ){ | ||||
| 26361 | d2.M = 12; | ||||
| 26362 | d2.Y--; | ||||
| 26363 | } | ||||
| 26364 | d2.validJD = 0; | ||||
| 26365 | computeJD(&d2); | ||||
| 26366 | } | ||||
| 26367 | d1.iJD -= d2.iJD; | ||||
| 26368 | d1.iJD += (u64)1486995408 * (u64)100000; | ||||
| 26369 | }else /* d1<d2 */{ | ||||
| 26370 | sign = '-'; | ||||
| 26371 | Y = d2.Y - d1.Y; | ||||
| 26372 | if( Y ){ | ||||
| 26373 | d2.Y = d1.Y; | ||||
| 26374 | d2.validJD = 0; | ||||
| 26375 | computeJD(&d2); | ||||
| 26376 | } | ||||
| 26377 | M = d2.M - d1.M; | ||||
| 26378 | if( M<0 ){ | ||||
| 26379 | Y--; | ||||
| 26380 | M += 12; | ||||
| 26381 | } | ||||
| 26382 | if( M!=0 ){ | ||||
| 26383 | d2.M = d1.M; | ||||
| 26384 | d2.validJD = 0; | ||||
| 26385 | computeJD(&d2); | ||||
| 26386 | } | ||||
| 26387 | while( d1.iJD>d2.iJD ){ | ||||
| 26388 | M--; | ||||
| 26389 | if( M<0 ){ | ||||
| 26390 | M = 11; | ||||
| 26391 | Y--; | ||||
| 26392 | } | ||||
| 26393 | d2.M++; | ||||
| 26394 | if( d2.M>12 ){ | ||||
| 26395 | d2.M = 1; | ||||
| 26396 | d2.Y++; | ||||
| 26397 | } | ||||
| 26398 | d2.validJD = 0; | ||||
| 26399 | computeJD(&d2); | ||||
| 26400 | } | ||||
| 26401 | d1.iJD = d2.iJD - d1.iJD; | ||||
| 26402 | d1.iJD += (u64)1486995408 * (u64)100000; | ||||
| 26403 | } | ||||
| 26404 | clearYMD_HMS_TZ(&d1); | ||||
| 26405 | computeYMD_HMS(&d1); | ||||
| 26406 | sqlite3StrAccumInit(&sRes, 0, 0, 0, 100); | ||||
| 26407 | sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f", | ||||
| 26408 | sign, Y, M, d1.D-1, d1.h, d1.m, d1.s); | ||||
| 26409 | sqlite3ResultStrAccum(context, &sRes); | ||||
| 26410 | } | ||||
| 26411 | |||||
| 26412 | |||||
| 26413 | /* | ||||
| 26414 | ** current_timestamp() | ||||
| 26415 | ** | ||||
| 26416 | ** This function returns the same value as datetime('now'). | ||||
| 26417 | */ | ||||
| 26418 | static void ctimestampFunc( | ||||
| 26419 | sqlite3_context *context, | ||||
| 26420 | int NotUsed, | ||||
| 26421 | sqlite3_value **NotUsed2 | ||||
| 26422 | ){ | ||||
| 26423 | UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2); | ||||
| 26424 | datetimeFunc(context, 0, 0); | ||||
| 26425 | } | ||||
| 26426 | #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */ | ||||
| 26427 | |||||
| 26428 | #ifdef SQLITE_OMIT_DATETIME_FUNCS | ||||
| 26429 | /* | ||||
| 26430 | ** If the library is compiled to omit the full-scale date and time | ||||
| 26431 | ** handling (to get a smaller binary), the following minimal version | ||||
| 26432 | ** of the functions current_time(), current_date() and current_timestamp() | ||||
| 26433 | ** are included instead. This is to support column declarations that | ||||
| 26434 | ** include "DEFAULT CURRENT_TIME" etc. | ||||
| 26435 | ** | ||||
| 26436 | ** This function uses the C-library functions time(), gmtime() | ||||
| 26437 | ** and strftime(). The format string to pass to strftime() is supplied | ||||
| 26438 | ** as the user-data for the function. | ||||
| 26439 | */ | ||||
| 26440 | static void currentTimeFunc( | ||||
| 26441 | sqlite3_context *context, | ||||
| 26442 | int argc, | ||||
| 26443 | sqlite3_value **argv | ||||
| 26444 | ){ | ||||
| 26445 | time_t t; | ||||
| 26446 | char *zFormat = (char *)sqlite3_user_data(context); | ||||
| 26447 | sqlite3_int64 iT; | ||||
| 26448 | struct tm *pTm; | ||||
| 26449 | struct tm sNow; | ||||
| 26450 | char zBuf[20]; | ||||
| 26451 | |||||
| 26452 | UNUSED_PARAMETER(argc)(void)(argc); | ||||
| 26453 | UNUSED_PARAMETER(argv)(void)(argv); | ||||
| 26454 | |||||
| 26455 | iT = sqlite3StmtCurrentTime(context); | ||||
| 26456 | if( iT<=0 ) return; | ||||
| 26457 | t = iT/1000 - 10000*(sqlite3_int64)21086676; | ||||
| 26458 | #if HAVE_GMTIME_R | ||||
| 26459 | pTm = gmtime_r(&t, &sNow); | ||||
| 26460 | #else | ||||
| 26461 | sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2)); | ||||
| 26462 | pTm = gmtime(&t); | ||||
| 26463 | if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); | ||||
| 26464 | sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2)); | ||||
| 26465 | #endif | ||||
| 26466 | if( pTm ){ | ||||
| 26467 | strftime(zBuf, 20, zFormat, &sNow); | ||||
| 26468 | sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT((sqlite3_destructor_type)-1)); | ||||
| 26469 | } | ||||
| 26470 | } | ||||
| 26471 | #endif | ||||
| 26472 | |||||
| 26473 | #if !defined(SQLITE_OMIT_DATETIME_FUNCS) && defined(SQLITE_DEBUG) | ||||
| 26474 | /* | ||||
| 26475 | ** datedebug(...) | ||||
| 26476 | ** | ||||
| 26477 | ** This routine returns JSON that describes the internal DateTime object. | ||||
| 26478 | ** Used for debugging and testing only. Subject to change. | ||||
| 26479 | */ | ||||
| 26480 | static void datedebugFunc( | ||||
| 26481 | sqlite3_context *context, | ||||
| 26482 | int argc, | ||||
| 26483 | sqlite3_value **argv | ||||
| 26484 | ){ | ||||
| 26485 | DateTime x; | ||||
| 26486 | if( isDate(context, argc, argv, &x)==0 ){ | ||||
| 26487 | char *zJson; | ||||
| 26488 | zJson = sqlite3_mprintf( | ||||
| 26489 | "{iJD:%lld,Y:%d,M:%d,D:%d,h:%d,m:%d,tz:%d," | ||||
| 26490 | "s:%.3f,validJD:%d,validYMS:%d,validHMS:%d," | ||||
| 26491 | "nFloor:%d,rawS:%d,isError:%d,useSubsec:%d," | ||||
| 26492 | "isUtc:%d,isLocal:%d}", | ||||
| 26493 | x.iJD, x.Y, x.M, x.D, x.h, x.m, x.tz, | ||||
| 26494 | x.s, x.validJD, x.validYMD, x.validHMS, | ||||
| 26495 | x.nFloor, x.rawS, x.isError, x.useSubsec, | ||||
| 26496 | x.isUtc, x.isLocal); | ||||
| 26497 | sqlite3_result_text(context, zJson, -1, sqlite3_free); | ||||
| 26498 | } | ||||
| 26499 | } | ||||
| 26500 | #endif /* !SQLITE_OMIT_DATETIME_FUNCS && SQLITE_DEBUG */ | ||||
| 26501 | |||||
| 26502 | |||||
| 26503 | /* | ||||
| 26504 | ** This function registered all of the above C functions as SQL | ||||
| 26505 | ** functions. This should be the only routine in this file with | ||||
| 26506 | ** external linkage. | ||||
| 26507 | */ | ||||
| 26508 | SQLITE_PRIVATEstatic void sqlite3RegisterDateTimeFunctions(void){ | ||||
| 26509 | static FuncDef aDateTimeFuncs[] = { | ||||
| 26510 | #ifndef SQLITE_OMIT_DATETIME_FUNCS | ||||
| 26511 | PURE_DATE(julianday, -1, 0, 0, juliandayFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , juliandayFunc, 0, 0, 0, "julianday", {0} }, | ||||
| 26512 | PURE_DATE(unixepoch, -1, 0, 0, unixepochFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , unixepochFunc, 0, 0, 0, "unixepoch", {0} }, | ||||
| 26513 | PURE_DATE(date, -1, 0, 0, dateFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , dateFunc, 0, 0, 0, "date", {0} }, | ||||
| 26514 | PURE_DATE(time, -1, 0, 0, timeFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , timeFunc, 0, 0, 0, "time", {0} }, | ||||
| 26515 | PURE_DATE(datetime, -1, 0, 0, datetimeFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , datetimeFunc, 0, 0, 0, "datetime", {0} }, | ||||
| 26516 | PURE_DATE(strftime, -1, 0, 0, strftimeFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , strftimeFunc, 0, 0, 0, "strftime", {0} }, | ||||
| 26517 | PURE_DATE(timediff, 2, 0, 0, timediffFunc ){2, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , timediffFunc, 0, 0, 0, "timediff", {0} }, | ||||
| 26518 | #ifdef SQLITE_DEBUG | ||||
| 26519 | PURE_DATE(datedebug, -1, 0, 0, datedebugFunc ){-1, 0x00800000| 0x2000|1|0x0800, (void*)&sqlite3Config, 0 , datedebugFunc, 0, 0, 0, "datedebug", {0} }, | ||||
| 26520 | #endif | ||||
| 26521 | DFUNCTION(current_time, 0, 0, 0, ctimeFunc ){0, 0x00800000|0x2000|1, 0, 0, ctimeFunc, 0, 0, 0, "current_time" , {0} }, | ||||
| 26522 | DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc){0, 0x00800000|0x2000|1, 0, 0, ctimestampFunc, 0, 0, 0, "current_timestamp" , {0} }, | ||||
| 26523 | DFUNCTION(current_date, 0, 0, 0, cdateFunc ){0, 0x00800000|0x2000|1, 0, 0, cdateFunc, 0, 0, 0, "current_date" , {0} }, | ||||
| 26524 | #else | ||||
| 26525 | STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc){0, 0x00800000| 0x2000|1|(0*0x0020), "%H:%M:%S", 0, currentTimeFunc , 0, 0, 0, "current_time", }, | ||||
| 26526 | STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc){0, 0x00800000| 0x2000|1|(0*0x0020), "%Y-%m-%d", 0, currentTimeFunc , 0, 0, 0, "current_date", }, | ||||
| 26527 | STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc){0, 0x00800000| 0x2000|1|(0*0x0020), "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc , 0, 0, 0, "current_timestamp", }, | ||||
| 26528 | #endif | ||||
| 26529 | }; | ||||
| 26530 | sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs)((int)(sizeof(aDateTimeFuncs)/sizeof(aDateTimeFuncs[0])))); | ||||
| 26531 | } | ||||
| 26532 | |||||
| 26533 | /************** End of date.c ************************************************/ | ||||
| 26534 | /************** Begin file os.c **********************************************/ | ||||
| 26535 | /* | ||||
| 26536 | ** 2005 November 29 | ||||
| 26537 | ** | ||||
| 26538 | ** The author disclaims copyright to this source code. In place of | ||||
| 26539 | ** a legal notice, here is a blessing: | ||||
| 26540 | ** | ||||
| 26541 | ** May you do good and not evil. | ||||
| 26542 | ** May you find forgiveness for yourself and forgive others. | ||||
| 26543 | ** May you share freely, never taking more than you give. | ||||
| 26544 | ** | ||||
| 26545 | ****************************************************************************** | ||||
| 26546 | ** | ||||
| 26547 | ** This file contains OS interface code that is common to all | ||||
| 26548 | ** architectures. | ||||
| 26549 | */ | ||||
| 26550 | /* #include "sqliteInt.h" */ | ||||
| 26551 | |||||
| 26552 | /* | ||||
| 26553 | ** If we compile with the SQLITE_TEST macro set, then the following block | ||||
| 26554 | ** of code will give us the ability to simulate a disk I/O error. This | ||||
| 26555 | ** is used for testing the I/O recovery logic. | ||||
| 26556 | */ | ||||
| 26557 | #if defined(SQLITE_TEST) | ||||
| 26558 | SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ | ||||
| 26559 | SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ | ||||
| 26560 | SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ | ||||
| 26561 | SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ | ||||
| 26562 | SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */ | ||||
| 26563 | SQLITE_API int sqlite3_diskfull_pending = 0; | ||||
| 26564 | SQLITE_API int sqlite3_diskfull = 0; | ||||
| 26565 | #endif /* defined(SQLITE_TEST) */ | ||||
| 26566 | |||||
| 26567 | /* | ||||
| 26568 | ** When testing, also keep a count of the number of open files. | ||||
| 26569 | */ | ||||
| 26570 | #if defined(SQLITE_TEST) | ||||
| 26571 | SQLITE_API int sqlite3_open_file_count = 0; | ||||
| 26572 | #endif /* defined(SQLITE_TEST) */ | ||||
| 26573 | |||||
| 26574 | /* | ||||
| 26575 | ** The default SQLite sqlite3_vfs implementations do not allocate | ||||
| 26576 | ** memory (actually, os_unix.c allocates a small amount of memory | ||||
| 26577 | ** from within OsOpen()), but some third-party implementations may. | ||||
| 26578 | ** So we test the effects of a malloc() failing and the sqlite3OsXXX() | ||||
| 26579 | ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. | ||||
| 26580 | ** | ||||
| 26581 | ** The following functions are instrumented for malloc() failure | ||||
| 26582 | ** testing: | ||||
| 26583 | ** | ||||
| 26584 | ** sqlite3OsRead() | ||||
| 26585 | ** sqlite3OsWrite() | ||||
| 26586 | ** sqlite3OsSync() | ||||
| 26587 | ** sqlite3OsFileSize() | ||||
| 26588 | ** sqlite3OsLock() | ||||
| 26589 | ** sqlite3OsCheckReservedLock() | ||||
| 26590 | ** sqlite3OsFileControl() | ||||
| 26591 | ** sqlite3OsShmMap() | ||||
| 26592 | ** sqlite3OsOpen() | ||||
| 26593 | ** sqlite3OsDelete() | ||||
| 26594 | ** sqlite3OsAccess() | ||||
| 26595 | ** sqlite3OsFullPathname() | ||||
| 26596 | ** | ||||
| 26597 | */ | ||||
| 26598 | #if defined(SQLITE_TEST) | ||||
| 26599 | SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1; | ||||
| 26600 | #define DO_OS_MALLOC_TEST(x) \ | ||||
| 26601 | if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \ | ||||
| 26602 | void *pTstAlloc = sqlite3Malloc(10); \ | ||||
| 26603 | if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); \ | ||||
| 26604 | sqlite3_free(pTstAlloc); \ | ||||
| 26605 | } | ||||
| 26606 | #else | ||||
| 26607 | #define DO_OS_MALLOC_TEST(x) | ||||
| 26608 | #endif | ||||
| 26609 | |||||
| 26610 | /* | ||||
| 26611 | ** The following routines are convenience wrappers around methods | ||||
| 26612 | ** of the sqlite3_file object. This is mostly just syntactic sugar. All | ||||
| 26613 | ** of this would be completely automatic if SQLite were coded using | ||||
| 26614 | ** C++ instead of plain old C. | ||||
| 26615 | */ | ||||
| 26616 | SQLITE_PRIVATEstatic void sqlite3OsClose(sqlite3_file *pId){ | ||||
| 26617 | if( pId->pMethods ){ | ||||
| 26618 | pId->pMethods->xClose(pId); | ||||
| 26619 | pId->pMethods = 0; | ||||
| 26620 | } | ||||
| 26621 | } | ||||
| 26622 | SQLITE_PRIVATEstatic int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){ | ||||
| 26623 | DO_OS_MALLOC_TEST(id); | ||||
| 26624 | return id->pMethods->xRead(id, pBuf, amt, offset); | ||||
| 26625 | } | ||||
| 26626 | SQLITE_PRIVATEstatic int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){ | ||||
| 26627 | DO_OS_MALLOC_TEST(id); | ||||
| 26628 | return id->pMethods->xWrite(id, pBuf, amt, offset); | ||||
| |||||
| 26629 | } | ||||
| 26630 | SQLITE_PRIVATEstatic int sqlite3OsTruncate(sqlite3_file *id, i64 size){ | ||||
| 26631 | return id->pMethods->xTruncate(id, size); | ||||
| 26632 | } | ||||
| 26633 | SQLITE_PRIVATEstatic int sqlite3OsSync(sqlite3_file *id, int flags){ | ||||
| 26634 | DO_OS_MALLOC_TEST(id); | ||||
| 26635 | return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK0; | ||||
| 26636 | } | ||||
| 26637 | SQLITE_PRIVATEstatic int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){ | ||||
| 26638 | DO_OS_MALLOC_TEST(id); | ||||
| 26639 | return id->pMethods->xFileSize(id, pSize); | ||||
| 26640 | } | ||||
| 26641 | SQLITE_PRIVATEstatic int sqlite3OsLock(sqlite3_file *id, int lockType){ | ||||
| 26642 | DO_OS_MALLOC_TEST(id); | ||||
| 26643 | assert( lockType>=SQLITE_LOCK_SHARED && lockType<=SQLITE_LOCK_EXCLUSIVE )((void) (0)); | ||||
| 26644 | return id->pMethods->xLock(id, lockType); | ||||
| 26645 | } | ||||
| 26646 | SQLITE_PRIVATEstatic int sqlite3OsUnlock(sqlite3_file *id, int lockType){ | ||||
| 26647 | assert( lockType==SQLITE_LOCK_NONE || lockType==SQLITE_LOCK_SHARED )((void) (0)); | ||||
| 26648 | return id->pMethods->xUnlock(id, lockType); | ||||
| 26649 | } | ||||
| 26650 | SQLITE_PRIVATEstatic int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){ | ||||
| 26651 | DO_OS_MALLOC_TEST(id); | ||||
| 26652 | return id->pMethods->xCheckReservedLock(id, pResOut); | ||||
| 26653 | } | ||||
| 26654 | |||||
| 26655 | /* | ||||
| 26656 | ** Use sqlite3OsFileControl() when we are doing something that might fail | ||||
| 26657 | ** and we need to know about the failures. Use sqlite3OsFileControlHint() | ||||
| 26658 | ** when simply tossing information over the wall to the VFS and we do not | ||||
| 26659 | ** really care if the VFS receives and understands the information since it | ||||
| 26660 | ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint() | ||||
| 26661 | ** routine has no return value since the return value would be meaningless. | ||||
| 26662 | */ | ||||
| 26663 | SQLITE_PRIVATEstatic int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ | ||||
| 26664 | if( id->pMethods==0 ) return SQLITE_NOTFOUND12; | ||||
| 26665 | #ifdef SQLITE_TEST | ||||
| 26666 | if( op!=SQLITE_FCNTL_COMMIT_PHASETWO22 | ||||
| 26667 | && op!=SQLITE_FCNTL_LOCK_TIMEOUT34 | ||||
| 26668 | && op!=SQLITE_FCNTL_CKPT_DONE37 | ||||
| 26669 | && op!=SQLITE_FCNTL_CKPT_START39 | ||||
| 26670 | ){ | ||||
| 26671 | /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite | ||||
| 26672 | ** is using a regular VFS, it is called after the corresponding | ||||
| 26673 | ** transaction has been committed. Injecting a fault at this point | ||||
| 26674 | ** confuses the test scripts - the COMMIT command returns SQLITE_NOMEM | ||||
| 26675 | ** but the transaction is committed anyway. | ||||
| 26676 | ** | ||||
| 26677 | ** The core must call OsFileControl() though, not OsFileControlHint(), | ||||
| 26678 | ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably | ||||
| 26679 | ** means the commit really has failed and an error should be returned | ||||
| 26680 | ** to the user. | ||||
| 26681 | ** | ||||
| 26682 | ** The CKPT_DONE and CKPT_START file-controls are write-only signals | ||||
| 26683 | ** to the cksumvfs. Their return code is meaningless and is ignored | ||||
| 26684 | ** by the SQLite core, so there is no point in simulating OOMs for them. | ||||
| 26685 | */ | ||||
| 26686 | DO_OS_MALLOC_TEST(id); | ||||
| 26687 | } | ||||
| 26688 | #endif | ||||
| 26689 | return id->pMethods->xFileControl(id, op, pArg); | ||||
| 26690 | } | ||||
| 26691 | SQLITE_PRIVATEstatic void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){ | ||||
| 26692 | if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg); | ||||
| 26693 | } | ||||
| 26694 | |||||
| 26695 | SQLITE_PRIVATEstatic int sqlite3OsSectorSize(sqlite3_file *id){ | ||||
| 26696 | int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; | ||||
| 26697 | return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE4096); | ||||
| 26698 | } | ||||
| 26699 | SQLITE_PRIVATEstatic int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ | ||||
| 26700 | if( NEVER(id->pMethods==0)(id->pMethods==0) ) return 0; | ||||
| 26701 | return id->pMethods->xDeviceCharacteristics(id); | ||||
| 26702 | } | ||||
| 26703 | #ifndef SQLITE_OMIT_WAL | ||||
| 26704 | SQLITE_PRIVATEstatic int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){ | ||||
| 26705 | return id->pMethods->xShmLock(id, offset, n, flags); | ||||
| 26706 | } | ||||
| 26707 | SQLITE_PRIVATEstatic void sqlite3OsShmBarrier(sqlite3_file *id){ | ||||
| 26708 | id->pMethods->xShmBarrier(id); | ||||
| 26709 | } | ||||
| 26710 | SQLITE_PRIVATEstatic int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){ | ||||
| 26711 | return id->pMethods->xShmUnmap(id, deleteFlag); | ||||
| 26712 | } | ||||
| 26713 | SQLITE_PRIVATEstatic int sqlite3OsShmMap( | ||||
| 26714 | sqlite3_file *id, /* Database file handle */ | ||||
| 26715 | int iPage, | ||||
| 26716 | int pgsz, | ||||
| 26717 | int bExtend, /* True to extend file if necessary */ | ||||
| 26718 | void volatile **pp /* OUT: Pointer to mapping */ | ||||
| 26719 | ){ | ||||
| 26720 | DO_OS_MALLOC_TEST(id); | ||||
| 26721 | return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); | ||||
| 26722 | } | ||||
| 26723 | #endif /* SQLITE_OMIT_WAL */ | ||||
| 26724 | |||||
| 26725 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 26726 | /* The real implementation of xFetch and xUnfetch */ | ||||
| 26727 | SQLITE_PRIVATEstatic int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ | ||||
| 26728 | DO_OS_MALLOC_TEST(id); | ||||
| 26729 | return id->pMethods->xFetch(id, iOff, iAmt, pp); | ||||
| 26730 | } | ||||
| 26731 | SQLITE_PRIVATEstatic int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ | ||||
| 26732 | return id->pMethods->xUnfetch(id, iOff, p); | ||||
| 26733 | } | ||||
| 26734 | #else | ||||
| 26735 | /* No-op stubs to use when memory-mapped I/O is disabled */ | ||||
| 26736 | SQLITE_PRIVATEstatic int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ | ||||
| 26737 | *pp = 0; | ||||
| 26738 | return SQLITE_OK0; | ||||
| 26739 | } | ||||
| 26740 | SQLITE_PRIVATEstatic int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ | ||||
| 26741 | return SQLITE_OK0; | ||||
| 26742 | } | ||||
| 26743 | #endif | ||||
| 26744 | |||||
| 26745 | /* | ||||
| 26746 | ** The next group of routines are convenience wrappers around the | ||||
| 26747 | ** VFS methods. | ||||
| 26748 | */ | ||||
| 26749 | SQLITE_PRIVATEstatic int sqlite3OsOpen( | ||||
| 26750 | sqlite3_vfs *pVfs, | ||||
| 26751 | const char *zPath, | ||||
| 26752 | sqlite3_file *pFile, | ||||
| 26753 | int flags, | ||||
| 26754 | int *pFlagsOut | ||||
| 26755 | ){ | ||||
| 26756 | int rc; | ||||
| 26757 | DO_OS_MALLOC_TEST(0); | ||||
| 26758 | /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed | ||||
| 26759 | ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, | ||||
| 26760 | ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before | ||||
| 26761 | ** reaching the VFS. */ | ||||
| 26762 | assert( zPath || (flags & SQLITE_OPEN_EXCLUSIVE) )((void) (0)); | ||||
| 26763 | rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut); | ||||
| 26764 | assert( rc==SQLITE_OK || pFile->pMethods==0 )((void) (0)); | ||||
| 26765 | return rc; | ||||
| 26766 | } | ||||
| 26767 | SQLITE_PRIVATEstatic int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ | ||||
| 26768 | DO_OS_MALLOC_TEST(0); | ||||
| 26769 | assert( dirSync==0 || dirSync==1 )((void) (0)); | ||||
| 26770 | return pVfs->xDelete!=0 ? pVfs->xDelete(pVfs, zPath, dirSync) : SQLITE_OK0; | ||||
| 26771 | } | ||||
| 26772 | SQLITE_PRIVATEstatic int sqlite3OsAccess( | ||||
| 26773 | sqlite3_vfs *pVfs, | ||||
| 26774 | const char *zPath, | ||||
| 26775 | int flags, | ||||
| 26776 | int *pResOut | ||||
| 26777 | ){ | ||||
| 26778 | DO_OS_MALLOC_TEST(0); | ||||
| 26779 | return pVfs->xAccess(pVfs, zPath, flags, pResOut); | ||||
| 26780 | } | ||||
| 26781 | SQLITE_PRIVATEstatic int sqlite3OsFullPathname( | ||||
| 26782 | sqlite3_vfs *pVfs, | ||||
| 26783 | const char *zPath, | ||||
| 26784 | int nPathOut, | ||||
| 26785 | char *zPathOut | ||||
| 26786 | ){ | ||||
| 26787 | DO_OS_MALLOC_TEST(0); | ||||
| 26788 | zPathOut[0] = 0; | ||||
| 26789 | return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); | ||||
| 26790 | } | ||||
| 26791 | #ifndef SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 26792 | SQLITE_PRIVATEstatic void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ | ||||
| 26793 | assert( zPath!=0 )((void) (0)); | ||||
| 26794 | assert( strlen(zPath)<=SQLITE_MAX_PATHLEN )((void) (0)); /* tag-20210611-1 */ | ||||
| 26795 | return pVfs->xDlOpen(pVfs, zPath); | ||||
| 26796 | } | ||||
| 26797 | SQLITE_PRIVATEstatic void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ | ||||
| 26798 | pVfs->xDlError(pVfs, nByte, zBufOut); | ||||
| 26799 | } | ||||
| 26800 | SQLITE_PRIVATEstatic void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ | ||||
| 26801 | return pVfs->xDlSym(pVfs, pHdle, zSym); | ||||
| 26802 | } | ||||
| 26803 | SQLITE_PRIVATEstatic void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){ | ||||
| 26804 | pVfs->xDlClose(pVfs, pHandle); | ||||
| 26805 | } | ||||
| 26806 | #endif /* SQLITE_OMIT_LOAD_EXTENSION */ | ||||
| 26807 | SQLITE_PRIVATEstatic int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ | ||||
| 26808 | if( sqlite3Config.iPrngSeed ){ | ||||
| 26809 | memset(zBufOut, 0, nByte); | ||||
| 26810 | if( ALWAYS(nByte>(signed)sizeof(unsigned))(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int); | ||||
| 26811 | memcpy(zBufOut, &sqlite3Config.iPrngSeed, nByte); | ||||
| 26812 | return SQLITE_OK0; | ||||
| 26813 | }else{ | ||||
| 26814 | return pVfs->xRandomness(pVfs, nByte, zBufOut); | ||||
| 26815 | } | ||||
| 26816 | |||||
| 26817 | } | ||||
| 26818 | SQLITE_PRIVATEstatic int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){ | ||||
| 26819 | return pVfs->xSleep(pVfs, nMicro); | ||||
| 26820 | } | ||||
| 26821 | SQLITE_PRIVATEstatic int sqlite3OsGetLastError(sqlite3_vfs *pVfs){ | ||||
| 26822 | return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0; | ||||
| 26823 | } | ||||
| 26824 | SQLITE_PRIVATEstatic int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ | ||||
| 26825 | int rc; | ||||
| 26826 | /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() | ||||
| 26827 | ** method to get the current date and time if that method is available | ||||
| 26828 | ** (if iVersion is 2 or greater and the function pointer is not NULL) and | ||||
| 26829 | ** will fall back to xCurrentTime() if xCurrentTimeInt64() is | ||||
| 26830 | ** unavailable. | ||||
| 26831 | */ | ||||
| 26832 | if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ | ||||
| 26833 | rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut); | ||||
| 26834 | }else{ | ||||
| 26835 | double r; | ||||
| 26836 | rc = pVfs->xCurrentTime(pVfs, &r); | ||||
| 26837 | *pTimeOut = (sqlite3_int64)(r*86400000.0); | ||||
| 26838 | } | ||||
| 26839 | return rc; | ||||
| 26840 | } | ||||
| 26841 | |||||
| 26842 | SQLITE_PRIVATEstatic int sqlite3OsOpenMalloc( | ||||
| 26843 | sqlite3_vfs *pVfs, | ||||
| 26844 | const char *zFile, | ||||
| 26845 | sqlite3_file **ppFile, | ||||
| 26846 | int flags, | ||||
| 26847 | int *pOutFlags | ||||
| 26848 | ){ | ||||
| 26849 | int rc; | ||||
| 26850 | sqlite3_file *pFile; | ||||
| 26851 | pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); | ||||
| 26852 | if( pFile ){ | ||||
| 26853 | rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); | ||||
| 26854 | if( rc!=SQLITE_OK0 ){ | ||||
| 26855 | sqlite3_free(pFile); | ||||
| 26856 | *ppFile = 0; | ||||
| 26857 | }else{ | ||||
| 26858 | *ppFile = pFile; | ||||
| 26859 | } | ||||
| 26860 | }else{ | ||||
| 26861 | *ppFile = 0; | ||||
| 26862 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 26863 | } | ||||
| 26864 | assert( *ppFile!=0 || rc!=SQLITE_OK )((void) (0)); | ||||
| 26865 | return rc; | ||||
| 26866 | } | ||||
| 26867 | SQLITE_PRIVATEstatic void sqlite3OsCloseFree(sqlite3_file *pFile){ | ||||
| 26868 | assert( pFile )((void) (0)); | ||||
| 26869 | sqlite3OsClose(pFile); | ||||
| 26870 | sqlite3_free(pFile); | ||||
| 26871 | } | ||||
| 26872 | |||||
| 26873 | /* | ||||
| 26874 | ** This function is a wrapper around the OS specific implementation of | ||||
| 26875 | ** sqlite3_os_init(). The purpose of the wrapper is to provide the | ||||
| 26876 | ** ability to simulate a malloc failure, so that the handling of an | ||||
| 26877 | ** error in sqlite3_os_init() by the upper layers can be tested. | ||||
| 26878 | */ | ||||
| 26879 | SQLITE_PRIVATEstatic int sqlite3OsInit(void){ | ||||
| 26880 | void *p = sqlite3_malloc(10); | ||||
| 26881 | if( p==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 26882 | sqlite3_free(p); | ||||
| 26883 | return sqlite3_os_init(); | ||||
| 26884 | } | ||||
| 26885 | |||||
| 26886 | /* | ||||
| 26887 | ** The list of all registered VFS implementations. | ||||
| 26888 | */ | ||||
| 26889 | static sqlite3_vfs * SQLITE_WSD vfsListvfsList = 0; | ||||
| 26890 | #define vfsListvfsList GLOBAL(sqlite3_vfs *, vfsList)vfsList | ||||
| 26891 | |||||
| 26892 | /* | ||||
| 26893 | ** Locate a VFS by name. If no name is given, simply return the | ||||
| 26894 | ** first VFS on the list. | ||||
| 26895 | */ | ||||
| 26896 | SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ | ||||
| 26897 | sqlite3_vfs *pVfs = 0; | ||||
| 26898 | #if SQLITE_THREADSAFE2 | ||||
| 26899 | sqlite3_mutex *mutex; | ||||
| 26900 | #endif | ||||
| 26901 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 26902 | int rc = sqlite3_initialize(); | ||||
| 26903 | if( rc ) return 0; | ||||
| 26904 | #endif | ||||
| 26905 | #if SQLITE_THREADSAFE2 | ||||
| 26906 | mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2); | ||||
| 26907 | #endif | ||||
| 26908 | sqlite3_mutex_enter(mutex); | ||||
| 26909 | for(pVfs = vfsListvfsList; pVfs; pVfs=pVfs->pNext){ | ||||
| 26910 | if( zVfs==0 ) break; | ||||
| 26911 | if( strcmp(zVfs, pVfs->zName)==0 ) break; | ||||
| 26912 | } | ||||
| 26913 | sqlite3_mutex_leave(mutex); | ||||
| 26914 | return pVfs; | ||||
| 26915 | } | ||||
| 26916 | |||||
| 26917 | /* | ||||
| 26918 | ** Unlink a VFS from the linked list | ||||
| 26919 | */ | ||||
| 26920 | static void vfsUnlink(sqlite3_vfs *pVfs){ | ||||
| 26921 | assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) )((void) (0)); | ||||
| 26922 | if( pVfs==0 ){ | ||||
| 26923 | /* No-op */ | ||||
| 26924 | }else if( vfsListvfsList==pVfs ){ | ||||
| 26925 | vfsListvfsList = pVfs->pNext; | ||||
| 26926 | }else if( vfsListvfsList ){ | ||||
| 26927 | sqlite3_vfs *p = vfsListvfsList; | ||||
| 26928 | while( p->pNext && p->pNext!=pVfs ){ | ||||
| 26929 | p = p->pNext; | ||||
| 26930 | } | ||||
| 26931 | if( p->pNext==pVfs ){ | ||||
| 26932 | p->pNext = pVfs->pNext; | ||||
| 26933 | } | ||||
| 26934 | } | ||||
| 26935 | } | ||||
| 26936 | |||||
| 26937 | /* | ||||
| 26938 | ** Register a VFS with the system. It is harmless to register the same | ||||
| 26939 | ** VFS multiple times. The new VFS becomes the default if makeDflt is | ||||
| 26940 | ** true. | ||||
| 26941 | */ | ||||
| 26942 | SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ | ||||
| 26943 | MUTEX_LOGIC(sqlite3_mutex *mutex;)sqlite3_mutex *mutex; | ||||
| 26944 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 26945 | int rc = sqlite3_initialize(); | ||||
| 26946 | if( rc ) return rc; | ||||
| 26947 | #endif | ||||
| 26948 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 26949 | if( pVfs==0 ) return SQLITE_MISUSE_BKPTsqlite3MisuseError(26949); | ||||
| 26950 | #endif | ||||
| 26951 | |||||
| 26952 | MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )mutex = sqlite3MutexAlloc(2); | ||||
| 26953 | sqlite3_mutex_enter(mutex); | ||||
| 26954 | vfsUnlink(pVfs); | ||||
| 26955 | if( makeDflt || vfsListvfsList==0 ){ | ||||
| 26956 | pVfs->pNext = vfsListvfsList; | ||||
| 26957 | vfsListvfsList = pVfs; | ||||
| 26958 | }else{ | ||||
| 26959 | pVfs->pNext = vfsListvfsList->pNext; | ||||
| 26960 | vfsListvfsList->pNext = pVfs; | ||||
| 26961 | } | ||||
| 26962 | assert(vfsList)((void) (0)); | ||||
| 26963 | sqlite3_mutex_leave(mutex); | ||||
| 26964 | return SQLITE_OK0; | ||||
| 26965 | } | ||||
| 26966 | |||||
| 26967 | /* | ||||
| 26968 | ** Unregister a VFS so that it is no longer accessible. | ||||
| 26969 | */ | ||||
| 26970 | SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ | ||||
| 26971 | MUTEX_LOGIC(sqlite3_mutex *mutex;)sqlite3_mutex *mutex; | ||||
| 26972 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 26973 | int rc = sqlite3_initialize(); | ||||
| 26974 | if( rc ) return rc; | ||||
| 26975 | #endif | ||||
| 26976 | MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )mutex = sqlite3MutexAlloc(2); | ||||
| 26977 | sqlite3_mutex_enter(mutex); | ||||
| 26978 | vfsUnlink(pVfs); | ||||
| 26979 | sqlite3_mutex_leave(mutex); | ||||
| 26980 | return SQLITE_OK0; | ||||
| 26981 | } | ||||
| 26982 | |||||
| 26983 | /************** End of os.c **************************************************/ | ||||
| 26984 | /************** Begin file fault.c *******************************************/ | ||||
| 26985 | /* | ||||
| 26986 | ** 2008 Jan 22 | ||||
| 26987 | ** | ||||
| 26988 | ** The author disclaims copyright to this source code. In place of | ||||
| 26989 | ** a legal notice, here is a blessing: | ||||
| 26990 | ** | ||||
| 26991 | ** May you do good and not evil. | ||||
| 26992 | ** May you find forgiveness for yourself and forgive others. | ||||
| 26993 | ** May you share freely, never taking more than you give. | ||||
| 26994 | ** | ||||
| 26995 | ************************************************************************* | ||||
| 26996 | ** | ||||
| 26997 | ** This file contains code to support the concept of "benign" | ||||
| 26998 | ** malloc failures (when the xMalloc() or xRealloc() method of the | ||||
| 26999 | ** sqlite3_mem_methods structure fails to allocate a block of memory | ||||
| 27000 | ** and returns 0). | ||||
| 27001 | ** | ||||
| 27002 | ** Most malloc failures are non-benign. After they occur, SQLite | ||||
| 27003 | ** abandons the current operation and returns an error code (usually | ||||
| 27004 | ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily | ||||
| 27005 | ** fatal. For example, if a malloc fails while resizing a hash table, this | ||||
| 27006 | ** is completely recoverable simply by not carrying out the resize. The | ||||
| 27007 | ** hash table will continue to function normally. So a malloc failure | ||||
| 27008 | ** during a hash table resize is a benign fault. | ||||
| 27009 | */ | ||||
| 27010 | |||||
| 27011 | /* #include "sqliteInt.h" */ | ||||
| 27012 | |||||
| 27013 | #ifndef SQLITE_UNTESTABLE | ||||
| 27014 | |||||
| 27015 | /* | ||||
| 27016 | ** Global variables. | ||||
| 27017 | */ | ||||
| 27018 | typedef struct BenignMallocHooks BenignMallocHooks; | ||||
| 27019 | static SQLITE_WSD struct BenignMallocHooks { | ||||
| 27020 | void (*xBenignBegin)(void); | ||||
| 27021 | void (*xBenignEnd)(void); | ||||
| 27022 | } sqlite3Hooks = { 0, 0 }; | ||||
| 27023 | |||||
| 27024 | /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks | ||||
| 27025 | ** structure. If writable static data is unsupported on the target, | ||||
| 27026 | ** we have to locate the state vector at run-time. In the more common | ||||
| 27027 | ** case where writable static data is supported, wsdHooks can refer directly | ||||
| 27028 | ** to the "sqlite3Hooks" state vector declared above. | ||||
| 27029 | */ | ||||
| 27030 | #ifdef SQLITE_OMIT_WSD | ||||
| 27031 | # define wsdHooksInit \ | ||||
| 27032 | BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)sqlite3Hooks | ||||
| 27033 | # define wsdHookssqlite3Hooks x[0] | ||||
| 27034 | #else | ||||
| 27035 | # define wsdHooksInit | ||||
| 27036 | # define wsdHookssqlite3Hooks sqlite3Hooks | ||||
| 27037 | #endif | ||||
| 27038 | |||||
| 27039 | |||||
| 27040 | /* | ||||
| 27041 | ** Register hooks to call when sqlite3BeginBenignMalloc() and | ||||
| 27042 | ** sqlite3EndBenignMalloc() are called, respectively. | ||||
| 27043 | */ | ||||
| 27044 | SQLITE_PRIVATEstatic void sqlite3BenignMallocHooks( | ||||
| 27045 | void (*xBenignBegin)(void), | ||||
| 27046 | void (*xBenignEnd)(void) | ||||
| 27047 | ){ | ||||
| 27048 | wsdHooksInit; | ||||
| 27049 | wsdHookssqlite3Hooks.xBenignBegin = xBenignBegin; | ||||
| 27050 | wsdHookssqlite3Hooks.xBenignEnd = xBenignEnd; | ||||
| 27051 | } | ||||
| 27052 | |||||
| 27053 | /* | ||||
| 27054 | ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that | ||||
| 27055 | ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() | ||||
| 27056 | ** indicates that subsequent malloc failures are non-benign. | ||||
| 27057 | */ | ||||
| 27058 | SQLITE_PRIVATEstatic void sqlite3BeginBenignMalloc(void){ | ||||
| 27059 | wsdHooksInit; | ||||
| 27060 | if( wsdHookssqlite3Hooks.xBenignBegin ){ | ||||
| 27061 | wsdHookssqlite3Hooks.xBenignBegin(); | ||||
| 27062 | } | ||||
| 27063 | } | ||||
| 27064 | SQLITE_PRIVATEstatic void sqlite3EndBenignMalloc(void){ | ||||
| 27065 | wsdHooksInit; | ||||
| 27066 | if( wsdHookssqlite3Hooks.xBenignEnd ){ | ||||
| 27067 | wsdHookssqlite3Hooks.xBenignEnd(); | ||||
| 27068 | } | ||||
| 27069 | } | ||||
| 27070 | |||||
| 27071 | #endif /* #ifndef SQLITE_UNTESTABLE */ | ||||
| 27072 | |||||
| 27073 | /************** End of fault.c ***********************************************/ | ||||
| 27074 | /************** Begin file mem0.c ********************************************/ | ||||
| 27075 | /* | ||||
| 27076 | ** 2008 October 28 | ||||
| 27077 | ** | ||||
| 27078 | ** The author disclaims copyright to this source code. In place of | ||||
| 27079 | ** a legal notice, here is a blessing: | ||||
| 27080 | ** | ||||
| 27081 | ** May you do good and not evil. | ||||
| 27082 | ** May you find forgiveness for yourself and forgive others. | ||||
| 27083 | ** May you share freely, never taking more than you give. | ||||
| 27084 | ** | ||||
| 27085 | ************************************************************************* | ||||
| 27086 | ** | ||||
| 27087 | ** This file contains a no-op memory allocation drivers for use when | ||||
| 27088 | ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented | ||||
| 27089 | ** here always fail. SQLite will not operate with these drivers. These | ||||
| 27090 | ** are merely placeholders. Real drivers must be substituted using | ||||
| 27091 | ** sqlite3_config() before SQLite will operate. | ||||
| 27092 | */ | ||||
| 27093 | /* #include "sqliteInt.h" */ | ||||
| 27094 | |||||
| 27095 | /* | ||||
| 27096 | ** This version of the memory allocator is the default. It is | ||||
| 27097 | ** used when no other memory allocator is specified using compile-time | ||||
| 27098 | ** macros. | ||||
| 27099 | */ | ||||
| 27100 | #ifdef SQLITE_ZERO_MALLOC | ||||
| 27101 | |||||
| 27102 | /* | ||||
| 27103 | ** No-op versions of all memory allocation routines | ||||
| 27104 | */ | ||||
| 27105 | static void *sqlite3MemMalloc(int nByte){ return 0; } | ||||
| 27106 | static void sqlite3MemFree(void *pPrior){ return; } | ||||
| 27107 | static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; } | ||||
| 27108 | static int sqlite3MemSize(void *pPrior){ return 0; } | ||||
| 27109 | static int sqlite3MemRoundup(int n){ return n; } | ||||
| 27110 | static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK0; } | ||||
| 27111 | static void sqlite3MemShutdown(void *NotUsed){ return; } | ||||
| 27112 | |||||
| 27113 | /* | ||||
| 27114 | ** This routine is the only routine in this file with external linkage. | ||||
| 27115 | ** | ||||
| 27116 | ** Populate the low-level memory allocation function pointers in | ||||
| 27117 | ** sqlite3GlobalConfig.m with pointers to the routines in this file. | ||||
| 27118 | */ | ||||
| 27119 | SQLITE_PRIVATEstatic void sqlite3MemSetDefault(void){ | ||||
| 27120 | static const sqlite3_mem_methods defaultMethods = { | ||||
| 27121 | sqlite3MemMalloc, | ||||
| 27122 | sqlite3MemFree, | ||||
| 27123 | sqlite3MemRealloc, | ||||
| 27124 | sqlite3MemSize, | ||||
| 27125 | sqlite3MemRoundup, | ||||
| 27126 | sqlite3MemInit, | ||||
| 27127 | sqlite3MemShutdown, | ||||
| 27128 | 0 | ||||
| 27129 | }; | ||||
| 27130 | sqlite3_config(SQLITE_CONFIG_MALLOC4, &defaultMethods); | ||||
| 27131 | } | ||||
| 27132 | |||||
| 27133 | #endif /* SQLITE_ZERO_MALLOC */ | ||||
| 27134 | |||||
| 27135 | /************** End of mem0.c ************************************************/ | ||||
| 27136 | /************** Begin file mem1.c ********************************************/ | ||||
| 27137 | /* | ||||
| 27138 | ** 2007 August 14 | ||||
| 27139 | ** | ||||
| 27140 | ** The author disclaims copyright to this source code. In place of | ||||
| 27141 | ** a legal notice, here is a blessing: | ||||
| 27142 | ** | ||||
| 27143 | ** May you do good and not evil. | ||||
| 27144 | ** May you find forgiveness for yourself and forgive others. | ||||
| 27145 | ** May you share freely, never taking more than you give. | ||||
| 27146 | ** | ||||
| 27147 | ************************************************************************* | ||||
| 27148 | ** | ||||
| 27149 | ** This file contains low-level memory allocation drivers for when | ||||
| 27150 | ** SQLite will use the standard C-library malloc/realloc/free interface | ||||
| 27151 | ** to obtain the memory it needs. | ||||
| 27152 | ** | ||||
| 27153 | ** This file contains implementations of the low-level memory allocation | ||||
| 27154 | ** routines specified in the sqlite3_mem_methods object. The content of | ||||
| 27155 | ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The | ||||
| 27156 | ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the | ||||
| 27157 | ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The | ||||
| 27158 | ** default configuration is to use memory allocation routines in this | ||||
| 27159 | ** file. | ||||
| 27160 | ** | ||||
| 27161 | ** C-preprocessor macro summary: | ||||
| 27162 | ** | ||||
| 27163 | ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if | ||||
| 27164 | ** the malloc_usable_size() interface exists | ||||
| 27165 | ** on the target platform. Or, this symbol | ||||
| 27166 | ** can be set manually, if desired. | ||||
| 27167 | ** If an equivalent interface exists by | ||||
| 27168 | ** a different name, using a separate -D | ||||
| 27169 | ** option to rename it. | ||||
| 27170 | ** | ||||
| 27171 | ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone | ||||
| 27172 | ** memory allocator. Set this symbol to enable | ||||
| 27173 | ** building on older macs. | ||||
| 27174 | ** | ||||
| 27175 | ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of | ||||
| 27176 | ** _msize() on windows systems. This might | ||||
| 27177 | ** be necessary when compiling for Delphi, | ||||
| 27178 | ** for example. | ||||
| 27179 | */ | ||||
| 27180 | /* #include "sqliteInt.h" */ | ||||
| 27181 | |||||
| 27182 | /* | ||||
| 27183 | ** This version of the memory allocator is the default. It is | ||||
| 27184 | ** used when no other memory allocator is specified using compile-time | ||||
| 27185 | ** macros. | ||||
| 27186 | */ | ||||
| 27187 | #ifdef SQLITE_SYSTEM_MALLOC1 | ||||
| 27188 | #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) | ||||
| 27189 | |||||
| 27190 | /* | ||||
| 27191 | ** Use the zone allocator available on apple products unless the | ||||
| 27192 | ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined. | ||||
| 27193 | */ | ||||
| 27194 | #include <sys/sysctl.h> | ||||
| 27195 | #include <malloc/malloc.h> | ||||
| 27196 | #ifdef SQLITE_MIGHT_BE_SINGLE_CORE | ||||
| 27197 | #include <libkern/OSAtomic.h> | ||||
| 27198 | #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */ | ||||
| 27199 | static malloc_zone_t* _sqliteZone_; | ||||
| 27200 | #define SQLITE_MALLOC(x)malloc(x) malloc_zone_malloc(_sqliteZone_, (x)) | ||||
| 27201 | #define SQLITE_FREE(x)free(x) malloc_zone_free(_sqliteZone_, (x)); | ||||
| 27202 | #define SQLITE_REALLOC(x,y)realloc((x),(y)) malloc_zone_realloc(_sqliteZone_, (x), (y)) | ||||
| 27203 | #define SQLITE_MALLOCSIZE(x) \ | ||||
| 27204 | (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x)) | ||||
| 27205 | |||||
| 27206 | #else /* if not __APPLE__ */ | ||||
| 27207 | |||||
| 27208 | /* | ||||
| 27209 | ** Use standard C library malloc and free on non-Apple systems. | ||||
| 27210 | ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined. | ||||
| 27211 | */ | ||||
| 27212 | #define SQLITE_MALLOC(x)malloc(x) malloc(x) | ||||
| 27213 | #define SQLITE_FREE(x)free(x) free(x) | ||||
| 27214 | #define SQLITE_REALLOC(x,y)realloc((x),(y)) realloc((x),(y)) | ||||
| 27215 | |||||
| 27216 | /* | ||||
| 27217 | ** The malloc.h header file is needed for malloc_usable_size() function | ||||
| 27218 | ** on some systems (e.g. Linux). | ||||
| 27219 | */ | ||||
| 27220 | #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE | ||||
| 27221 | # define SQLITE_USE_MALLOC_H 1 | ||||
| 27222 | # define SQLITE_USE_MALLOC_USABLE_SIZE 1 | ||||
| 27223 | /* | ||||
| 27224 | ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The | ||||
| 27225 | ** use of _msize() is automatic, but can be disabled by compiling with | ||||
| 27226 | ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires | ||||
| 27227 | ** the malloc.h header file. | ||||
| 27228 | */ | ||||
| 27229 | #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE) | ||||
| 27230 | # define SQLITE_USE_MALLOC_H | ||||
| 27231 | # define SQLITE_USE_MSIZE | ||||
| 27232 | #endif | ||||
| 27233 | |||||
| 27234 | /* | ||||
| 27235 | ** Include the malloc.h header file, if necessary. Also set define macro | ||||
| 27236 | ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize() | ||||
| 27237 | ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux). | ||||
| 27238 | ** The memory size function can always be overridden manually by defining | ||||
| 27239 | ** the macro SQLITE_MALLOCSIZE to the desired function name. | ||||
| 27240 | */ | ||||
| 27241 | #if defined(SQLITE_USE_MALLOC_H) | ||||
| 27242 | # include <malloc.h> | ||||
| 27243 | # if defined(SQLITE_USE_MALLOC_USABLE_SIZE) | ||||
| 27244 | # if !defined(SQLITE_MALLOCSIZE) | ||||
| 27245 | # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) | ||||
| 27246 | # endif | ||||
| 27247 | # elif defined(SQLITE_USE_MSIZE) | ||||
| 27248 | # if !defined(SQLITE_MALLOCSIZE) | ||||
| 27249 | # define SQLITE_MALLOCSIZE _msize | ||||
| 27250 | # endif | ||||
| 27251 | # endif | ||||
| 27252 | #endif /* defined(SQLITE_USE_MALLOC_H) */ | ||||
| 27253 | |||||
| 27254 | #endif /* __APPLE__ or not __APPLE__ */ | ||||
| 27255 | |||||
| 27256 | /* | ||||
| 27257 | ** Like malloc(), but remember the size of the allocation | ||||
| 27258 | ** so that we can find it later using sqlite3MemSize(). | ||||
| 27259 | ** | ||||
| 27260 | ** For this low-level routine, we are guaranteed that nByte>0 because | ||||
| 27261 | ** cases of nByte<=0 will be intercepted and dealt with by higher level | ||||
| 27262 | ** routines. | ||||
| 27263 | */ | ||||
| 27264 | static void *sqlite3MemMalloc(int nByte){ | ||||
| 27265 | #ifdef SQLITE_MALLOCSIZE | ||||
| 27266 | void *p; | ||||
| 27267 | testcase( ROUND8(nByte)==nByte ); | ||||
| 27268 | p = SQLITE_MALLOC( nByte )malloc(nByte); | ||||
| 27269 | if( p==0 ){ | ||||
| 27270 | testcase( sqlite3GlobalConfig.xLog!=0 ); | ||||
| 27271 | sqlite3_log(SQLITE_NOMEM7, "failed to allocate %u bytes of memory", nByte); | ||||
| 27272 | } | ||||
| 27273 | return p; | ||||
| 27274 | #else | ||||
| 27275 | sqlite3_int64 *p; | ||||
| 27276 | assert( nByte>0 )((void) (0)); | ||||
| 27277 | testcase( ROUND8(nByte)!=nByte ); | ||||
| 27278 | p = SQLITE_MALLOC( nByte+8 )malloc(nByte+8); | ||||
| 27279 | if( p ){ | ||||
| 27280 | p[0] = nByte; | ||||
| 27281 | p++; | ||||
| 27282 | }else{ | ||||
| 27283 | testcase( sqlite3GlobalConfig.xLog!=0 ); | ||||
| 27284 | sqlite3_log(SQLITE_NOMEM7, "failed to allocate %u bytes of memory", nByte); | ||||
| 27285 | } | ||||
| 27286 | return (void *)p; | ||||
| 27287 | #endif | ||||
| 27288 | } | ||||
| 27289 | |||||
| 27290 | /* | ||||
| 27291 | ** Like free() but works for allocations obtained from sqlite3MemMalloc() | ||||
| 27292 | ** or sqlite3MemRealloc(). | ||||
| 27293 | ** | ||||
| 27294 | ** For this low-level routine, we already know that pPrior!=0 since | ||||
| 27295 | ** cases where pPrior==0 will have been intercepted and dealt with | ||||
| 27296 | ** by higher-level routines. | ||||
| 27297 | */ | ||||
| 27298 | static void sqlite3MemFree(void *pPrior){ | ||||
| 27299 | #ifdef SQLITE_MALLOCSIZE | ||||
| 27300 | SQLITE_FREE(pPrior)free(pPrior); | ||||
| 27301 | #else | ||||
| 27302 | sqlite3_int64 *p = (sqlite3_int64*)pPrior; | ||||
| 27303 | assert( pPrior!=0 )((void) (0)); | ||||
| 27304 | p--; | ||||
| 27305 | SQLITE_FREE(p)free(p); | ||||
| 27306 | #endif | ||||
| 27307 | } | ||||
| 27308 | |||||
| 27309 | /* | ||||
| 27310 | ** Report the allocated size of a prior return from xMalloc() | ||||
| 27311 | ** or xRealloc(). | ||||
| 27312 | */ | ||||
| 27313 | static int sqlite3MemSize(void *pPrior){ | ||||
| 27314 | #ifdef SQLITE_MALLOCSIZE | ||||
| 27315 | assert( pPrior!=0 )((void) (0)); | ||||
| 27316 | return (int)SQLITE_MALLOCSIZE(pPrior); | ||||
| 27317 | #else | ||||
| 27318 | sqlite3_int64 *p; | ||||
| 27319 | assert( pPrior!=0 )((void) (0)); | ||||
| 27320 | p = (sqlite3_int64*)pPrior; | ||||
| 27321 | p--; | ||||
| 27322 | return (int)p[0]; | ||||
| 27323 | #endif | ||||
| 27324 | } | ||||
| 27325 | |||||
| 27326 | /* | ||||
| 27327 | ** Like realloc(). Resize an allocation previously obtained from | ||||
| 27328 | ** sqlite3MemMalloc(). | ||||
| 27329 | ** | ||||
| 27330 | ** For this low-level interface, we know that pPrior!=0. Cases where | ||||
| 27331 | ** pPrior==0 while have been intercepted by higher-level routine and | ||||
| 27332 | ** redirected to xMalloc. Similarly, we know that nByte>0 because | ||||
| 27333 | ** cases where nByte<=0 will have been intercepted by higher-level | ||||
| 27334 | ** routines and redirected to xFree. | ||||
| 27335 | */ | ||||
| 27336 | static void *sqlite3MemRealloc(void *pPrior, int nByte){ | ||||
| 27337 | #ifdef SQLITE_MALLOCSIZE | ||||
| 27338 | void *p = SQLITE_REALLOC(pPrior, nByte)realloc((pPrior),(nByte)); | ||||
| 27339 | if( p==0 ){ | ||||
| 27340 | testcase( sqlite3GlobalConfig.xLog!=0 ); | ||||
| 27341 | sqlite3_log(SQLITE_NOMEM7, | ||||
| 27342 | "failed memory resize %u to %u bytes", | ||||
| 27343 | SQLITE_MALLOCSIZE(pPrior), nByte); | ||||
| 27344 | } | ||||
| 27345 | return p; | ||||
| 27346 | #else | ||||
| 27347 | sqlite3_int64 *p = (sqlite3_int64*)pPrior; | ||||
| 27348 | assert( pPrior!=0 && nByte>0 )((void) (0)); | ||||
| 27349 | assert( nByte==ROUND8(nByte) )((void) (0)); /* EV: R-46199-30249 */ | ||||
| 27350 | p--; | ||||
| 27351 | p = SQLITE_REALLOC(p, nByte+8 )realloc((p),(nByte+8)); | ||||
| 27352 | if( p ){ | ||||
| 27353 | p[0] = nByte; | ||||
| 27354 | p++; | ||||
| 27355 | }else{ | ||||
| 27356 | testcase( sqlite3GlobalConfig.xLog!=0 ); | ||||
| 27357 | sqlite3_log(SQLITE_NOMEM7, | ||||
| 27358 | "failed memory resize %u to %u bytes", | ||||
| 27359 | sqlite3MemSize(pPrior), nByte); | ||||
| 27360 | } | ||||
| 27361 | return (void*)p; | ||||
| 27362 | #endif | ||||
| 27363 | } | ||||
| 27364 | |||||
| 27365 | /* | ||||
| 27366 | ** Round up a request size to the next valid allocation size. | ||||
| 27367 | */ | ||||
| 27368 | static int sqlite3MemRoundup(int n){ | ||||
| 27369 | return ROUND8(n)(((n)+7)&~7); | ||||
| 27370 | } | ||||
| 27371 | |||||
| 27372 | /* | ||||
| 27373 | ** Initialize this module. | ||||
| 27374 | */ | ||||
| 27375 | static int sqlite3MemInit(void *NotUsed){ | ||||
| 27376 | #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) | ||||
| 27377 | int cpuCount; | ||||
| 27378 | size_t len; | ||||
| 27379 | if( _sqliteZone_ ){ | ||||
| 27380 | return SQLITE_OK0; | ||||
| 27381 | } | ||||
| 27382 | len = sizeof(cpuCount); | ||||
| 27383 | /* One usually wants to use hw.activecpu for MT decisions, but not here */ | ||||
| 27384 | sysctlbyname("hw.ncpu", &cpuCount, &len, NULL((void*)0), 0); | ||||
| 27385 | if( cpuCount>1 ){ | ||||
| 27386 | /* defer MT decisions to system malloc */ | ||||
| 27387 | _sqliteZone_ = malloc_default_zone(); | ||||
| 27388 | }else{ | ||||
| 27389 | /* only 1 core, use our own zone to contention over global locks, | ||||
| 27390 | ** e.g. we have our own dedicated locks */ | ||||
| 27391 | _sqliteZone_ = malloc_create_zone(4096, 0); | ||||
| 27392 | malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap"); | ||||
| 27393 | } | ||||
| 27394 | #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */ | ||||
| 27395 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 27396 | return SQLITE_OK0; | ||||
| 27397 | } | ||||
| 27398 | |||||
| 27399 | /* | ||||
| 27400 | ** Deinitialize this module. | ||||
| 27401 | */ | ||||
| 27402 | static void sqlite3MemShutdown(void *NotUsed){ | ||||
| 27403 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 27404 | return; | ||||
| 27405 | } | ||||
| 27406 | |||||
| 27407 | /* | ||||
| 27408 | ** This routine is the only routine in this file with external linkage. | ||||
| 27409 | ** | ||||
| 27410 | ** Populate the low-level memory allocation function pointers in | ||||
| 27411 | ** sqlite3GlobalConfig.m with pointers to the routines in this file. | ||||
| 27412 | */ | ||||
| 27413 | SQLITE_PRIVATEstatic void sqlite3MemSetDefault(void){ | ||||
| 27414 | static const sqlite3_mem_methods defaultMethods = { | ||||
| 27415 | sqlite3MemMalloc, | ||||
| 27416 | sqlite3MemFree, | ||||
| 27417 | sqlite3MemRealloc, | ||||
| 27418 | sqlite3MemSize, | ||||
| 27419 | sqlite3MemRoundup, | ||||
| 27420 | sqlite3MemInit, | ||||
| 27421 | sqlite3MemShutdown, | ||||
| 27422 | 0 | ||||
| 27423 | }; | ||||
| 27424 | sqlite3_config(SQLITE_CONFIG_MALLOC4, &defaultMethods); | ||||
| 27425 | } | ||||
| 27426 | |||||
| 27427 | #endif /* SQLITE_SYSTEM_MALLOC */ | ||||
| 27428 | |||||
| 27429 | /************** End of mem1.c ************************************************/ | ||||
| 27430 | /************** Begin file mem2.c ********************************************/ | ||||
| 27431 | /* | ||||
| 27432 | ** 2007 August 15 | ||||
| 27433 | ** | ||||
| 27434 | ** The author disclaims copyright to this source code. In place of | ||||
| 27435 | ** a legal notice, here is a blessing: | ||||
| 27436 | ** | ||||
| 27437 | ** May you do good and not evil. | ||||
| 27438 | ** May you find forgiveness for yourself and forgive others. | ||||
| 27439 | ** May you share freely, never taking more than you give. | ||||
| 27440 | ** | ||||
| 27441 | ************************************************************************* | ||||
| 27442 | ** | ||||
| 27443 | ** This file contains low-level memory allocation drivers for when | ||||
| 27444 | ** SQLite will use the standard C-library malloc/realloc/free interface | ||||
| 27445 | ** to obtain the memory it needs while adding lots of additional debugging | ||||
| 27446 | ** information to each allocation in order to help detect and fix memory | ||||
| 27447 | ** leaks and memory usage errors. | ||||
| 27448 | ** | ||||
| 27449 | ** This file contains implementations of the low-level memory allocation | ||||
| 27450 | ** routines specified in the sqlite3_mem_methods object. | ||||
| 27451 | */ | ||||
| 27452 | /* #include "sqliteInt.h" */ | ||||
| 27453 | |||||
| 27454 | /* | ||||
| 27455 | ** This version of the memory allocator is used only if the | ||||
| 27456 | ** SQLITE_MEMDEBUG macro is defined | ||||
| 27457 | */ | ||||
| 27458 | #ifdef SQLITE_MEMDEBUG | ||||
| 27459 | |||||
| 27460 | /* | ||||
| 27461 | ** The backtrace functionality is only available with GLIBC | ||||
| 27462 | */ | ||||
| 27463 | #ifdef __GLIBC__2 | ||||
| 27464 | extern int backtrace(void**,int); | ||||
| 27465 | extern void backtrace_symbols_fd(void*const*,int,int); | ||||
| 27466 | #else | ||||
| 27467 | # define backtrace(A,B) 1 | ||||
| 27468 | # define backtrace_symbols_fd(A,B,C) | ||||
| 27469 | #endif | ||||
| 27470 | /* #include <stdio.h> */ | ||||
| 27471 | |||||
| 27472 | /* | ||||
| 27473 | ** Each memory allocation looks like this: | ||||
| 27474 | ** | ||||
| 27475 | ** ------------------------------------------------------------------------ | ||||
| 27476 | ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard | | ||||
| 27477 | ** ------------------------------------------------------------------------ | ||||
| 27478 | ** | ||||
| 27479 | ** The application code sees only a pointer to the allocation. We have | ||||
| 27480 | ** to back up from the allocation pointer to find the MemBlockHdr. The | ||||
| 27481 | ** MemBlockHdr tells us the size of the allocation and the number of | ||||
| 27482 | ** backtrace pointers. There is also a guard word at the end of the | ||||
| 27483 | ** MemBlockHdr. | ||||
| 27484 | */ | ||||
| 27485 | struct MemBlockHdr { | ||||
| 27486 | i64 iSize; /* Size of this allocation */ | ||||
| 27487 | struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */ | ||||
| 27488 | char nBacktrace; /* Number of backtraces on this alloc */ | ||||
| 27489 | char nBacktraceSlots; /* Available backtrace slots */ | ||||
| 27490 | u8 nTitle; /* Bytes of title; includes '\0' */ | ||||
| 27491 | u8 eType; /* Allocation type code */ | ||||
| 27492 | int iForeGuard; /* Guard word for sanity */ | ||||
| 27493 | }; | ||||
| 27494 | |||||
| 27495 | /* | ||||
| 27496 | ** Guard words | ||||
| 27497 | */ | ||||
| 27498 | #define FOREGUARD 0x80F5E153 | ||||
| 27499 | #define REARGUARD 0xE4676B53 | ||||
| 27500 | |||||
| 27501 | /* | ||||
| 27502 | ** Number of malloc size increments to track. | ||||
| 27503 | */ | ||||
| 27504 | #define NCSIZE 1000 | ||||
| 27505 | |||||
| 27506 | /* | ||||
| 27507 | ** All of the static variables used by this module are collected | ||||
| 27508 | ** into a single structure named "mem". This is to keep the | ||||
| 27509 | ** static variables organized and to reduce namespace pollution | ||||
| 27510 | ** when this module is combined with other in the amalgamation. | ||||
| 27511 | */ | ||||
| 27512 | static struct { | ||||
| 27513 | |||||
| 27514 | /* | ||||
| 27515 | ** Mutex to control access to the memory allocation subsystem. | ||||
| 27516 | */ | ||||
| 27517 | sqlite3_mutex *mutex; | ||||
| 27518 | |||||
| 27519 | /* | ||||
| 27520 | ** Head and tail of a linked list of all outstanding allocations | ||||
| 27521 | */ | ||||
| 27522 | struct MemBlockHdr *pFirst; | ||||
| 27523 | struct MemBlockHdr *pLast; | ||||
| 27524 | |||||
| 27525 | /* | ||||
| 27526 | ** The number of levels of backtrace to save in new allocations. | ||||
| 27527 | */ | ||||
| 27528 | int nBacktrace; | ||||
| 27529 | void (*xBacktrace)(int, int, void **); | ||||
| 27530 | |||||
| 27531 | /* | ||||
| 27532 | ** Title text to insert in front of each block | ||||
| 27533 | */ | ||||
| 27534 | int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ | ||||
| 27535 | char zTitle[100]; /* The title text */ | ||||
| 27536 | |||||
| 27537 | /* | ||||
| 27538 | ** sqlite3MallocDisallow() increments the following counter. | ||||
| 27539 | ** sqlite3MallocAllow() decrements it. | ||||
| 27540 | */ | ||||
| 27541 | int disallow; /* Do not allow memory allocation */ | ||||
| 27542 | |||||
| 27543 | /* | ||||
| 27544 | ** Gather statistics on the sizes of memory allocations. | ||||
| 27545 | ** nAlloc[i] is the number of allocation attempts of i*8 | ||||
| 27546 | ** bytes. i==NCSIZE is the number of allocation attempts for | ||||
| 27547 | ** sizes more than NCSIZE*8 bytes. | ||||
| 27548 | */ | ||||
| 27549 | int nAlloc[NCSIZE]; /* Total number of allocations */ | ||||
| 27550 | int nCurrent[NCSIZE]; /* Current number of allocations */ | ||||
| 27551 | int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */ | ||||
| 27552 | |||||
| 27553 | } mem; | ||||
| 27554 | |||||
| 27555 | |||||
| 27556 | /* | ||||
| 27557 | ** Adjust memory usage statistics | ||||
| 27558 | */ | ||||
| 27559 | static void adjustStats(int iSize, int increment){ | ||||
| 27560 | int i = ROUND8(iSize)(((iSize)+7)&~7)/8; | ||||
| 27561 | if( i>NCSIZE-1 ){ | ||||
| 27562 | i = NCSIZE - 1; | ||||
| 27563 | } | ||||
| 27564 | if( increment>0 ){ | ||||
| 27565 | mem.nAlloc[i]++; | ||||
| 27566 | mem.nCurrent[i]++; | ||||
| 27567 | if( mem.nCurrent[i]>mem.mxCurrent[i] ){ | ||||
| 27568 | mem.mxCurrent[i] = mem.nCurrent[i]; | ||||
| 27569 | } | ||||
| 27570 | }else{ | ||||
| 27571 | mem.nCurrent[i]--; | ||||
| 27572 | assert( mem.nCurrent[i]>=0 )((void) (0)); | ||||
| 27573 | } | ||||
| 27574 | } | ||||
| 27575 | |||||
| 27576 | /* | ||||
| 27577 | ** Given an allocation, find the MemBlockHdr for that allocation. | ||||
| 27578 | ** | ||||
| 27579 | ** This routine checks the guards at either end of the allocation and | ||||
| 27580 | ** if they are incorrect it asserts. | ||||
| 27581 | */ | ||||
| 27582 | static struct MemBlockHdr *sqlite3MemsysGetHeader(const void *pAllocation){ | ||||
| 27583 | struct MemBlockHdr *p; | ||||
| 27584 | int *pInt; | ||||
| 27585 | u8 *pU8; | ||||
| 27586 | int nReserve; | ||||
| 27587 | |||||
| 27588 | p = (struct MemBlockHdr*)pAllocation; | ||||
| 27589 | p--; | ||||
| 27590 | assert( p->iForeGuard==(int)FOREGUARD )((void) (0)); | ||||
| 27591 | nReserve = ROUND8(p->iSize)(((p->iSize)+7)&~7); | ||||
| 27592 | pInt = (int*)pAllocation; | ||||
| 27593 | pU8 = (u8*)pAllocation; | ||||
| 27594 | assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD )((void) (0)); | ||||
| 27595 | /* This checks any of the "extra" bytes allocated due | ||||
| 27596 | ** to rounding up to an 8 byte boundary to ensure | ||||
| 27597 | ** they haven't been overwritten. | ||||
| 27598 | */ | ||||
| 27599 | while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 )((void) (0)); | ||||
| 27600 | return p; | ||||
| 27601 | } | ||||
| 27602 | |||||
| 27603 | /* | ||||
| 27604 | ** Return the number of bytes currently allocated at address p. | ||||
| 27605 | */ | ||||
| 27606 | static int sqlite3MemSize(void *p){ | ||||
| 27607 | struct MemBlockHdr *pHdr; | ||||
| 27608 | if( !p ){ | ||||
| 27609 | return 0; | ||||
| 27610 | } | ||||
| 27611 | pHdr = sqlite3MemsysGetHeader(p); | ||||
| 27612 | return (int)pHdr->iSize; | ||||
| 27613 | } | ||||
| 27614 | |||||
| 27615 | /* | ||||
| 27616 | ** Initialize the memory allocation subsystem. | ||||
| 27617 | */ | ||||
| 27618 | static int sqlite3MemInit(void *NotUsed){ | ||||
| 27619 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 27620 | assert( (sizeof(struct MemBlockHdr)&7) == 0 )((void) (0)); | ||||
| 27621 | if( !sqlite3GlobalConfigsqlite3Config.bMemstat ){ | ||||
| 27622 | /* If memory status is enabled, then the malloc.c wrapper will already | ||||
| 27623 | ** hold the STATIC_MEM mutex when the routines here are invoked. */ | ||||
| 27624 | mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM3); | ||||
| 27625 | } | ||||
| 27626 | return SQLITE_OK0; | ||||
| 27627 | } | ||||
| 27628 | |||||
| 27629 | /* | ||||
| 27630 | ** Deinitialize the memory allocation subsystem. | ||||
| 27631 | */ | ||||
| 27632 | static void sqlite3MemShutdown(void *NotUsed){ | ||||
| 27633 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 27634 | mem.mutex = 0; | ||||
| 27635 | } | ||||
| 27636 | |||||
| 27637 | /* | ||||
| 27638 | ** Round up a request size to the next valid allocation size. | ||||
| 27639 | */ | ||||
| 27640 | static int sqlite3MemRoundup(int n){ | ||||
| 27641 | return ROUND8(n)(((n)+7)&~7); | ||||
| 27642 | } | ||||
| 27643 | |||||
| 27644 | /* | ||||
| 27645 | ** Fill a buffer with pseudo-random bytes. This is used to preset | ||||
| 27646 | ** the content of a new memory allocation to unpredictable values and | ||||
| 27647 | ** to clear the content of a freed allocation to unpredictable values. | ||||
| 27648 | */ | ||||
| 27649 | static void randomFill(char *pBuf, int nByte){ | ||||
| 27650 | unsigned int x, y, r; | ||||
| 27651 | x = SQLITE_PTR_TO_INT(pBuf)((int)(long int)(pBuf)); | ||||
| 27652 | y = nByte | 1; | ||||
| 27653 | while( nByte >= 4 ){ | ||||
| 27654 | x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); | ||||
| 27655 | y = y*1103515245 + 12345; | ||||
| 27656 | r = x ^ y; | ||||
| 27657 | *(int*)pBuf = r; | ||||
| 27658 | pBuf += 4; | ||||
| 27659 | nByte -= 4; | ||||
| 27660 | } | ||||
| 27661 | while( nByte-- > 0 ){ | ||||
| 27662 | x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); | ||||
| 27663 | y = y*1103515245 + 12345; | ||||
| 27664 | r = x ^ y; | ||||
| 27665 | *(pBuf++) = r & 0xff; | ||||
| 27666 | } | ||||
| 27667 | } | ||||
| 27668 | |||||
| 27669 | /* | ||||
| 27670 | ** Allocate nByte bytes of memory. | ||||
| 27671 | */ | ||||
| 27672 | static void *sqlite3MemMalloc(int nByte){ | ||||
| 27673 | struct MemBlockHdr *pHdr; | ||||
| 27674 | void **pBt; | ||||
| 27675 | char *z; | ||||
| 27676 | int *pInt; | ||||
| 27677 | void *p = 0; | ||||
| 27678 | int totalSize; | ||||
| 27679 | int nReserve; | ||||
| 27680 | sqlite3_mutex_enter(mem.mutex); | ||||
| 27681 | assert( mem.disallow==0 )((void) (0)); | ||||
| 27682 | nReserve = ROUND8(nByte)(((nByte)+7)&~7); | ||||
| 27683 | totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + | ||||
| 27684 | mem.nBacktrace*sizeof(void*) + mem.nTitle; | ||||
| 27685 | p = malloc(totalSize); | ||||
| 27686 | if( p ){ | ||||
| 27687 | z = p; | ||||
| 27688 | pBt = (void**)&z[mem.nTitle]; | ||||
| 27689 | pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; | ||||
| 27690 | pHdr->pNext = 0; | ||||
| 27691 | pHdr->pPrev = mem.pLast; | ||||
| 27692 | if( mem.pLast ){ | ||||
| 27693 | mem.pLast->pNext = pHdr; | ||||
| 27694 | }else{ | ||||
| 27695 | mem.pFirst = pHdr; | ||||
| 27696 | } | ||||
| 27697 | mem.pLast = pHdr; | ||||
| 27698 | pHdr->iForeGuard = FOREGUARD; | ||||
| 27699 | pHdr->eType = MEMTYPE_HEAP0x01; | ||||
| 27700 | pHdr->nBacktraceSlots = mem.nBacktrace; | ||||
| 27701 | pHdr->nTitle = mem.nTitle; | ||||
| 27702 | if( mem.nBacktrace ){ | ||||
| 27703 | void *aAddr[40]; | ||||
| 27704 | pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; | ||||
| 27705 | memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); | ||||
| 27706 | assert(pBt[0])((void) (0)); | ||||
| 27707 | if( mem.xBacktrace ){ | ||||
| 27708 | mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); | ||||
| 27709 | } | ||||
| 27710 | }else{ | ||||
| 27711 | pHdr->nBacktrace = 0; | ||||
| 27712 | } | ||||
| 27713 | if( mem.nTitle ){ | ||||
| 27714 | memcpy(z, mem.zTitle, mem.nTitle); | ||||
| 27715 | } | ||||
| 27716 | pHdr->iSize = nByte; | ||||
| 27717 | adjustStats(nByte, +1); | ||||
| 27718 | pInt = (int*)&pHdr[1]; | ||||
| 27719 | pInt[nReserve/sizeof(int)] = REARGUARD; | ||||
| 27720 | randomFill((char*)pInt, nByte); | ||||
| 27721 | memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); | ||||
| 27722 | p = (void*)pInt; | ||||
| 27723 | } | ||||
| 27724 | sqlite3_mutex_leave(mem.mutex); | ||||
| 27725 | return p; | ||||
| 27726 | } | ||||
| 27727 | |||||
| 27728 | /* | ||||
| 27729 | ** Free memory. | ||||
| 27730 | */ | ||||
| 27731 | static void sqlite3MemFree(void *pPrior){ | ||||
| 27732 | struct MemBlockHdr *pHdr; | ||||
| 27733 | void **pBt; | ||||
| 27734 | char *z; | ||||
| 27735 | assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0((void) (0)) | ||||
| 27736 | || mem.mutex!=0 )((void) (0)); | ||||
| 27737 | pHdr = sqlite3MemsysGetHeader(pPrior); | ||||
| 27738 | pBt = (void**)pHdr; | ||||
| 27739 | pBt -= pHdr->nBacktraceSlots; | ||||
| 27740 | sqlite3_mutex_enter(mem.mutex); | ||||
| 27741 | if( pHdr->pPrev ){ | ||||
| 27742 | assert( pHdr->pPrev->pNext==pHdr )((void) (0)); | ||||
| 27743 | pHdr->pPrev->pNext = pHdr->pNext; | ||||
| 27744 | }else{ | ||||
| 27745 | assert( mem.pFirst==pHdr )((void) (0)); | ||||
| 27746 | mem.pFirst = pHdr->pNext; | ||||
| 27747 | } | ||||
| 27748 | if( pHdr->pNext ){ | ||||
| 27749 | assert( pHdr->pNext->pPrev==pHdr )((void) (0)); | ||||
| 27750 | pHdr->pNext->pPrev = pHdr->pPrev; | ||||
| 27751 | }else{ | ||||
| 27752 | assert( mem.pLast==pHdr )((void) (0)); | ||||
| 27753 | mem.pLast = pHdr->pPrev; | ||||
| 27754 | } | ||||
| 27755 | z = (char*)pBt; | ||||
| 27756 | z -= pHdr->nTitle; | ||||
| 27757 | adjustStats((int)pHdr->iSize, -1); | ||||
| 27758 | randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + | ||||
| 27759 | (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); | ||||
| 27760 | free(z); | ||||
| 27761 | sqlite3_mutex_leave(mem.mutex); | ||||
| 27762 | } | ||||
| 27763 | |||||
| 27764 | /* | ||||
| 27765 | ** Change the size of an existing memory allocation. | ||||
| 27766 | ** | ||||
| 27767 | ** For this debugging implementation, we *always* make a copy of the | ||||
| 27768 | ** allocation into a new place in memory. In this way, if the | ||||
| 27769 | ** higher level code is using pointer to the old allocation, it is | ||||
| 27770 | ** much more likely to break and we are much more liking to find | ||||
| 27771 | ** the error. | ||||
| 27772 | */ | ||||
| 27773 | static void *sqlite3MemRealloc(void *pPrior, int nByte){ | ||||
| 27774 | struct MemBlockHdr *pOldHdr; | ||||
| 27775 | void *pNew; | ||||
| 27776 | assert( mem.disallow==0 )((void) (0)); | ||||
| 27777 | assert( (nByte & 7)==0 )((void) (0)); /* EV: R-46199-30249 */ | ||||
| 27778 | pOldHdr = sqlite3MemsysGetHeader(pPrior); | ||||
| 27779 | pNew = sqlite3MemMalloc(nByte); | ||||
| 27780 | if( pNew ){ | ||||
| 27781 | memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize)); | ||||
| 27782 | if( nByte>pOldHdr->iSize ){ | ||||
| 27783 | randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); | ||||
| 27784 | } | ||||
| 27785 | sqlite3MemFree(pPrior); | ||||
| 27786 | } | ||||
| 27787 | return pNew; | ||||
| 27788 | } | ||||
| 27789 | |||||
| 27790 | /* | ||||
| 27791 | ** Populate the low-level memory allocation function pointers in | ||||
| 27792 | ** sqlite3GlobalConfig.m with pointers to the routines in this file. | ||||
| 27793 | */ | ||||
| 27794 | SQLITE_PRIVATEstatic void sqlite3MemSetDefault(void){ | ||||
| 27795 | static const sqlite3_mem_methods defaultMethods = { | ||||
| 27796 | sqlite3MemMalloc, | ||||
| 27797 | sqlite3MemFree, | ||||
| 27798 | sqlite3MemRealloc, | ||||
| 27799 | sqlite3MemSize, | ||||
| 27800 | sqlite3MemRoundup, | ||||
| 27801 | sqlite3MemInit, | ||||
| 27802 | sqlite3MemShutdown, | ||||
| 27803 | 0 | ||||
| 27804 | }; | ||||
| 27805 | sqlite3_config(SQLITE_CONFIG_MALLOC4, &defaultMethods); | ||||
| 27806 | } | ||||
| 27807 | |||||
| 27808 | /* | ||||
| 27809 | ** Set the "type" of an allocation. | ||||
| 27810 | */ | ||||
| 27811 | SQLITE_PRIVATEstatic void sqlite3MemdebugSetType(void *p, u8 eType){ | ||||
| 27812 | if( p && sqlite3GlobalConfigsqlite3Config.m.xFree==sqlite3MemFree ){ | ||||
| 27813 | struct MemBlockHdr *pHdr; | ||||
| 27814 | pHdr = sqlite3MemsysGetHeader(p); | ||||
| 27815 | assert( pHdr->iForeGuard==FOREGUARD )((void) (0)); | ||||
| 27816 | pHdr->eType = eType; | ||||
| 27817 | } | ||||
| 27818 | } | ||||
| 27819 | |||||
| 27820 | /* | ||||
| 27821 | ** Return TRUE if the mask of type in eType matches the type of the | ||||
| 27822 | ** allocation p. Also return true if p==NULL. | ||||
| 27823 | ** | ||||
| 27824 | ** This routine is designed for use within an assert() statement, to | ||||
| 27825 | ** verify the type of an allocation. For example: | ||||
| 27826 | ** | ||||
| 27827 | ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); | ||||
| 27828 | */ | ||||
| 27829 | SQLITE_PRIVATEstatic int sqlite3MemdebugHasType(const void *p, u8 eType)1{ | ||||
| 27830 | int rc = 1; | ||||
| 27831 | if( p && sqlite3GlobalConfigsqlite3Config.m.xFree==sqlite3MemFree ){ | ||||
| 27832 | struct MemBlockHdr *pHdr; | ||||
| 27833 | pHdr = sqlite3MemsysGetHeader(p); | ||||
| 27834 | assert( pHdr->iForeGuard==FOREGUARD )((void) (0)); /* Allocation is valid */ | ||||
| 27835 | if( (pHdr->eType&eType)==0 ){ | ||||
| 27836 | rc = 0; | ||||
| 27837 | } | ||||
| 27838 | } | ||||
| 27839 | return rc; | ||||
| 27840 | } | ||||
| 27841 | |||||
| 27842 | /* | ||||
| 27843 | ** Return TRUE if the mask of type in eType matches no bits of the type of the | ||||
| 27844 | ** allocation p. Also return true if p==NULL. | ||||
| 27845 | ** | ||||
| 27846 | ** This routine is designed for use within an assert() statement, to | ||||
| 27847 | ** verify the type of an allocation. For example: | ||||
| 27848 | ** | ||||
| 27849 | ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); | ||||
| 27850 | */ | ||||
| 27851 | SQLITE_PRIVATEstatic int sqlite3MemdebugNoType(const void *p, u8 eType)1{ | ||||
| 27852 | int rc = 1; | ||||
| 27853 | if( p && sqlite3GlobalConfigsqlite3Config.m.xFree==sqlite3MemFree ){ | ||||
| 27854 | struct MemBlockHdr *pHdr; | ||||
| 27855 | pHdr = sqlite3MemsysGetHeader(p); | ||||
| 27856 | assert( pHdr->iForeGuard==FOREGUARD )((void) (0)); /* Allocation is valid */ | ||||
| 27857 | if( (pHdr->eType&eType)!=0 ){ | ||||
| 27858 | rc = 0; | ||||
| 27859 | } | ||||
| 27860 | } | ||||
| 27861 | return rc; | ||||
| 27862 | } | ||||
| 27863 | |||||
| 27864 | /* | ||||
| 27865 | ** Set the number of backtrace levels kept for each allocation. | ||||
| 27866 | ** A value of zero turns off backtracing. The number is always rounded | ||||
| 27867 | ** up to a multiple of 2. | ||||
| 27868 | */ | ||||
| 27869 | SQLITE_PRIVATEstatic void sqlite3MemdebugBacktrace(int depth){ | ||||
| 27870 | if( depth<0 ){ depth = 0; } | ||||
| 27871 | if( depth>20 ){ depth = 20; } | ||||
| 27872 | depth = (depth+1)&0xfe; | ||||
| 27873 | mem.nBacktrace = depth; | ||||
| 27874 | } | ||||
| 27875 | |||||
| 27876 | SQLITE_PRIVATEstatic void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ | ||||
| 27877 | mem.xBacktrace = xBacktrace; | ||||
| 27878 | } | ||||
| 27879 | |||||
| 27880 | /* | ||||
| 27881 | ** Set the title string for subsequent allocations. | ||||
| 27882 | */ | ||||
| 27883 | SQLITE_PRIVATEstatic void sqlite3MemdebugSettitle(const char *zTitle){ | ||||
| 27884 | unsigned int n = sqlite3Strlen30(zTitle) + 1; | ||||
| 27885 | sqlite3_mutex_enter(mem.mutex); | ||||
| 27886 | if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; | ||||
| 27887 | memcpy(mem.zTitle, zTitle, n); | ||||
| 27888 | mem.zTitle[n] = 0; | ||||
| 27889 | mem.nTitle = ROUND8(n)(((n)+7)&~7); | ||||
| 27890 | sqlite3_mutex_leave(mem.mutex); | ||||
| 27891 | } | ||||
| 27892 | |||||
| 27893 | SQLITE_PRIVATEstatic void sqlite3MemdebugSync(){ | ||||
| 27894 | struct MemBlockHdr *pHdr; | ||||
| 27895 | for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ | ||||
| 27896 | void **pBt = (void**)pHdr; | ||||
| 27897 | pBt -= pHdr->nBacktraceSlots; | ||||
| 27898 | mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); | ||||
| 27899 | } | ||||
| 27900 | } | ||||
| 27901 | |||||
| 27902 | /* | ||||
| 27903 | ** Open the file indicated and write a log of all unfreed memory | ||||
| 27904 | ** allocations into that log. | ||||
| 27905 | */ | ||||
| 27906 | SQLITE_PRIVATEstatic void sqlite3MemdebugDump(const char *zFilename){ | ||||
| 27907 | FILE *out; | ||||
| 27908 | struct MemBlockHdr *pHdr; | ||||
| 27909 | void **pBt; | ||||
| 27910 | int i; | ||||
| 27911 | out = fopen(zFilename, "w"); | ||||
| 27912 | if( out==0 ){ | ||||
| 27913 | fprintf(stderrstderr, "** Unable to output memory debug output log: %s **\n", | ||||
| 27914 | zFilename); | ||||
| 27915 | return; | ||||
| 27916 | } | ||||
| 27917 | for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ | ||||
| 27918 | char *z = (char*)pHdr; | ||||
| 27919 | z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; | ||||
| 27920 | fprintf(out, "**** %lld bytes at %p from %s ****\n", | ||||
| 27921 | pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); | ||||
| 27922 | if( pHdr->nBacktrace ){ | ||||
| 27923 | fflush(out); | ||||
| 27924 | pBt = (void**)pHdr; | ||||
| 27925 | pBt -= pHdr->nBacktraceSlots; | ||||
| 27926 | backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); | ||||
| 27927 | fprintf(out, "\n"); | ||||
| 27928 | } | ||||
| 27929 | } | ||||
| 27930 | fprintf(out, "COUNTS:\n"); | ||||
| 27931 | for(i=0; i<NCSIZE-1; i++){ | ||||
| 27932 | if( mem.nAlloc[i] ){ | ||||
| 27933 | fprintf(out, " %5d: %10d %10d %10d\n", | ||||
| 27934 | i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]); | ||||
| 27935 | } | ||||
| 27936 | } | ||||
| 27937 | if( mem.nAlloc[NCSIZE-1] ){ | ||||
| 27938 | fprintf(out, " %5d: %10d %10d %10d\n", | ||||
| 27939 | NCSIZE*8-8, mem.nAlloc[NCSIZE-1], | ||||
| 27940 | mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]); | ||||
| 27941 | } | ||||
| 27942 | fclose(out); | ||||
| 27943 | } | ||||
| 27944 | |||||
| 27945 | /* | ||||
| 27946 | ** Return the number of times sqlite3MemMalloc() has been called. | ||||
| 27947 | */ | ||||
| 27948 | SQLITE_PRIVATEstatic int sqlite3MemdebugMallocCount(){ | ||||
| 27949 | int i; | ||||
| 27950 | int nTotal = 0; | ||||
| 27951 | for(i=0; i<NCSIZE; i++){ | ||||
| 27952 | nTotal += mem.nAlloc[i]; | ||||
| 27953 | } | ||||
| 27954 | return nTotal; | ||||
| 27955 | } | ||||
| 27956 | |||||
| 27957 | |||||
| 27958 | #endif /* SQLITE_MEMDEBUG */ | ||||
| 27959 | |||||
| 27960 | /************** End of mem2.c ************************************************/ | ||||
| 27961 | /************** Begin file mem3.c ********************************************/ | ||||
| 27962 | /* | ||||
| 27963 | ** 2007 October 14 | ||||
| 27964 | ** | ||||
| 27965 | ** The author disclaims copyright to this source code. In place of | ||||
| 27966 | ** a legal notice, here is a blessing: | ||||
| 27967 | ** | ||||
| 27968 | ** May you do good and not evil. | ||||
| 27969 | ** May you find forgiveness for yourself and forgive others. | ||||
| 27970 | ** May you share freely, never taking more than you give. | ||||
| 27971 | ** | ||||
| 27972 | ************************************************************************* | ||||
| 27973 | ** This file contains the C functions that implement a memory | ||||
| 27974 | ** allocation subsystem for use by SQLite. | ||||
| 27975 | ** | ||||
| 27976 | ** This version of the memory allocation subsystem omits all | ||||
| 27977 | ** use of malloc(). The SQLite user supplies a block of memory | ||||
| 27978 | ** before calling sqlite3_initialize() from which allocations | ||||
| 27979 | ** are made and returned by the xMalloc() and xRealloc() | ||||
| 27980 | ** implementations. Once sqlite3_initialize() has been called, | ||||
| 27981 | ** the amount of memory available to SQLite is fixed and cannot | ||||
| 27982 | ** be changed. | ||||
| 27983 | ** | ||||
| 27984 | ** This version of the memory allocation subsystem is included | ||||
| 27985 | ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined. | ||||
| 27986 | */ | ||||
| 27987 | /* #include "sqliteInt.h" */ | ||||
| 27988 | |||||
| 27989 | /* | ||||
| 27990 | ** This version of the memory allocator is only built into the library | ||||
| 27991 | ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not | ||||
| 27992 | ** mean that the library will use a memory-pool by default, just that | ||||
| 27993 | ** it is available. The mempool allocator is activated by calling | ||||
| 27994 | ** sqlite3_config(). | ||||
| 27995 | */ | ||||
| 27996 | #ifdef SQLITE_ENABLE_MEMSYS3 | ||||
| 27997 | |||||
| 27998 | /* | ||||
| 27999 | ** Maximum size (in Mem3Blocks) of a "small" chunk. | ||||
| 28000 | */ | ||||
| 28001 | #define MX_SMALL 10 | ||||
| 28002 | |||||
| 28003 | |||||
| 28004 | /* | ||||
| 28005 | ** Number of freelist hash slots | ||||
| 28006 | */ | ||||
| 28007 | #define N_HASH 61 | ||||
| 28008 | |||||
| 28009 | /* | ||||
| 28010 | ** A memory allocation (also called a "chunk") consists of two or | ||||
| 28011 | ** more blocks where each block is 8 bytes. The first 8 bytes are | ||||
| 28012 | ** a header that is not returned to the user. | ||||
| 28013 | ** | ||||
| 28014 | ** A chunk is two or more blocks that is either checked out or | ||||
| 28015 | ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the | ||||
| 28016 | ** size of the allocation in blocks if the allocation is free. | ||||
| 28017 | ** The u.hdr.size4x&1 bit is true if the chunk is checked out and | ||||
| 28018 | ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit | ||||
| 28019 | ** is true if the previous chunk is checked out and false if the | ||||
| 28020 | ** previous chunk is free. The u.hdr.prevSize field is the size of | ||||
| 28021 | ** the previous chunk in blocks if the previous chunk is on the | ||||
| 28022 | ** freelist. If the previous chunk is checked out, then | ||||
| 28023 | ** u.hdr.prevSize can be part of the data for that chunk and should | ||||
| 28024 | ** not be read or written. | ||||
| 28025 | ** | ||||
| 28026 | ** We often identify a chunk by its index in mem3.aPool[]. When | ||||
| 28027 | ** this is done, the chunk index refers to the second block of | ||||
| 28028 | ** the chunk. In this way, the first chunk has an index of 1. | ||||
| 28029 | ** A chunk index of 0 means "no such chunk" and is the equivalent | ||||
| 28030 | ** of a NULL pointer. | ||||
| 28031 | ** | ||||
| 28032 | ** The second block of free chunks is of the form u.list. The | ||||
| 28033 | ** two fields form a double-linked list of chunks of related sizes. | ||||
| 28034 | ** Pointers to the head of the list are stored in mem3.aiSmall[] | ||||
| 28035 | ** for smaller chunks and mem3.aiHash[] for larger chunks. | ||||
| 28036 | ** | ||||
| 28037 | ** The second block of a chunk is user data if the chunk is checked | ||||
| 28038 | ** out. If a chunk is checked out, the user data may extend into | ||||
| 28039 | ** the u.hdr.prevSize value of the following chunk. | ||||
| 28040 | */ | ||||
| 28041 | typedef struct Mem3Block Mem3Block; | ||||
| 28042 | struct Mem3Block { | ||||
| 28043 | union { | ||||
| 28044 | struct { | ||||
| 28045 | u32 prevSize; /* Size of previous chunk in Mem3Block elements */ | ||||
| 28046 | u32 size4x; /* 4x the size of current chunk in Mem3Block elements */ | ||||
| 28047 | } hdr; | ||||
| 28048 | struct { | ||||
| 28049 | u32 next; /* Index in mem3.aPool[] of next free chunk */ | ||||
| 28050 | u32 prev; /* Index in mem3.aPool[] of previous free chunk */ | ||||
| 28051 | } list; | ||||
| 28052 | } u; | ||||
| 28053 | }; | ||||
| 28054 | |||||
| 28055 | /* | ||||
| 28056 | ** All of the static variables used by this module are collected | ||||
| 28057 | ** into a single structure named "mem3". This is to keep the | ||||
| 28058 | ** static variables organized and to reduce namespace pollution | ||||
| 28059 | ** when this module is combined with other in the amalgamation. | ||||
| 28060 | */ | ||||
| 28061 | static SQLITE_WSD struct Mem3Global { | ||||
| 28062 | /* | ||||
| 28063 | ** Memory available for allocation. nPool is the size of the array | ||||
| 28064 | ** (in Mem3Blocks) pointed to by aPool less 2. | ||||
| 28065 | */ | ||||
| 28066 | u32 nPool; | ||||
| 28067 | Mem3Block *aPool; | ||||
| 28068 | |||||
| 28069 | /* | ||||
| 28070 | ** True if we are evaluating an out-of-memory callback. | ||||
| 28071 | */ | ||||
| 28072 | int alarmBusy; | ||||
| 28073 | |||||
| 28074 | /* | ||||
| 28075 | ** Mutex to control access to the memory allocation subsystem. | ||||
| 28076 | */ | ||||
| 28077 | sqlite3_mutex *mutex; | ||||
| 28078 | |||||
| 28079 | /* | ||||
| 28080 | ** The minimum amount of free space that we have seen. | ||||
| 28081 | */ | ||||
| 28082 | u32 mnKeyBlk; | ||||
| 28083 | |||||
| 28084 | /* | ||||
| 28085 | ** iKeyBlk is the index of the key chunk. Most new allocations | ||||
| 28086 | ** occur off of this chunk. szKeyBlk is the size (in Mem3Blocks) | ||||
| 28087 | ** of the current key chunk. iKeyBlk is 0 if there is no key chunk. | ||||
| 28088 | ** The key chunk is not in either the aiHash[] or aiSmall[]. | ||||
| 28089 | */ | ||||
| 28090 | u32 iKeyBlk; | ||||
| 28091 | u32 szKeyBlk; | ||||
| 28092 | |||||
| 28093 | /* | ||||
| 28094 | ** Array of lists of free blocks according to the block size | ||||
| 28095 | ** for smaller chunks, or a hash on the block size for larger | ||||
| 28096 | ** chunks. | ||||
| 28097 | */ | ||||
| 28098 | u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */ | ||||
| 28099 | u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */ | ||||
| 28100 | } mem3 = { 97535575 }; | ||||
| 28101 | |||||
| 28102 | #define mem3 GLOBAL(struct Mem3Global, mem3)mem3 | ||||
| 28103 | |||||
| 28104 | /* | ||||
| 28105 | ** Unlink the chunk at mem3.aPool[i] from list it is currently | ||||
| 28106 | ** on. *pRoot is the list that i is a member of. | ||||
| 28107 | */ | ||||
| 28108 | static void memsys3UnlinkFromList(u32 i, u32 *pRoot){ | ||||
| 28109 | u32 next = mem3.aPool[i].u.list.next; | ||||
| 28110 | u32 prev = mem3.aPool[i].u.list.prev; | ||||
| 28111 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28112 | if( prev==0 ){ | ||||
| 28113 | *pRoot = next; | ||||
| 28114 | }else{ | ||||
| 28115 | mem3.aPool[prev].u.list.next = next; | ||||
| 28116 | } | ||||
| 28117 | if( next ){ | ||||
| 28118 | mem3.aPool[next].u.list.prev = prev; | ||||
| 28119 | } | ||||
| 28120 | mem3.aPool[i].u.list.next = 0; | ||||
| 28121 | mem3.aPool[i].u.list.prev = 0; | ||||
| 28122 | } | ||||
| 28123 | |||||
| 28124 | /* | ||||
| 28125 | ** Unlink the chunk at index i from | ||||
| 28126 | ** whatever list is currently a member of. | ||||
| 28127 | */ | ||||
| 28128 | static void memsys3Unlink(u32 i){ | ||||
| 28129 | u32 size, hash; | ||||
| 28130 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28131 | assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 )((void) (0)); | ||||
| 28132 | assert( i>=1 )((void) (0)); | ||||
| 28133 | size = mem3.aPool[i-1].u.hdr.size4x/4; | ||||
| 28134 | assert( size==mem3.aPool[i+size-1].u.hdr.prevSize )((void) (0)); | ||||
| 28135 | assert( size>=2 )((void) (0)); | ||||
| 28136 | if( size <= MX_SMALL ){ | ||||
| 28137 | memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]); | ||||
| 28138 | }else{ | ||||
| 28139 | hash = size % N_HASH; | ||||
| 28140 | memsys3UnlinkFromList(i, &mem3.aiHash[hash]); | ||||
| 28141 | } | ||||
| 28142 | } | ||||
| 28143 | |||||
| 28144 | /* | ||||
| 28145 | ** Link the chunk at mem3.aPool[i] so that is on the list rooted | ||||
| 28146 | ** at *pRoot. | ||||
| 28147 | */ | ||||
| 28148 | static void memsys3LinkIntoList(u32 i, u32 *pRoot){ | ||||
| 28149 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28150 | mem3.aPool[i].u.list.next = *pRoot; | ||||
| 28151 | mem3.aPool[i].u.list.prev = 0; | ||||
| 28152 | if( *pRoot ){ | ||||
| 28153 | mem3.aPool[*pRoot].u.list.prev = i; | ||||
| 28154 | } | ||||
| 28155 | *pRoot = i; | ||||
| 28156 | } | ||||
| 28157 | |||||
| 28158 | /* | ||||
| 28159 | ** Link the chunk at index i into either the appropriate | ||||
| 28160 | ** small chunk list, or into the large chunk hash table. | ||||
| 28161 | */ | ||||
| 28162 | static void memsys3Link(u32 i){ | ||||
| 28163 | u32 size, hash; | ||||
| 28164 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28165 | assert( i>=1 )((void) (0)); | ||||
| 28166 | assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 )((void) (0)); | ||||
| 28167 | size = mem3.aPool[i-1].u.hdr.size4x/4; | ||||
| 28168 | assert( size==mem3.aPool[i+size-1].u.hdr.prevSize )((void) (0)); | ||||
| 28169 | assert( size>=2 )((void) (0)); | ||||
| 28170 | if( size <= MX_SMALL ){ | ||||
| 28171 | memsys3LinkIntoList(i, &mem3.aiSmall[size-2]); | ||||
| 28172 | }else{ | ||||
| 28173 | hash = size % N_HASH; | ||||
| 28174 | memsys3LinkIntoList(i, &mem3.aiHash[hash]); | ||||
| 28175 | } | ||||
| 28176 | } | ||||
| 28177 | |||||
| 28178 | /* | ||||
| 28179 | ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex | ||||
| 28180 | ** will already be held (obtained by code in malloc.c) if | ||||
| 28181 | ** sqlite3GlobalConfig.bMemStat is true. | ||||
| 28182 | */ | ||||
| 28183 | static void memsys3Enter(void){ | ||||
| 28184 | if( sqlite3GlobalConfigsqlite3Config.bMemstat==0 && mem3.mutex==0 ){ | ||||
| 28185 | mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM3); | ||||
| 28186 | } | ||||
| 28187 | sqlite3_mutex_enter(mem3.mutex); | ||||
| 28188 | } | ||||
| 28189 | static void memsys3Leave(void){ | ||||
| 28190 | sqlite3_mutex_leave(mem3.mutex); | ||||
| 28191 | } | ||||
| 28192 | |||||
| 28193 | /* | ||||
| 28194 | ** Called when we are unable to satisfy an allocation of nBytes. | ||||
| 28195 | */ | ||||
| 28196 | static void memsys3OutOfMemory(int nByte){ | ||||
| 28197 | if( !mem3.alarmBusy ){ | ||||
| 28198 | mem3.alarmBusy = 1; | ||||
| 28199 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28200 | sqlite3_mutex_leave(mem3.mutex); | ||||
| 28201 | sqlite3_release_memory(nByte); | ||||
| 28202 | sqlite3_mutex_enter(mem3.mutex); | ||||
| 28203 | mem3.alarmBusy = 0; | ||||
| 28204 | } | ||||
| 28205 | } | ||||
| 28206 | |||||
| 28207 | |||||
| 28208 | /* | ||||
| 28209 | ** Chunk i is a free chunk that has been unlinked. Adjust its | ||||
| 28210 | ** size parameters for check-out and return a pointer to the | ||||
| 28211 | ** user portion of the chunk. | ||||
| 28212 | */ | ||||
| 28213 | static void *memsys3Checkout(u32 i, u32 nBlock){ | ||||
| 28214 | u32 x; | ||||
| 28215 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28216 | assert( i>=1 )((void) (0)); | ||||
| 28217 | assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock )((void) (0)); | ||||
| 28218 | assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock )((void) (0)); | ||||
| 28219 | x = mem3.aPool[i-1].u.hdr.size4x; | ||||
| 28220 | mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); | ||||
| 28221 | mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; | ||||
| 28222 | mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2; | ||||
| 28223 | return &mem3.aPool[i]; | ||||
| 28224 | } | ||||
| 28225 | |||||
| 28226 | /* | ||||
| 28227 | ** Carve a piece off of the end of the mem3.iKeyBlk free chunk. | ||||
| 28228 | ** Return a pointer to the new allocation. Or, if the key chunk | ||||
| 28229 | ** is not large enough, return 0. | ||||
| 28230 | */ | ||||
| 28231 | static void *memsys3FromKeyBlk(u32 nBlock){ | ||||
| 28232 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28233 | assert( mem3.szKeyBlk>=nBlock )((void) (0)); | ||||
| 28234 | if( nBlock>=mem3.szKeyBlk-1 ){ | ||||
| 28235 | /* Use the entire key chunk */ | ||||
| 28236 | void *p = memsys3Checkout(mem3.iKeyBlk, mem3.szKeyBlk); | ||||
| 28237 | mem3.iKeyBlk = 0; | ||||
| 28238 | mem3.szKeyBlk = 0; | ||||
| 28239 | mem3.mnKeyBlk = 0; | ||||
| 28240 | return p; | ||||
| 28241 | }else{ | ||||
| 28242 | /* Split the key block. Return the tail. */ | ||||
| 28243 | u32 newi, x; | ||||
| 28244 | newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock; | ||||
| 28245 | assert( newi > mem3.iKeyBlk+1 )((void) (0)); | ||||
| 28246 | mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock; | ||||
| 28247 | mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2; | ||||
| 28248 | mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; | ||||
| 28249 | mem3.szKeyBlk -= nBlock; | ||||
| 28250 | mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk; | ||||
| 28251 | x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; | ||||
| 28252 | mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; | ||||
| 28253 | if( mem3.szKeyBlk < mem3.mnKeyBlk ){ | ||||
| 28254 | mem3.mnKeyBlk = mem3.szKeyBlk; | ||||
| 28255 | } | ||||
| 28256 | return (void*)&mem3.aPool[newi]; | ||||
| 28257 | } | ||||
| 28258 | } | ||||
| 28259 | |||||
| 28260 | /* | ||||
| 28261 | ** *pRoot is the head of a list of free chunks of the same size | ||||
| 28262 | ** or same size hash. In other words, *pRoot is an entry in either | ||||
| 28263 | ** mem3.aiSmall[] or mem3.aiHash[]. | ||||
| 28264 | ** | ||||
| 28265 | ** This routine examines all entries on the given list and tries | ||||
| 28266 | ** to coalesce each entries with adjacent free chunks. | ||||
| 28267 | ** | ||||
| 28268 | ** If it sees a chunk that is larger than mem3.iKeyBlk, it replaces | ||||
| 28269 | ** the current mem3.iKeyBlk with the new larger chunk. In order for | ||||
| 28270 | ** this mem3.iKeyBlk replacement to work, the key chunk must be | ||||
| 28271 | ** linked into the hash tables. That is not the normal state of | ||||
| 28272 | ** affairs, of course. The calling routine must link the key | ||||
| 28273 | ** chunk before invoking this routine, then must unlink the (possibly | ||||
| 28274 | ** changed) key chunk once this routine has finished. | ||||
| 28275 | */ | ||||
| 28276 | static void memsys3Merge(u32 *pRoot){ | ||||
| 28277 | u32 iNext, prev, size, i, x; | ||||
| 28278 | |||||
| 28279 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28280 | for(i=*pRoot; i>0; i=iNext){ | ||||
| 28281 | iNext = mem3.aPool[i].u.list.next; | ||||
| 28282 | size = mem3.aPool[i-1].u.hdr.size4x; | ||||
| 28283 | assert( (size&1)==0 )((void) (0)); | ||||
| 28284 | if( (size&2)==0 ){ | ||||
| 28285 | memsys3UnlinkFromList(i, pRoot); | ||||
| 28286 | assert( i > mem3.aPool[i-1].u.hdr.prevSize )((void) (0)); | ||||
| 28287 | prev = i - mem3.aPool[i-1].u.hdr.prevSize; | ||||
| 28288 | if( prev==iNext ){ | ||||
| 28289 | iNext = mem3.aPool[prev].u.list.next; | ||||
| 28290 | } | ||||
| 28291 | memsys3Unlink(prev); | ||||
| 28292 | size = i + size/4 - prev; | ||||
| 28293 | x = mem3.aPool[prev-1].u.hdr.size4x & 2; | ||||
| 28294 | mem3.aPool[prev-1].u.hdr.size4x = size*4 | x; | ||||
| 28295 | mem3.aPool[prev+size-1].u.hdr.prevSize = size; | ||||
| 28296 | memsys3Link(prev); | ||||
| 28297 | i = prev; | ||||
| 28298 | }else{ | ||||
| 28299 | size /= 4; | ||||
| 28300 | } | ||||
| 28301 | if( size>mem3.szKeyBlk ){ | ||||
| 28302 | mem3.iKeyBlk = i; | ||||
| 28303 | mem3.szKeyBlk = size; | ||||
| 28304 | } | ||||
| 28305 | } | ||||
| 28306 | } | ||||
| 28307 | |||||
| 28308 | /* | ||||
| 28309 | ** Return a block of memory of at least nBytes in size. | ||||
| 28310 | ** Return NULL if unable. | ||||
| 28311 | ** | ||||
| 28312 | ** This function assumes that the necessary mutexes, if any, are | ||||
| 28313 | ** already held by the caller. Hence "Unsafe". | ||||
| 28314 | */ | ||||
| 28315 | static void *memsys3MallocUnsafe(int nByte){ | ||||
| 28316 | u32 i; | ||||
| 28317 | u32 nBlock; | ||||
| 28318 | u32 toFree; | ||||
| 28319 | |||||
| 28320 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28321 | assert( sizeof(Mem3Block)==8 )((void) (0)); | ||||
| 28322 | if( nByte<=12 ){ | ||||
| 28323 | nBlock = 2; | ||||
| 28324 | }else{ | ||||
| 28325 | nBlock = (nByte + 11)/8; | ||||
| 28326 | } | ||||
| 28327 | assert( nBlock>=2 )((void) (0)); | ||||
| 28328 | |||||
| 28329 | /* STEP 1: | ||||
| 28330 | ** Look for an entry of the correct size in either the small | ||||
| 28331 | ** chunk table or in the large chunk hash table. This is | ||||
| 28332 | ** successful most of the time (about 9 times out of 10). | ||||
| 28333 | */ | ||||
| 28334 | if( nBlock <= MX_SMALL ){ | ||||
| 28335 | i = mem3.aiSmall[nBlock-2]; | ||||
| 28336 | if( i>0 ){ | ||||
| 28337 | memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]); | ||||
| 28338 | return memsys3Checkout(i, nBlock); | ||||
| 28339 | } | ||||
| 28340 | }else{ | ||||
| 28341 | int hash = nBlock % N_HASH; | ||||
| 28342 | for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){ | ||||
| 28343 | if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){ | ||||
| 28344 | memsys3UnlinkFromList(i, &mem3.aiHash[hash]); | ||||
| 28345 | return memsys3Checkout(i, nBlock); | ||||
| 28346 | } | ||||
| 28347 | } | ||||
| 28348 | } | ||||
| 28349 | |||||
| 28350 | /* STEP 2: | ||||
| 28351 | ** Try to satisfy the allocation by carving a piece off of the end | ||||
| 28352 | ** of the key chunk. This step usually works if step 1 fails. | ||||
| 28353 | */ | ||||
| 28354 | if( mem3.szKeyBlk>=nBlock ){ | ||||
| 28355 | return memsys3FromKeyBlk(nBlock); | ||||
| 28356 | } | ||||
| 28357 | |||||
| 28358 | |||||
| 28359 | /* STEP 3: | ||||
| 28360 | ** Loop through the entire memory pool. Coalesce adjacent free | ||||
| 28361 | ** chunks. Recompute the key chunk as the largest free chunk. | ||||
| 28362 | ** Then try again to satisfy the allocation by carving a piece off | ||||
| 28363 | ** of the end of the key chunk. This step happens very | ||||
| 28364 | ** rarely (we hope!) | ||||
| 28365 | */ | ||||
| 28366 | for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){ | ||||
| 28367 | memsys3OutOfMemory(toFree); | ||||
| 28368 | if( mem3.iKeyBlk ){ | ||||
| 28369 | memsys3Link(mem3.iKeyBlk); | ||||
| 28370 | mem3.iKeyBlk = 0; | ||||
| 28371 | mem3.szKeyBlk = 0; | ||||
| 28372 | } | ||||
| 28373 | for(i=0; i<N_HASH; i++){ | ||||
| 28374 | memsys3Merge(&mem3.aiHash[i]); | ||||
| 28375 | } | ||||
| 28376 | for(i=0; i<MX_SMALL-1; i++){ | ||||
| 28377 | memsys3Merge(&mem3.aiSmall[i]); | ||||
| 28378 | } | ||||
| 28379 | if( mem3.szKeyBlk ){ | ||||
| 28380 | memsys3Unlink(mem3.iKeyBlk); | ||||
| 28381 | if( mem3.szKeyBlk>=nBlock ){ | ||||
| 28382 | return memsys3FromKeyBlk(nBlock); | ||||
| 28383 | } | ||||
| 28384 | } | ||||
| 28385 | } | ||||
| 28386 | |||||
| 28387 | /* If none of the above worked, then we fail. */ | ||||
| 28388 | return 0; | ||||
| 28389 | } | ||||
| 28390 | |||||
| 28391 | /* | ||||
| 28392 | ** Free an outstanding memory allocation. | ||||
| 28393 | ** | ||||
| 28394 | ** This function assumes that the necessary mutexes, if any, are | ||||
| 28395 | ** already held by the caller. Hence "Unsafe". | ||||
| 28396 | */ | ||||
| 28397 | static void memsys3FreeUnsafe(void *pOld){ | ||||
| 28398 | Mem3Block *p = (Mem3Block*)pOld; | ||||
| 28399 | int i; | ||||
| 28400 | u32 size, x; | ||||
| 28401 | assert( sqlite3_mutex_held(mem3.mutex) )((void) (0)); | ||||
| 28402 | assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] )((void) (0)); | ||||
| 28403 | i = p - mem3.aPool; | ||||
| 28404 | assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 )((void) (0)); | ||||
| 28405 | size = mem3.aPool[i-1].u.hdr.size4x/4; | ||||
| 28406 | assert( i+size<=mem3.nPool+1 )((void) (0)); | ||||
| 28407 | mem3.aPool[i-1].u.hdr.size4x &= ~1; | ||||
| 28408 | mem3.aPool[i+size-1].u.hdr.prevSize = size; | ||||
| 28409 | mem3.aPool[i+size-1].u.hdr.size4x &= ~2; | ||||
| 28410 | memsys3Link(i); | ||||
| 28411 | |||||
| 28412 | /* Try to expand the key using the newly freed chunk */ | ||||
| 28413 | if( mem3.iKeyBlk ){ | ||||
| 28414 | while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){ | ||||
| 28415 | size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize; | ||||
| 28416 | mem3.iKeyBlk -= size; | ||||
| 28417 | mem3.szKeyBlk += size; | ||||
| 28418 | memsys3Unlink(mem3.iKeyBlk); | ||||
| 28419 | x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; | ||||
| 28420 | mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; | ||||
| 28421 | mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk; | ||||
| 28422 | } | ||||
| 28423 | x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; | ||||
| 28424 | while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){ | ||||
| 28425 | memsys3Unlink(mem3.iKeyBlk+mem3.szKeyBlk); | ||||
| 28426 | mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4; | ||||
| 28427 | mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; | ||||
| 28428 | mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk; | ||||
| 28429 | } | ||||
| 28430 | } | ||||
| 28431 | } | ||||
| 28432 | |||||
| 28433 | /* | ||||
| 28434 | ** Return the size of an outstanding allocation, in bytes. The | ||||
| 28435 | ** size returned omits the 8-byte header overhead. This only | ||||
| 28436 | ** works for chunks that are currently checked out. | ||||
| 28437 | */ | ||||
| 28438 | static int memsys3Size(void *p){ | ||||
| 28439 | Mem3Block *pBlock; | ||||
| 28440 | assert( p!=0 )((void) (0)); | ||||
| 28441 | pBlock = (Mem3Block*)p; | ||||
| 28442 | assert( (pBlock[-1].u.hdr.size4x&1)!=0 )((void) (0)); | ||||
| 28443 | return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; | ||||
| 28444 | } | ||||
| 28445 | |||||
| 28446 | /* | ||||
| 28447 | ** Round up a request size to the next valid allocation size. | ||||
| 28448 | */ | ||||
| 28449 | static int memsys3Roundup(int n){ | ||||
| 28450 | if( n<=12 ){ | ||||
| 28451 | return 12; | ||||
| 28452 | }else{ | ||||
| 28453 | return ((n+11)&~7) - 4; | ||||
| 28454 | } | ||||
| 28455 | } | ||||
| 28456 | |||||
| 28457 | /* | ||||
| 28458 | ** Allocate nBytes of memory. | ||||
| 28459 | */ | ||||
| 28460 | static void *memsys3Malloc(int nBytes){ | ||||
| 28461 | sqlite3_int64 *p; | ||||
| 28462 | assert( nBytes>0 )((void) (0)); /* malloc.c filters out 0 byte requests */ | ||||
| 28463 | memsys3Enter(); | ||||
| 28464 | p = memsys3MallocUnsafe(nBytes); | ||||
| 28465 | memsys3Leave(); | ||||
| 28466 | return (void*)p; | ||||
| 28467 | } | ||||
| 28468 | |||||
| 28469 | /* | ||||
| 28470 | ** Free memory. | ||||
| 28471 | */ | ||||
| 28472 | static void memsys3Free(void *pPrior){ | ||||
| 28473 | assert( pPrior )((void) (0)); | ||||
| 28474 | memsys3Enter(); | ||||
| 28475 | memsys3FreeUnsafe(pPrior); | ||||
| 28476 | memsys3Leave(); | ||||
| 28477 | } | ||||
| 28478 | |||||
| 28479 | /* | ||||
| 28480 | ** Change the size of an existing memory allocation | ||||
| 28481 | */ | ||||
| 28482 | static void *memsys3Realloc(void *pPrior, int nBytes){ | ||||
| 28483 | int nOld; | ||||
| 28484 | void *p; | ||||
| 28485 | if( pPrior==0 ){ | ||||
| 28486 | return sqlite3_malloc(nBytes); | ||||
| 28487 | } | ||||
| 28488 | if( nBytes<=0 ){ | ||||
| 28489 | sqlite3_free(pPrior); | ||||
| 28490 | return 0; | ||||
| 28491 | } | ||||
| 28492 | nOld = memsys3Size(pPrior); | ||||
| 28493 | if( nBytes<=nOld && nBytes>=nOld-128 ){ | ||||
| 28494 | return pPrior; | ||||
| 28495 | } | ||||
| 28496 | memsys3Enter(); | ||||
| 28497 | p = memsys3MallocUnsafe(nBytes); | ||||
| 28498 | if( p ){ | ||||
| 28499 | if( nOld<nBytes ){ | ||||
| 28500 | memcpy(p, pPrior, nOld); | ||||
| 28501 | }else{ | ||||
| 28502 | memcpy(p, pPrior, nBytes); | ||||
| 28503 | } | ||||
| 28504 | memsys3FreeUnsafe(pPrior); | ||||
| 28505 | } | ||||
| 28506 | memsys3Leave(); | ||||
| 28507 | return p; | ||||
| 28508 | } | ||||
| 28509 | |||||
| 28510 | /* | ||||
| 28511 | ** Initialize this module. | ||||
| 28512 | */ | ||||
| 28513 | static int memsys3Init(void *NotUsed){ | ||||
| 28514 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 28515 | if( !sqlite3GlobalConfigsqlite3Config.pHeap ){ | ||||
| 28516 | return SQLITE_ERROR1; | ||||
| 28517 | } | ||||
| 28518 | |||||
| 28519 | /* Store a pointer to the memory block in global structure mem3. */ | ||||
| 28520 | assert( sizeof(Mem3Block)==8 )((void) (0)); | ||||
| 28521 | mem3.aPool = (Mem3Block *)sqlite3GlobalConfigsqlite3Config.pHeap; | ||||
| 28522 | mem3.nPool = (sqlite3GlobalConfigsqlite3Config.nHeap / sizeof(Mem3Block)) - 2; | ||||
| 28523 | |||||
| 28524 | /* Initialize the key block. */ | ||||
| 28525 | mem3.szKeyBlk = mem3.nPool; | ||||
| 28526 | mem3.mnKeyBlk = mem3.szKeyBlk; | ||||
| 28527 | mem3.iKeyBlk = 1; | ||||
| 28528 | mem3.aPool[0].u.hdr.size4x = (mem3.szKeyBlk<<2) + 2; | ||||
| 28529 | mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool; | ||||
| 28530 | mem3.aPool[mem3.nPool].u.hdr.size4x = 1; | ||||
| 28531 | |||||
| 28532 | return SQLITE_OK0; | ||||
| 28533 | } | ||||
| 28534 | |||||
| 28535 | /* | ||||
| 28536 | ** Deinitialize this module. | ||||
| 28537 | */ | ||||
| 28538 | static void memsys3Shutdown(void *NotUsed){ | ||||
| 28539 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 28540 | mem3.mutex = 0; | ||||
| 28541 | return; | ||||
| 28542 | } | ||||
| 28543 | |||||
| 28544 | |||||
| 28545 | |||||
| 28546 | /* | ||||
| 28547 | ** Open the file indicated and write a log of all unfreed memory | ||||
| 28548 | ** allocations into that log. | ||||
| 28549 | */ | ||||
| 28550 | SQLITE_PRIVATEstatic void sqlite3Memsys3Dump(const char *zFilename){ | ||||
| 28551 | #ifdef SQLITE_DEBUG | ||||
| 28552 | FILE *out; | ||||
| 28553 | u32 i, j; | ||||
| 28554 | u32 size; | ||||
| 28555 | if( zFilename==0 || zFilename[0]==0 ){ | ||||
| 28556 | out = stdoutstdout; | ||||
| 28557 | }else{ | ||||
| 28558 | out = fopen(zFilename, "w"); | ||||
| 28559 | if( out==0 ){ | ||||
| 28560 | fprintf(stderrstderr, "** Unable to output memory debug output log: %s **\n", | ||||
| 28561 | zFilename); | ||||
| 28562 | return; | ||||
| 28563 | } | ||||
| 28564 | } | ||||
| 28565 | memsys3Enter(); | ||||
| 28566 | fprintf(out, "CHUNKS:\n"); | ||||
| 28567 | for(i=1; i<=mem3.nPool; i+=size/4){ | ||||
| 28568 | size = mem3.aPool[i-1].u.hdr.size4x; | ||||
| 28569 | if( size/4<=1 ){ | ||||
| 28570 | fprintf(out, "%p size error\n", &mem3.aPool[i]); | ||||
| 28571 | assert( 0 )((void) (0)); | ||||
| 28572 | break; | ||||
| 28573 | } | ||||
| 28574 | if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){ | ||||
| 28575 | fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]); | ||||
| 28576 | assert( 0 )((void) (0)); | ||||
| 28577 | break; | ||||
| 28578 | } | ||||
| 28579 | if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){ | ||||
| 28580 | fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]); | ||||
| 28581 | assert( 0 )((void) (0)); | ||||
| 28582 | break; | ||||
| 28583 | } | ||||
| 28584 | if( size&1 ){ | ||||
| 28585 | fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8); | ||||
| 28586 | }else{ | ||||
| 28587 | fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8, | ||||
| 28588 | i==mem3.iKeyBlk ? " **key**" : ""); | ||||
| 28589 | } | ||||
| 28590 | } | ||||
| 28591 | for(i=0; i<MX_SMALL-1; i++){ | ||||
| 28592 | if( mem3.aiSmall[i]==0 ) continue; | ||||
| 28593 | fprintf(out, "small(%2d):", i); | ||||
| 28594 | for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){ | ||||
| 28595 | fprintf(out, " %p(%d)", &mem3.aPool[j], | ||||
| 28596 | (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); | ||||
| 28597 | } | ||||
| 28598 | fprintf(out, "\n"); | ||||
| 28599 | } | ||||
| 28600 | for(i=0; i<N_HASH; i++){ | ||||
| 28601 | if( mem3.aiHash[i]==0 ) continue; | ||||
| 28602 | fprintf(out, "hash(%2d):", i); | ||||
| 28603 | for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){ | ||||
| 28604 | fprintf(out, " %p(%d)", &mem3.aPool[j], | ||||
| 28605 | (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); | ||||
| 28606 | } | ||||
| 28607 | fprintf(out, "\n"); | ||||
| 28608 | } | ||||
| 28609 | fprintf(out, "key=%d\n", mem3.iKeyBlk); | ||||
| 28610 | fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8); | ||||
| 28611 | fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*8); | ||||
| 28612 | sqlite3_mutex_leave(mem3.mutex); | ||||
| 28613 | if( out==stdoutstdout ){ | ||||
| 28614 | fflush(stdoutstdout); | ||||
| 28615 | }else{ | ||||
| 28616 | fclose(out); | ||||
| 28617 | } | ||||
| 28618 | #else | ||||
| 28619 | UNUSED_PARAMETER(zFilename)(void)(zFilename); | ||||
| 28620 | #endif | ||||
| 28621 | } | ||||
| 28622 | |||||
| 28623 | /* | ||||
| 28624 | ** This routine is the only routine in this file with external | ||||
| 28625 | ** linkage. | ||||
| 28626 | ** | ||||
| 28627 | ** Populate the low-level memory allocation function pointers in | ||||
| 28628 | ** sqlite3GlobalConfig.m with pointers to the routines in this file. The | ||||
| 28629 | ** arguments specify the block of memory to manage. | ||||
| 28630 | ** | ||||
| 28631 | ** This routine is only called by sqlite3_config(), and therefore | ||||
| 28632 | ** is not required to be threadsafe (it is not). | ||||
| 28633 | */ | ||||
| 28634 | SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ | ||||
| 28635 | static const sqlite3_mem_methods mempoolMethods = { | ||||
| 28636 | memsys3Malloc, | ||||
| 28637 | memsys3Free, | ||||
| 28638 | memsys3Realloc, | ||||
| 28639 | memsys3Size, | ||||
| 28640 | memsys3Roundup, | ||||
| 28641 | memsys3Init, | ||||
| 28642 | memsys3Shutdown, | ||||
| 28643 | 0 | ||||
| 28644 | }; | ||||
| 28645 | return &mempoolMethods; | ||||
| 28646 | } | ||||
| 28647 | |||||
| 28648 | #endif /* SQLITE_ENABLE_MEMSYS3 */ | ||||
| 28649 | |||||
| 28650 | /************** End of mem3.c ************************************************/ | ||||
| 28651 | /************** Begin file mem5.c ********************************************/ | ||||
| 28652 | /* | ||||
| 28653 | ** 2007 October 14 | ||||
| 28654 | ** | ||||
| 28655 | ** The author disclaims copyright to this source code. In place of | ||||
| 28656 | ** a legal notice, here is a blessing: | ||||
| 28657 | ** | ||||
| 28658 | ** May you do good and not evil. | ||||
| 28659 | ** May you find forgiveness for yourself and forgive others. | ||||
| 28660 | ** May you share freely, never taking more than you give. | ||||
| 28661 | ** | ||||
| 28662 | ************************************************************************* | ||||
| 28663 | ** This file contains the C functions that implement a memory | ||||
| 28664 | ** allocation subsystem for use by SQLite. | ||||
| 28665 | ** | ||||
| 28666 | ** This version of the memory allocation subsystem omits all | ||||
| 28667 | ** use of malloc(). The application gives SQLite a block of memory | ||||
| 28668 | ** before calling sqlite3_initialize() from which allocations | ||||
| 28669 | ** are made and returned by the xMalloc() and xRealloc() | ||||
| 28670 | ** implementations. Once sqlite3_initialize() has been called, | ||||
| 28671 | ** the amount of memory available to SQLite is fixed and cannot | ||||
| 28672 | ** be changed. | ||||
| 28673 | ** | ||||
| 28674 | ** This version of the memory allocation subsystem is included | ||||
| 28675 | ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined. | ||||
| 28676 | ** | ||||
| 28677 | ** This memory allocator uses the following algorithm: | ||||
| 28678 | ** | ||||
| 28679 | ** 1. All memory allocation sizes are rounded up to a power of 2. | ||||
| 28680 | ** | ||||
| 28681 | ** 2. If two adjacent free blocks are the halves of a larger block, | ||||
| 28682 | ** then the two blocks are coalesced into the single larger block. | ||||
| 28683 | ** | ||||
| 28684 | ** 3. New memory is allocated from the first available free block. | ||||
| 28685 | ** | ||||
| 28686 | ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions | ||||
| 28687 | ** Concerning Dynamic Storage Allocation". Journal of the Association for | ||||
| 28688 | ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499. | ||||
| 28689 | ** | ||||
| 28690 | ** Let n be the size of the largest allocation divided by the minimum | ||||
| 28691 | ** allocation size (after rounding all sizes up to a power of 2.) Let M | ||||
| 28692 | ** be the maximum amount of memory ever outstanding at one time. Let | ||||
| 28693 | ** N be the total amount of memory available for allocation. Robson | ||||
| 28694 | ** proved that this memory allocator will never breakdown due to | ||||
| 28695 | ** fragmentation as long as the following constraint holds: | ||||
| 28696 | ** | ||||
| 28697 | ** N >= M*(1 + log2(n)/2) - n + 1 | ||||
| 28698 | ** | ||||
| 28699 | ** The sqlite3_status() logic tracks the maximum values of n and M so | ||||
| 28700 | ** that an application can, at any time, verify this constraint. | ||||
| 28701 | */ | ||||
| 28702 | /* #include "sqliteInt.h" */ | ||||
| 28703 | |||||
| 28704 | /* | ||||
| 28705 | ** This version of the memory allocator is used only when | ||||
| 28706 | ** SQLITE_ENABLE_MEMSYS5 is defined. | ||||
| 28707 | */ | ||||
| 28708 | #ifdef SQLITE_ENABLE_MEMSYS5 | ||||
| 28709 | |||||
| 28710 | /* | ||||
| 28711 | ** A minimum allocation is an instance of the following structure. | ||||
| 28712 | ** Larger allocations are an array of these structures where the | ||||
| 28713 | ** size of the array is a power of 2. | ||||
| 28714 | ** | ||||
| 28715 | ** The size of this object must be a power of two. That fact is | ||||
| 28716 | ** verified in memsys5Init(). | ||||
| 28717 | */ | ||||
| 28718 | typedef struct Mem5Link Mem5Link; | ||||
| 28719 | struct Mem5Link { | ||||
| 28720 | int next; /* Index of next free chunk */ | ||||
| 28721 | int prev; /* Index of previous free chunk */ | ||||
| 28722 | }; | ||||
| 28723 | |||||
| 28724 | /* | ||||
| 28725 | ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since | ||||
| 28726 | ** mem5.szAtom is always at least 8 and 32-bit integers are used, | ||||
| 28727 | ** it is not actually possible to reach this limit. | ||||
| 28728 | */ | ||||
| 28729 | #define LOGMAX 30 | ||||
| 28730 | |||||
| 28731 | /* | ||||
| 28732 | ** Masks used for mem5.aCtrl[] elements. | ||||
| 28733 | */ | ||||
| 28734 | #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */ | ||||
| 28735 | #define CTRL_FREE 0x20 /* True if not checked out */ | ||||
| 28736 | |||||
| 28737 | /* | ||||
| 28738 | ** All of the static variables used by this module are collected | ||||
| 28739 | ** into a single structure named "mem5". This is to keep the | ||||
| 28740 | ** static variables organized and to reduce namespace pollution | ||||
| 28741 | ** when this module is combined with other in the amalgamation. | ||||
| 28742 | */ | ||||
| 28743 | static SQLITE_WSD struct Mem5Global { | ||||
| 28744 | /* | ||||
| 28745 | ** Memory available for allocation | ||||
| 28746 | */ | ||||
| 28747 | int szAtom; /* Smallest possible allocation in bytes */ | ||||
| 28748 | int nBlock; /* Number of szAtom sized blocks in zPool */ | ||||
| 28749 | u8 *zPool; /* Memory available to be allocated */ | ||||
| 28750 | |||||
| 28751 | /* | ||||
| 28752 | ** Mutex to control access to the memory allocation subsystem. | ||||
| 28753 | */ | ||||
| 28754 | sqlite3_mutex *mutex; | ||||
| 28755 | |||||
| 28756 | #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) | ||||
| 28757 | /* | ||||
| 28758 | ** Performance statistics | ||||
| 28759 | */ | ||||
| 28760 | u64 nAlloc; /* Total number of calls to malloc */ | ||||
| 28761 | u64 totalAlloc; /* Total of all malloc calls - includes internal frag */ | ||||
| 28762 | u64 totalExcess; /* Total internal fragmentation */ | ||||
| 28763 | u32 currentOut; /* Current checkout, including internal fragmentation */ | ||||
| 28764 | u32 currentCount; /* Current number of distinct checkouts */ | ||||
| 28765 | u32 maxOut; /* Maximum instantaneous currentOut */ | ||||
| 28766 | u32 maxCount; /* Maximum instantaneous currentCount */ | ||||
| 28767 | u32 maxRequest; /* Largest allocation (exclusive of internal frag) */ | ||||
| 28768 | #endif | ||||
| 28769 | |||||
| 28770 | /* | ||||
| 28771 | ** Lists of free blocks. aiFreelist[0] is a list of free blocks of | ||||
| 28772 | ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2. | ||||
| 28773 | ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth. | ||||
| 28774 | */ | ||||
| 28775 | int aiFreelist[LOGMAX+1]; | ||||
| 28776 | |||||
| 28777 | /* | ||||
| 28778 | ** Space for tracking which blocks are checked out and the size | ||||
| 28779 | ** of each block. One byte per block. | ||||
| 28780 | */ | ||||
| 28781 | u8 *aCtrl; | ||||
| 28782 | |||||
| 28783 | } mem5; | ||||
| 28784 | |||||
| 28785 | /* | ||||
| 28786 | ** Access the static variable through a macro for SQLITE_OMIT_WSD. | ||||
| 28787 | */ | ||||
| 28788 | #define mem5 GLOBAL(struct Mem5Global, mem5)mem5 | ||||
| 28789 | |||||
| 28790 | /* | ||||
| 28791 | ** Assuming mem5.zPool is divided up into an array of Mem5Link | ||||
| 28792 | ** structures, return a pointer to the idx-th such link. | ||||
| 28793 | */ | ||||
| 28794 | #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom])) | ||||
| 28795 | |||||
| 28796 | /* | ||||
| 28797 | ** Unlink the chunk at mem5.aPool[i] from list it is currently | ||||
| 28798 | ** on. It should be found on mem5.aiFreelist[iLogsize]. | ||||
| 28799 | */ | ||||
| 28800 | static void memsys5Unlink(int i, int iLogsize){ | ||||
| 28801 | int next, prev; | ||||
| 28802 | assert( i>=0 && i<mem5.nBlock )((void) (0)); | ||||
| 28803 | assert( iLogsize>=0 && iLogsize<=LOGMAX )((void) (0)); | ||||
| 28804 | assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize )((void) (0)); | ||||
| 28805 | |||||
| 28806 | next = MEM5LINK(i)->next; | ||||
| 28807 | prev = MEM5LINK(i)->prev; | ||||
| 28808 | if( prev<0 ){ | ||||
| 28809 | mem5.aiFreelist[iLogsize] = next; | ||||
| 28810 | }else{ | ||||
| 28811 | MEM5LINK(prev)->next = next; | ||||
| 28812 | } | ||||
| 28813 | if( next>=0 ){ | ||||
| 28814 | MEM5LINK(next)->prev = prev; | ||||
| 28815 | } | ||||
| 28816 | } | ||||
| 28817 | |||||
| 28818 | /* | ||||
| 28819 | ** Link the chunk at mem5.aPool[i] so that is on the iLogsize | ||||
| 28820 | ** free list. | ||||
| 28821 | */ | ||||
| 28822 | static void memsys5Link(int i, int iLogsize){ | ||||
| 28823 | int x; | ||||
| 28824 | assert( sqlite3_mutex_held(mem5.mutex) )((void) (0)); | ||||
| 28825 | assert( i>=0 && i<mem5.nBlock )((void) (0)); | ||||
| 28826 | assert( iLogsize>=0 && iLogsize<=LOGMAX )((void) (0)); | ||||
| 28827 | assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize )((void) (0)); | ||||
| 28828 | |||||
| 28829 | x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize]; | ||||
| 28830 | MEM5LINK(i)->prev = -1; | ||||
| 28831 | if( x>=0 ){ | ||||
| 28832 | assert( x<mem5.nBlock )((void) (0)); | ||||
| 28833 | MEM5LINK(x)->prev = i; | ||||
| 28834 | } | ||||
| 28835 | mem5.aiFreelist[iLogsize] = i; | ||||
| 28836 | } | ||||
| 28837 | |||||
| 28838 | /* | ||||
| 28839 | ** Obtain or release the mutex needed to access global data structures. | ||||
| 28840 | */ | ||||
| 28841 | static void memsys5Enter(void){ | ||||
| 28842 | sqlite3_mutex_enter(mem5.mutex); | ||||
| 28843 | } | ||||
| 28844 | static void memsys5Leave(void){ | ||||
| 28845 | sqlite3_mutex_leave(mem5.mutex); | ||||
| 28846 | } | ||||
| 28847 | |||||
| 28848 | /* | ||||
| 28849 | ** Return the size of an outstanding allocation, in bytes. | ||||
| 28850 | ** This only works for chunks that are currently checked out. | ||||
| 28851 | */ | ||||
| 28852 | static int memsys5Size(void *p){ | ||||
| 28853 | int iSize, i; | ||||
| 28854 | assert( p!=0 )((void) (0)); | ||||
| 28855 | i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom); | ||||
| 28856 | assert( i>=0 && i<mem5.nBlock )((void) (0)); | ||||
| 28857 | iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE)); | ||||
| 28858 | return iSize; | ||||
| 28859 | } | ||||
| 28860 | |||||
| 28861 | /* | ||||
| 28862 | ** Return a block of memory of at least nBytes in size. | ||||
| 28863 | ** Return NULL if unable. Return NULL if nBytes==0. | ||||
| 28864 | ** | ||||
| 28865 | ** The caller guarantees that nByte is positive. | ||||
| 28866 | ** | ||||
| 28867 | ** The caller has obtained a mutex prior to invoking this | ||||
| 28868 | ** routine so there is never any chance that two or more | ||||
| 28869 | ** threads can be in this routine at the same time. | ||||
| 28870 | */ | ||||
| 28871 | static void *memsys5MallocUnsafe(int nByte){ | ||||
| 28872 | int i; /* Index of a mem5.aPool[] slot */ | ||||
| 28873 | int iBin; /* Index into mem5.aiFreelist[] */ | ||||
| 28874 | int iFullSz; /* Size of allocation rounded up to power of 2 */ | ||||
| 28875 | int iLogsize; /* Log2 of iFullSz/POW2_MIN */ | ||||
| 28876 | |||||
| 28877 | /* nByte must be a positive */ | ||||
| 28878 | assert( nByte>0 )((void) (0)); | ||||
| 28879 | |||||
| 28880 | /* No more than 1GiB per allocation */ | ||||
| 28881 | if( nByte > 0x40000000 ) return 0; | ||||
| 28882 | |||||
| 28883 | #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) | ||||
| 28884 | /* Keep track of the maximum allocation request. Even unfulfilled | ||||
| 28885 | ** requests are counted */ | ||||
| 28886 | if( (u32)nByte>mem5.maxRequest ){ | ||||
| 28887 | mem5.maxRequest = nByte; | ||||
| 28888 | } | ||||
| 28889 | #endif | ||||
| 28890 | |||||
| 28891 | |||||
| 28892 | /* Round nByte up to the next valid power of two */ | ||||
| 28893 | for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){} | ||||
| 28894 | |||||
| 28895 | /* Make sure mem5.aiFreelist[iLogsize] contains at least one free | ||||
| 28896 | ** block. If not, then split a block of the next larger power of | ||||
| 28897 | ** two in order to create a new free block of size iLogsize. | ||||
| 28898 | */ | ||||
| 28899 | for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){} | ||||
| 28900 | if( iBin>LOGMAX ){ | ||||
| 28901 | testcase( sqlite3GlobalConfig.xLog!=0 ); | ||||
| 28902 | sqlite3_log(SQLITE_NOMEM7, "failed to allocate %u bytes", nByte); | ||||
| 28903 | return 0; | ||||
| 28904 | } | ||||
| 28905 | i = mem5.aiFreelist[iBin]; | ||||
| 28906 | memsys5Unlink(i, iBin); | ||||
| 28907 | while( iBin>iLogsize ){ | ||||
| 28908 | int newSize; | ||||
| 28909 | |||||
| 28910 | iBin--; | ||||
| 28911 | newSize = 1 << iBin; | ||||
| 28912 | mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; | ||||
| 28913 | memsys5Link(i+newSize, iBin); | ||||
| 28914 | } | ||||
| 28915 | mem5.aCtrl[i] = iLogsize; | ||||
| 28916 | |||||
| 28917 | #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) | ||||
| 28918 | /* Update allocator performance statistics. */ | ||||
| 28919 | mem5.nAlloc++; | ||||
| 28920 | mem5.totalAlloc += iFullSz; | ||||
| 28921 | mem5.totalExcess += iFullSz - nByte; | ||||
| 28922 | mem5.currentCount++; | ||||
| 28923 | mem5.currentOut += iFullSz; | ||||
| 28924 | if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount; | ||||
| 28925 | if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut; | ||||
| 28926 | #endif | ||||
| 28927 | |||||
| 28928 | #ifdef SQLITE_DEBUG | ||||
| 28929 | /* Make sure the allocated memory does not assume that it is set to zero | ||||
| 28930 | ** or retains a value from a previous allocation */ | ||||
| 28931 | memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz); | ||||
| 28932 | #endif | ||||
| 28933 | |||||
| 28934 | /* Return a pointer to the allocated memory. */ | ||||
| 28935 | return (void*)&mem5.zPool[i*mem5.szAtom]; | ||||
| 28936 | } | ||||
| 28937 | |||||
| 28938 | /* | ||||
| 28939 | ** Free an outstanding memory allocation. | ||||
| 28940 | */ | ||||
| 28941 | static void memsys5FreeUnsafe(void *pOld){ | ||||
| 28942 | u32 size, iLogsize; | ||||
| 28943 | int iBlock; | ||||
| 28944 | |||||
| 28945 | /* Set iBlock to the index of the block pointed to by pOld in | ||||
| 28946 | ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool. | ||||
| 28947 | */ | ||||
| 28948 | iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom); | ||||
| 28949 | |||||
| 28950 | /* Check that the pointer pOld points to a valid, non-free block. */ | ||||
| 28951 | assert( iBlock>=0 && iBlock<mem5.nBlock )((void) (0)); | ||||
| 28952 | assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 )((void) (0)); | ||||
| 28953 | assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 )((void) (0)); | ||||
| 28954 | |||||
| 28955 | iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE; | ||||
| 28956 | size = 1<<iLogsize; | ||||
| 28957 | assert( iBlock+size-1<(u32)mem5.nBlock )((void) (0)); | ||||
| 28958 | |||||
| 28959 | mem5.aCtrl[iBlock] |= CTRL_FREE; | ||||
| 28960 | mem5.aCtrl[iBlock+size-1] |= CTRL_FREE; | ||||
| 28961 | |||||
| 28962 | #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) | ||||
| 28963 | assert( mem5.currentCount>0 )((void) (0)); | ||||
| 28964 | assert( mem5.currentOut>=(size*mem5.szAtom) )((void) (0)); | ||||
| 28965 | mem5.currentCount--; | ||||
| 28966 | mem5.currentOut -= size*mem5.szAtom; | ||||
| 28967 | assert( mem5.currentOut>0 || mem5.currentCount==0 )((void) (0)); | ||||
| 28968 | assert( mem5.currentCount>0 || mem5.currentOut==0 )((void) (0)); | ||||
| 28969 | #endif | ||||
| 28970 | |||||
| 28971 | mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; | ||||
| 28972 | while( ALWAYS(iLogsize<LOGMAX)(iLogsize<LOGMAX) ){ | ||||
| 28973 | int iBuddy; | ||||
| 28974 | if( (iBlock>>iLogsize) & 1 ){ | ||||
| 28975 | iBuddy = iBlock - size; | ||||
| 28976 | assert( iBuddy>=0 )((void) (0)); | ||||
| 28977 | }else{ | ||||
| 28978 | iBuddy = iBlock + size; | ||||
| 28979 | if( iBuddy>=mem5.nBlock ) break; | ||||
| 28980 | } | ||||
| 28981 | if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break; | ||||
| 28982 | memsys5Unlink(iBuddy, iLogsize); | ||||
| 28983 | iLogsize++; | ||||
| 28984 | if( iBuddy<iBlock ){ | ||||
| 28985 | mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize; | ||||
| 28986 | mem5.aCtrl[iBlock] = 0; | ||||
| 28987 | iBlock = iBuddy; | ||||
| 28988 | }else{ | ||||
| 28989 | mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; | ||||
| 28990 | mem5.aCtrl[iBuddy] = 0; | ||||
| 28991 | } | ||||
| 28992 | size *= 2; | ||||
| 28993 | } | ||||
| 28994 | |||||
| 28995 | #ifdef SQLITE_DEBUG | ||||
| 28996 | /* Overwrite freed memory with the 0x55 bit pattern to verify that it is | ||||
| 28997 | ** not used after being freed */ | ||||
| 28998 | memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size); | ||||
| 28999 | #endif | ||||
| 29000 | |||||
| 29001 | memsys5Link(iBlock, iLogsize); | ||||
| 29002 | } | ||||
| 29003 | |||||
| 29004 | /* | ||||
| 29005 | ** Allocate nBytes of memory. | ||||
| 29006 | */ | ||||
| 29007 | static void *memsys5Malloc(int nBytes){ | ||||
| 29008 | sqlite3_int64 *p = 0; | ||||
| 29009 | if( nBytes>0 ){ | ||||
| 29010 | memsys5Enter(); | ||||
| 29011 | p = memsys5MallocUnsafe(nBytes); | ||||
| 29012 | memsys5Leave(); | ||||
| 29013 | } | ||||
| 29014 | return (void*)p; | ||||
| 29015 | } | ||||
| 29016 | |||||
| 29017 | /* | ||||
| 29018 | ** Free memory. | ||||
| 29019 | ** | ||||
| 29020 | ** The outer layer memory allocator prevents this routine from | ||||
| 29021 | ** being called with pPrior==0. | ||||
| 29022 | */ | ||||
| 29023 | static void memsys5Free(void *pPrior){ | ||||
| 29024 | assert( pPrior!=0 )((void) (0)); | ||||
| 29025 | memsys5Enter(); | ||||
| 29026 | memsys5FreeUnsafe(pPrior); | ||||
| 29027 | memsys5Leave(); | ||||
| 29028 | } | ||||
| 29029 | |||||
| 29030 | /* | ||||
| 29031 | ** Change the size of an existing memory allocation. | ||||
| 29032 | ** | ||||
| 29033 | ** The outer layer memory allocator prevents this routine from | ||||
| 29034 | ** being called with pPrior==0. | ||||
| 29035 | ** | ||||
| 29036 | ** nBytes is always a value obtained from a prior call to | ||||
| 29037 | ** memsys5Round(). Hence nBytes is always a non-negative power | ||||
| 29038 | ** of two. If nBytes==0 that means that an oversize allocation | ||||
| 29039 | ** (an allocation larger than 0x40000000) was requested and this | ||||
| 29040 | ** routine should return 0 without freeing pPrior. | ||||
| 29041 | */ | ||||
| 29042 | static void *memsys5Realloc(void *pPrior, int nBytes){ | ||||
| 29043 | int nOld; | ||||
| 29044 | void *p; | ||||
| 29045 | assert( pPrior!=0 )((void) (0)); | ||||
| 29046 | assert( (nBytes&(nBytes-1))==0 )((void) (0)); /* EV: R-46199-30249 */ | ||||
| 29047 | assert( nBytes>=0 )((void) (0)); | ||||
| 29048 | if( nBytes==0 ){ | ||||
| 29049 | return 0; | ||||
| 29050 | } | ||||
| 29051 | nOld = memsys5Size(pPrior); | ||||
| 29052 | if( nBytes<=nOld ){ | ||||
| 29053 | return pPrior; | ||||
| 29054 | } | ||||
| 29055 | p = memsys5Malloc(nBytes); | ||||
| 29056 | if( p ){ | ||||
| 29057 | memcpy(p, pPrior, nOld); | ||||
| 29058 | memsys5Free(pPrior); | ||||
| 29059 | } | ||||
| 29060 | return p; | ||||
| 29061 | } | ||||
| 29062 | |||||
| 29063 | /* | ||||
| 29064 | ** Round up a request size to the next valid allocation size. If | ||||
| 29065 | ** the allocation is too large to be handled by this allocation system, | ||||
| 29066 | ** return 0. | ||||
| 29067 | ** | ||||
| 29068 | ** All allocations must be a power of two and must be expressed by a | ||||
| 29069 | ** 32-bit signed integer. Hence the largest allocation is 0x40000000 | ||||
| 29070 | ** or 1073741824 bytes. | ||||
| 29071 | */ | ||||
| 29072 | static int memsys5Roundup(int n){ | ||||
| 29073 | int iFullSz; | ||||
| 29074 | if( n<=mem5.szAtom*2 ){ | ||||
| 29075 | if( n<=mem5.szAtom ) return mem5.szAtom; | ||||
| 29076 | return mem5.szAtom*2; | ||||
| 29077 | } | ||||
| 29078 | if( n>0x10000000 ){ | ||||
| 29079 | if( n>0x40000000 ) return 0; | ||||
| 29080 | if( n>0x20000000 ) return 0x40000000; | ||||
| 29081 | return 0x20000000; | ||||
| 29082 | } | ||||
| 29083 | for(iFullSz=mem5.szAtom*8; iFullSz<n; iFullSz *= 4); | ||||
| 29084 | if( (iFullSz/2)>=(i64)n ) return iFullSz/2; | ||||
| 29085 | return iFullSz; | ||||
| 29086 | } | ||||
| 29087 | |||||
| 29088 | /* | ||||
| 29089 | ** Return the ceiling of the logarithm base 2 of iValue. | ||||
| 29090 | ** | ||||
| 29091 | ** Examples: memsys5Log(1) -> 0 | ||||
| 29092 | ** memsys5Log(2) -> 1 | ||||
| 29093 | ** memsys5Log(4) -> 2 | ||||
| 29094 | ** memsys5Log(5) -> 3 | ||||
| 29095 | ** memsys5Log(8) -> 3 | ||||
| 29096 | ** memsys5Log(9) -> 4 | ||||
| 29097 | */ | ||||
| 29098 | static int memsys5Log(int iValue){ | ||||
| 29099 | int iLog; | ||||
| 29100 | for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++); | ||||
| 29101 | return iLog; | ||||
| 29102 | } | ||||
| 29103 | |||||
| 29104 | /* | ||||
| 29105 | ** Initialize the memory allocator. | ||||
| 29106 | ** | ||||
| 29107 | ** This routine is not threadsafe. The caller must be holding a mutex | ||||
| 29108 | ** to prevent multiple threads from entering at the same time. | ||||
| 29109 | */ | ||||
| 29110 | static int memsys5Init(void *NotUsed){ | ||||
| 29111 | int ii; /* Loop counter */ | ||||
| 29112 | int nByte; /* Number of bytes of memory available to this allocator */ | ||||
| 29113 | u8 *zByte; /* Memory usable by this allocator */ | ||||
| 29114 | int nMinLog; /* Log base 2 of minimum allocation size in bytes */ | ||||
| 29115 | int iOffset; /* An offset into mem5.aCtrl[] */ | ||||
| 29116 | |||||
| 29117 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 29118 | |||||
| 29119 | /* For the purposes of this routine, disable the mutex */ | ||||
| 29120 | mem5.mutex = 0; | ||||
| 29121 | |||||
| 29122 | /* The size of a Mem5Link object must be a power of two. Verify that | ||||
| 29123 | ** this is case. | ||||
| 29124 | */ | ||||
| 29125 | assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 )((void) (0)); | ||||
| 29126 | |||||
| 29127 | nByte = sqlite3GlobalConfigsqlite3Config.nHeap; | ||||
| 29128 | zByte = (u8*)sqlite3GlobalConfigsqlite3Config.pHeap; | ||||
| 29129 | assert( zByte!=0 )((void) (0)); /* sqlite3_config() does not allow otherwise */ | ||||
| 29130 | |||||
| 29131 | /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */ | ||||
| 29132 | nMinLog = memsys5Log(sqlite3GlobalConfigsqlite3Config.mnReq); | ||||
| 29133 | mem5.szAtom = (1<<nMinLog); | ||||
| 29134 | while( (int)sizeof(Mem5Link)>mem5.szAtom ){ | ||||
| 29135 | mem5.szAtom = mem5.szAtom << 1; | ||||
| 29136 | } | ||||
| 29137 | |||||
| 29138 | mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8))); | ||||
| 29139 | mem5.zPool = zByte; | ||||
| 29140 | mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom]; | ||||
| 29141 | |||||
| 29142 | for(ii=0; ii<=LOGMAX; ii++){ | ||||
| 29143 | mem5.aiFreelist[ii] = -1; | ||||
| 29144 | } | ||||
| 29145 | |||||
| 29146 | iOffset = 0; | ||||
| 29147 | for(ii=LOGMAX; ii>=0; ii--){ | ||||
| 29148 | int nAlloc = (1<<ii); | ||||
| 29149 | if( (iOffset+nAlloc)<=mem5.nBlock ){ | ||||
| 29150 | mem5.aCtrl[iOffset] = ii | CTRL_FREE; | ||||
| 29151 | memsys5Link(iOffset, ii); | ||||
| 29152 | iOffset += nAlloc; | ||||
| 29153 | } | ||||
| 29154 | assert((iOffset+nAlloc)>mem5.nBlock)((void) (0)); | ||||
| 29155 | } | ||||
| 29156 | |||||
| 29157 | /* If a mutex is required for normal operation, allocate one */ | ||||
| 29158 | if( sqlite3GlobalConfigsqlite3Config.bMemstat==0 ){ | ||||
| 29159 | mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM3); | ||||
| 29160 | } | ||||
| 29161 | |||||
| 29162 | return SQLITE_OK0; | ||||
| 29163 | } | ||||
| 29164 | |||||
| 29165 | /* | ||||
| 29166 | ** Deinitialize this module. | ||||
| 29167 | */ | ||||
| 29168 | static void memsys5Shutdown(void *NotUsed){ | ||||
| 29169 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 29170 | mem5.mutex = 0; | ||||
| 29171 | return; | ||||
| 29172 | } | ||||
| 29173 | |||||
| 29174 | #ifdef SQLITE_TEST | ||||
| 29175 | /* | ||||
| 29176 | ** Open the file indicated and write a log of all unfreed memory | ||||
| 29177 | ** allocations into that log. | ||||
| 29178 | */ | ||||
| 29179 | SQLITE_PRIVATEstatic void sqlite3Memsys5Dump(const char *zFilename){ | ||||
| 29180 | FILE *out; | ||||
| 29181 | int i, j, n; | ||||
| 29182 | int nMinLog; | ||||
| 29183 | |||||
| 29184 | if( zFilename==0 || zFilename[0]==0 ){ | ||||
| 29185 | out = stdoutstdout; | ||||
| 29186 | }else{ | ||||
| 29187 | out = fopen(zFilename, "w"); | ||||
| 29188 | if( out==0 ){ | ||||
| 29189 | fprintf(stderrstderr, "** Unable to output memory debug output log: %s **\n", | ||||
| 29190 | zFilename); | ||||
| 29191 | return; | ||||
| 29192 | } | ||||
| 29193 | } | ||||
| 29194 | memsys5Enter(); | ||||
| 29195 | nMinLog = memsys5Log(mem5.szAtom); | ||||
| 29196 | for(i=0; i<=LOGMAX && i+nMinLog<32; i++){ | ||||
| 29197 | for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){} | ||||
| 29198 | fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n); | ||||
| 29199 | } | ||||
| 29200 | fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc); | ||||
| 29201 | fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc); | ||||
| 29202 | fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess); | ||||
| 29203 | fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut); | ||||
| 29204 | fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount); | ||||
| 29205 | fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut); | ||||
| 29206 | fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount); | ||||
| 29207 | fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest); | ||||
| 29208 | memsys5Leave(); | ||||
| 29209 | if( out==stdoutstdout ){ | ||||
| 29210 | fflush(stdoutstdout); | ||||
| 29211 | }else{ | ||||
| 29212 | fclose(out); | ||||
| 29213 | } | ||||
| 29214 | } | ||||
| 29215 | #endif | ||||
| 29216 | |||||
| 29217 | /* | ||||
| 29218 | ** This routine is the only routine in this file with external | ||||
| 29219 | ** linkage. It returns a pointer to a static sqlite3_mem_methods | ||||
| 29220 | ** struct populated with the memsys5 methods. | ||||
| 29221 | */ | ||||
| 29222 | SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){ | ||||
| 29223 | static const sqlite3_mem_methods memsys5Methods = { | ||||
| 29224 | memsys5Malloc, | ||||
| 29225 | memsys5Free, | ||||
| 29226 | memsys5Realloc, | ||||
| 29227 | memsys5Size, | ||||
| 29228 | memsys5Roundup, | ||||
| 29229 | memsys5Init, | ||||
| 29230 | memsys5Shutdown, | ||||
| 29231 | 0 | ||||
| 29232 | }; | ||||
| 29233 | return &memsys5Methods; | ||||
| 29234 | } | ||||
| 29235 | |||||
| 29236 | #endif /* SQLITE_ENABLE_MEMSYS5 */ | ||||
| 29237 | |||||
| 29238 | /************** End of mem5.c ************************************************/ | ||||
| 29239 | /************** Begin file mutex.c *******************************************/ | ||||
| 29240 | /* | ||||
| 29241 | ** 2007 August 14 | ||||
| 29242 | ** | ||||
| 29243 | ** The author disclaims copyright to this source code. In place of | ||||
| 29244 | ** a legal notice, here is a blessing: | ||||
| 29245 | ** | ||||
| 29246 | ** May you do good and not evil. | ||||
| 29247 | ** May you find forgiveness for yourself and forgive others. | ||||
| 29248 | ** May you share freely, never taking more than you give. | ||||
| 29249 | ** | ||||
| 29250 | ************************************************************************* | ||||
| 29251 | ** This file contains the C functions that implement mutexes. | ||||
| 29252 | ** | ||||
| 29253 | ** This file contains code that is common across all mutex implementations. | ||||
| 29254 | */ | ||||
| 29255 | /* #include "sqliteInt.h" */ | ||||
| 29256 | |||||
| 29257 | #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT) | ||||
| 29258 | /* | ||||
| 29259 | ** For debugging purposes, record when the mutex subsystem is initialized | ||||
| 29260 | ** and uninitialized so that we can assert() if there is an attempt to | ||||
| 29261 | ** allocate a mutex while the system is uninitialized. | ||||
| 29262 | */ | ||||
| 29263 | static SQLITE_WSD int mutexIsInit = 0; | ||||
| 29264 | #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */ | ||||
| 29265 | |||||
| 29266 | |||||
| 29267 | #ifndef SQLITE_MUTEX_OMIT | ||||
| 29268 | |||||
| 29269 | #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS | ||||
| 29270 | /* | ||||
| 29271 | ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains | ||||
| 29272 | ** the implementation of a wrapper around the system default mutex | ||||
| 29273 | ** implementation (sqlite3DefaultMutex()). | ||||
| 29274 | ** | ||||
| 29275 | ** Most calls are passed directly through to the underlying default | ||||
| 29276 | ** mutex implementation. Except, if a mutex is configured by calling | ||||
| 29277 | ** sqlite3MutexWarnOnContention() on it, then if contention is ever | ||||
| 29278 | ** encountered within xMutexEnter() a warning is emitted via sqlite3_log(). | ||||
| 29279 | ** | ||||
| 29280 | ** This type of mutex is used as the database handle mutex when testing | ||||
| 29281 | ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode. | ||||
| 29282 | */ | ||||
| 29283 | |||||
| 29284 | /* | ||||
| 29285 | ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS | ||||
| 29286 | ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex | ||||
| 29287 | ** allocated by the system mutex implementation. Variable iType is usually set | ||||
| 29288 | ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST | ||||
| 29289 | ** or one of the static mutex identifiers. Or, if this is a recursive mutex | ||||
| 29290 | ** that has been configured using sqlite3MutexWarnOnContention(), it is | ||||
| 29291 | ** set to SQLITE_MUTEX_WARNONCONTENTION. | ||||
| 29292 | */ | ||||
| 29293 | typedef struct CheckMutex CheckMutex; | ||||
| 29294 | struct CheckMutex { | ||||
| 29295 | int iType; | ||||
| 29296 | sqlite3_mutex *mutex; | ||||
| 29297 | }; | ||||
| 29298 | |||||
| 29299 | #define SQLITE_MUTEX_WARNONCONTENTION (-1) | ||||
| 29300 | |||||
| 29301 | /* | ||||
| 29302 | ** Pointer to real mutex methods object used by the CheckMutex | ||||
| 29303 | ** implementation. Set by checkMutexInit(). | ||||
| 29304 | */ | ||||
| 29305 | static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods; | ||||
| 29306 | |||||
| 29307 | #ifdef SQLITE_DEBUG | ||||
| 29308 | static int checkMutexHeld(sqlite3_mutex *p){ | ||||
| 29309 | return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex); | ||||
| 29310 | } | ||||
| 29311 | static int checkMutexNotheld(sqlite3_mutex *p){ | ||||
| 29312 | return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex); | ||||
| 29313 | } | ||||
| 29314 | #endif | ||||
| 29315 | |||||
| 29316 | /* | ||||
| 29317 | ** Initialize and deinitialize the mutex subsystem. | ||||
| 29318 | */ | ||||
| 29319 | static int checkMutexInit(void){ | ||||
| 29320 | pGlobalMutexMethods = sqlite3DefaultMutex(); | ||||
| 29321 | return SQLITE_OK0; | ||||
| 29322 | } | ||||
| 29323 | static int checkMutexEnd(void){ | ||||
| 29324 | pGlobalMutexMethods = 0; | ||||
| 29325 | return SQLITE_OK0; | ||||
| 29326 | } | ||||
| 29327 | |||||
| 29328 | /* | ||||
| 29329 | ** Allocate a mutex. | ||||
| 29330 | */ | ||||
| 29331 | static sqlite3_mutex *checkMutexAlloc(int iType){ | ||||
| 29332 | static CheckMutex staticMutexes[] = { | ||||
| 29333 | {2, 0}, {3, 0}, {4, 0}, {5, 0}, | ||||
| 29334 | {6, 0}, {7, 0}, {8, 0}, {9, 0}, | ||||
| 29335 | {10, 0}, {11, 0}, {12, 0}, {13, 0} | ||||
| 29336 | }; | ||||
| 29337 | CheckMutex *p = 0; | ||||
| 29338 | |||||
| 29339 | assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 )((void) (0)); | ||||
| 29340 | if( iType<2 ){ | ||||
| 29341 | p = sqlite3MallocZero(sizeof(CheckMutex)); | ||||
| 29342 | if( p==0 ) return 0; | ||||
| 29343 | p->iType = iType; | ||||
| 29344 | }else{ | ||||
| 29345 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 29346 | if( iType-2>=ArraySize(staticMutexes)((int)(sizeof(staticMutexes)/sizeof(staticMutexes[0]))) ){ | ||||
| 29347 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(29347); | ||||
| 29348 | return 0; | ||||
| 29349 | } | ||||
| 29350 | #endif | ||||
| 29351 | p = &staticMutexes[iType-2]; | ||||
| 29352 | } | ||||
| 29353 | |||||
| 29354 | if( p->mutex==0 ){ | ||||
| 29355 | p->mutex = pGlobalMutexMethods->xMutexAlloc(iType); | ||||
| 29356 | if( p->mutex==0 ){ | ||||
| 29357 | if( iType<2 ){ | ||||
| 29358 | sqlite3_free(p); | ||||
| 29359 | } | ||||
| 29360 | p = 0; | ||||
| 29361 | } | ||||
| 29362 | } | ||||
| 29363 | |||||
| 29364 | return (sqlite3_mutex*)p; | ||||
| 29365 | } | ||||
| 29366 | |||||
| 29367 | /* | ||||
| 29368 | ** Free a mutex. | ||||
| 29369 | */ | ||||
| 29370 | static void checkMutexFree(sqlite3_mutex *p){ | ||||
| 29371 | assert( SQLITE_MUTEX_RECURSIVE<2 )((void) (0)); | ||||
| 29372 | assert( SQLITE_MUTEX_FAST<2 )((void) (0)); | ||||
| 29373 | assert( SQLITE_MUTEX_WARNONCONTENTION<2 )((void) (0)); | ||||
| 29374 | |||||
| 29375 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 29376 | if( ((CheckMutex*)p)->iType<2 ) | ||||
| 29377 | #endif | ||||
| 29378 | { | ||||
| 29379 | CheckMutex *pCheck = (CheckMutex*)p; | ||||
| 29380 | pGlobalMutexMethods->xMutexFree(pCheck->mutex); | ||||
| 29381 | sqlite3_free(pCheck); | ||||
| 29382 | } | ||||
| 29383 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 29384 | else{ | ||||
| 29385 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(29385); | ||||
| 29386 | } | ||||
| 29387 | #endif | ||||
| 29388 | } | ||||
| 29389 | |||||
| 29390 | /* | ||||
| 29391 | ** Enter the mutex. | ||||
| 29392 | */ | ||||
| 29393 | static void checkMutexEnter(sqlite3_mutex *p){ | ||||
| 29394 | CheckMutex *pCheck = (CheckMutex*)p; | ||||
| 29395 | if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){ | ||||
| 29396 | if( SQLITE_OK0==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){ | ||||
| 29397 | return; | ||||
| 29398 | } | ||||
| 29399 | sqlite3_log(SQLITE_MISUSE21, | ||||
| 29400 | "illegal multi-threaded access to database connection" | ||||
| 29401 | ); | ||||
| 29402 | } | ||||
| 29403 | pGlobalMutexMethods->xMutexEnter(pCheck->mutex); | ||||
| 29404 | } | ||||
| 29405 | |||||
| 29406 | /* | ||||
| 29407 | ** Enter the mutex (do not block). | ||||
| 29408 | */ | ||||
| 29409 | static int checkMutexTry(sqlite3_mutex *p){ | ||||
| 29410 | CheckMutex *pCheck = (CheckMutex*)p; | ||||
| 29411 | return pGlobalMutexMethods->xMutexTry(pCheck->mutex); | ||||
| 29412 | } | ||||
| 29413 | |||||
| 29414 | /* | ||||
| 29415 | ** Leave the mutex. | ||||
| 29416 | */ | ||||
| 29417 | static void checkMutexLeave(sqlite3_mutex *p){ | ||||
| 29418 | CheckMutex *pCheck = (CheckMutex*)p; | ||||
| 29419 | pGlobalMutexMethods->xMutexLeave(pCheck->mutex); | ||||
| 29420 | } | ||||
| 29421 | |||||
| 29422 | sqlite3_mutex_methods const *multiThreadedCheckMutex(void){ | ||||
| 29423 | static const sqlite3_mutex_methods sMutex = { | ||||
| 29424 | checkMutexInit, | ||||
| 29425 | checkMutexEnd, | ||||
| 29426 | checkMutexAlloc, | ||||
| 29427 | checkMutexFree, | ||||
| 29428 | checkMutexEnter, | ||||
| 29429 | checkMutexTry, | ||||
| 29430 | checkMutexLeave, | ||||
| 29431 | #ifdef SQLITE_DEBUG | ||||
| 29432 | checkMutexHeld, | ||||
| 29433 | checkMutexNotheld | ||||
| 29434 | #else | ||||
| 29435 | 0, | ||||
| 29436 | 0 | ||||
| 29437 | #endif | ||||
| 29438 | }; | ||||
| 29439 | return &sMutex; | ||||
| 29440 | } | ||||
| 29441 | |||||
| 29442 | /* | ||||
| 29443 | ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as | ||||
| 29444 | ** one on which there should be no contention. | ||||
| 29445 | */ | ||||
| 29446 | SQLITE_PRIVATEstatic void sqlite3MutexWarnOnContention(sqlite3_mutex *p){ | ||||
| 29447 | if( sqlite3GlobalConfigsqlite3Config.mutex.xMutexAlloc==checkMutexAlloc ){ | ||||
| 29448 | CheckMutex *pCheck = (CheckMutex*)p; | ||||
| 29449 | assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE )((void) (0)); | ||||
| 29450 | pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION; | ||||
| 29451 | } | ||||
| 29452 | } | ||||
| 29453 | #endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */ | ||||
| 29454 | |||||
| 29455 | /* | ||||
| 29456 | ** Initialize the mutex system. | ||||
| 29457 | */ | ||||
| 29458 | SQLITE_PRIVATEstatic int sqlite3MutexInit(void){ | ||||
| 29459 | int rc = SQLITE_OK0; | ||||
| 29460 | if( !sqlite3GlobalConfigsqlite3Config.mutex.xMutexAlloc ){ | ||||
| 29461 | /* If the xMutexAlloc method has not been set, then the user did not | ||||
| 29462 | ** install a mutex implementation via sqlite3_config() prior to | ||||
| 29463 | ** sqlite3_initialize() being called. This block copies pointers to | ||||
| 29464 | ** the default implementation into the sqlite3GlobalConfig structure. | ||||
| 29465 | */ | ||||
| 29466 | sqlite3_mutex_methods const *pFrom; | ||||
| 29467 | sqlite3_mutex_methods *pTo = &sqlite3GlobalConfigsqlite3Config.mutex; | ||||
| 29468 | |||||
| 29469 | if( sqlite3GlobalConfigsqlite3Config.bCoreMutex ){ | ||||
| 29470 | #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS | ||||
| 29471 | pFrom = multiThreadedCheckMutex(); | ||||
| 29472 | #else | ||||
| 29473 | pFrom = sqlite3DefaultMutex(); | ||||
| 29474 | #endif | ||||
| 29475 | }else{ | ||||
| 29476 | pFrom = sqlite3NoopMutex(); | ||||
| 29477 | } | ||||
| 29478 | pTo->xMutexInit = pFrom->xMutexInit; | ||||
| 29479 | pTo->xMutexEnd = pFrom->xMutexEnd; | ||||
| 29480 | pTo->xMutexFree = pFrom->xMutexFree; | ||||
| 29481 | pTo->xMutexEnter = pFrom->xMutexEnter; | ||||
| 29482 | pTo->xMutexTry = pFrom->xMutexTry; | ||||
| 29483 | pTo->xMutexLeave = pFrom->xMutexLeave; | ||||
| 29484 | pTo->xMutexHeld = pFrom->xMutexHeld; | ||||
| 29485 | pTo->xMutexNotheld = pFrom->xMutexNotheld; | ||||
| 29486 | sqlite3MemoryBarrier(); | ||||
| 29487 | pTo->xMutexAlloc = pFrom->xMutexAlloc; | ||||
| 29488 | } | ||||
| 29489 | assert( sqlite3GlobalConfig.mutex.xMutexInit )((void) (0)); | ||||
| 29490 | rc = sqlite3GlobalConfigsqlite3Config.mutex.xMutexInit(); | ||||
| 29491 | |||||
| 29492 | #ifdef SQLITE_DEBUG | ||||
| 29493 | GLOBAL(int, mutexIsInit)mutexIsInit = 1; | ||||
| 29494 | #endif | ||||
| 29495 | |||||
| 29496 | sqlite3MemoryBarrier(); | ||||
| 29497 | return rc; | ||||
| 29498 | } | ||||
| 29499 | |||||
| 29500 | /* | ||||
| 29501 | ** Shutdown the mutex system. This call frees resources allocated by | ||||
| 29502 | ** sqlite3MutexInit(). | ||||
| 29503 | */ | ||||
| 29504 | SQLITE_PRIVATEstatic int sqlite3MutexEnd(void){ | ||||
| 29505 | int rc = SQLITE_OK0; | ||||
| 29506 | if( sqlite3GlobalConfigsqlite3Config.mutex.xMutexEnd ){ | ||||
| 29507 | rc = sqlite3GlobalConfigsqlite3Config.mutex.xMutexEnd(); | ||||
| 29508 | } | ||||
| 29509 | |||||
| 29510 | #ifdef SQLITE_DEBUG | ||||
| 29511 | GLOBAL(int, mutexIsInit)mutexIsInit = 0; | ||||
| 29512 | #endif | ||||
| 29513 | |||||
| 29514 | return rc; | ||||
| 29515 | } | ||||
| 29516 | |||||
| 29517 | /* | ||||
| 29518 | ** Retrieve a pointer to a static mutex or allocate a new dynamic one. | ||||
| 29519 | */ | ||||
| 29520 | SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){ | ||||
| 29521 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 29522 | if( id<=SQLITE_MUTEX_RECURSIVE1 && sqlite3_initialize() ) return 0; | ||||
| 29523 | if( id>SQLITE_MUTEX_RECURSIVE1 && sqlite3MutexInit() ) return 0; | ||||
| 29524 | #endif | ||||
| 29525 | assert( sqlite3GlobalConfig.mutex.xMutexAlloc )((void) (0)); | ||||
| 29526 | return sqlite3GlobalConfigsqlite3Config.mutex.xMutexAlloc(id); | ||||
| 29527 | } | ||||
| 29528 | |||||
| 29529 | SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3MutexAlloc(int id){ | ||||
| 29530 | if( !sqlite3GlobalConfigsqlite3Config.bCoreMutex ){ | ||||
| 29531 | return 0; | ||||
| 29532 | } | ||||
| 29533 | assert( GLOBAL(int, mutexIsInit) )((void) (0)); | ||||
| 29534 | assert( sqlite3GlobalConfig.mutex.xMutexAlloc )((void) (0)); | ||||
| 29535 | return sqlite3GlobalConfigsqlite3Config.mutex.xMutexAlloc(id); | ||||
| 29536 | } | ||||
| 29537 | |||||
| 29538 | /* | ||||
| 29539 | ** Free a dynamic mutex. | ||||
| 29540 | */ | ||||
| 29541 | SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){ | ||||
| 29542 | if( p ){ | ||||
| 29543 | assert( sqlite3GlobalConfig.mutex.xMutexFree )((void) (0)); | ||||
| 29544 | sqlite3GlobalConfigsqlite3Config.mutex.xMutexFree(p); | ||||
| 29545 | } | ||||
| 29546 | } | ||||
| 29547 | |||||
| 29548 | /* | ||||
| 29549 | ** Obtain the mutex p. If some other thread already has the mutex, block | ||||
| 29550 | ** until it can be obtained. | ||||
| 29551 | */ | ||||
| 29552 | SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ | ||||
| 29553 | if( p ){ | ||||
| 29554 | assert( sqlite3GlobalConfig.mutex.xMutexEnter )((void) (0)); | ||||
| 29555 | sqlite3GlobalConfigsqlite3Config.mutex.xMutexEnter(p); | ||||
| 29556 | } | ||||
| 29557 | } | ||||
| 29558 | |||||
| 29559 | /* | ||||
| 29560 | ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another | ||||
| 29561 | ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. | ||||
| 29562 | */ | ||||
| 29563 | SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){ | ||||
| 29564 | int rc = SQLITE_OK0; | ||||
| 29565 | if( p ){ | ||||
| 29566 | assert( sqlite3GlobalConfig.mutex.xMutexTry )((void) (0)); | ||||
| 29567 | return sqlite3GlobalConfigsqlite3Config.mutex.xMutexTry(p); | ||||
| 29568 | } | ||||
| 29569 | return rc; | ||||
| 29570 | } | ||||
| 29571 | |||||
| 29572 | /* | ||||
| 29573 | ** The sqlite3_mutex_leave() routine exits a mutex that was previously | ||||
| 29574 | ** entered by the same thread. The behavior is undefined if the mutex | ||||
| 29575 | ** is not currently entered. If a NULL pointer is passed as an argument | ||||
| 29576 | ** this function is a no-op. | ||||
| 29577 | */ | ||||
| 29578 | SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){ | ||||
| 29579 | if( p ){ | ||||
| 29580 | assert( sqlite3GlobalConfig.mutex.xMutexLeave )((void) (0)); | ||||
| 29581 | sqlite3GlobalConfigsqlite3Config.mutex.xMutexLeave(p); | ||||
| 29582 | } | ||||
| 29583 | } | ||||
| 29584 | |||||
| 29585 | #ifndef NDEBUG1 | ||||
| 29586 | /* | ||||
| 29587 | ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are | ||||
| 29588 | ** intended for use inside assert() statements. | ||||
| 29589 | ** | ||||
| 29590 | ** Because these routines raise false-positive alerts in TSAN, disable | ||||
| 29591 | ** them (make them always return 1) when compiling with TSAN. | ||||
| 29592 | */ | ||||
| 29593 | SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){ | ||||
| 29594 | # if defined(__has_feature)0 | ||||
| 29595 | # if __has_feature(thread_sanitizer)0 | ||||
| 29596 | p = 0; | ||||
| 29597 | # endif | ||||
| 29598 | # endif | ||||
| 29599 | assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld )((void) (0)); | ||||
| 29600 | return p==0 || sqlite3GlobalConfigsqlite3Config.mutex.xMutexHeld(p); | ||||
| 29601 | } | ||||
| 29602 | SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ | ||||
| 29603 | # if defined(__has_feature)0 | ||||
| 29604 | # if __has_feature(thread_sanitizer)0 | ||||
| 29605 | p = 0; | ||||
| 29606 | # endif | ||||
| 29607 | # endif | ||||
| 29608 | assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld )((void) (0)); | ||||
| 29609 | return p==0 || sqlite3GlobalConfigsqlite3Config.mutex.xMutexNotheld(p); | ||||
| 29610 | } | ||||
| 29611 | #endif /* NDEBUG */ | ||||
| 29612 | |||||
| 29613 | #endif /* !defined(SQLITE_MUTEX_OMIT) */ | ||||
| 29614 | |||||
| 29615 | /************** End of mutex.c ***********************************************/ | ||||
| 29616 | /************** Begin file mutex_noop.c **************************************/ | ||||
| 29617 | /* | ||||
| 29618 | ** 2008 October 07 | ||||
| 29619 | ** | ||||
| 29620 | ** The author disclaims copyright to this source code. In place of | ||||
| 29621 | ** a legal notice, here is a blessing: | ||||
| 29622 | ** | ||||
| 29623 | ** May you do good and not evil. | ||||
| 29624 | ** May you find forgiveness for yourself and forgive others. | ||||
| 29625 | ** May you share freely, never taking more than you give. | ||||
| 29626 | ** | ||||
| 29627 | ************************************************************************* | ||||
| 29628 | ** This file contains the C functions that implement mutexes. | ||||
| 29629 | ** | ||||
| 29630 | ** This implementation in this file does not provide any mutual | ||||
| 29631 | ** exclusion and is thus suitable for use only in applications | ||||
| 29632 | ** that use SQLite in a single thread. The routines defined | ||||
| 29633 | ** here are place-holders. Applications can substitute working | ||||
| 29634 | ** mutex routines at start-time using the | ||||
| 29635 | ** | ||||
| 29636 | ** sqlite3_config(SQLITE_CONFIG_MUTEX,...) | ||||
| 29637 | ** | ||||
| 29638 | ** interface. | ||||
| 29639 | ** | ||||
| 29640 | ** If compiled with SQLITE_DEBUG, then additional logic is inserted | ||||
| 29641 | ** that does error checking on mutexes to make sure they are being | ||||
| 29642 | ** called correctly. | ||||
| 29643 | */ | ||||
| 29644 | /* #include "sqliteInt.h" */ | ||||
| 29645 | |||||
| 29646 | #ifndef SQLITE_MUTEX_OMIT | ||||
| 29647 | |||||
| 29648 | #ifndef SQLITE_DEBUG | ||||
| 29649 | /* | ||||
| 29650 | ** Stub routines for all mutex methods. | ||||
| 29651 | ** | ||||
| 29652 | ** This routines provide no mutual exclusion or error checking. | ||||
| 29653 | */ | ||||
| 29654 | static int noopMutexInit(void){ return SQLITE_OK0; } | ||||
| 29655 | static int noopMutexEnd(void){ return SQLITE_OK0; } | ||||
| 29656 | static sqlite3_mutex *noopMutexAlloc(int id){ | ||||
| 29657 | UNUSED_PARAMETER(id)(void)(id); | ||||
| 29658 | return (sqlite3_mutex*)8; | ||||
| 29659 | } | ||||
| 29660 | static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p)(void)(p); return; } | ||||
| 29661 | static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p)(void)(p); return; } | ||||
| 29662 | static int noopMutexTry(sqlite3_mutex *p){ | ||||
| 29663 | UNUSED_PARAMETER(p)(void)(p); | ||||
| 29664 | return SQLITE_OK0; | ||||
| 29665 | } | ||||
| 29666 | static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p)(void)(p); return; } | ||||
| 29667 | |||||
| 29668 | SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3NoopMutex(void){ | ||||
| 29669 | static const sqlite3_mutex_methods sMutex = { | ||||
| 29670 | noopMutexInit, | ||||
| 29671 | noopMutexEnd, | ||||
| 29672 | noopMutexAlloc, | ||||
| 29673 | noopMutexFree, | ||||
| 29674 | noopMutexEnter, | ||||
| 29675 | noopMutexTry, | ||||
| 29676 | noopMutexLeave, | ||||
| 29677 | |||||
| 29678 | 0, | ||||
| 29679 | 0, | ||||
| 29680 | }; | ||||
| 29681 | |||||
| 29682 | return &sMutex; | ||||
| 29683 | } | ||||
| 29684 | #endif /* !SQLITE_DEBUG */ | ||||
| 29685 | |||||
| 29686 | #ifdef SQLITE_DEBUG | ||||
| 29687 | /* | ||||
| 29688 | ** In this implementation, error checking is provided for testing | ||||
| 29689 | ** and debugging purposes. The mutexes still do not provide any | ||||
| 29690 | ** mutual exclusion. | ||||
| 29691 | */ | ||||
| 29692 | |||||
| 29693 | /* | ||||
| 29694 | ** The mutex object | ||||
| 29695 | */ | ||||
| 29696 | typedef struct sqlite3_debug_mutex { | ||||
| 29697 | int id; /* The mutex type */ | ||||
| 29698 | int cnt; /* Number of entries without a matching leave */ | ||||
| 29699 | } sqlite3_debug_mutex; | ||||
| 29700 | |||||
| 29701 | /* | ||||
| 29702 | ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are | ||||
| 29703 | ** intended for use inside assert() statements. | ||||
| 29704 | */ | ||||
| 29705 | static int debugMutexHeld(sqlite3_mutex *pX){ | ||||
| 29706 | sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; | ||||
| 29707 | return p==0 || p->cnt>0; | ||||
| 29708 | } | ||||
| 29709 | static int debugMutexNotheld(sqlite3_mutex *pX){ | ||||
| 29710 | sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; | ||||
| 29711 | return p==0 || p->cnt==0; | ||||
| 29712 | } | ||||
| 29713 | |||||
| 29714 | /* | ||||
| 29715 | ** Initialize and deinitialize the mutex subsystem. | ||||
| 29716 | */ | ||||
| 29717 | static int debugMutexInit(void){ return SQLITE_OK0; } | ||||
| 29718 | static int debugMutexEnd(void){ return SQLITE_OK0; } | ||||
| 29719 | |||||
| 29720 | /* | ||||
| 29721 | ** The sqlite3_mutex_alloc() routine allocates a new | ||||
| 29722 | ** mutex and returns a pointer to it. If it returns NULL | ||||
| 29723 | ** that means that a mutex could not be allocated. | ||||
| 29724 | */ | ||||
| 29725 | static sqlite3_mutex *debugMutexAlloc(int id){ | ||||
| 29726 | static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS313 - 1]; | ||||
| 29727 | sqlite3_debug_mutex *pNew = 0; | ||||
| 29728 | switch( id ){ | ||||
| 29729 | case SQLITE_MUTEX_FAST0: | ||||
| 29730 | case SQLITE_MUTEX_RECURSIVE1: { | ||||
| 29731 | pNew = sqlite3Malloc(sizeof(*pNew)); | ||||
| 29732 | if( pNew ){ | ||||
| 29733 | pNew->id = id; | ||||
| 29734 | pNew->cnt = 0; | ||||
| 29735 | } | ||||
| 29736 | break; | ||||
| 29737 | } | ||||
| 29738 | default: { | ||||
| 29739 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 29740 | if( id-2<0 || id-2>=ArraySize(aStatic)((int)(sizeof(aStatic)/sizeof(aStatic[0]))) ){ | ||||
| 29741 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(29741); | ||||
| 29742 | return 0; | ||||
| 29743 | } | ||||
| 29744 | #endif | ||||
| 29745 | pNew = &aStatic[id-2]; | ||||
| 29746 | pNew->id = id; | ||||
| 29747 | break; | ||||
| 29748 | } | ||||
| 29749 | } | ||||
| 29750 | return (sqlite3_mutex*)pNew; | ||||
| 29751 | } | ||||
| 29752 | |||||
| 29753 | /* | ||||
| 29754 | ** This routine deallocates a previously allocated mutex. | ||||
| 29755 | */ | ||||
| 29756 | static void debugMutexFree(sqlite3_mutex *pX){ | ||||
| 29757 | sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; | ||||
| 29758 | assert( p->cnt==0 )((void) (0)); | ||||
| 29759 | if( p->id==SQLITE_MUTEX_RECURSIVE1 || p->id==SQLITE_MUTEX_FAST0 ){ | ||||
| 29760 | sqlite3_free(p); | ||||
| 29761 | }else{ | ||||
| 29762 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 29763 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(29763); | ||||
| 29764 | #endif | ||||
| 29765 | } | ||||
| 29766 | } | ||||
| 29767 | |||||
| 29768 | /* | ||||
| 29769 | ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt | ||||
| 29770 | ** to enter a mutex. If another thread is already within the mutex, | ||||
| 29771 | ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return | ||||
| 29772 | ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK | ||||
| 29773 | ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can | ||||
| 29774 | ** be entered multiple times by the same thread. In such cases the, | ||||
| 29775 | ** mutex must be exited an equal number of times before another thread | ||||
| 29776 | ** can enter. If the same thread tries to enter any other kind of mutex | ||||
| 29777 | ** more than once, the behavior is undefined. | ||||
| 29778 | */ | ||||
| 29779 | static void debugMutexEnter(sqlite3_mutex *pX){ | ||||
| 29780 | sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; | ||||
| 29781 | assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) )((void) (0)); | ||||
| 29782 | p->cnt++; | ||||
| 29783 | } | ||||
| 29784 | static int debugMutexTry(sqlite3_mutex *pX){ | ||||
| 29785 | sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; | ||||
| 29786 | assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) )((void) (0)); | ||||
| 29787 | p->cnt++; | ||||
| 29788 | return SQLITE_OK0; | ||||
| 29789 | } | ||||
| 29790 | |||||
| 29791 | /* | ||||
| 29792 | ** The sqlite3_mutex_leave() routine exits a mutex that was | ||||
| 29793 | ** previously entered by the same thread. The behavior | ||||
| 29794 | ** is undefined if the mutex is not currently entered or | ||||
| 29795 | ** is not currently allocated. SQLite will never do either. | ||||
| 29796 | */ | ||||
| 29797 | static void debugMutexLeave(sqlite3_mutex *pX){ | ||||
| 29798 | sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; | ||||
| 29799 | assert( debugMutexHeld(pX) )((void) (0)); | ||||
| 29800 | p->cnt--; | ||||
| 29801 | assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) )((void) (0)); | ||||
| 29802 | } | ||||
| 29803 | |||||
| 29804 | SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3NoopMutex(void){ | ||||
| 29805 | static const sqlite3_mutex_methods sMutex = { | ||||
| 29806 | debugMutexInit, | ||||
| 29807 | debugMutexEnd, | ||||
| 29808 | debugMutexAlloc, | ||||
| 29809 | debugMutexFree, | ||||
| 29810 | debugMutexEnter, | ||||
| 29811 | debugMutexTry, | ||||
| 29812 | debugMutexLeave, | ||||
| 29813 | |||||
| 29814 | debugMutexHeld, | ||||
| 29815 | debugMutexNotheld | ||||
| 29816 | }; | ||||
| 29817 | |||||
| 29818 | return &sMutex; | ||||
| 29819 | } | ||||
| 29820 | #endif /* SQLITE_DEBUG */ | ||||
| 29821 | |||||
| 29822 | /* | ||||
| 29823 | ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation | ||||
| 29824 | ** is used regardless of the run-time threadsafety setting. | ||||
| 29825 | */ | ||||
| 29826 | #ifdef SQLITE_MUTEX_NOOP | ||||
| 29827 | SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ | ||||
| 29828 | return sqlite3NoopMutex(); | ||||
| 29829 | } | ||||
| 29830 | #endif /* defined(SQLITE_MUTEX_NOOP) */ | ||||
| 29831 | #endif /* !defined(SQLITE_MUTEX_OMIT) */ | ||||
| 29832 | |||||
| 29833 | /************** End of mutex_noop.c ******************************************/ | ||||
| 29834 | /************** Begin file mutex_unix.c **************************************/ | ||||
| 29835 | /* | ||||
| 29836 | ** 2007 August 28 | ||||
| 29837 | ** | ||||
| 29838 | ** The author disclaims copyright to this source code. In place of | ||||
| 29839 | ** a legal notice, here is a blessing: | ||||
| 29840 | ** | ||||
| 29841 | ** May you do good and not evil. | ||||
| 29842 | ** May you find forgiveness for yourself and forgive others. | ||||
| 29843 | ** May you share freely, never taking more than you give. | ||||
| 29844 | ** | ||||
| 29845 | ************************************************************************* | ||||
| 29846 | ** This file contains the C functions that implement mutexes for pthreads | ||||
| 29847 | */ | ||||
| 29848 | /* #include "sqliteInt.h" */ | ||||
| 29849 | |||||
| 29850 | /* | ||||
| 29851 | ** The code in this file is only used if we are compiling threadsafe | ||||
| 29852 | ** under unix with pthreads. | ||||
| 29853 | ** | ||||
| 29854 | ** Note that this implementation requires a version of pthreads that | ||||
| 29855 | ** supports recursive mutexes. | ||||
| 29856 | */ | ||||
| 29857 | #ifdef SQLITE_MUTEX_PTHREADS | ||||
| 29858 | |||||
| 29859 | #include <pthread.h> | ||||
| 29860 | |||||
| 29861 | /* | ||||
| 29862 | ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields | ||||
| 29863 | ** are necessary under two conditions: (1) Debug builds and (2) using | ||||
| 29864 | ** home-grown mutexes. Encapsulate these conditions into a single #define. | ||||
| 29865 | */ | ||||
| 29866 | #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX) | ||||
| 29867 | # define SQLITE_MUTEX_NREF0 1 | ||||
| 29868 | #else | ||||
| 29869 | # define SQLITE_MUTEX_NREF0 0 | ||||
| 29870 | #endif | ||||
| 29871 | |||||
| 29872 | /* | ||||
| 29873 | ** Each recursive mutex is an instance of the following structure. | ||||
| 29874 | */ | ||||
| 29875 | struct sqlite3_mutex { | ||||
| 29876 | pthread_mutex_t mutex; /* Mutex controlling the lock */ | ||||
| 29877 | #if SQLITE_MUTEX_NREF0 || defined(SQLITE_ENABLE_API_ARMOR1) | ||||
| 29878 | int id; /* Mutex type */ | ||||
| 29879 | #endif | ||||
| 29880 | #if SQLITE_MUTEX_NREF0 | ||||
| 29881 | volatile int nRef; /* Number of entrances */ | ||||
| 29882 | volatile pthread_t owner; /* Thread that is within this mutex */ | ||||
| 29883 | int trace; /* True to trace changes */ | ||||
| 29884 | #endif | ||||
| 29885 | }; | ||||
| 29886 | #if SQLITE_MUTEX_NREF0 | ||||
| 29887 | # define SQLITE3_MUTEX_INITIALIZER(id){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, id } \ | ||||
| 29888 | {PTHREAD_MUTEX_INITIALIZER{ { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } },id,0,(pthread_t)0,0} | ||||
| 29889 | #elif defined(SQLITE_ENABLE_API_ARMOR1) | ||||
| 29890 | # define SQLITE3_MUTEX_INITIALIZER(id){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, id } { PTHREAD_MUTEX_INITIALIZER{ { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, id } | ||||
| 29891 | #else | ||||
| 29892 | #define SQLITE3_MUTEX_INITIALIZER(id){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, id } { PTHREAD_MUTEX_INITIALIZER{ { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } } } | ||||
| 29893 | #endif | ||||
| 29894 | |||||
| 29895 | /* | ||||
| 29896 | ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are | ||||
| 29897 | ** intended for use only inside assert() statements. On some platforms, | ||||
| 29898 | ** there might be race conditions that can cause these routines to | ||||
| 29899 | ** deliver incorrect results. In particular, if pthread_equal() is | ||||
| 29900 | ** not an atomic operation, then these routines might delivery | ||||
| 29901 | ** incorrect results. On most platforms, pthread_equal() is a | ||||
| 29902 | ** comparison of two integers and is therefore atomic. But we are | ||||
| 29903 | ** told that HPUX is not such a platform. If so, then these routines | ||||
| 29904 | ** will not always work correctly on HPUX. | ||||
| 29905 | ** | ||||
| 29906 | ** On those platforms where pthread_equal() is not atomic, SQLite | ||||
| 29907 | ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to | ||||
| 29908 | ** make sure no assert() statements are evaluated and hence these | ||||
| 29909 | ** routines are never called. | ||||
| 29910 | */ | ||||
| 29911 | #if !defined(NDEBUG1) || defined(SQLITE_DEBUG) | ||||
| 29912 | static int pthreadMutexHeld(sqlite3_mutex *p){ | ||||
| 29913 | return (p->nRef!=0 && pthread_equal(p->owner, pthread_self())); | ||||
| 29914 | } | ||||
| 29915 | static int pthreadMutexNotheld(sqlite3_mutex *p){ | ||||
| 29916 | return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0; | ||||
| 29917 | } | ||||
| 29918 | #endif | ||||
| 29919 | |||||
| 29920 | /* | ||||
| 29921 | ** Try to provide a memory barrier operation, needed for initialization | ||||
| 29922 | ** and also for the implementation of xShmBarrier in the VFS in cases | ||||
| 29923 | ** where SQLite is compiled without mutexes. | ||||
| 29924 | */ | ||||
| 29925 | SQLITE_PRIVATEstatic void sqlite3MemoryBarrier(void){ | ||||
| 29926 | #if defined(SQLITE_MEMORY_BARRIER) | ||||
| 29927 | SQLITE_MEMORY_BARRIER; | ||||
| 29928 | #elif defined(__GNUC__4) && GCC_VERSION(4*1000000+2*1000+1)>=4001000 | ||||
| 29929 | __sync_synchronize(); | ||||
| 29930 | #endif | ||||
| 29931 | } | ||||
| 29932 | |||||
| 29933 | /* | ||||
| 29934 | ** Initialize and deinitialize the mutex subsystem. | ||||
| 29935 | */ | ||||
| 29936 | static int pthreadMutexInit(void){ return SQLITE_OK0; } | ||||
| 29937 | static int pthreadMutexEnd(void){ return SQLITE_OK0; } | ||||
| 29938 | |||||
| 29939 | /* | ||||
| 29940 | ** The sqlite3_mutex_alloc() routine allocates a new | ||||
| 29941 | ** mutex and returns a pointer to it. If it returns NULL | ||||
| 29942 | ** that means that a mutex could not be allocated. SQLite | ||||
| 29943 | ** will unwind its stack and return an error. The argument | ||||
| 29944 | ** to sqlite3_mutex_alloc() is one of these integer constants: | ||||
| 29945 | ** | ||||
| 29946 | ** <ul> | ||||
| 29947 | ** <li> SQLITE_MUTEX_FAST | ||||
| 29948 | ** <li> SQLITE_MUTEX_RECURSIVE | ||||
| 29949 | ** <li> SQLITE_MUTEX_STATIC_MAIN | ||||
| 29950 | ** <li> SQLITE_MUTEX_STATIC_MEM | ||||
| 29951 | ** <li> SQLITE_MUTEX_STATIC_OPEN | ||||
| 29952 | ** <li> SQLITE_MUTEX_STATIC_PRNG | ||||
| 29953 | ** <li> SQLITE_MUTEX_STATIC_LRU | ||||
| 29954 | ** <li> SQLITE_MUTEX_STATIC_PMEM | ||||
| 29955 | ** <li> SQLITE_MUTEX_STATIC_APP1 | ||||
| 29956 | ** <li> SQLITE_MUTEX_STATIC_APP2 | ||||
| 29957 | ** <li> SQLITE_MUTEX_STATIC_APP3 | ||||
| 29958 | ** <li> SQLITE_MUTEX_STATIC_VFS1 | ||||
| 29959 | ** <li> SQLITE_MUTEX_STATIC_VFS2 | ||||
| 29960 | ** <li> SQLITE_MUTEX_STATIC_VFS3 | ||||
| 29961 | ** </ul> | ||||
| 29962 | ** | ||||
| 29963 | ** The first two constants cause sqlite3_mutex_alloc() to create | ||||
| 29964 | ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE | ||||
| 29965 | ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. | ||||
| 29966 | ** The mutex implementation does not need to make a distinction | ||||
| 29967 | ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does | ||||
| 29968 | ** not want to. But SQLite will only request a recursive mutex in | ||||
| 29969 | ** cases where it really needs one. If a faster non-recursive mutex | ||||
| 29970 | ** implementation is available on the host platform, the mutex subsystem | ||||
| 29971 | ** might return such a mutex in response to SQLITE_MUTEX_FAST. | ||||
| 29972 | ** | ||||
| 29973 | ** The other allowed parameters to sqlite3_mutex_alloc() each return | ||||
| 29974 | ** a pointer to a static preexisting mutex. Six static mutexes are | ||||
| 29975 | ** used by the current version of SQLite. Future versions of SQLite | ||||
| 29976 | ** may add additional static mutexes. Static mutexes are for internal | ||||
| 29977 | ** use by SQLite only. Applications that use SQLite mutexes should | ||||
| 29978 | ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or | ||||
| 29979 | ** SQLITE_MUTEX_RECURSIVE. | ||||
| 29980 | ** | ||||
| 29981 | ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST | ||||
| 29982 | ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() | ||||
| 29983 | ** returns a different mutex on every call. But for the static | ||||
| 29984 | ** mutex types, the same mutex is returned on every call that has | ||||
| 29985 | ** the same type number. | ||||
| 29986 | */ | ||||
| 29987 | static sqlite3_mutex *pthreadMutexAlloc(int iType){ | ||||
| 29988 | static sqlite3_mutex staticMutexes[] = { | ||||
| 29989 | SQLITE3_MUTEX_INITIALIZER(2){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 2 }, | ||||
| 29990 | SQLITE3_MUTEX_INITIALIZER(3){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 3 }, | ||||
| 29991 | SQLITE3_MUTEX_INITIALIZER(4){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 4 }, | ||||
| 29992 | SQLITE3_MUTEX_INITIALIZER(5){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 5 }, | ||||
| 29993 | SQLITE3_MUTEX_INITIALIZER(6){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 6 }, | ||||
| 29994 | SQLITE3_MUTEX_INITIALIZER(7){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 7 }, | ||||
| 29995 | SQLITE3_MUTEX_INITIALIZER(8){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 8 }, | ||||
| 29996 | SQLITE3_MUTEX_INITIALIZER(9){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 9 }, | ||||
| 29997 | SQLITE3_MUTEX_INITIALIZER(10){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 10 }, | ||||
| 29998 | SQLITE3_MUTEX_INITIALIZER(11){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 11 }, | ||||
| 29999 | SQLITE3_MUTEX_INITIALIZER(12){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 12 }, | ||||
| 30000 | SQLITE3_MUTEX_INITIALIZER(13){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 13 } | ||||
| 30001 | }; | ||||
| 30002 | sqlite3_mutex *p; | ||||
| 30003 | switch( iType ){ | ||||
| 30004 | case SQLITE_MUTEX_RECURSIVE1: { | ||||
| 30005 | p = sqlite3MallocZero( sizeof(*p) ); | ||||
| 30006 | if( p ){ | ||||
| 30007 | #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX | ||||
| 30008 | /* If recursive mutexes are not available, we will have to | ||||
| 30009 | ** build our own. See below. */ | ||||
| 30010 | pthread_mutex_init(&p->mutex, 0); | ||||
| 30011 | #else | ||||
| 30012 | /* Use a recursive mutex if it is available */ | ||||
| 30013 | pthread_mutexattr_t recursiveAttr; | ||||
| 30014 | pthread_mutexattr_init(&recursiveAttr); | ||||
| 30015 | pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE); | ||||
| 30016 | pthread_mutex_init(&p->mutex, &recursiveAttr); | ||||
| 30017 | pthread_mutexattr_destroy(&recursiveAttr); | ||||
| 30018 | #endif | ||||
| 30019 | #if SQLITE_MUTEX_NREF0 || defined(SQLITE_ENABLE_API_ARMOR1) | ||||
| 30020 | p->id = SQLITE_MUTEX_RECURSIVE1; | ||||
| 30021 | #endif | ||||
| 30022 | } | ||||
| 30023 | break; | ||||
| 30024 | } | ||||
| 30025 | case SQLITE_MUTEX_FAST0: { | ||||
| 30026 | p = sqlite3MallocZero( sizeof(*p) ); | ||||
| 30027 | if( p ){ | ||||
| 30028 | pthread_mutex_init(&p->mutex, 0); | ||||
| 30029 | #if SQLITE_MUTEX_NREF0 || defined(SQLITE_ENABLE_API_ARMOR1) | ||||
| 30030 | p->id = SQLITE_MUTEX_FAST0; | ||||
| 30031 | #endif | ||||
| 30032 | } | ||||
| 30033 | break; | ||||
| 30034 | } | ||||
| 30035 | default: { | ||||
| 30036 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 30037 | if( iType-2<0 || iType-2>=ArraySize(staticMutexes)((int)(sizeof(staticMutexes)/sizeof(staticMutexes[0]))) ){ | ||||
| 30038 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(30038); | ||||
| 30039 | return 0; | ||||
| 30040 | } | ||||
| 30041 | #endif | ||||
| 30042 | p = &staticMutexes[iType-2]; | ||||
| 30043 | break; | ||||
| 30044 | } | ||||
| 30045 | } | ||||
| 30046 | #if SQLITE_MUTEX_NREF0 || defined(SQLITE_ENABLE_API_ARMOR1) | ||||
| 30047 | assert( p==0 || p->id==iType )((void) (0)); | ||||
| 30048 | #endif | ||||
| 30049 | return p; | ||||
| 30050 | } | ||||
| 30051 | |||||
| 30052 | |||||
| 30053 | /* | ||||
| 30054 | ** This routine deallocates a previously | ||||
| 30055 | ** allocated mutex. SQLite is careful to deallocate every | ||||
| 30056 | ** mutex that it allocates. | ||||
| 30057 | */ | ||||
| 30058 | static void pthreadMutexFree(sqlite3_mutex *p){ | ||||
| 30059 | assert( p->nRef==0 )((void) (0)); | ||||
| 30060 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 30061 | if( p->id==SQLITE_MUTEX_FAST0 || p->id==SQLITE_MUTEX_RECURSIVE1 ) | ||||
| 30062 | #endif | ||||
| 30063 | { | ||||
| 30064 | pthread_mutex_destroy(&p->mutex); | ||||
| 30065 | sqlite3_free(p); | ||||
| 30066 | } | ||||
| 30067 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 30068 | else{ | ||||
| 30069 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(30069); | ||||
| 30070 | } | ||||
| 30071 | #endif | ||||
| 30072 | } | ||||
| 30073 | |||||
| 30074 | /* | ||||
| 30075 | ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt | ||||
| 30076 | ** to enter a mutex. If another thread is already within the mutex, | ||||
| 30077 | ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return | ||||
| 30078 | ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK | ||||
| 30079 | ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can | ||||
| 30080 | ** be entered multiple times by the same thread. In such cases the, | ||||
| 30081 | ** mutex must be exited an equal number of times before another thread | ||||
| 30082 | ** can enter. If the same thread tries to enter any other kind of mutex | ||||
| 30083 | ** more than once, the behavior is undefined. | ||||
| 30084 | */ | ||||
| 30085 | static void pthreadMutexEnter(sqlite3_mutex *p){ | ||||
| 30086 | assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) )((void) (0)); | ||||
| 30087 | |||||
| 30088 | #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX | ||||
| 30089 | /* If recursive mutexes are not available, then we have to grow | ||||
| 30090 | ** our own. This implementation assumes that pthread_equal() | ||||
| 30091 | ** is atomic - that it cannot be deceived into thinking self | ||||
| 30092 | ** and p->owner are equal if p->owner changes between two values | ||||
| 30093 | ** that are not equal to self while the comparison is taking place. | ||||
| 30094 | ** This implementation also assumes a coherent cache - that | ||||
| 30095 | ** separate processes cannot read different values from the same | ||||
| 30096 | ** address at the same time. If either of these two conditions | ||||
| 30097 | ** are not met, then the mutexes will fail and problems will result. | ||||
| 30098 | */ | ||||
| 30099 | { | ||||
| 30100 | pthread_t self = pthread_self(); | ||||
| 30101 | if( p->nRef>0 && pthread_equal(p->owner, self) ){ | ||||
| 30102 | p->nRef++; | ||||
| 30103 | }else{ | ||||
| 30104 | pthread_mutex_lock(&p->mutex); | ||||
| 30105 | assert( p->nRef==0 )((void) (0)); | ||||
| 30106 | p->owner = self; | ||||
| 30107 | p->nRef = 1; | ||||
| 30108 | } | ||||
| 30109 | } | ||||
| 30110 | #else | ||||
| 30111 | /* Use the built-in recursive mutexes if they are available. | ||||
| 30112 | */ | ||||
| 30113 | pthread_mutex_lock(&p->mutex); | ||||
| 30114 | #if SQLITE_MUTEX_NREF0 | ||||
| 30115 | assert( p->nRef>0 || p->owner==0 )((void) (0)); | ||||
| 30116 | p->owner = pthread_self(); | ||||
| 30117 | p->nRef++; | ||||
| 30118 | #endif | ||||
| 30119 | #endif | ||||
| 30120 | |||||
| 30121 | #ifdef SQLITE_DEBUG | ||||
| 30122 | if( p->trace ){ | ||||
| 30123 | printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); | ||||
| 30124 | } | ||||
| 30125 | #endif | ||||
| 30126 | } | ||||
| 30127 | static int pthreadMutexTry(sqlite3_mutex *p){ | ||||
| 30128 | int rc; | ||||
| 30129 | assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) )((void) (0)); | ||||
| 30130 | |||||
| 30131 | #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX | ||||
| 30132 | /* If recursive mutexes are not available, then we have to grow | ||||
| 30133 | ** our own. This implementation assumes that pthread_equal() | ||||
| 30134 | ** is atomic - that it cannot be deceived into thinking self | ||||
| 30135 | ** and p->owner are equal if p->owner changes between two values | ||||
| 30136 | ** that are not equal to self while the comparison is taking place. | ||||
| 30137 | ** This implementation also assumes a coherent cache - that | ||||
| 30138 | ** separate processes cannot read different values from the same | ||||
| 30139 | ** address at the same time. If either of these two conditions | ||||
| 30140 | ** are not met, then the mutexes will fail and problems will result. | ||||
| 30141 | */ | ||||
| 30142 | { | ||||
| 30143 | pthread_t self = pthread_self(); | ||||
| 30144 | if( p->nRef>0 && pthread_equal(p->owner, self) ){ | ||||
| 30145 | p->nRef++; | ||||
| 30146 | rc = SQLITE_OK0; | ||||
| 30147 | }else if( pthread_mutex_trylock(&p->mutex)==0 ){ | ||||
| 30148 | assert( p->nRef==0 )((void) (0)); | ||||
| 30149 | p->owner = self; | ||||
| 30150 | p->nRef = 1; | ||||
| 30151 | rc = SQLITE_OK0; | ||||
| 30152 | }else{ | ||||
| 30153 | rc = SQLITE_BUSY5; | ||||
| 30154 | } | ||||
| 30155 | } | ||||
| 30156 | #else | ||||
| 30157 | /* Use the built-in recursive mutexes if they are available. | ||||
| 30158 | */ | ||||
| 30159 | if( pthread_mutex_trylock(&p->mutex)==0 ){ | ||||
| 30160 | #if SQLITE_MUTEX_NREF0 | ||||
| 30161 | p->owner = pthread_self(); | ||||
| 30162 | p->nRef++; | ||||
| 30163 | #endif | ||||
| 30164 | rc = SQLITE_OK0; | ||||
| 30165 | }else{ | ||||
| 30166 | rc = SQLITE_BUSY5; | ||||
| 30167 | } | ||||
| 30168 | #endif | ||||
| 30169 | |||||
| 30170 | #ifdef SQLITE_DEBUG | ||||
| 30171 | if( rc==SQLITE_OK0 && p->trace ){ | ||||
| 30172 | printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); | ||||
| 30173 | } | ||||
| 30174 | #endif | ||||
| 30175 | return rc; | ||||
| 30176 | } | ||||
| 30177 | |||||
| 30178 | /* | ||||
| 30179 | ** The sqlite3_mutex_leave() routine exits a mutex that was | ||||
| 30180 | ** previously entered by the same thread. The behavior | ||||
| 30181 | ** is undefined if the mutex is not currently entered or | ||||
| 30182 | ** is not currently allocated. SQLite will never do either. | ||||
| 30183 | */ | ||||
| 30184 | static void pthreadMutexLeave(sqlite3_mutex *p){ | ||||
| 30185 | assert( pthreadMutexHeld(p) )((void) (0)); | ||||
| 30186 | #if SQLITE_MUTEX_NREF0 | ||||
| 30187 | p->nRef--; | ||||
| 30188 | if( p->nRef==0 ) p->owner = 0; | ||||
| 30189 | #endif | ||||
| 30190 | assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE )((void) (0)); | ||||
| 30191 | |||||
| 30192 | #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX | ||||
| 30193 | if( p->nRef==0 ){ | ||||
| 30194 | pthread_mutex_unlock(&p->mutex); | ||||
| 30195 | } | ||||
| 30196 | #else | ||||
| 30197 | pthread_mutex_unlock(&p->mutex); | ||||
| 30198 | #endif | ||||
| 30199 | |||||
| 30200 | #ifdef SQLITE_DEBUG | ||||
| 30201 | if( p->trace ){ | ||||
| 30202 | printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); | ||||
| 30203 | } | ||||
| 30204 | #endif | ||||
| 30205 | } | ||||
| 30206 | |||||
| 30207 | SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ | ||||
| 30208 | static const sqlite3_mutex_methods sMutex = { | ||||
| 30209 | pthreadMutexInit, | ||||
| 30210 | pthreadMutexEnd, | ||||
| 30211 | pthreadMutexAlloc, | ||||
| 30212 | pthreadMutexFree, | ||||
| 30213 | pthreadMutexEnter, | ||||
| 30214 | pthreadMutexTry, | ||||
| 30215 | pthreadMutexLeave, | ||||
| 30216 | #ifdef SQLITE_DEBUG | ||||
| 30217 | pthreadMutexHeld, | ||||
| 30218 | pthreadMutexNotheld | ||||
| 30219 | #else | ||||
| 30220 | 0, | ||||
| 30221 | 0 | ||||
| 30222 | #endif | ||||
| 30223 | }; | ||||
| 30224 | |||||
| 30225 | return &sMutex; | ||||
| 30226 | } | ||||
| 30227 | |||||
| 30228 | #endif /* SQLITE_MUTEX_PTHREADS */ | ||||
| 30229 | |||||
| 30230 | /************** End of mutex_unix.c ******************************************/ | ||||
| 30231 | /************** Begin file mutex_w32.c ***************************************/ | ||||
| 30232 | /* | ||||
| 30233 | ** 2007 August 14 | ||||
| 30234 | ** | ||||
| 30235 | ** The author disclaims copyright to this source code. In place of | ||||
| 30236 | ** a legal notice, here is a blessing: | ||||
| 30237 | ** | ||||
| 30238 | ** May you do good and not evil. | ||||
| 30239 | ** May you find forgiveness for yourself and forgive others. | ||||
| 30240 | ** May you share freely, never taking more than you give. | ||||
| 30241 | ** | ||||
| 30242 | ************************************************************************* | ||||
| 30243 | ** This file contains the C functions that implement mutexes for Win32. | ||||
| 30244 | */ | ||||
| 30245 | /* #include "sqliteInt.h" */ | ||||
| 30246 | |||||
| 30247 | #if SQLITE_OS_WIN0 | ||||
| 30248 | /* | ||||
| 30249 | ** Include code that is common to all os_*.c files | ||||
| 30250 | */ | ||||
| 30251 | /* #include "os_common.h" */ | ||||
| 30252 | |||||
| 30253 | /* | ||||
| 30254 | ** Include the header file for the Windows VFS. | ||||
| 30255 | */ | ||||
| 30256 | /************** Include os_win.h in the middle of mutex_w32.c ****************/ | ||||
| 30257 | /************** Begin file os_win.h ******************************************/ | ||||
| 30258 | /* | ||||
| 30259 | ** 2013 November 25 | ||||
| 30260 | ** | ||||
| 30261 | ** The author disclaims copyright to this source code. In place of | ||||
| 30262 | ** a legal notice, here is a blessing: | ||||
| 30263 | ** | ||||
| 30264 | ** May you do good and not evil. | ||||
| 30265 | ** May you find forgiveness for yourself and forgive others. | ||||
| 30266 | ** May you share freely, never taking more than you give. | ||||
| 30267 | ** | ||||
| 30268 | ****************************************************************************** | ||||
| 30269 | ** | ||||
| 30270 | ** This file contains code that is specific to Windows. | ||||
| 30271 | */ | ||||
| 30272 | #ifndef SQLITE_OS_WIN_H | ||||
| 30273 | #define SQLITE_OS_WIN_H | ||||
| 30274 | |||||
| 30275 | /* | ||||
| 30276 | ** Include the primary Windows SDK header file. | ||||
| 30277 | */ | ||||
| 30278 | #include "windows.h" | ||||
| 30279 | |||||
| 30280 | #ifdef __CYGWIN__ | ||||
| 30281 | # include <sys/cygwin.h> | ||||
| 30282 | # include <sys/stat.h> /* amalgamator: dontcache */ | ||||
| 30283 | # include <unistd.h> /* amalgamator: dontcache */ | ||||
| 30284 | # include <errno(*__errno_location ()).h> /* amalgamator: dontcache */ | ||||
| 30285 | #endif | ||||
| 30286 | |||||
| 30287 | /* | ||||
| 30288 | ** Determine if we are dealing with Windows NT. | ||||
| 30289 | ** | ||||
| 30290 | ** We ought to be able to determine if we are compiling for Windows 9x or | ||||
| 30291 | ** Windows NT using the _WIN32_WINNT macro as follows: | ||||
| 30292 | ** | ||||
| 30293 | ** #if defined(_WIN32_WINNT) | ||||
| 30294 | ** # define SQLITE_OS_WINNT 1 | ||||
| 30295 | ** #else | ||||
| 30296 | ** # define SQLITE_OS_WINNT 0 | ||||
| 30297 | ** #endif | ||||
| 30298 | ** | ||||
| 30299 | ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as | ||||
| 30300 | ** it ought to, so the above test does not work. We'll just assume that | ||||
| 30301 | ** everything is Windows NT unless the programmer explicitly says otherwise | ||||
| 30302 | ** by setting SQLITE_OS_WINNT to 0. | ||||
| 30303 | */ | ||||
| 30304 | #if SQLITE_OS_WIN0 && !defined(SQLITE_OS_WINNT) | ||||
| 30305 | # define SQLITE_OS_WINNT 1 | ||||
| 30306 | #endif | ||||
| 30307 | |||||
| 30308 | /* | ||||
| 30309 | ** Determine if we are dealing with Windows CE - which has a much reduced | ||||
| 30310 | ** API. | ||||
| 30311 | */ | ||||
| 30312 | #if defined(_WIN32_WCE) | ||||
| 30313 | # define SQLITE_OS_WINCE 1 | ||||
| 30314 | #else | ||||
| 30315 | # define SQLITE_OS_WINCE 0 | ||||
| 30316 | #endif | ||||
| 30317 | |||||
| 30318 | /* | ||||
| 30319 | ** Determine if we are dealing with WinRT, which provides only a subset of | ||||
| 30320 | ** the full Win32 API. | ||||
| 30321 | */ | ||||
| 30322 | #if !defined(SQLITE_OS_WINRT) | ||||
| 30323 | # define SQLITE_OS_WINRT 0 | ||||
| 30324 | #endif | ||||
| 30325 | |||||
| 30326 | /* | ||||
| 30327 | ** For WinCE, some API function parameters do not appear to be declared as | ||||
| 30328 | ** volatile. | ||||
| 30329 | */ | ||||
| 30330 | #if SQLITE_OS_WINCE | ||||
| 30331 | # define SQLITE_WIN32_VOLATILE | ||||
| 30332 | #else | ||||
| 30333 | # define SQLITE_WIN32_VOLATILE volatile | ||||
| 30334 | #endif | ||||
| 30335 | |||||
| 30336 | /* | ||||
| 30337 | ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex() | ||||
| 30338 | ** functions are not available (e.g. those not using MSVC, Cygwin, etc). | ||||
| 30339 | */ | ||||
| 30340 | #if SQLITE_OS_WIN0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ | ||||
| 30341 | SQLITE_THREADSAFE2>0 && !defined(__CYGWIN__) | ||||
| 30342 | # define SQLITE_OS_WIN_THREADS 1 | ||||
| 30343 | #else | ||||
| 30344 | # define SQLITE_OS_WIN_THREADS 0 | ||||
| 30345 | #endif | ||||
| 30346 | |||||
| 30347 | #endif /* SQLITE_OS_WIN_H */ | ||||
| 30348 | |||||
| 30349 | /************** End of os_win.h **********************************************/ | ||||
| 30350 | /************** Continuing where we left off in mutex_w32.c ******************/ | ||||
| 30351 | #endif | ||||
| 30352 | |||||
| 30353 | /* | ||||
| 30354 | ** The code in this file is only used if we are compiling multithreaded | ||||
| 30355 | ** on a Win32 system. | ||||
| 30356 | */ | ||||
| 30357 | #ifdef SQLITE_MUTEX_W32 | ||||
| 30358 | |||||
| 30359 | /* | ||||
| 30360 | ** Each recursive mutex is an instance of the following structure. | ||||
| 30361 | */ | ||||
| 30362 | struct sqlite3_mutex { | ||||
| 30363 | CRITICAL_SECTION mutex; /* Mutex controlling the lock */ | ||||
| 30364 | int id; /* Mutex type */ | ||||
| 30365 | #ifdef SQLITE_DEBUG | ||||
| 30366 | volatile int nRef; /* Number of entrances */ | ||||
| 30367 | volatile DWORD owner; /* Thread holding this mutex */ | ||||
| 30368 | volatile LONG trace; /* True to trace changes */ | ||||
| 30369 | #endif | ||||
| 30370 | }; | ||||
| 30371 | |||||
| 30372 | /* | ||||
| 30373 | ** These are the initializer values used when declaring a "static" mutex | ||||
| 30374 | ** on Win32. It should be noted that all mutexes require initialization | ||||
| 30375 | ** on the Win32 platform. | ||||
| 30376 | */ | ||||
| 30377 | #define SQLITE_W32_MUTEX_INITIALIZER { 0 } | ||||
| 30378 | |||||
| 30379 | #ifdef SQLITE_DEBUG | ||||
| 30380 | #define SQLITE3_MUTEX_INITIALIZER(id){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, id } { SQLITE_W32_MUTEX_INITIALIZER, id, \ | ||||
| 30381 | 0L, (DWORD)0, 0 } | ||||
| 30382 | #else | ||||
| 30383 | #define SQLITE3_MUTEX_INITIALIZER(id){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, id } { SQLITE_W32_MUTEX_INITIALIZER, id } | ||||
| 30384 | #endif | ||||
| 30385 | |||||
| 30386 | #ifdef SQLITE_DEBUG | ||||
| 30387 | /* | ||||
| 30388 | ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are | ||||
| 30389 | ** intended for use only inside assert() statements. | ||||
| 30390 | */ | ||||
| 30391 | static int winMutexHeld(sqlite3_mutex *p){ | ||||
| 30392 | return p->nRef!=0 && p->owner==GetCurrentThreadId(); | ||||
| 30393 | } | ||||
| 30394 | |||||
| 30395 | static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ | ||||
| 30396 | return p->nRef==0 || p->owner!=tid; | ||||
| 30397 | } | ||||
| 30398 | |||||
| 30399 | static int winMutexNotheld(sqlite3_mutex *p){ | ||||
| 30400 | DWORD tid = GetCurrentThreadId(); | ||||
| 30401 | return winMutexNotheld2(p, tid); | ||||
| 30402 | } | ||||
| 30403 | #endif | ||||
| 30404 | |||||
| 30405 | /* | ||||
| 30406 | ** Try to provide a memory barrier operation, needed for initialization | ||||
| 30407 | ** and also for the xShmBarrier method of the VFS in cases when SQLite is | ||||
| 30408 | ** compiled without mutexes (SQLITE_THREADSAFE=0). | ||||
| 30409 | */ | ||||
| 30410 | SQLITE_PRIVATEstatic void sqlite3MemoryBarrier(void){ | ||||
| 30411 | #if defined(SQLITE_MEMORY_BARRIER) | ||||
| 30412 | SQLITE_MEMORY_BARRIER; | ||||
| 30413 | #elif defined(__GNUC__4) | ||||
| 30414 | __sync_synchronize(); | ||||
| 30415 | #elif MSVC_VERSION0>=1400 | ||||
| 30416 | _ReadWriteBarrier(); | ||||
| 30417 | #elif defined(MemoryBarrier) | ||||
| 30418 | MemoryBarrier(); | ||||
| 30419 | #endif | ||||
| 30420 | } | ||||
| 30421 | |||||
| 30422 | /* | ||||
| 30423 | ** Initialize and deinitialize the mutex subsystem. | ||||
| 30424 | */ | ||||
| 30425 | static sqlite3_mutex winMutex_staticMutexes[] = { | ||||
| 30426 | SQLITE3_MUTEX_INITIALIZER(2){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 2 }, | ||||
| 30427 | SQLITE3_MUTEX_INITIALIZER(3){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 3 }, | ||||
| 30428 | SQLITE3_MUTEX_INITIALIZER(4){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 4 }, | ||||
| 30429 | SQLITE3_MUTEX_INITIALIZER(5){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 5 }, | ||||
| 30430 | SQLITE3_MUTEX_INITIALIZER(6){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 6 }, | ||||
| 30431 | SQLITE3_MUTEX_INITIALIZER(7){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 7 }, | ||||
| 30432 | SQLITE3_MUTEX_INITIALIZER(8){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 8 }, | ||||
| 30433 | SQLITE3_MUTEX_INITIALIZER(9){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 9 }, | ||||
| 30434 | SQLITE3_MUTEX_INITIALIZER(10){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 10 }, | ||||
| 30435 | SQLITE3_MUTEX_INITIALIZER(11){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 11 }, | ||||
| 30436 | SQLITE3_MUTEX_INITIALIZER(12){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 12 }, | ||||
| 30437 | SQLITE3_MUTEX_INITIALIZER(13){ { { 0, 0, 0, 0, PTHREAD_MUTEX_TIMED_NP, 0, 0, { 0, 0 } } }, 13 } | ||||
| 30438 | }; | ||||
| 30439 | |||||
| 30440 | static int winMutex_isInit = 0; | ||||
| 30441 | static int winMutex_isNt = -1; /* <0 means "need to query" */ | ||||
| 30442 | |||||
| 30443 | /* As the winMutexInit() and winMutexEnd() functions are called as part | ||||
| 30444 | ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the | ||||
| 30445 | ** "interlocked" magic used here is probably not strictly necessary. | ||||
| 30446 | */ | ||||
| 30447 | static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0; | ||||
| 30448 | |||||
| 30449 | SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */ | ||||
| 30450 | SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ | ||||
| 30451 | |||||
| 30452 | static int winMutexInit(void){ | ||||
| 30453 | /* The first to increment to 1 does actual initialization */ | ||||
| 30454 | if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){ | ||||
| 30455 | int i; | ||||
| 30456 | for(i=0; i<ArraySize(winMutex_staticMutexes)((int)(sizeof(winMutex_staticMutexes)/sizeof(winMutex_staticMutexes [0]))); i++){ | ||||
| 30457 | #if SQLITE_OS_WINRT | ||||
| 30458 | InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0); | ||||
| 30459 | #else | ||||
| 30460 | InitializeCriticalSection(&winMutex_staticMutexes[i].mutex); | ||||
| 30461 | #endif | ||||
| 30462 | } | ||||
| 30463 | winMutex_isInit = 1; | ||||
| 30464 | }else{ | ||||
| 30465 | /* Another thread is (in the process of) initializing the static | ||||
| 30466 | ** mutexes */ | ||||
| 30467 | while( !winMutex_isInit ){ | ||||
| 30468 | sqlite3_win32_sleep(1); | ||||
| 30469 | } | ||||
| 30470 | } | ||||
| 30471 | return SQLITE_OK0; | ||||
| 30472 | } | ||||
| 30473 | |||||
| 30474 | static int winMutexEnd(void){ | ||||
| 30475 | /* The first to decrement to 0 does actual shutdown | ||||
| 30476 | ** (which should be the last to shutdown.) */ | ||||
| 30477 | if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){ | ||||
| 30478 | if( winMutex_isInit==1 ){ | ||||
| 30479 | int i; | ||||
| 30480 | for(i=0; i<ArraySize(winMutex_staticMutexes)((int)(sizeof(winMutex_staticMutexes)/sizeof(winMutex_staticMutexes [0]))); i++){ | ||||
| 30481 | DeleteCriticalSection(&winMutex_staticMutexes[i].mutex); | ||||
| 30482 | } | ||||
| 30483 | winMutex_isInit = 0; | ||||
| 30484 | } | ||||
| 30485 | } | ||||
| 30486 | return SQLITE_OK0; | ||||
| 30487 | } | ||||
| 30488 | |||||
| 30489 | /* | ||||
| 30490 | ** The sqlite3_mutex_alloc() routine allocates a new | ||||
| 30491 | ** mutex and returns a pointer to it. If it returns NULL | ||||
| 30492 | ** that means that a mutex could not be allocated. SQLite | ||||
| 30493 | ** will unwind its stack and return an error. The argument | ||||
| 30494 | ** to sqlite3_mutex_alloc() is one of these integer constants: | ||||
| 30495 | ** | ||||
| 30496 | ** <ul> | ||||
| 30497 | ** <li> SQLITE_MUTEX_FAST | ||||
| 30498 | ** <li> SQLITE_MUTEX_RECURSIVE | ||||
| 30499 | ** <li> SQLITE_MUTEX_STATIC_MAIN | ||||
| 30500 | ** <li> SQLITE_MUTEX_STATIC_MEM | ||||
| 30501 | ** <li> SQLITE_MUTEX_STATIC_OPEN | ||||
| 30502 | ** <li> SQLITE_MUTEX_STATIC_PRNG | ||||
| 30503 | ** <li> SQLITE_MUTEX_STATIC_LRU | ||||
| 30504 | ** <li> SQLITE_MUTEX_STATIC_PMEM | ||||
| 30505 | ** <li> SQLITE_MUTEX_STATIC_APP1 | ||||
| 30506 | ** <li> SQLITE_MUTEX_STATIC_APP2 | ||||
| 30507 | ** <li> SQLITE_MUTEX_STATIC_APP3 | ||||
| 30508 | ** <li> SQLITE_MUTEX_STATIC_VFS1 | ||||
| 30509 | ** <li> SQLITE_MUTEX_STATIC_VFS2 | ||||
| 30510 | ** <li> SQLITE_MUTEX_STATIC_VFS3 | ||||
| 30511 | ** </ul> | ||||
| 30512 | ** | ||||
| 30513 | ** The first two constants cause sqlite3_mutex_alloc() to create | ||||
| 30514 | ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE | ||||
| 30515 | ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. | ||||
| 30516 | ** The mutex implementation does not need to make a distinction | ||||
| 30517 | ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does | ||||
| 30518 | ** not want to. But SQLite will only request a recursive mutex in | ||||
| 30519 | ** cases where it really needs one. If a faster non-recursive mutex | ||||
| 30520 | ** implementation is available on the host platform, the mutex subsystem | ||||
| 30521 | ** might return such a mutex in response to SQLITE_MUTEX_FAST. | ||||
| 30522 | ** | ||||
| 30523 | ** The other allowed parameters to sqlite3_mutex_alloc() each return | ||||
| 30524 | ** a pointer to a static preexisting mutex. Six static mutexes are | ||||
| 30525 | ** used by the current version of SQLite. Future versions of SQLite | ||||
| 30526 | ** may add additional static mutexes. Static mutexes are for internal | ||||
| 30527 | ** use by SQLite only. Applications that use SQLite mutexes should | ||||
| 30528 | ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or | ||||
| 30529 | ** SQLITE_MUTEX_RECURSIVE. | ||||
| 30530 | ** | ||||
| 30531 | ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST | ||||
| 30532 | ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() | ||||
| 30533 | ** returns a different mutex on every call. But for the static | ||||
| 30534 | ** mutex types, the same mutex is returned on every call that has | ||||
| 30535 | ** the same type number. | ||||
| 30536 | */ | ||||
| 30537 | static sqlite3_mutex *winMutexAlloc(int iType){ | ||||
| 30538 | sqlite3_mutex *p; | ||||
| 30539 | |||||
| 30540 | switch( iType ){ | ||||
| 30541 | case SQLITE_MUTEX_FAST0: | ||||
| 30542 | case SQLITE_MUTEX_RECURSIVE1: { | ||||
| 30543 | p = sqlite3MallocZero( sizeof(*p) ); | ||||
| 30544 | if( p ){ | ||||
| 30545 | p->id = iType; | ||||
| 30546 | #ifdef SQLITE_DEBUG | ||||
| 30547 | #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC | ||||
| 30548 | p->trace = 1; | ||||
| 30549 | #endif | ||||
| 30550 | #endif | ||||
| 30551 | #if SQLITE_OS_WINRT | ||||
| 30552 | InitializeCriticalSectionEx(&p->mutex, 0, 0); | ||||
| 30553 | #else | ||||
| 30554 | InitializeCriticalSection(&p->mutex); | ||||
| 30555 | #endif | ||||
| 30556 | } | ||||
| 30557 | break; | ||||
| 30558 | } | ||||
| 30559 | default: { | ||||
| 30560 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 30561 | if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes)((int)(sizeof(winMutex_staticMutexes)/sizeof(winMutex_staticMutexes [0]))) ){ | ||||
| 30562 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(30562); | ||||
| 30563 | return 0; | ||||
| 30564 | } | ||||
| 30565 | #endif | ||||
| 30566 | p = &winMutex_staticMutexes[iType-2]; | ||||
| 30567 | #ifdef SQLITE_DEBUG | ||||
| 30568 | #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC | ||||
| 30569 | InterlockedCompareExchange(&p->trace, 1, 0); | ||||
| 30570 | #endif | ||||
| 30571 | #endif | ||||
| 30572 | break; | ||||
| 30573 | } | ||||
| 30574 | } | ||||
| 30575 | assert( p==0 || p->id==iType )((void) (0)); | ||||
| 30576 | return p; | ||||
| 30577 | } | ||||
| 30578 | |||||
| 30579 | |||||
| 30580 | /* | ||||
| 30581 | ** This routine deallocates a previously | ||||
| 30582 | ** allocated mutex. SQLite is careful to deallocate every | ||||
| 30583 | ** mutex that it allocates. | ||||
| 30584 | */ | ||||
| 30585 | static void winMutexFree(sqlite3_mutex *p){ | ||||
| 30586 | assert( p )((void) (0)); | ||||
| 30587 | assert( p->nRef==0 && p->owner==0 )((void) (0)); | ||||
| 30588 | if( p->id==SQLITE_MUTEX_FAST0 || p->id==SQLITE_MUTEX_RECURSIVE1 ){ | ||||
| 30589 | DeleteCriticalSection(&p->mutex); | ||||
| 30590 | sqlite3_free(p); | ||||
| 30591 | }else{ | ||||
| 30592 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 30593 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(30593); | ||||
| 30594 | #endif | ||||
| 30595 | } | ||||
| 30596 | } | ||||
| 30597 | |||||
| 30598 | /* | ||||
| 30599 | ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt | ||||
| 30600 | ** to enter a mutex. If another thread is already within the mutex, | ||||
| 30601 | ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return | ||||
| 30602 | ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK | ||||
| 30603 | ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can | ||||
| 30604 | ** be entered multiple times by the same thread. In such cases the, | ||||
| 30605 | ** mutex must be exited an equal number of times before another thread | ||||
| 30606 | ** can enter. If the same thread tries to enter any other kind of mutex | ||||
| 30607 | ** more than once, the behavior is undefined. | ||||
| 30608 | */ | ||||
| 30609 | static void winMutexEnter(sqlite3_mutex *p){ | ||||
| 30610 | #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) | ||||
| 30611 | DWORD tid = GetCurrentThreadId(); | ||||
| 30612 | #endif | ||||
| 30613 | #ifdef SQLITE_DEBUG | ||||
| 30614 | assert( p )((void) (0)); | ||||
| 30615 | assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) )((void) (0)); | ||||
| 30616 | #else | ||||
| 30617 | assert( p )((void) (0)); | ||||
| 30618 | #endif | ||||
| 30619 | assert( winMutex_isInit==1 )((void) (0)); | ||||
| 30620 | EnterCriticalSection(&p->mutex); | ||||
| 30621 | #ifdef SQLITE_DEBUG | ||||
| 30622 | assert( p->nRef>0 || p->owner==0 )((void) (0)); | ||||
| 30623 | p->owner = tid; | ||||
| 30624 | p->nRef++; | ||||
| 30625 | if( p->trace ){ | ||||
| 30626 | OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", | ||||
| 30627 | tid, p->id, p, p->trace, p->nRef)); | ||||
| 30628 | } | ||||
| 30629 | #endif | ||||
| 30630 | } | ||||
| 30631 | |||||
| 30632 | static int winMutexTry(sqlite3_mutex *p){ | ||||
| 30633 | #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) | ||||
| 30634 | DWORD tid = GetCurrentThreadId(); | ||||
| 30635 | #endif | ||||
| 30636 | int rc = SQLITE_BUSY5; | ||||
| 30637 | assert( p )((void) (0)); | ||||
| 30638 | assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) )((void) (0)); | ||||
| 30639 | /* | ||||
| 30640 | ** The sqlite3_mutex_try() routine is very rarely used, and when it | ||||
| 30641 | ** is used it is merely an optimization. So it is OK for it to always | ||||
| 30642 | ** fail. | ||||
| 30643 | ** | ||||
| 30644 | ** The TryEnterCriticalSection() interface is only available on WinNT. | ||||
| 30645 | ** And some windows compilers complain if you try to use it without | ||||
| 30646 | ** first doing some #defines that prevent SQLite from building on Win98. | ||||
| 30647 | ** For that reason, we will omit this optimization for now. See | ||||
| 30648 | ** ticket #2685. | ||||
| 30649 | */ | ||||
| 30650 | #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400 | ||||
| 30651 | assert( winMutex_isInit==1 )((void) (0)); | ||||
| 30652 | assert( winMutex_isNt>=-1 && winMutex_isNt<=1 )((void) (0)); | ||||
| 30653 | if( winMutex_isNt<0 ){ | ||||
| 30654 | winMutex_isNt = sqlite3_win32_is_nt(); | ||||
| 30655 | } | ||||
| 30656 | assert( winMutex_isNt==0 || winMutex_isNt==1 )((void) (0)); | ||||
| 30657 | if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){ | ||||
| 30658 | #ifdef SQLITE_DEBUG | ||||
| 30659 | p->owner = tid; | ||||
| 30660 | p->nRef++; | ||||
| 30661 | #endif | ||||
| 30662 | rc = SQLITE_OK0; | ||||
| 30663 | } | ||||
| 30664 | #else | ||||
| 30665 | UNUSED_PARAMETER(p)(void)(p); | ||||
| 30666 | #endif | ||||
| 30667 | #ifdef SQLITE_DEBUG | ||||
| 30668 | if( p->trace ){ | ||||
| 30669 | OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n", | ||||
| 30670 | tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc))); | ||||
| 30671 | } | ||||
| 30672 | #endif | ||||
| 30673 | return rc; | ||||
| 30674 | } | ||||
| 30675 | |||||
| 30676 | /* | ||||
| 30677 | ** The sqlite3_mutex_leave() routine exits a mutex that was | ||||
| 30678 | ** previously entered by the same thread. The behavior | ||||
| 30679 | ** is undefined if the mutex is not currently entered or | ||||
| 30680 | ** is not currently allocated. SQLite will never do either. | ||||
| 30681 | */ | ||||
| 30682 | static void winMutexLeave(sqlite3_mutex *p){ | ||||
| 30683 | #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) | ||||
| 30684 | DWORD tid = GetCurrentThreadId(); | ||||
| 30685 | #endif | ||||
| 30686 | assert( p )((void) (0)); | ||||
| 30687 | #ifdef SQLITE_DEBUG | ||||
| 30688 | assert( p->nRef>0 )((void) (0)); | ||||
| 30689 | assert( p->owner==tid )((void) (0)); | ||||
| 30690 | p->nRef--; | ||||
| 30691 | if( p->nRef==0 ) p->owner = 0; | ||||
| 30692 | assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE )((void) (0)); | ||||
| 30693 | #endif | ||||
| 30694 | assert( winMutex_isInit==1 )((void) (0)); | ||||
| 30695 | LeaveCriticalSection(&p->mutex); | ||||
| 30696 | #ifdef SQLITE_DEBUG | ||||
| 30697 | if( p->trace ){ | ||||
| 30698 | OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", | ||||
| 30699 | tid, p->id, p, p->trace, p->nRef)); | ||||
| 30700 | } | ||||
| 30701 | #endif | ||||
| 30702 | } | ||||
| 30703 | |||||
| 30704 | SQLITE_PRIVATEstatic sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ | ||||
| 30705 | static const sqlite3_mutex_methods sMutex = { | ||||
| 30706 | winMutexInit, | ||||
| 30707 | winMutexEnd, | ||||
| 30708 | winMutexAlloc, | ||||
| 30709 | winMutexFree, | ||||
| 30710 | winMutexEnter, | ||||
| 30711 | winMutexTry, | ||||
| 30712 | winMutexLeave, | ||||
| 30713 | #ifdef SQLITE_DEBUG | ||||
| 30714 | winMutexHeld, | ||||
| 30715 | winMutexNotheld | ||||
| 30716 | #else | ||||
| 30717 | 0, | ||||
| 30718 | 0 | ||||
| 30719 | #endif | ||||
| 30720 | }; | ||||
| 30721 | return &sMutex; | ||||
| 30722 | } | ||||
| 30723 | |||||
| 30724 | #endif /* SQLITE_MUTEX_W32 */ | ||||
| 30725 | |||||
| 30726 | /************** End of mutex_w32.c *******************************************/ | ||||
| 30727 | /************** Begin file malloc.c ******************************************/ | ||||
| 30728 | /* | ||||
| 30729 | ** 2001 September 15 | ||||
| 30730 | ** | ||||
| 30731 | ** The author disclaims copyright to this source code. In place of | ||||
| 30732 | ** a legal notice, here is a blessing: | ||||
| 30733 | ** | ||||
| 30734 | ** May you do good and not evil. | ||||
| 30735 | ** May you find forgiveness for yourself and forgive others. | ||||
| 30736 | ** May you share freely, never taking more than you give. | ||||
| 30737 | ** | ||||
| 30738 | ************************************************************************* | ||||
| 30739 | ** | ||||
| 30740 | ** Memory allocation functions used throughout sqlite. | ||||
| 30741 | */ | ||||
| 30742 | /* #include "sqliteInt.h" */ | ||||
| 30743 | /* #include <stdarg.h> */ | ||||
| 30744 | |||||
| 30745 | /* | ||||
| 30746 | ** Attempt to release up to n bytes of non-essential memory currently | ||||
| 30747 | ** held by SQLite. An example of non-essential memory is memory used to | ||||
| 30748 | ** cache database pages that are not currently in use. | ||||
| 30749 | */ | ||||
| 30750 | SQLITE_API int sqlite3_release_memory(int n){ | ||||
| 30751 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 30752 | return sqlite3PcacheReleaseMemory(n); | ||||
| 30753 | #else | ||||
| 30754 | /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine | ||||
| 30755 | ** is a no-op returning zero if SQLite is not compiled with | ||||
| 30756 | ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */ | ||||
| 30757 | UNUSED_PARAMETER(n)(void)(n); | ||||
| 30758 | return 0; | ||||
| 30759 | #endif | ||||
| 30760 | } | ||||
| 30761 | |||||
| 30762 | /* | ||||
| 30763 | ** Default value of the hard heap limit. 0 means "no limit". | ||||
| 30764 | */ | ||||
| 30765 | #ifndef SQLITE_MAX_MEMORY0 | ||||
| 30766 | # define SQLITE_MAX_MEMORY0 0 | ||||
| 30767 | #endif | ||||
| 30768 | |||||
| 30769 | /* | ||||
| 30770 | ** State information local to the memory allocation subsystem. | ||||
| 30771 | */ | ||||
| 30772 | static SQLITE_WSD struct Mem0Global { | ||||
| 30773 | sqlite3_mutex *mutex; /* Mutex to serialize access */ | ||||
| 30774 | sqlite3_int64 alarmThreshold; /* The soft heap limit */ | ||||
| 30775 | sqlite3_int64 hardLimit; /* The hard upper bound on memory */ | ||||
| 30776 | |||||
| 30777 | /* | ||||
| 30778 | ** True if heap is nearly "full" where "full" is defined by the | ||||
| 30779 | ** sqlite3_soft_heap_limit() setting. | ||||
| 30780 | */ | ||||
| 30781 | int nearlyFull; | ||||
| 30782 | } mem0mem0 = { 0, SQLITE_MAX_MEMORY0, SQLITE_MAX_MEMORY0, 0 }; | ||||
| 30783 | |||||
| 30784 | #define mem0mem0 GLOBAL(struct Mem0Global, mem0)mem0 | ||||
| 30785 | |||||
| 30786 | /* | ||||
| 30787 | ** Return the memory allocator mutex. sqlite3_status() needs it. | ||||
| 30788 | */ | ||||
| 30789 | SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3MallocMutex(void){ | ||||
| 30790 | return mem0mem0.mutex; | ||||
| 30791 | } | ||||
| 30792 | |||||
| 30793 | #ifndef SQLITE_OMIT_DEPRECATED1 | ||||
| 30794 | /* | ||||
| 30795 | ** Deprecated external interface. It used to set an alarm callback | ||||
| 30796 | ** that was invoked when memory usage grew too large. Now it is a | ||||
| 30797 | ** no-op. | ||||
| 30798 | */ | ||||
| 30799 | SQLITE_API int sqlite3_memory_alarm( | ||||
| 30800 | void(*xCallback)(void *pArg, sqlite3_int64 used,int N), | ||||
| 30801 | void *pArg, | ||||
| 30802 | sqlite3_int64 iThreshold | ||||
| 30803 | ){ | ||||
| 30804 | (void)xCallback; | ||||
| 30805 | (void)pArg; | ||||
| 30806 | (void)iThreshold; | ||||
| 30807 | return SQLITE_OK0; | ||||
| 30808 | } | ||||
| 30809 | #endif | ||||
| 30810 | |||||
| 30811 | /* | ||||
| 30812 | ** Set the soft heap-size limit for the library. An argument of | ||||
| 30813 | ** zero disables the limit. A negative argument is a no-op used to | ||||
| 30814 | ** obtain the return value. | ||||
| 30815 | ** | ||||
| 30816 | ** The return value is the value of the heap limit just before this | ||||
| 30817 | ** interface was called. | ||||
| 30818 | ** | ||||
| 30819 | ** If the hard heap limit is enabled, then the soft heap limit cannot | ||||
| 30820 | ** be disabled nor raised above the hard heap limit. | ||||
| 30821 | */ | ||||
| 30822 | SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){ | ||||
| 30823 | sqlite3_int64 priorLimit; | ||||
| 30824 | sqlite3_int64 excess; | ||||
| 30825 | sqlite3_int64 nUsed; | ||||
| 30826 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 30827 | int rc = sqlite3_initialize(); | ||||
| 30828 | if( rc ) return -1; | ||||
| 30829 | #endif | ||||
| 30830 | sqlite3_mutex_enter(mem0mem0.mutex); | ||||
| 30831 | priorLimit = mem0mem0.alarmThreshold; | ||||
| 30832 | if( n<0 ){ | ||||
| 30833 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 30834 | return priorLimit; | ||||
| 30835 | } | ||||
| 30836 | if( mem0mem0.hardLimit>0 && (n>mem0mem0.hardLimit || n==0) ){ | ||||
| 30837 | n = mem0mem0.hardLimit; | ||||
| 30838 | } | ||||
| 30839 | mem0mem0.alarmThreshold = n; | ||||
| 30840 | nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED0); | ||||
| 30841 | AtomicStore(&mem0.nearlyFull, n>0 && n<=nUsed)__atomic_store_n((&mem0.nearlyFull),(n>0 && n<= nUsed),0); | ||||
| 30842 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 30843 | excess = sqlite3_memory_used() - n; | ||||
| 30844 | if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff)); | ||||
| 30845 | return priorLimit; | ||||
| 30846 | } | ||||
| 30847 | SQLITE_API void sqlite3_soft_heap_limit(int n){ | ||||
| 30848 | if( n<0 ) n = 0; | ||||
| 30849 | sqlite3_soft_heap_limit64(n); | ||||
| 30850 | } | ||||
| 30851 | |||||
| 30852 | /* | ||||
| 30853 | ** Set the hard heap-size limit for the library. An argument of zero | ||||
| 30854 | ** disables the hard heap limit. A negative argument is a no-op used | ||||
| 30855 | ** to obtain the return value without affecting the hard heap limit. | ||||
| 30856 | ** | ||||
| 30857 | ** The return value is the value of the hard heap limit just prior to | ||||
| 30858 | ** calling this interface. | ||||
| 30859 | ** | ||||
| 30860 | ** Setting the hard heap limit will also activate the soft heap limit | ||||
| 30861 | ** and constrain the soft heap limit to be no more than the hard heap | ||||
| 30862 | ** limit. | ||||
| 30863 | */ | ||||
| 30864 | SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){ | ||||
| 30865 | sqlite3_int64 priorLimit; | ||||
| 30866 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 30867 | int rc = sqlite3_initialize(); | ||||
| 30868 | if( rc ) return -1; | ||||
| 30869 | #endif | ||||
| 30870 | sqlite3_mutex_enter(mem0mem0.mutex); | ||||
| 30871 | priorLimit = mem0mem0.hardLimit; | ||||
| 30872 | if( n>=0 ){ | ||||
| 30873 | mem0mem0.hardLimit = n; | ||||
| 30874 | if( n<mem0mem0.alarmThreshold || mem0mem0.alarmThreshold==0 ){ | ||||
| 30875 | mem0mem0.alarmThreshold = n; | ||||
| 30876 | } | ||||
| 30877 | } | ||||
| 30878 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 30879 | return priorLimit; | ||||
| 30880 | } | ||||
| 30881 | |||||
| 30882 | |||||
| 30883 | /* | ||||
| 30884 | ** Initialize the memory allocation subsystem. | ||||
| 30885 | */ | ||||
| 30886 | SQLITE_PRIVATEstatic int sqlite3MallocInit(void){ | ||||
| 30887 | int rc; | ||||
| 30888 | if( sqlite3GlobalConfigsqlite3Config.m.xMalloc==0 ){ | ||||
| 30889 | sqlite3MemSetDefault(); | ||||
| 30890 | } | ||||
| 30891 | mem0mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM3); | ||||
| 30892 | if( sqlite3GlobalConfigsqlite3Config.pPage==0 || sqlite3GlobalConfigsqlite3Config.szPage<512 | ||||
| 30893 | || sqlite3GlobalConfigsqlite3Config.nPage<=0 ){ | ||||
| 30894 | sqlite3GlobalConfigsqlite3Config.pPage = 0; | ||||
| 30895 | sqlite3GlobalConfigsqlite3Config.szPage = 0; | ||||
| 30896 | } | ||||
| 30897 | rc = sqlite3GlobalConfigsqlite3Config.m.xInit(sqlite3GlobalConfigsqlite3Config.m.pAppData); | ||||
| 30898 | if( rc!=SQLITE_OK0 ) memset(&mem0mem0, 0, sizeof(mem0mem0)); | ||||
| 30899 | return rc; | ||||
| 30900 | } | ||||
| 30901 | |||||
| 30902 | /* | ||||
| 30903 | ** Return true if the heap is currently under memory pressure - in other | ||||
| 30904 | ** words if the amount of heap used is close to the limit set by | ||||
| 30905 | ** sqlite3_soft_heap_limit(). | ||||
| 30906 | */ | ||||
| 30907 | SQLITE_PRIVATEstatic int sqlite3HeapNearlyFull(void){ | ||||
| 30908 | return AtomicLoad(&mem0.nearlyFull)__atomic_load_n((&mem0.nearlyFull),0); | ||||
| 30909 | } | ||||
| 30910 | |||||
| 30911 | /* | ||||
| 30912 | ** Deinitialize the memory allocation subsystem. | ||||
| 30913 | */ | ||||
| 30914 | SQLITE_PRIVATEstatic void sqlite3MallocEnd(void){ | ||||
| 30915 | if( sqlite3GlobalConfigsqlite3Config.m.xShutdown ){ | ||||
| 30916 | sqlite3GlobalConfigsqlite3Config.m.xShutdown(sqlite3GlobalConfigsqlite3Config.m.pAppData); | ||||
| 30917 | } | ||||
| 30918 | memset(&mem0mem0, 0, sizeof(mem0mem0)); | ||||
| 30919 | } | ||||
| 30920 | |||||
| 30921 | /* | ||||
| 30922 | ** Return the amount of memory currently checked out. | ||||
| 30923 | */ | ||||
| 30924 | SQLITE_API sqlite3_int64 sqlite3_memory_used(void){ | ||||
| 30925 | sqlite3_int64 res, mx; | ||||
| 30926 | sqlite3_status64(SQLITE_STATUS_MEMORY_USED0, &res, &mx, 0); | ||||
| 30927 | return res; | ||||
| 30928 | } | ||||
| 30929 | |||||
| 30930 | /* | ||||
| 30931 | ** Return the maximum amount of memory that has ever been | ||||
| 30932 | ** checked out since either the beginning of this process | ||||
| 30933 | ** or since the most recent reset. | ||||
| 30934 | */ | ||||
| 30935 | SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ | ||||
| 30936 | sqlite3_int64 res, mx; | ||||
| 30937 | sqlite3_status64(SQLITE_STATUS_MEMORY_USED0, &res, &mx, resetFlag); | ||||
| 30938 | return mx; | ||||
| 30939 | } | ||||
| 30940 | |||||
| 30941 | /* | ||||
| 30942 | ** Trigger the alarm | ||||
| 30943 | */ | ||||
| 30944 | static void sqlite3MallocAlarm(int nByte){ | ||||
| 30945 | if( mem0mem0.alarmThreshold<=0 ) return; | ||||
| 30946 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 30947 | sqlite3_release_memory(nByte); | ||||
| 30948 | sqlite3_mutex_enter(mem0mem0.mutex); | ||||
| 30949 | } | ||||
| 30950 | |||||
| 30951 | #ifdef SQLITE_DEBUG | ||||
| 30952 | /* | ||||
| 30953 | ** This routine is called whenever an out-of-memory condition is seen, | ||||
| 30954 | ** It's only purpose to to serve as a breakpoint for gdb or similar | ||||
| 30955 | ** code debuggers when working on out-of-memory conditions, for example | ||||
| 30956 | ** caused by PRAGMA hard_heap_limit=N. | ||||
| 30957 | */ | ||||
| 30958 | static SQLITE_NOINLINE__attribute__((noinline)) void test_oom_breakpoint(u64 n){ | ||||
| 30959 | static u64 nOomFault = 0; | ||||
| 30960 | nOomFault += n; | ||||
| 30961 | /* The assert() is never reached in a human lifetime. It is here mostly | ||||
| 30962 | ** to prevent code optimizers from optimizing out this function. */ | ||||
| 30963 | assert( (nOomFault>>32) < 0xffffffff )((void) (0)); | ||||
| 30964 | } | ||||
| 30965 | #else | ||||
| 30966 | # define test_oom_breakpoint(X) /* No-op for production builds */ | ||||
| 30967 | #endif | ||||
| 30968 | |||||
| 30969 | /* | ||||
| 30970 | ** Do a memory allocation with statistics and alarms. Assume the | ||||
| 30971 | ** lock is already held. | ||||
| 30972 | */ | ||||
| 30973 | static void mallocWithAlarm(int n, void **pp){ | ||||
| 30974 | void *p; | ||||
| 30975 | int nFull; | ||||
| 30976 | assert( sqlite3_mutex_held(mem0.mutex) )((void) (0)); | ||||
| 30977 | assert( n>0 )((void) (0)); | ||||
| 30978 | |||||
| 30979 | /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal | ||||
| 30980 | ** implementation of malloc_good_size(), which must be called in debug | ||||
| 30981 | ** mode and specifically when the DMD "Dark Matter Detector" is enabled | ||||
| 30982 | ** or else a crash results. Hence, do not attempt to optimize out the | ||||
| 30983 | ** following xRoundup() call. */ | ||||
| 30984 | nFull = sqlite3GlobalConfigsqlite3Config.m.xRoundup(n); | ||||
| 30985 | |||||
| 30986 | sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE5, n); | ||||
| 30987 | if( mem0mem0.alarmThreshold>0 ){ | ||||
| 30988 | sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED0); | ||||
| 30989 | if( nUsed >= mem0mem0.alarmThreshold - nFull ){ | ||||
| 30990 | AtomicStore(&mem0.nearlyFull, 1)__atomic_store_n((&mem0.nearlyFull),(1),0); | ||||
| 30991 | sqlite3MallocAlarm(nFull); | ||||
| 30992 | if( mem0mem0.hardLimit ){ | ||||
| 30993 | nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED0); | ||||
| 30994 | if( nUsed >= mem0mem0.hardLimit - nFull ){ | ||||
| 30995 | test_oom_breakpoint(1); | ||||
| 30996 | *pp = 0; | ||||
| 30997 | return; | ||||
| 30998 | } | ||||
| 30999 | } | ||||
| 31000 | }else{ | ||||
| 31001 | AtomicStore(&mem0.nearlyFull, 0)__atomic_store_n((&mem0.nearlyFull),(0),0); | ||||
| 31002 | } | ||||
| 31003 | } | ||||
| 31004 | p = sqlite3GlobalConfigsqlite3Config.m.xMalloc(nFull); | ||||
| 31005 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 31006 | if( p==0 && mem0mem0.alarmThreshold>0 ){ | ||||
| 31007 | sqlite3MallocAlarm(nFull); | ||||
| 31008 | p = sqlite3GlobalConfigsqlite3Config.m.xMalloc(nFull); | ||||
| 31009 | } | ||||
| 31010 | #endif | ||||
| 31011 | if( p ){ | ||||
| 31012 | nFull = sqlite3MallocSize(p); | ||||
| 31013 | sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED0, nFull); | ||||
| 31014 | sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT9, 1); | ||||
| 31015 | } | ||||
| 31016 | *pp = p; | ||||
| 31017 | } | ||||
| 31018 | |||||
| 31019 | /* | ||||
| 31020 | ** Maximum size of any single memory allocation. | ||||
| 31021 | ** | ||||
| 31022 | ** This is not a limit on the total amount of memory used. This is | ||||
| 31023 | ** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc(). | ||||
| 31024 | ** | ||||
| 31025 | ** The upper bound is slightly less than 2GiB: 0x7ffffeff == 2,147,483,391 | ||||
| 31026 | ** This provides a 256-byte safety margin for defense against 32-bit | ||||
| 31027 | ** signed integer overflow bugs when computing memory allocation sizes. | ||||
| 31028 | ** Paranoid applications might want to reduce the maximum allocation size | ||||
| 31029 | ** further for an even larger safety margin. 0x3fffffff or 0x0fffffff | ||||
| 31030 | ** or even smaller would be reasonable upper bounds on the size of a memory | ||||
| 31031 | ** allocations for most applications. | ||||
| 31032 | */ | ||||
| 31033 | #ifndef SQLITE_MAX_ALLOCATION_SIZE2147483391 | ||||
| 31034 | # define SQLITE_MAX_ALLOCATION_SIZE2147483391 2147483391 | ||||
| 31035 | #endif | ||||
| 31036 | #if SQLITE_MAX_ALLOCATION_SIZE2147483391>2147483391 | ||||
| 31037 | # error Maximum size for SQLITE_MAX_ALLOCATION_SIZE2147483391 is 2147483391 | ||||
| 31038 | #endif | ||||
| 31039 | |||||
| 31040 | /* | ||||
| 31041 | ** Allocate memory. This routine is like sqlite3_malloc() except that it | ||||
| 31042 | ** assumes the memory subsystem has already been initialized. | ||||
| 31043 | */ | ||||
| 31044 | SQLITE_PRIVATEstatic void *sqlite3Malloc(u64 n){ | ||||
| 31045 | void *p; | ||||
| 31046 | if( n==0 || n>SQLITE_MAX_ALLOCATION_SIZE2147483391 ){ | ||||
| 31047 | p = 0; | ||||
| 31048 | }else if( sqlite3GlobalConfigsqlite3Config.bMemstat ){ | ||||
| 31049 | sqlite3_mutex_enter(mem0mem0.mutex); | ||||
| 31050 | mallocWithAlarm((int)n, &p); | ||||
| 31051 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 31052 | }else{ | ||||
| 31053 | p = sqlite3GlobalConfigsqlite3Config.m.xMalloc((int)n); | ||||
| 31054 | } | ||||
| 31055 | assert( EIGHT_BYTE_ALIGNMENT(p) )((void) (0)); /* IMP: R-11148-40995 */ | ||||
| 31056 | return p; | ||||
| 31057 | } | ||||
| 31058 | |||||
| 31059 | /* | ||||
| 31060 | ** This version of the memory allocation is for use by the application. | ||||
| 31061 | ** First make sure the memory subsystem is initialized, then do the | ||||
| 31062 | ** allocation. | ||||
| 31063 | */ | ||||
| 31064 | SQLITE_API void *sqlite3_malloc(int n){ | ||||
| 31065 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 31066 | if( sqlite3_initialize() ) return 0; | ||||
| 31067 | #endif | ||||
| 31068 | return n<=0 ? 0 : sqlite3Malloc(n); | ||||
| 31069 | } | ||||
| 31070 | SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){ | ||||
| 31071 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 31072 | if( sqlite3_initialize() ) return 0; | ||||
| 31073 | #endif | ||||
| 31074 | return sqlite3Malloc(n); | ||||
| 31075 | } | ||||
| 31076 | |||||
| 31077 | /* | ||||
| 31078 | ** TRUE if p is a lookaside memory allocation from db | ||||
| 31079 | */ | ||||
| 31080 | #ifndef SQLITE_OMIT_LOOKASIDE | ||||
| 31081 | static int isLookaside(sqlite3 *db, const void *p){ | ||||
| 31082 | return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pTrueEnd)(((uptr)(p)>=(uptr)(db->lookaside.pStart))&&((uptr )(p)<(uptr)(db->lookaside.pTrueEnd))); | ||||
| 31083 | } | ||||
| 31084 | #else | ||||
| 31085 | #define isLookaside(A,B) 0 | ||||
| 31086 | #endif | ||||
| 31087 | |||||
| 31088 | /* | ||||
| 31089 | ** Return the size of a memory allocation previously obtained from | ||||
| 31090 | ** sqlite3Malloc() or sqlite3_malloc(). | ||||
| 31091 | */ | ||||
| 31092 | SQLITE_PRIVATEstatic int sqlite3MallocSize(const void *p){ | ||||
| 31093 | assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) )((void) (0)); | ||||
| 31094 | return sqlite3GlobalConfigsqlite3Config.m.xSize((void*)p); | ||||
| 31095 | } | ||||
| 31096 | static int lookasideMallocSize(sqlite3 *db, const void *p){ | ||||
| 31097 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 31098 | return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL128; | ||||
| 31099 | #else | ||||
| 31100 | return db->lookaside.szTrue; | ||||
| 31101 | #endif | ||||
| 31102 | } | ||||
| 31103 | SQLITE_PRIVATEstatic int sqlite3DbMallocSize(sqlite3 *db, const void *p){ | ||||
| 31104 | assert( p!=0 )((void) (0)); | ||||
| 31105 | #ifdef SQLITE_DEBUG | ||||
| 31106 | if( db==0 ){ | ||||
| 31107 | assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) )((void) (0)); | ||||
| 31108 | assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) )((void) (0)); | ||||
| 31109 | }else if( !isLookaside(db,p) ){ | ||||
| 31110 | assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31111 | assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31112 | } | ||||
| 31113 | #endif | ||||
| 31114 | if( db ){ | ||||
| 31115 | if( ((uptr)p)<(uptr)(db->lookaside.pTrueEnd) ){ | ||||
| 31116 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 31117 | if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ | ||||
| 31118 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31119 | return LOOKASIDE_SMALL128; | ||||
| 31120 | } | ||||
| 31121 | #endif | ||||
| 31122 | if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ | ||||
| 31123 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31124 | return db->lookaside.szTrue; | ||||
| 31125 | } | ||||
| 31126 | } | ||||
| 31127 | } | ||||
| 31128 | return sqlite3GlobalConfigsqlite3Config.m.xSize((void*)p); | ||||
| 31129 | } | ||||
| 31130 | SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){ | ||||
| 31131 | assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) )((void) (0)); | ||||
| 31132 | assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) )((void) (0)); | ||||
| 31133 | return p ? sqlite3GlobalConfigsqlite3Config.m.xSize(p) : 0; | ||||
| 31134 | } | ||||
| 31135 | |||||
| 31136 | /* | ||||
| 31137 | ** Free memory previously obtained from sqlite3Malloc(). | ||||
| 31138 | */ | ||||
| 31139 | SQLITE_API void sqlite3_free(void *p){ | ||||
| 31140 | if( p==0 ) return; /* IMP: R-49053-54554 */ | ||||
| 31141 | assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) )((void) (0)); | ||||
| 31142 | assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) )((void) (0)); | ||||
| 31143 | if( sqlite3GlobalConfigsqlite3Config.bMemstat ){ | ||||
| 31144 | sqlite3_mutex_enter(mem0mem0.mutex); | ||||
| 31145 | sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED0, sqlite3MallocSize(p)); | ||||
| 31146 | sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT9, 1); | ||||
| 31147 | sqlite3GlobalConfigsqlite3Config.m.xFree(p); | ||||
| 31148 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 31149 | }else{ | ||||
| 31150 | sqlite3GlobalConfigsqlite3Config.m.xFree(p); | ||||
| 31151 | } | ||||
| 31152 | } | ||||
| 31153 | |||||
| 31154 | /* | ||||
| 31155 | ** Add the size of memory allocation "p" to the count in | ||||
| 31156 | ** *db->pnBytesFreed. | ||||
| 31157 | */ | ||||
| 31158 | static SQLITE_NOINLINE__attribute__((noinline)) void measureAllocationSize(sqlite3 *db, void *p){ | ||||
| 31159 | *db->pnBytesFreed += sqlite3DbMallocSize(db,p); | ||||
| 31160 | } | ||||
| 31161 | |||||
| 31162 | /* | ||||
| 31163 | ** Free memory that might be associated with a particular database | ||||
| 31164 | ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op. | ||||
| 31165 | ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL. | ||||
| 31166 | */ | ||||
| 31167 | SQLITE_PRIVATEstatic void sqlite3DbFreeNN(sqlite3 *db, void *p){ | ||||
| 31168 | assert( db==0 || sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31169 | assert( p!=0 )((void) (0)); | ||||
| 31170 | if( db ){ | ||||
| 31171 | if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ | ||||
| 31172 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 31173 | if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ | ||||
| 31174 | LookasideSlot *pBuf = (LookasideSlot*)p; | ||||
| 31175 | assert( db->pnBytesFreed==0 )((void) (0)); | ||||
| 31176 | #ifdef SQLITE_DEBUG | ||||
| 31177 | memset(p, 0xaa, LOOKASIDE_SMALL128); /* Trash freed content */ | ||||
| 31178 | #endif | ||||
| 31179 | pBuf->pNext = db->lookaside.pSmallFree; | ||||
| 31180 | db->lookaside.pSmallFree = pBuf; | ||||
| 31181 | return; | ||||
| 31182 | } | ||||
| 31183 | #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ | ||||
| 31184 | if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ | ||||
| 31185 | LookasideSlot *pBuf = (LookasideSlot*)p; | ||||
| 31186 | assert( db->pnBytesFreed==0 )((void) (0)); | ||||
| 31187 | #ifdef SQLITE_DEBUG | ||||
| 31188 | memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */ | ||||
| 31189 | #endif | ||||
| 31190 | pBuf->pNext = db->lookaside.pFree; | ||||
| 31191 | db->lookaside.pFree = pBuf; | ||||
| 31192 | return; | ||||
| 31193 | } | ||||
| 31194 | } | ||||
| 31195 | if( db->pnBytesFreed ){ | ||||
| 31196 | measureAllocationSize(db, p); | ||||
| 31197 | return; | ||||
| 31198 | } | ||||
| 31199 | } | ||||
| 31200 | assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31201 | assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31202 | assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) )((void) (0)); | ||||
| 31203 | sqlite3MemdebugSetType(p, MEMTYPE_HEAP); | ||||
| 31204 | sqlite3_free(p); | ||||
| 31205 | } | ||||
| 31206 | SQLITE_PRIVATEstatic void sqlite3DbNNFreeNN(sqlite3 *db, void *p){ | ||||
| 31207 | assert( db!=0 )((void) (0)); | ||||
| 31208 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31209 | assert( p!=0 )((void) (0)); | ||||
| 31210 | if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ | ||||
| 31211 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 31212 | if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ | ||||
| 31213 | LookasideSlot *pBuf = (LookasideSlot*)p; | ||||
| 31214 | assert( db->pnBytesFreed==0 )((void) (0)); | ||||
| 31215 | #ifdef SQLITE_DEBUG | ||||
| 31216 | memset(p, 0xaa, LOOKASIDE_SMALL128); /* Trash freed content */ | ||||
| 31217 | #endif | ||||
| 31218 | pBuf->pNext = db->lookaside.pSmallFree; | ||||
| 31219 | db->lookaside.pSmallFree = pBuf; | ||||
| 31220 | return; | ||||
| 31221 | } | ||||
| 31222 | #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ | ||||
| 31223 | if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ | ||||
| 31224 | LookasideSlot *pBuf = (LookasideSlot*)p; | ||||
| 31225 | assert( db->pnBytesFreed==0 )((void) (0)); | ||||
| 31226 | #ifdef SQLITE_DEBUG | ||||
| 31227 | memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */ | ||||
| 31228 | #endif | ||||
| 31229 | pBuf->pNext = db->lookaside.pFree; | ||||
| 31230 | db->lookaside.pFree = pBuf; | ||||
| 31231 | return; | ||||
| 31232 | } | ||||
| 31233 | } | ||||
| 31234 | if( db->pnBytesFreed ){ | ||||
| 31235 | measureAllocationSize(db, p); | ||||
| 31236 | return; | ||||
| 31237 | } | ||||
| 31238 | assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31239 | assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31240 | sqlite3MemdebugSetType(p, MEMTYPE_HEAP); | ||||
| 31241 | sqlite3_free(p); | ||||
| 31242 | } | ||||
| 31243 | SQLITE_PRIVATEstatic void sqlite3DbFree(sqlite3 *db, void *p){ | ||||
| 31244 | assert( db==0 || sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31245 | if( p ) sqlite3DbFreeNN(db, p); | ||||
| 31246 | } | ||||
| 31247 | |||||
| 31248 | /* | ||||
| 31249 | ** Change the size of an existing memory allocation | ||||
| 31250 | */ | ||||
| 31251 | SQLITE_PRIVATEstatic void *sqlite3Realloc(void *pOld, u64 nBytes){ | ||||
| 31252 | int nOld, nNew, nDiff; | ||||
| 31253 | void *pNew; | ||||
| 31254 | assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) )((void) (0)); | ||||
| 31255 | assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) )((void) (0)); | ||||
| 31256 | if( pOld==0 ){ | ||||
| 31257 | return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ | ||||
| 31258 | } | ||||
| 31259 | if( nBytes==0 ){ | ||||
| 31260 | sqlite3_free(pOld); /* IMP: R-26507-47431 */ | ||||
| 31261 | return 0; | ||||
| 31262 | } | ||||
| 31263 | if( nBytes>=0x7fffff00 ){ | ||||
| 31264 | /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ | ||||
| 31265 | return 0; | ||||
| 31266 | } | ||||
| 31267 | nOld = sqlite3MallocSize(pOld); | ||||
| 31268 | /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second | ||||
| 31269 | ** argument to xRealloc is always a value returned by a prior call to | ||||
| 31270 | ** xRoundup. */ | ||||
| 31271 | nNew = sqlite3GlobalConfigsqlite3Config.m.xRoundup((int)nBytes); | ||||
| 31272 | if( nOld==nNew ){ | ||||
| 31273 | pNew = pOld; | ||||
| 31274 | }else if( sqlite3GlobalConfigsqlite3Config.bMemstat ){ | ||||
| 31275 | sqlite3_int64 nUsed; | ||||
| 31276 | sqlite3_mutex_enter(mem0mem0.mutex); | ||||
| 31277 | sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE5, (int)nBytes); | ||||
| 31278 | nDiff = nNew - nOld; | ||||
| 31279 | if( nDiff>0 && (nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED0)) >= | ||||
| 31280 | mem0mem0.alarmThreshold-nDiff ){ | ||||
| 31281 | sqlite3MallocAlarm(nDiff); | ||||
| 31282 | if( mem0mem0.hardLimit>0 && nUsed >= mem0mem0.hardLimit - nDiff ){ | ||||
| 31283 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 31284 | test_oom_breakpoint(1); | ||||
| 31285 | return 0; | ||||
| 31286 | } | ||||
| 31287 | } | ||||
| 31288 | pNew = sqlite3GlobalConfigsqlite3Config.m.xRealloc(pOld, nNew); | ||||
| 31289 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 31290 | if( pNew==0 && mem0mem0.alarmThreshold>0 ){ | ||||
| 31291 | sqlite3MallocAlarm((int)nBytes); | ||||
| 31292 | pNew = sqlite3GlobalConfigsqlite3Config.m.xRealloc(pOld, nNew); | ||||
| 31293 | } | ||||
| 31294 | #endif | ||||
| 31295 | if( pNew ){ | ||||
| 31296 | nNew = sqlite3MallocSize(pNew); | ||||
| 31297 | sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED0, nNew-nOld); | ||||
| 31298 | } | ||||
| 31299 | sqlite3_mutex_leave(mem0mem0.mutex); | ||||
| 31300 | }else{ | ||||
| 31301 | pNew = sqlite3GlobalConfigsqlite3Config.m.xRealloc(pOld, nNew); | ||||
| 31302 | } | ||||
| 31303 | assert( EIGHT_BYTE_ALIGNMENT(pNew) )((void) (0)); /* IMP: R-11148-40995 */ | ||||
| 31304 | return pNew; | ||||
| 31305 | } | ||||
| 31306 | |||||
| 31307 | /* | ||||
| 31308 | ** The public interface to sqlite3Realloc. Make sure that the memory | ||||
| 31309 | ** subsystem is initialized prior to invoking sqliteRealloc. | ||||
| 31310 | */ | ||||
| 31311 | SQLITE_API void *sqlite3_realloc(void *pOld, int n){ | ||||
| 31312 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 31313 | if( sqlite3_initialize() ) return 0; | ||||
| 31314 | #endif | ||||
| 31315 | if( n<0 ) n = 0; /* IMP: R-26507-47431 */ | ||||
| 31316 | return sqlite3Realloc(pOld, n); | ||||
| 31317 | } | ||||
| 31318 | SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){ | ||||
| 31319 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 31320 | if( sqlite3_initialize() ) return 0; | ||||
| 31321 | #endif | ||||
| 31322 | return sqlite3Realloc(pOld, n); | ||||
| 31323 | } | ||||
| 31324 | |||||
| 31325 | |||||
| 31326 | /* | ||||
| 31327 | ** Allocate and zero memory. | ||||
| 31328 | */ | ||||
| 31329 | SQLITE_PRIVATEstatic void *sqlite3MallocZero(u64 n){ | ||||
| 31330 | void *p = sqlite3Malloc(n); | ||||
| 31331 | if( p ){ | ||||
| 31332 | memset(p, 0, (size_t)n); | ||||
| 31333 | } | ||||
| 31334 | return p; | ||||
| 31335 | } | ||||
| 31336 | |||||
| 31337 | /* | ||||
| 31338 | ** Allocate and zero memory. If the allocation fails, make | ||||
| 31339 | ** the mallocFailed flag in the connection pointer. | ||||
| 31340 | */ | ||||
| 31341 | SQLITE_PRIVATEstatic void *sqlite3DbMallocZero(sqlite3 *db, u64 n){ | ||||
| 31342 | void *p; | ||||
| 31343 | testcase( db==0 ); | ||||
| 31344 | p = sqlite3DbMallocRaw(db, n); | ||||
| 31345 | if( p ) memset(p, 0, (size_t)n); | ||||
| 31346 | return p; | ||||
| 31347 | } | ||||
| 31348 | |||||
| 31349 | |||||
| 31350 | /* Finish the work of sqlite3DbMallocRawNN for the unusual and | ||||
| 31351 | ** slower case when the allocation cannot be fulfilled using lookaside. | ||||
| 31352 | */ | ||||
| 31353 | static SQLITE_NOINLINE__attribute__((noinline)) void *dbMallocRawFinish(sqlite3 *db, u64 n){ | ||||
| 31354 | void *p; | ||||
| 31355 | assert( db!=0 )((void) (0)); | ||||
| 31356 | p = sqlite3Malloc(n); | ||||
| 31357 | if( !p ) sqlite3OomFault(db); | ||||
| 31358 | sqlite3MemdebugSetType(p, | ||||
| 31359 | (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); | ||||
| 31360 | return p; | ||||
| 31361 | } | ||||
| 31362 | |||||
| 31363 | /* | ||||
| 31364 | ** Allocate memory, either lookaside (if possible) or heap. | ||||
| 31365 | ** If the allocation fails, set the mallocFailed flag in | ||||
| 31366 | ** the connection pointer. | ||||
| 31367 | ** | ||||
| 31368 | ** If db!=0 and db->mallocFailed is true (indicating a prior malloc | ||||
| 31369 | ** failure on the same database connection) then always return 0. | ||||
| 31370 | ** Hence for a particular database connection, once malloc starts | ||||
| 31371 | ** failing, it fails consistently until mallocFailed is reset. | ||||
| 31372 | ** This is an important assumption. There are many places in the | ||||
| 31373 | ** code that do things like this: | ||||
| 31374 | ** | ||||
| 31375 | ** int *a = (int*)sqlite3DbMallocRaw(db, 100); | ||||
| 31376 | ** int *b = (int*)sqlite3DbMallocRaw(db, 200); | ||||
| 31377 | ** if( b ) a[10] = 9; | ||||
| 31378 | ** | ||||
| 31379 | ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed | ||||
| 31380 | ** that all prior mallocs (ex: "a") worked too. | ||||
| 31381 | ** | ||||
| 31382 | ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is | ||||
| 31383 | ** not a NULL pointer. | ||||
| 31384 | */ | ||||
| 31385 | SQLITE_PRIVATEstatic void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){ | ||||
| 31386 | void *p; | ||||
| 31387 | if( db ) return sqlite3DbMallocRawNN(db, n); | ||||
| 31388 | p = sqlite3Malloc(n); | ||||
| 31389 | sqlite3MemdebugSetType(p, MEMTYPE_HEAP); | ||||
| 31390 | return p; | ||||
| 31391 | } | ||||
| 31392 | SQLITE_PRIVATEstatic void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){ | ||||
| 31393 | #ifndef SQLITE_OMIT_LOOKASIDE | ||||
| 31394 | LookasideSlot *pBuf; | ||||
| 31395 | assert( db!=0 )((void) (0)); | ||||
| 31396 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31397 | assert( db->pnBytesFreed==0 )((void) (0)); | ||||
| 31398 | if( n>db->lookaside.sz ){ | ||||
| 31399 | if( !db->lookaside.bDisable ){ | ||||
| 31400 | db->lookaside.anStat[1]++; | ||||
| 31401 | }else if( db->mallocFailed ){ | ||||
| 31402 | return 0; | ||||
| 31403 | } | ||||
| 31404 | return dbMallocRawFinish(db, n); | ||||
| 31405 | } | ||||
| 31406 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 31407 | if( n<=LOOKASIDE_SMALL128 ){ | ||||
| 31408 | if( (pBuf = db->lookaside.pSmallFree)!=0 ){ | ||||
| 31409 | db->lookaside.pSmallFree = pBuf->pNext; | ||||
| 31410 | db->lookaside.anStat[0]++; | ||||
| 31411 | return (void*)pBuf; | ||||
| 31412 | }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){ | ||||
| 31413 | db->lookaside.pSmallInit = pBuf->pNext; | ||||
| 31414 | db->lookaside.anStat[0]++; | ||||
| 31415 | return (void*)pBuf; | ||||
| 31416 | } | ||||
| 31417 | } | ||||
| 31418 | #endif | ||||
| 31419 | if( (pBuf = db->lookaside.pFree)!=0 ){ | ||||
| 31420 | db->lookaside.pFree = pBuf->pNext; | ||||
| 31421 | db->lookaside.anStat[0]++; | ||||
| 31422 | return (void*)pBuf; | ||||
| 31423 | }else if( (pBuf = db->lookaside.pInit)!=0 ){ | ||||
| 31424 | db->lookaside.pInit = pBuf->pNext; | ||||
| 31425 | db->lookaside.anStat[0]++; | ||||
| 31426 | return (void*)pBuf; | ||||
| 31427 | }else{ | ||||
| 31428 | db->lookaside.anStat[2]++; | ||||
| 31429 | } | ||||
| 31430 | #else | ||||
| 31431 | assert( db!=0 )((void) (0)); | ||||
| 31432 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31433 | assert( db->pnBytesFreed==0 )((void) (0)); | ||||
| 31434 | if( db->mallocFailed ){ | ||||
| 31435 | return 0; | ||||
| 31436 | } | ||||
| 31437 | #endif | ||||
| 31438 | return dbMallocRawFinish(db, n); | ||||
| 31439 | } | ||||
| 31440 | |||||
| 31441 | /* Forward declaration */ | ||||
| 31442 | static SQLITE_NOINLINE__attribute__((noinline)) void *dbReallocFinish(sqlite3 *db, void *p, u64 n); | ||||
| 31443 | |||||
| 31444 | /* | ||||
| 31445 | ** Resize the block of memory pointed to by p to n bytes. If the | ||||
| 31446 | ** resize fails, set the mallocFailed flag in the connection object. | ||||
| 31447 | */ | ||||
| 31448 | SQLITE_PRIVATEstatic void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){ | ||||
| 31449 | assert( db!=0 )((void) (0)); | ||||
| 31450 | if( p==0 ) return sqlite3DbMallocRawNN(db, n); | ||||
| 31451 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31452 | if( ((uptr)p)<(uptr)db->lookaside.pEnd ){ | ||||
| 31453 | #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE | ||||
| 31454 | if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){ | ||||
| 31455 | if( n<=LOOKASIDE_SMALL128 ) return p; | ||||
| 31456 | }else | ||||
| 31457 | #endif | ||||
| 31458 | if( ((uptr)p)>=(uptr)db->lookaside.pStart ){ | ||||
| 31459 | if( n<=db->lookaside.szTrue ) return p; | ||||
| 31460 | } | ||||
| 31461 | } | ||||
| 31462 | return dbReallocFinish(db, p, n); | ||||
| 31463 | } | ||||
| 31464 | static SQLITE_NOINLINE__attribute__((noinline)) void *dbReallocFinish(sqlite3 *db, void *p, u64 n){ | ||||
| 31465 | void *pNew = 0; | ||||
| 31466 | assert( db!=0 )((void) (0)); | ||||
| 31467 | assert( p!=0 )((void) (0)); | ||||
| 31468 | if( db->mallocFailed==0 ){ | ||||
| 31469 | if( isLookaside(db, p) ){ | ||||
| 31470 | pNew = sqlite3DbMallocRawNN(db, n); | ||||
| 31471 | if( pNew ){ | ||||
| 31472 | memcpy(pNew, p, lookasideMallocSize(db, p)); | ||||
| 31473 | sqlite3DbFree(db, p); | ||||
| 31474 | } | ||||
| 31475 | }else{ | ||||
| 31476 | assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31477 | assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) )((void) (0)); | ||||
| 31478 | sqlite3MemdebugSetType(p, MEMTYPE_HEAP); | ||||
| 31479 | pNew = sqlite3Realloc(p, n); | ||||
| 31480 | if( !pNew ){ | ||||
| 31481 | sqlite3OomFault(db); | ||||
| 31482 | } | ||||
| 31483 | sqlite3MemdebugSetType(pNew, | ||||
| 31484 | (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); | ||||
| 31485 | } | ||||
| 31486 | } | ||||
| 31487 | return pNew; | ||||
| 31488 | } | ||||
| 31489 | |||||
| 31490 | /* | ||||
| 31491 | ** Attempt to reallocate p. If the reallocation fails, then free p | ||||
| 31492 | ** and set the mallocFailed flag in the database connection. | ||||
| 31493 | */ | ||||
| 31494 | SQLITE_PRIVATEstatic void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){ | ||||
| 31495 | void *pNew; | ||||
| 31496 | pNew = sqlite3DbRealloc(db, p, n); | ||||
| 31497 | if( !pNew ){ | ||||
| 31498 | sqlite3DbFree(db, p); | ||||
| 31499 | } | ||||
| 31500 | return pNew; | ||||
| 31501 | } | ||||
| 31502 | |||||
| 31503 | /* | ||||
| 31504 | ** Make a copy of a string in memory obtained from sqliteMalloc(). These | ||||
| 31505 | ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This | ||||
| 31506 | ** is because when memory debugging is turned on, these two functions are | ||||
| 31507 | ** called via macros that record the current file and line number in the | ||||
| 31508 | ** ThreadData structure. | ||||
| 31509 | */ | ||||
| 31510 | SQLITE_PRIVATEstatic char *sqlite3DbStrDup(sqlite3 *db, const char *z){ | ||||
| 31511 | char *zNew; | ||||
| 31512 | size_t n; | ||||
| 31513 | if( z==0 ){ | ||||
| 31514 | return 0; | ||||
| 31515 | } | ||||
| 31516 | n = strlen(z) + 1; | ||||
| 31517 | zNew = sqlite3DbMallocRaw(db, n); | ||||
| 31518 | if( zNew ){ | ||||
| 31519 | memcpy(zNew, z, n); | ||||
| 31520 | } | ||||
| 31521 | return zNew; | ||||
| 31522 | } | ||||
| 31523 | SQLITE_PRIVATEstatic char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ | ||||
| 31524 | char *zNew; | ||||
| 31525 | assert( db!=0 )((void) (0)); | ||||
| 31526 | assert( z!=0 || n==0 )((void) (0)); | ||||
| 31527 | assert( (n&0x7fffffff)==n )((void) (0)); | ||||
| 31528 | zNew = z ? sqlite3DbMallocRawNN(db, n+1) : 0; | ||||
| 31529 | if( zNew ){ | ||||
| 31530 | memcpy(zNew, z, (size_t)n); | ||||
| 31531 | zNew[n] = 0; | ||||
| 31532 | } | ||||
| 31533 | return zNew; | ||||
| 31534 | } | ||||
| 31535 | |||||
| 31536 | /* | ||||
| 31537 | ** The text between zStart and zEnd represents a phrase within a larger | ||||
| 31538 | ** SQL statement. Make a copy of this phrase in space obtained form | ||||
| 31539 | ** sqlite3DbMalloc(). Omit leading and trailing whitespace. | ||||
| 31540 | */ | ||||
| 31541 | SQLITE_PRIVATEstatic char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){ | ||||
| 31542 | int n; | ||||
| 31543 | #ifdef SQLITE_DEBUG | ||||
| 31544 | /* Because of the way the parser works, the span is guaranteed to contain | ||||
| 31545 | ** at least one non-space character */ | ||||
| 31546 | for(n=0; sqlite3Isspace(zStart[n])(sqlite3CtypeMap[(unsigned char)(zStart[n])]&0x01); n++){ assert( &zStart[n]<zEnd )((void) (0)); } | ||||
| 31547 | #endif | ||||
| 31548 | while( sqlite3Isspace(zStart[0])(sqlite3CtypeMap[(unsigned char)(zStart[0])]&0x01) ) zStart++; | ||||
| 31549 | n = (int)(zEnd - zStart); | ||||
| 31550 | while( sqlite3Isspace(zStart[n-1])(sqlite3CtypeMap[(unsigned char)(zStart[n-1])]&0x01) ) n--; | ||||
| 31551 | return sqlite3DbStrNDup(db, zStart, n); | ||||
| 31552 | } | ||||
| 31553 | |||||
| 31554 | /* | ||||
| 31555 | ** Free any prior content in *pz and replace it with a copy of zNew. | ||||
| 31556 | */ | ||||
| 31557 | SQLITE_PRIVATEstatic void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ | ||||
| 31558 | char *z = sqlite3DbStrDup(db, zNew); | ||||
| 31559 | sqlite3DbFree(db, *pz); | ||||
| 31560 | *pz = z; | ||||
| 31561 | } | ||||
| 31562 | |||||
| 31563 | /* | ||||
| 31564 | ** Call this routine to record the fact that an OOM (out-of-memory) error | ||||
| 31565 | ** has happened. This routine will set db->mallocFailed, and also | ||||
| 31566 | ** temporarily disable the lookaside memory allocator and interrupt | ||||
| 31567 | ** any running VDBEs. | ||||
| 31568 | ** | ||||
| 31569 | ** Always return a NULL pointer so that this routine can be invoked using | ||||
| 31570 | ** | ||||
| 31571 | ** return sqlite3OomFault(db); | ||||
| 31572 | ** | ||||
| 31573 | ** and thereby avoid unnecessary stack frame allocations for the overwhelmingly | ||||
| 31574 | ** common case where no OOM occurs. | ||||
| 31575 | */ | ||||
| 31576 | SQLITE_PRIVATEstatic void *sqlite3OomFault(sqlite3 *db){ | ||||
| 31577 | if( db->mallocFailed==0 && db->bBenignMalloc==0 ){ | ||||
| 31578 | db->mallocFailed = 1; | ||||
| 31579 | if( db->nVdbeExec>0 ){ | ||||
| 31580 | AtomicStore(&db->u1.isInterrupted, 1)__atomic_store_n((&db->u1.isInterrupted),(1),0); | ||||
| 31581 | } | ||||
| 31582 | DisableLookasidedb->lookaside.bDisable++;db->lookaside.sz=0; | ||||
| 31583 | if( db->pParse ){ | ||||
| 31584 | Parse *pParse; | ||||
| 31585 | sqlite3ErrorMsg(db->pParse, "out of memory"); | ||||
| 31586 | db->pParse->rc = SQLITE_NOMEM_BKPT7; | ||||
| 31587 | for(pParse=db->pParse->pOuterParse; pParse; pParse = pParse->pOuterParse){ | ||||
| 31588 | pParse->nErr++; | ||||
| 31589 | pParse->rc = SQLITE_NOMEM7; | ||||
| 31590 | } | ||||
| 31591 | } | ||||
| 31592 | } | ||||
| 31593 | return 0; | ||||
| 31594 | } | ||||
| 31595 | |||||
| 31596 | /* | ||||
| 31597 | ** This routine reactivates the memory allocator and clears the | ||||
| 31598 | ** db->mallocFailed flag as necessary. | ||||
| 31599 | ** | ||||
| 31600 | ** The memory allocator is not restarted if there are running | ||||
| 31601 | ** VDBEs. | ||||
| 31602 | */ | ||||
| 31603 | SQLITE_PRIVATEstatic void sqlite3OomClear(sqlite3 *db){ | ||||
| 31604 | if( db->mallocFailed && db->nVdbeExec==0 ){ | ||||
| 31605 | db->mallocFailed = 0; | ||||
| 31606 | AtomicStore(&db->u1.isInterrupted, 0)__atomic_store_n((&db->u1.isInterrupted),(0),0); | ||||
| 31607 | assert( db->lookaside.bDisable>0 )((void) (0)); | ||||
| 31608 | EnableLookasidedb->lookaside.bDisable--; db->lookaside.sz=db->lookaside .bDisable?0:db->lookaside.szTrue; | ||||
| 31609 | } | ||||
| 31610 | } | ||||
| 31611 | |||||
| 31612 | /* | ||||
| 31613 | ** Take actions at the end of an API call to deal with error codes. | ||||
| 31614 | */ | ||||
| 31615 | static SQLITE_NOINLINE__attribute__((noinline)) int apiHandleError(sqlite3 *db, int rc){ | ||||
| 31616 | if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM(10 | (12<<8)) ){ | ||||
| 31617 | sqlite3OomClear(db); | ||||
| 31618 | sqlite3Error(db, SQLITE_NOMEM7); | ||||
| 31619 | return SQLITE_NOMEM_BKPT7; | ||||
| 31620 | } | ||||
| 31621 | return rc & db->errMask; | ||||
| 31622 | } | ||||
| 31623 | |||||
| 31624 | /* | ||||
| 31625 | ** This function must be called before exiting any API function (i.e. | ||||
| 31626 | ** returning control to the user) that has called sqlite3_malloc or | ||||
| 31627 | ** sqlite3_realloc. | ||||
| 31628 | ** | ||||
| 31629 | ** The returned value is normally a copy of the second argument to this | ||||
| 31630 | ** function. However, if a malloc() failure has occurred since the previous | ||||
| 31631 | ** invocation SQLITE_NOMEM is returned instead. | ||||
| 31632 | ** | ||||
| 31633 | ** If an OOM as occurred, then the connection error-code (the value | ||||
| 31634 | ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM. | ||||
| 31635 | */ | ||||
| 31636 | SQLITE_PRIVATEstatic int sqlite3ApiExit(sqlite3* db, int rc){ | ||||
| 31637 | /* If the db handle must hold the connection handle mutex here. | ||||
| 31638 | ** Otherwise the read (and possible write) of db->mallocFailed | ||||
| 31639 | ** is unsafe, as is the call to sqlite3Error(). | ||||
| 31640 | */ | ||||
| 31641 | assert( db!=0 )((void) (0)); | ||||
| 31642 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 31643 | if( db->mallocFailed || rc ){ | ||||
| 31644 | return apiHandleError(db, rc); | ||||
| 31645 | } | ||||
| 31646 | return 0; | ||||
| 31647 | } | ||||
| 31648 | |||||
| 31649 | /************** End of malloc.c **********************************************/ | ||||
| 31650 | /************** Begin file printf.c ******************************************/ | ||||
| 31651 | /* | ||||
| 31652 | ** The "printf" code that follows dates from the 1980's. It is in | ||||
| 31653 | ** the public domain. | ||||
| 31654 | ** | ||||
| 31655 | ************************************************************************** | ||||
| 31656 | ** | ||||
| 31657 | ** This file contains code for a set of "printf"-like routines. These | ||||
| 31658 | ** routines format strings much like the printf() from the standard C | ||||
| 31659 | ** library, though the implementation here has enhancements to support | ||||
| 31660 | ** SQLite. | ||||
| 31661 | */ | ||||
| 31662 | /* #include "sqliteInt.h" */ | ||||
| 31663 | |||||
| 31664 | /* | ||||
| 31665 | ** Conversion types fall into various categories as defined by the | ||||
| 31666 | ** following enumeration. | ||||
| 31667 | */ | ||||
| 31668 | #define etRADIX0 0 /* non-decimal integer types. %x %o */ | ||||
| 31669 | #define etFLOAT1 1 /* Floating point. %f */ | ||||
| 31670 | #define etEXP2 2 /* Exponentional notation. %e and %E */ | ||||
| 31671 | #define etGENERIC3 3 /* Floating or exponential, depending on exponent. %g */ | ||||
| 31672 | #define etSIZE4 4 /* Return number of characters processed so far. %n */ | ||||
| 31673 | #define etSTRING5 5 /* Strings. %s */ | ||||
| 31674 | #define etDYNSTRING6 6 /* Dynamically allocated strings. %z */ | ||||
| 31675 | #define etPERCENT7 7 /* Percent symbol. %% */ | ||||
| 31676 | #define etCHARX8 8 /* Characters. %c */ | ||||
| 31677 | /* The rest are extensions, not normally found in printf() */ | ||||
| 31678 | #define etESCAPE_q9 9 /* Strings with '\'' doubled. %q */ | ||||
| 31679 | #define etESCAPE_Q10 10 /* Strings with '\'' doubled and enclosed in '', | ||||
| 31680 | NULL pointers replaced by SQL NULL. %Q */ | ||||
| 31681 | #define etTOKEN11 11 /* a pointer to a Token structure */ | ||||
| 31682 | #define etSRCITEM12 12 /* a pointer to a SrcItem */ | ||||
| 31683 | #define etPOINTER13 13 /* The %p conversion */ | ||||
| 31684 | #define etESCAPE_w14 14 /* %w -> Strings with '\"' doubled */ | ||||
| 31685 | #define etORDINAL15 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ | ||||
| 31686 | #define etDECIMAL16 16 /* %d or %u, but not %x, %o */ | ||||
| 31687 | |||||
| 31688 | #define etINVALID17 17 /* Any unrecognized conversion type */ | ||||
| 31689 | |||||
| 31690 | |||||
| 31691 | /* | ||||
| 31692 | ** An "etByte" is an 8-bit unsigned value. | ||||
| 31693 | */ | ||||
| 31694 | typedef unsigned char etByte; | ||||
| 31695 | |||||
| 31696 | /* | ||||
| 31697 | ** Each builtin conversion character (ex: the 'd' in "%d") is described | ||||
| 31698 | ** by an instance of the following structure | ||||
| 31699 | */ | ||||
| 31700 | typedef struct et_info { /* Information about each format field */ | ||||
| 31701 | char fmttype; /* The format field code letter */ | ||||
| 31702 | etByte base; /* The base for radix conversion */ | ||||
| 31703 | etByte flags; /* One or more of FLAG_ constants below */ | ||||
| 31704 | etByte type; /* Conversion paradigm */ | ||||
| 31705 | etByte charset; /* Offset into aDigits[] of the digits string */ | ||||
| 31706 | etByte prefix; /* Offset into aPrefix[] of the prefix string */ | ||||
| 31707 | } et_info; | ||||
| 31708 | |||||
| 31709 | /* | ||||
| 31710 | ** Allowed values for et_info.flags | ||||
| 31711 | */ | ||||
| 31712 | #define FLAG_SIGNED1 1 /* True if the value to convert is signed */ | ||||
| 31713 | #define FLAG_STRING4 4 /* Allow infinite precision */ | ||||
| 31714 | |||||
| 31715 | |||||
| 31716 | /* | ||||
| 31717 | ** The following table is searched linearly, so it is good to put the | ||||
| 31718 | ** most frequently used conversion types first. | ||||
| 31719 | */ | ||||
| 31720 | static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; | ||||
| 31721 | static const char aPrefix[] = "-x0\000X0"; | ||||
| 31722 | static const et_info fmtinfo[] = { | ||||
| 31723 | { 'd', 10, 1, etDECIMAL16, 0, 0 }, | ||||
| 31724 | { 's', 0, 4, etSTRING5, 0, 0 }, | ||||
| 31725 | { 'g', 0, 1, etGENERIC3, 30, 0 }, | ||||
| 31726 | { 'z', 0, 4, etDYNSTRING6, 0, 0 }, | ||||
| 31727 | { 'q', 0, 4, etESCAPE_q9, 0, 0 }, | ||||
| 31728 | { 'Q', 0, 4, etESCAPE_Q10, 0, 0 }, | ||||
| 31729 | { 'w', 0, 4, etESCAPE_w14, 0, 0 }, | ||||
| 31730 | { 'c', 0, 0, etCHARX8, 0, 0 }, | ||||
| 31731 | { 'o', 8, 0, etRADIX0, 0, 2 }, | ||||
| 31732 | { 'u', 10, 0, etDECIMAL16, 0, 0 }, | ||||
| 31733 | { 'x', 16, 0, etRADIX0, 16, 1 }, | ||||
| 31734 | { 'X', 16, 0, etRADIX0, 0, 4 }, | ||||
| 31735 | #ifndef SQLITE_OMIT_FLOATING_POINT | ||||
| 31736 | { 'f', 0, 1, etFLOAT1, 0, 0 }, | ||||
| 31737 | { 'e', 0, 1, etEXP2, 30, 0 }, | ||||
| 31738 | { 'E', 0, 1, etEXP2, 14, 0 }, | ||||
| 31739 | { 'G', 0, 1, etGENERIC3, 14, 0 }, | ||||
| 31740 | #endif | ||||
| 31741 | { 'i', 10, 1, etDECIMAL16, 0, 0 }, | ||||
| 31742 | { 'n', 0, 0, etSIZE4, 0, 0 }, | ||||
| 31743 | { '%', 0, 0, etPERCENT7, 0, 0 }, | ||||
| 31744 | { 'p', 16, 0, etPOINTER13, 0, 1 }, | ||||
| 31745 | |||||
| 31746 | /* All the rest are undocumented and are for internal use only */ | ||||
| 31747 | { 'T', 0, 0, etTOKEN11, 0, 0 }, | ||||
| 31748 | { 'S', 0, 0, etSRCITEM12, 0, 0 }, | ||||
| 31749 | { 'r', 10, 1, etORDINAL15, 0, 0 }, | ||||
| 31750 | }; | ||||
| 31751 | |||||
| 31752 | /* Notes: | ||||
| 31753 | ** | ||||
| 31754 | ** %S Takes a pointer to SrcItem. Shows name or database.name | ||||
| 31755 | ** %!S Like %S but prefer the zName over the zAlias | ||||
| 31756 | */ | ||||
| 31757 | |||||
| 31758 | /* | ||||
| 31759 | ** Set the StrAccum object to an error mode. | ||||
| 31760 | */ | ||||
| 31761 | SQLITE_PRIVATEstatic void sqlite3StrAccumSetError(StrAccum *p, u8 eError){ | ||||
| 31762 | assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG )((void) (0)); | ||||
| 31763 | p->accError = eError; | ||||
| 31764 | if( p->mxAlloc ) sqlite3_str_reset(p); | ||||
| 31765 | if( eError==SQLITE_TOOBIG18 ) sqlite3ErrorToParser(p->db, eError); | ||||
| 31766 | } | ||||
| 31767 | |||||
| 31768 | /* | ||||
| 31769 | ** Extra argument values from a PrintfArguments object | ||||
| 31770 | */ | ||||
| 31771 | static sqlite3_int64 getIntArg(PrintfArguments *p){ | ||||
| 31772 | if( p->nArg<=p->nUsed ) return 0; | ||||
| 31773 | return sqlite3_value_int64(p->apArg[p->nUsed++]); | ||||
| 31774 | } | ||||
| 31775 | static double getDoubleArg(PrintfArguments *p){ | ||||
| 31776 | if( p->nArg<=p->nUsed ) return 0.0; | ||||
| 31777 | return sqlite3_value_double(p->apArg[p->nUsed++]); | ||||
| 31778 | } | ||||
| 31779 | static char *getTextArg(PrintfArguments *p){ | ||||
| 31780 | if( p->nArg<=p->nUsed ) return 0; | ||||
| 31781 | return (char*)sqlite3_value_text(p->apArg[p->nUsed++]); | ||||
| 31782 | } | ||||
| 31783 | |||||
| 31784 | /* | ||||
| 31785 | ** Allocate memory for a temporary buffer needed for printf rendering. | ||||
| 31786 | ** | ||||
| 31787 | ** If the requested size of the temp buffer is larger than the size | ||||
| 31788 | ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error. | ||||
| 31789 | ** Do the size check before the memory allocation to prevent rogue | ||||
| 31790 | ** SQL from requesting large allocations using the precision or width | ||||
| 31791 | ** field of the printf() function. | ||||
| 31792 | */ | ||||
| 31793 | static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){ | ||||
| 31794 | char *z; | ||||
| 31795 | if( pAccum->accError ) return 0; | ||||
| 31796 | if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){ | ||||
| 31797 | sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG18); | ||||
| 31798 | return 0; | ||||
| 31799 | } | ||||
| 31800 | z = sqlite3DbMallocRaw(pAccum->db, n); | ||||
| 31801 | if( z==0 ){ | ||||
| 31802 | sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM7); | ||||
| 31803 | } | ||||
| 31804 | return z; | ||||
| 31805 | } | ||||
| 31806 | |||||
| 31807 | /* | ||||
| 31808 | ** On machines with a small stack size, you can redefine the | ||||
| 31809 | ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. | ||||
| 31810 | */ | ||||
| 31811 | #ifndef SQLITE_PRINT_BUF_SIZE70 | ||||
| 31812 | # define SQLITE_PRINT_BUF_SIZE70 70 | ||||
| 31813 | #endif | ||||
| 31814 | #define etBUFSIZE70 SQLITE_PRINT_BUF_SIZE70 /* Size of the output buffer */ | ||||
| 31815 | |||||
| 31816 | /* | ||||
| 31817 | ** Hard limit on the precision of floating-point conversions. | ||||
| 31818 | */ | ||||
| 31819 | #ifndef SQLITE_PRINTF_PRECISION_LIMIT | ||||
| 31820 | # define SQLITE_FP_PRECISION_LIMIT100000000 100000000 | ||||
| 31821 | #endif | ||||
| 31822 | |||||
| 31823 | /* | ||||
| 31824 | ** Render a string given by "fmt" into the StrAccum object. | ||||
| 31825 | */ | ||||
| 31826 | SQLITE_API void sqlite3_str_vappendf( | ||||
| 31827 | sqlite3_str *pAccum, /* Accumulate results here */ | ||||
| 31828 | const char *fmt, /* Format string */ | ||||
| 31829 | va_list ap /* arguments */ | ||||
| 31830 | ){ | ||||
| 31831 | int c; /* Next character in the format string */ | ||||
| 31832 | char *bufpt; /* Pointer to the conversion buffer */ | ||||
| 31833 | int precision; /* Precision of the current field */ | ||||
| 31834 | int length; /* Length of the field */ | ||||
| 31835 | int idx; /* A general purpose loop counter */ | ||||
| 31836 | int width; /* Width of the current field */ | ||||
| 31837 | etByte flag_leftjustify; /* True if "-" flag is present */ | ||||
| 31838 | etByte flag_prefix; /* '+' or ' ' or 0 for prefix */ | ||||
| 31839 | etByte flag_alternateform; /* True if "#" flag is present */ | ||||
| 31840 | etByte flag_altform2; /* True if "!" flag is present */ | ||||
| 31841 | etByte flag_zeropad; /* True if field width constant starts with zero */ | ||||
| 31842 | etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */ | ||||
| 31843 | etByte done; /* Loop termination flag */ | ||||
| 31844 | etByte cThousand; /* Thousands separator for %d and %u */ | ||||
| 31845 | etByte xtype = etINVALID17; /* Conversion paradigm */ | ||||
| 31846 | u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */ | ||||
| 31847 | char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ | ||||
| 31848 | sqlite_uint64 longvalue; /* Value for integer types */ | ||||
| 31849 | double realvalue; /* Value for real types */ | ||||
| 31850 | const et_info *infop; /* Pointer to the appropriate info structure */ | ||||
| 31851 | char *zOut; /* Rendering buffer */ | ||||
| 31852 | int nOut; /* Size of the rendering buffer */ | ||||
| 31853 | char *zExtra = 0; /* Malloced memory used by some conversion */ | ||||
| 31854 | int exp, e2; /* exponent of real numbers */ | ||||
| 31855 | etByte flag_dp; /* True if decimal point should be shown */ | ||||
| 31856 | etByte flag_rtz; /* True if trailing zeros should be removed */ | ||||
| 31857 | |||||
| 31858 | PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */ | ||||
| 31859 | char buf[etBUFSIZE70]; /* Conversion buffer */ | ||||
| 31860 | |||||
| 31861 | /* pAccum never starts out with an empty buffer that was obtained from | ||||
| 31862 | ** malloc(). This precondition is required by the mprintf("%z...") | ||||
| 31863 | ** optimization. */ | ||||
| 31864 | assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 )((void) (0)); | ||||
| 31865 | |||||
| 31866 | bufpt = 0; | ||||
| 31867 | if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC0x02)!=0 ){ | ||||
| 31868 | pArgList = va_arg(ap, PrintfArguments*)__builtin_va_arg(ap, PrintfArguments*); | ||||
| 31869 | bArgList = 1; | ||||
| 31870 | }else{ | ||||
| 31871 | bArgList = 0; | ||||
| 31872 | } | ||||
| 31873 | for(; (c=(*fmt))!=0; ++fmt){ | ||||
| 31874 | if( c!='%' ){ | ||||
| 31875 | bufpt = (char *)fmt; | ||||
| 31876 | #if HAVE_STRCHRNUL | ||||
| 31877 | fmt = strchrnul(fmt, '%'); | ||||
| 31878 | #else | ||||
| 31879 | do{ fmt++; }while( *fmt && *fmt != '%' ); | ||||
| 31880 | #endif | ||||
| 31881 | sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt)); | ||||
| 31882 | if( *fmt==0 ) break; | ||||
| 31883 | } | ||||
| 31884 | if( (c=(*++fmt))==0 ){ | ||||
| 31885 | sqlite3_str_append(pAccum, "%", 1); | ||||
| 31886 | break; | ||||
| 31887 | } | ||||
| 31888 | /* Find out what flags are present */ | ||||
| 31889 | flag_leftjustify = flag_prefix = cThousand = | ||||
| 31890 | flag_alternateform = flag_altform2 = flag_zeropad = 0; | ||||
| 31891 | done = 0; | ||||
| 31892 | width = 0; | ||||
| 31893 | flag_long = 0; | ||||
| 31894 | precision = -1; | ||||
| 31895 | do{ | ||||
| 31896 | switch( c ){ | ||||
| 31897 | case '-': flag_leftjustify = 1; break; | ||||
| 31898 | case '+': flag_prefix = '+'; break; | ||||
| 31899 | case ' ': flag_prefix = ' '; break; | ||||
| 31900 | case '#': flag_alternateform = 1; break; | ||||
| 31901 | case '!': flag_altform2 = 1; break; | ||||
| 31902 | case '0': flag_zeropad = 1; break; | ||||
| 31903 | case ',': cThousand = ','; break; | ||||
| 31904 | default: done = 1; break; | ||||
| 31905 | case 'l': { | ||||
| 31906 | flag_long = 1; | ||||
| 31907 | c = *++fmt; | ||||
| 31908 | if( c=='l' ){ | ||||
| 31909 | c = *++fmt; | ||||
| 31910 | flag_long = 2; | ||||
| 31911 | } | ||||
| 31912 | done = 1; | ||||
| 31913 | break; | ||||
| 31914 | } | ||||
| 31915 | case '1': case '2': case '3': case '4': case '5': | ||||
| 31916 | case '6': case '7': case '8': case '9': { | ||||
| 31917 | unsigned wx = c - '0'; | ||||
| 31918 | while( (c = *++fmt)>='0' && c<='9' ){ | ||||
| 31919 | wx = wx*10 + c - '0'; | ||||
| 31920 | } | ||||
| 31921 | testcase( wx>0x7fffffff ); | ||||
| 31922 | width = wx & 0x7fffffff; | ||||
| 31923 | #ifdef SQLITE_PRINTF_PRECISION_LIMIT | ||||
| 31924 | if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ | ||||
| 31925 | width = SQLITE_PRINTF_PRECISION_LIMIT; | ||||
| 31926 | } | ||||
| 31927 | #endif | ||||
| 31928 | if( c!='.' && c!='l' ){ | ||||
| 31929 | done = 1; | ||||
| 31930 | }else{ | ||||
| 31931 | fmt--; | ||||
| 31932 | } | ||||
| 31933 | break; | ||||
| 31934 | } | ||||
| 31935 | case '*': { | ||||
| 31936 | if( bArgList ){ | ||||
| 31937 | width = (int)getIntArg(pArgList); | ||||
| 31938 | }else{ | ||||
| 31939 | width = va_arg(ap,int)__builtin_va_arg(ap, int); | ||||
| 31940 | } | ||||
| 31941 | if( width<0 ){ | ||||
| 31942 | flag_leftjustify = 1; | ||||
| 31943 | width = width >= -2147483647 ? -width : 0; | ||||
| 31944 | } | ||||
| 31945 | #ifdef SQLITE_PRINTF_PRECISION_LIMIT | ||||
| 31946 | if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ | ||||
| 31947 | width = SQLITE_PRINTF_PRECISION_LIMIT; | ||||
| 31948 | } | ||||
| 31949 | #endif | ||||
| 31950 | if( (c = fmt[1])!='.' && c!='l' ){ | ||||
| 31951 | c = *++fmt; | ||||
| 31952 | done = 1; | ||||
| 31953 | } | ||||
| 31954 | break; | ||||
| 31955 | } | ||||
| 31956 | case '.': { | ||||
| 31957 | c = *++fmt; | ||||
| 31958 | if( c=='*' ){ | ||||
| 31959 | if( bArgList ){ | ||||
| 31960 | precision = (int)getIntArg(pArgList); | ||||
| 31961 | }else{ | ||||
| 31962 | precision = va_arg(ap,int)__builtin_va_arg(ap, int); | ||||
| 31963 | } | ||||
| 31964 | if( precision<0 ){ | ||||
| 31965 | precision = precision >= -2147483647 ? -precision : -1; | ||||
| 31966 | } | ||||
| 31967 | c = *++fmt; | ||||
| 31968 | }else{ | ||||
| 31969 | unsigned px = 0; | ||||
| 31970 | while( c>='0' && c<='9' ){ | ||||
| 31971 | px = px*10 + c - '0'; | ||||
| 31972 | c = *++fmt; | ||||
| 31973 | } | ||||
| 31974 | testcase( px>0x7fffffff ); | ||||
| 31975 | precision = px & 0x7fffffff; | ||||
| 31976 | } | ||||
| 31977 | #ifdef SQLITE_PRINTF_PRECISION_LIMIT | ||||
| 31978 | if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){ | ||||
| 31979 | precision = SQLITE_PRINTF_PRECISION_LIMIT; | ||||
| 31980 | } | ||||
| 31981 | #endif | ||||
| 31982 | if( c=='l' ){ | ||||
| 31983 | --fmt; | ||||
| 31984 | }else{ | ||||
| 31985 | done = 1; | ||||
| 31986 | } | ||||
| 31987 | break; | ||||
| 31988 | } | ||||
| 31989 | } | ||||
| 31990 | }while( !done && (c=(*++fmt))!=0 ); | ||||
| 31991 | |||||
| 31992 | /* Fetch the info entry for the field */ | ||||
| 31993 | infop = &fmtinfo[0]; | ||||
| 31994 | xtype = etINVALID17; | ||||
| 31995 | for(idx=0; idx<ArraySize(fmtinfo)((int)(sizeof(fmtinfo)/sizeof(fmtinfo[0]))); idx++){ | ||||
| 31996 | if( c==fmtinfo[idx].fmttype ){ | ||||
| 31997 | infop = &fmtinfo[idx]; | ||||
| 31998 | xtype = infop->type; | ||||
| 31999 | break; | ||||
| 32000 | } | ||||
| 32001 | } | ||||
| 32002 | |||||
| 32003 | /* | ||||
| 32004 | ** At this point, variables are initialized as follows: | ||||
| 32005 | ** | ||||
| 32006 | ** flag_alternateform TRUE if a '#' is present. | ||||
| 32007 | ** flag_altform2 TRUE if a '!' is present. | ||||
| 32008 | ** flag_prefix '+' or ' ' or zero | ||||
| 32009 | ** flag_leftjustify TRUE if a '-' is present or if the | ||||
| 32010 | ** field width was negative. | ||||
| 32011 | ** flag_zeropad TRUE if the width began with 0. | ||||
| 32012 | ** flag_long 1 for "l", 2 for "ll" | ||||
| 32013 | ** width The specified field width. This is | ||||
| 32014 | ** always non-negative. Zero is the default. | ||||
| 32015 | ** precision The specified precision. The default | ||||
| 32016 | ** is -1. | ||||
| 32017 | ** xtype The class of the conversion. | ||||
| 32018 | ** infop Pointer to the appropriate info struct. | ||||
| 32019 | */ | ||||
| 32020 | assert( width>=0 )((void) (0)); | ||||
| 32021 | assert( precision>=(-1) )((void) (0)); | ||||
| 32022 | switch( xtype ){ | ||||
| 32023 | case etPOINTER13: | ||||
| 32024 | flag_long = sizeof(char*)==sizeof(i64) ? 2 : | ||||
| 32025 | sizeof(char*)==sizeof(long int) ? 1 : 0; | ||||
| 32026 | /* no break */ deliberate_fall_through__attribute__((fallthrough)); | ||||
| 32027 | case etORDINAL15: | ||||
| 32028 | case etRADIX0: | ||||
| 32029 | cThousand = 0; | ||||
| 32030 | /* no break */ deliberate_fall_through__attribute__((fallthrough)); | ||||
| 32031 | case etDECIMAL16: | ||||
| 32032 | if( infop->flags & FLAG_SIGNED1 ){ | ||||
| 32033 | i64 v; | ||||
| 32034 | if( bArgList ){ | ||||
| 32035 | v = getIntArg(pArgList); | ||||
| 32036 | }else if( flag_long ){ | ||||
| 32037 | if( flag_long==2 ){ | ||||
| 32038 | v = va_arg(ap,i64)__builtin_va_arg(ap, i64) ; | ||||
| 32039 | }else{ | ||||
| 32040 | v = va_arg(ap,long int)__builtin_va_arg(ap, long int); | ||||
| 32041 | } | ||||
| 32042 | }else{ | ||||
| 32043 | v = va_arg(ap,int)__builtin_va_arg(ap, int); | ||||
| 32044 | } | ||||
| 32045 | if( v<0 ){ | ||||
| 32046 | testcase( v==SMALLEST_INT64 ); | ||||
| 32047 | testcase( v==(-1) ); | ||||
| 32048 | longvalue = ~v; | ||||
| 32049 | longvalue++; | ||||
| 32050 | prefix = '-'; | ||||
| 32051 | }else{ | ||||
| 32052 | longvalue = v; | ||||
| 32053 | prefix = flag_prefix; | ||||
| 32054 | } | ||||
| 32055 | }else{ | ||||
| 32056 | if( bArgList ){ | ||||
| 32057 | longvalue = (u64)getIntArg(pArgList); | ||||
| 32058 | }else if( flag_long ){ | ||||
| 32059 | if( flag_long==2 ){ | ||||
| 32060 | longvalue = va_arg(ap,u64)__builtin_va_arg(ap, u64); | ||||
| 32061 | }else{ | ||||
| 32062 | longvalue = va_arg(ap,unsigned long int)__builtin_va_arg(ap, unsigned long int); | ||||
| 32063 | } | ||||
| 32064 | }else{ | ||||
| 32065 | longvalue = va_arg(ap,unsigned int)__builtin_va_arg(ap, unsigned int); | ||||
| 32066 | } | ||||
| 32067 | prefix = 0; | ||||
| 32068 | } | ||||
| 32069 | if( longvalue==0 ) flag_alternateform = 0; | ||||
| 32070 | if( flag_zeropad && precision<width-(prefix!=0) ){ | ||||
| 32071 | precision = width-(prefix!=0); | ||||
| 32072 | } | ||||
| 32073 | if( precision<etBUFSIZE70-10-etBUFSIZE70/3 ){ | ||||
| 32074 | nOut = etBUFSIZE70; | ||||
| 32075 | zOut = buf; | ||||
| 32076 | }else{ | ||||
| 32077 | u64 n; | ||||
| 32078 | n = (u64)precision + 10; | ||||
| 32079 | if( cThousand ) n += precision/3; | ||||
| 32080 | zOut = zExtra = printfTempBuf(pAccum, n); | ||||
| 32081 | if( zOut==0 ) return; | ||||
| 32082 | nOut = (int)n; | ||||
| 32083 | } | ||||
| 32084 | bufpt = &zOut[nOut-1]; | ||||
| 32085 | if( xtype==etORDINAL15 ){ | ||||
| 32086 | static const char zOrd[] = "thstndrd"; | ||||
| 32087 | int x = (int)(longvalue % 10); | ||||
| 32088 | if( x>=4 || (longvalue/10)%10==1 ){ | ||||
| 32089 | x = 0; | ||||
| 32090 | } | ||||
| 32091 | *(--bufpt) = zOrd[x*2+1]; | ||||
| 32092 | *(--bufpt) = zOrd[x*2]; | ||||
| 32093 | } | ||||
| 32094 | { | ||||
| 32095 | const char *cset = &aDigits[infop->charset]; | ||||
| 32096 | u8 base = infop->base; | ||||
| 32097 | do{ /* Convert to ascii */ | ||||
| 32098 | *(--bufpt) = cset[longvalue%base]; | ||||
| 32099 | longvalue = longvalue/base; | ||||
| 32100 | }while( longvalue>0 ); | ||||
| 32101 | } | ||||
| 32102 | length = (int)(&zOut[nOut-1]-bufpt); | ||||
| 32103 | while( precision>length ){ | ||||
| 32104 | *(--bufpt) = '0'; /* Zero pad */ | ||||
| 32105 | length++; | ||||
| 32106 | } | ||||
| 32107 | if( cThousand ){ | ||||
| 32108 | int nn = (length - 1)/3; /* Number of "," to insert */ | ||||
| 32109 | int ix = (length - 1)%3 + 1; | ||||
| 32110 | bufpt -= nn; | ||||
| 32111 | for(idx=0; nn>0; idx++){ | ||||
| 32112 | bufpt[idx] = bufpt[idx+nn]; | ||||
| 32113 | ix--; | ||||
| 32114 | if( ix==0 ){ | ||||
| 32115 | bufpt[++idx] = cThousand; | ||||
| 32116 | nn--; | ||||
| 32117 | ix = 3; | ||||
| 32118 | } | ||||
| 32119 | } | ||||
| 32120 | } | ||||
| 32121 | if( prefix ) *(--bufpt) = prefix; /* Add sign */ | ||||
| 32122 | if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ | ||||
| 32123 | const char *pre; | ||||
| 32124 | char x; | ||||
| 32125 | pre = &aPrefix[infop->prefix]; | ||||
| 32126 | for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; | ||||
| 32127 | } | ||||
| 32128 | length = (int)(&zOut[nOut-1]-bufpt); | ||||
| 32129 | break; | ||||
| 32130 | case etFLOAT1: | ||||
| 32131 | case etEXP2: | ||||
| 32132 | case etGENERIC3: { | ||||
| 32133 | FpDecode s; | ||||
| 32134 | int iRound; | ||||
| 32135 | int j; | ||||
| 32136 | |||||
| 32137 | if( bArgList ){ | ||||
| 32138 | realvalue = getDoubleArg(pArgList); | ||||
| 32139 | }else{ | ||||
| 32140 | realvalue = va_arg(ap,double)__builtin_va_arg(ap, double); | ||||
| 32141 | } | ||||
| 32142 | if( precision<0 ) precision = 6; /* Set default precision */ | ||||
| 32143 | #ifdef SQLITE_FP_PRECISION_LIMIT100000000 | ||||
| 32144 | if( precision>SQLITE_FP_PRECISION_LIMIT100000000 ){ | ||||
| 32145 | precision = SQLITE_FP_PRECISION_LIMIT100000000; | ||||
| 32146 | } | ||||
| 32147 | #endif | ||||
| 32148 | if( xtype==etFLOAT1 ){ | ||||
| 32149 | iRound = -precision; | ||||
| 32150 | }else if( xtype==etGENERIC3 ){ | ||||
| 32151 | if( precision==0 ) precision = 1; | ||||
| 32152 | iRound = precision; | ||||
| 32153 | }else{ | ||||
| 32154 | iRound = precision+1; | ||||
| 32155 | } | ||||
| 32156 | sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 26 : 16); | ||||
| 32157 | if( s.isSpecial ){ | ||||
| 32158 | if( s.isSpecial==2 ){ | ||||
| 32159 | bufpt = flag_zeropad ? "null" : "NaN"; | ||||
| 32160 | length = sqlite3Strlen30(bufpt); | ||||
| 32161 | break; | ||||
| 32162 | }else if( flag_zeropad ){ | ||||
| 32163 | s.z[0] = '9'; | ||||
| 32164 | s.iDP = 1000; | ||||
| 32165 | s.n = 1; | ||||
| 32166 | }else{ | ||||
| 32167 | memcpy(buf, "-Inf", 5); | ||||
| 32168 | bufpt = buf; | ||||
| 32169 | if( s.sign=='-' ){ | ||||
| 32170 | /* no-op */ | ||||
| 32171 | }else if( flag_prefix ){ | ||||
| 32172 | buf[0] = flag_prefix; | ||||
| 32173 | }else{ | ||||
| 32174 | bufpt++; | ||||
| 32175 | } | ||||
| 32176 | length = sqlite3Strlen30(bufpt); | ||||
| 32177 | break; | ||||
| 32178 | } | ||||
| 32179 | } | ||||
| 32180 | if( s.sign=='-' ){ | ||||
| 32181 | prefix = '-'; | ||||
| 32182 | }else{ | ||||
| 32183 | prefix = flag_prefix; | ||||
| 32184 | } | ||||
| 32185 | |||||
| 32186 | exp = s.iDP-1; | ||||
| 32187 | |||||
| 32188 | /* | ||||
| 32189 | ** If the field type is etGENERIC, then convert to either etEXP | ||||
| 32190 | ** or etFLOAT, as appropriate. | ||||
| 32191 | */ | ||||
| 32192 | if( xtype==etGENERIC3 ){ | ||||
| 32193 | assert( precision>0 )((void) (0)); | ||||
| 32194 | precision--; | ||||
| 32195 | flag_rtz = !flag_alternateform; | ||||
| 32196 | if( exp<-4 || exp>precision ){ | ||||
| 32197 | xtype = etEXP2; | ||||
| 32198 | }else{ | ||||
| 32199 | precision = precision - exp; | ||||
| 32200 | xtype = etFLOAT1; | ||||
| 32201 | } | ||||
| 32202 | }else{ | ||||
| 32203 | flag_rtz = flag_altform2; | ||||
| 32204 | } | ||||
| 32205 | if( xtype==etEXP2 ){ | ||||
| 32206 | e2 = 0; | ||||
| 32207 | }else{ | ||||
| 32208 | e2 = s.iDP - 1; | ||||
| 32209 | } | ||||
| 32210 | bufpt = buf; | ||||
| 32211 | { | ||||
| 32212 | i64 szBufNeeded; /* Size of a temporary buffer needed */ | ||||
| 32213 | szBufNeeded = MAX(e2,0)((e2)>(0)?(e2):(0))+(i64)precision+(i64)width+15; | ||||
| 32214 | if( cThousand && e2>0 ) szBufNeeded += (e2+2)/3; | ||||
| 32215 | if( szBufNeeded > etBUFSIZE70 ){ | ||||
| 32216 | bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded); | ||||
| 32217 | if( bufpt==0 ) return; | ||||
| 32218 | } | ||||
| 32219 | } | ||||
| 32220 | zOut = bufpt; | ||||
| 32221 | flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; | ||||
| 32222 | /* The sign in front of the number */ | ||||
| 32223 | if( prefix ){ | ||||
| 32224 | *(bufpt++) = prefix; | ||||
| 32225 | } | ||||
| 32226 | /* Digits prior to the decimal point */ | ||||
| 32227 | j = 0; | ||||
| 32228 | if( e2<0 ){ | ||||
| 32229 | *(bufpt++) = '0'; | ||||
| 32230 | }else{ | ||||
| 32231 | for(; e2>=0; e2--){ | ||||
| 32232 | *(bufpt++) = j<s.n ? s.z[j++] : '0'; | ||||
| 32233 | if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ','; | ||||
| 32234 | } | ||||
| 32235 | } | ||||
| 32236 | /* The decimal point */ | ||||
| 32237 | if( flag_dp ){ | ||||
| 32238 | *(bufpt++) = '.'; | ||||
| 32239 | } | ||||
| 32240 | /* "0" digits after the decimal point but before the first | ||||
| 32241 | ** significant digit of the number */ | ||||
| 32242 | for(e2++; e2<0 && precision>0; precision--, e2++){ | ||||
| 32243 | *(bufpt++) = '0'; | ||||
| 32244 | } | ||||
| 32245 | /* Significant digits after the decimal point */ | ||||
| 32246 | while( (precision--)>0 ){ | ||||
| 32247 | *(bufpt++) = j<s.n ? s.z[j++] : '0'; | ||||
| 32248 | } | ||||
| 32249 | /* Remove trailing zeros and the "." if no digits follow the "." */ | ||||
| 32250 | if( flag_rtz && flag_dp ){ | ||||
| 32251 | while( bufpt[-1]=='0' ) *(--bufpt) = 0; | ||||
| 32252 | assert( bufpt>zOut )((void) (0)); | ||||
| 32253 | if( bufpt[-1]=='.' ){ | ||||
| 32254 | if( flag_altform2 ){ | ||||
| 32255 | *(bufpt++) = '0'; | ||||
| 32256 | }else{ | ||||
| 32257 | *(--bufpt) = 0; | ||||
| 32258 | } | ||||
| 32259 | } | ||||
| 32260 | } | ||||
| 32261 | /* Add the "eNNN" suffix */ | ||||
| 32262 | if( xtype==etEXP2 ){ | ||||
| 32263 | exp = s.iDP - 1; | ||||
| 32264 | *(bufpt++) = aDigits[infop->charset]; | ||||
| 32265 | if( exp<0 ){ | ||||
| 32266 | *(bufpt++) = '-'; exp = -exp; | ||||
| 32267 | }else{ | ||||
| 32268 | *(bufpt++) = '+'; | ||||
| 32269 | } | ||||
| 32270 | if( exp>=100 ){ | ||||
| 32271 | *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */ | ||||
| 32272 | exp %= 100; | ||||
| 32273 | } | ||||
| 32274 | *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */ | ||||
| 32275 | *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */ | ||||
| 32276 | } | ||||
| 32277 | *bufpt = 0; | ||||
| 32278 | |||||
| 32279 | /* The converted number is in buf[] and zero terminated. Output it. | ||||
| 32280 | ** Note that the number is in the usual order, not reversed as with | ||||
| 32281 | ** integer conversions. */ | ||||
| 32282 | length = (int)(bufpt-zOut); | ||||
| 32283 | bufpt = zOut; | ||||
| 32284 | |||||
| 32285 | /* Special case: Add leading zeros if the flag_zeropad flag is | ||||
| 32286 | ** set and we are not left justified */ | ||||
| 32287 | if( flag_zeropad && !flag_leftjustify && length < width){ | ||||
| 32288 | int i; | ||||
| 32289 | int nPad = width - length; | ||||
| 32290 | for(i=width; i>=nPad; i--){ | ||||
| 32291 | bufpt[i] = bufpt[i-nPad]; | ||||
| 32292 | } | ||||
| 32293 | i = prefix!=0; | ||||
| 32294 | while( nPad-- ) bufpt[i++] = '0'; | ||||
| 32295 | length = width; | ||||
| 32296 | } | ||||
| 32297 | break; | ||||
| 32298 | } | ||||
| 32299 | case etSIZE4: | ||||
| 32300 | if( !bArgList ){ | ||||
| 32301 | *(va_arg(ap,int*)__builtin_va_arg(ap, int*)) = pAccum->nChar; | ||||
| 32302 | } | ||||
| 32303 | length = width = 0; | ||||
| 32304 | break; | ||||
| 32305 | case etPERCENT7: | ||||
| 32306 | buf[0] = '%'; | ||||
| 32307 | bufpt = buf; | ||||
| 32308 | length = 1; | ||||
| 32309 | break; | ||||
| 32310 | case etCHARX8: | ||||
| 32311 | if( bArgList ){ | ||||
| 32312 | bufpt = getTextArg(pArgList); | ||||
| 32313 | length = 1; | ||||
| 32314 | if( bufpt ){ | ||||
| 32315 | buf[0] = c = *(bufpt++); | ||||
| 32316 | if( (c&0xc0)==0xc0 ){ | ||||
| 32317 | while( length<4 && (bufpt[0]&0xc0)==0x80 ){ | ||||
| 32318 | buf[length++] = *(bufpt++); | ||||
| 32319 | } | ||||
| 32320 | } | ||||
| 32321 | }else{ | ||||
| 32322 | buf[0] = 0; | ||||
| 32323 | } | ||||
| 32324 | }else{ | ||||
| 32325 | unsigned int ch = va_arg(ap,unsigned int)__builtin_va_arg(ap, unsigned int); | ||||
| 32326 | length = sqlite3AppendOneUtf8Character(buf, ch); | ||||
| 32327 | } | ||||
| 32328 | if( precision>1 ){ | ||||
| 32329 | i64 nPrior = 1; | ||||
| 32330 | width -= precision-1; | ||||
| 32331 | if( width>1 && !flag_leftjustify ){ | ||||
| 32332 | sqlite3_str_appendchar(pAccum, width-1, ' '); | ||||
| 32333 | width = 0; | ||||
| 32334 | } | ||||
| 32335 | sqlite3_str_append(pAccum, buf, length); | ||||
| 32336 | precision--; | ||||
| 32337 | while( precision > 1 ){ | ||||
| 32338 | i64 nCopyBytes; | ||||
| 32339 | if( nPrior > precision-1 ) nPrior = precision - 1; | ||||
| 32340 | nCopyBytes = length*nPrior; | ||||
| 32341 | if( nCopyBytes + pAccum->nChar >= pAccum->nAlloc ){ | ||||
| 32342 | sqlite3StrAccumEnlarge(pAccum, nCopyBytes); | ||||
| 32343 | } | ||||
| 32344 | if( pAccum->accError ) break; | ||||
| 32345 | sqlite3_str_append(pAccum, | ||||
| 32346 | &pAccum->zText[pAccum->nChar-nCopyBytes], nCopyBytes); | ||||
| 32347 | precision -= nPrior; | ||||
| 32348 | nPrior *= 2; | ||||
| 32349 | } | ||||
| 32350 | } | ||||
| 32351 | bufpt = buf; | ||||
| 32352 | flag_altform2 = 1; | ||||
| 32353 | goto adjust_width_for_utf8; | ||||
| 32354 | case etSTRING5: | ||||
| 32355 | case etDYNSTRING6: | ||||
| 32356 | if( bArgList ){ | ||||
| 32357 | bufpt = getTextArg(pArgList); | ||||
| 32358 | xtype = etSTRING5; | ||||
| 32359 | }else{ | ||||
| 32360 | bufpt = va_arg(ap,char*)__builtin_va_arg(ap, char*); | ||||
| 32361 | } | ||||
| 32362 | if( bufpt==0 ){ | ||||
| 32363 | bufpt = ""; | ||||
| 32364 | }else if( xtype==etDYNSTRING6 ){ | ||||
| 32365 | if( pAccum->nChar==0 | ||||
| 32366 | && pAccum->mxAlloc | ||||
| 32367 | && width==0 | ||||
| 32368 | && precision<0 | ||||
| 32369 | && pAccum->accError==0 | ||||
| 32370 | ){ | ||||
| 32371 | /* Special optimization for sqlite3_mprintf("%z..."): | ||||
| 32372 | ** Extend an existing memory allocation rather than creating | ||||
| 32373 | ** a new one. */ | ||||
| 32374 | assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 )((void) (0)); | ||||
| 32375 | pAccum->zText = bufpt; | ||||
| 32376 | pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt); | ||||
| 32377 | pAccum->nChar = 0x7fffffff & (int)strlen(bufpt); | ||||
| 32378 | pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED0x04; | ||||
| 32379 | length = 0; | ||||
| 32380 | break; | ||||
| 32381 | } | ||||
| 32382 | zExtra = bufpt; | ||||
| 32383 | } | ||||
| 32384 | if( precision>=0 ){ | ||||
| 32385 | if( flag_altform2 ){ | ||||
| 32386 | /* Set length to the number of bytes needed in order to display | ||||
| 32387 | ** precision characters */ | ||||
| 32388 | unsigned char *z = (unsigned char*)bufpt; | ||||
| 32389 | while( precision-- > 0 && z[0] ){ | ||||
| 32390 | SQLITE_SKIP_UTF8(z){ if( (*(z++))>=0xc0 ){ while( (*z & 0xc0)==0x80 ){ z++ ; } } }; | ||||
| 32391 | } | ||||
| 32392 | length = (int)(z - (unsigned char*)bufpt); | ||||
| 32393 | }else{ | ||||
| 32394 | for(length=0; length<precision && bufpt[length]; length++){} | ||||
| 32395 | } | ||||
| 32396 | }else{ | ||||
| 32397 | length = 0x7fffffff & (int)strlen(bufpt); | ||||
| 32398 | } | ||||
| 32399 | adjust_width_for_utf8: | ||||
| 32400 | if( flag_altform2 && width>0 ){ | ||||
| 32401 | /* Adjust width to account for extra bytes in UTF-8 characters */ | ||||
| 32402 | int ii = length - 1; | ||||
| 32403 | while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++; | ||||
| 32404 | } | ||||
| 32405 | break; | ||||
| 32406 | case etESCAPE_q9: /* %q: Escape ' characters */ | ||||
| 32407 | case etESCAPE_Q10: /* %Q: Escape ' and enclose in '...' */ | ||||
| 32408 | case etESCAPE_w14: { /* %w: Escape " characters */ | ||||
| 32409 | i64 i, j, k, n; | ||||
| 32410 | int needQuote = 0; | ||||
| 32411 | char ch; | ||||
| 32412 | char *escarg; | ||||
| 32413 | char q; | ||||
| 32414 | |||||
| 32415 | if( bArgList ){ | ||||
| 32416 | escarg = getTextArg(pArgList); | ||||
| 32417 | }else{ | ||||
| 32418 | escarg = va_arg(ap,char*)__builtin_va_arg(ap, char*); | ||||
| 32419 | } | ||||
| 32420 | if( escarg==0 ){ | ||||
| 32421 | escarg = (xtype==etESCAPE_Q10 ? "NULL" : "(NULL)"); | ||||
| 32422 | }else if( xtype==etESCAPE_Q10 ){ | ||||
| 32423 | needQuote = 1; | ||||
| 32424 | } | ||||
| 32425 | if( xtype==etESCAPE_w14 ){ | ||||
| 32426 | q = '"'; | ||||
| 32427 | flag_alternateform = 0; | ||||
| 32428 | }else{ | ||||
| 32429 | q = '\''; | ||||
| 32430 | } | ||||
| 32431 | /* For %q, %Q, and %w, the precision is the number of bytes (or | ||||
| 32432 | ** characters if the ! flags is present) to use from the input. | ||||
| 32433 | ** Because of the extra quoting characters inserted, the number | ||||
| 32434 | ** of output characters may be larger than the precision. | ||||
| 32435 | */ | ||||
| 32436 | k = precision; | ||||
| 32437 | for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){ | ||||
| 32438 | if( ch==q ) n++; | ||||
| 32439 | if( flag_altform2 && (ch&0xc0)==0xc0 ){ | ||||
| 32440 | while( (escarg[i+1]&0xc0)==0x80 ){ i++; } | ||||
| 32441 | } | ||||
| 32442 | } | ||||
| 32443 | if( flag_alternateform ){ | ||||
| 32444 | /* For %#q, do unistr()-style backslash escapes for | ||||
| 32445 | ** all control characters, and for backslash itself. | ||||
| 32446 | ** For %#Q, do the same but only if there is at least | ||||
| 32447 | ** one control character. */ | ||||
| 32448 | u32 nBack = 0; | ||||
| 32449 | u32 nCtrl = 0; | ||||
| 32450 | for(k=0; k<i; k++){ | ||||
| 32451 | if( escarg[k]=='\\' ){ | ||||
| 32452 | nBack++; | ||||
| 32453 | }else if( ((u8*)escarg)[k]<=0x1f ){ | ||||
| 32454 | nCtrl++; | ||||
| 32455 | } | ||||
| 32456 | } | ||||
| 32457 | if( nCtrl || xtype==etESCAPE_q9 ){ | ||||
| 32458 | n += nBack + 5*nCtrl; | ||||
| 32459 | if( xtype==etESCAPE_Q10 ){ | ||||
| 32460 | n += 10; | ||||
| 32461 | needQuote = 2; | ||||
| 32462 | } | ||||
| 32463 | }else{ | ||||
| 32464 | flag_alternateform = 0; | ||||
| 32465 | } | ||||
| 32466 | } | ||||
| 32467 | n += i + 3; | ||||
| 32468 | if( n>etBUFSIZE70 ){ | ||||
| 32469 | bufpt = zExtra = printfTempBuf(pAccum, n); | ||||
| 32470 | if( bufpt==0 ) return; | ||||
| 32471 | }else{ | ||||
| 32472 | bufpt = buf; | ||||
| 32473 | } | ||||
| 32474 | j = 0; | ||||
| 32475 | if( needQuote ){ | ||||
| 32476 | if( needQuote==2 ){ | ||||
| 32477 | memcpy(&bufpt[j], "unistr('", 8); | ||||
| 32478 | j += 8; | ||||
| 32479 | }else{ | ||||
| 32480 | bufpt[j++] = '\''; | ||||
| 32481 | } | ||||
| 32482 | } | ||||
| 32483 | k = i; | ||||
| 32484 | if( flag_alternateform ){ | ||||
| 32485 | for(i=0; i<k; i++){ | ||||
| 32486 | bufpt[j++] = ch = escarg[i]; | ||||
| 32487 | if( ch==q ){ | ||||
| 32488 | bufpt[j++] = ch; | ||||
| 32489 | }else if( ch=='\\' ){ | ||||
| 32490 | bufpt[j++] = '\\'; | ||||
| 32491 | }else if( ((unsigned char)ch)<=0x1f ){ | ||||
| 32492 | bufpt[j-1] = '\\'; | ||||
| 32493 | bufpt[j++] = 'u'; | ||||
| 32494 | bufpt[j++] = '0'; | ||||
| 32495 | bufpt[j++] = '0'; | ||||
| 32496 | bufpt[j++] = ch>=0x10 ? '1' : '0'; | ||||
| 32497 | bufpt[j++] = "0123456789abcdef"[ch&0xf]; | ||||
| 32498 | } | ||||
| 32499 | } | ||||
| 32500 | }else{ | ||||
| 32501 | for(i=0; i<k; i++){ | ||||
| 32502 | bufpt[j++] = ch = escarg[i]; | ||||
| 32503 | if( ch==q ) bufpt[j++] = ch; | ||||
| 32504 | } | ||||
| 32505 | } | ||||
| 32506 | if( needQuote ){ | ||||
| 32507 | bufpt[j++] = '\''; | ||||
| 32508 | if( needQuote==2 ) bufpt[j++] = ')'; | ||||
| 32509 | } | ||||
| 32510 | bufpt[j] = 0; | ||||
| 32511 | length = j; | ||||
| 32512 | goto adjust_width_for_utf8; | ||||
| 32513 | } | ||||
| 32514 | case etTOKEN11: { | ||||
| 32515 | if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL0x01)==0 ) return; | ||||
| 32516 | if( flag_alternateform ){ | ||||
| 32517 | /* %#T means an Expr pointer that uses Expr.u.zToken */ | ||||
| 32518 | Expr *pExpr = va_arg(ap,Expr*)__builtin_va_arg(ap, Expr*); | ||||
| 32519 | if( ALWAYS(pExpr)(pExpr) && ALWAYS(!ExprHasProperty(pExpr,EP_IntValue))(!(((pExpr)->flags&(u32)(0x000800))!=0)) ){ | ||||
| 32520 | sqlite3_str_appendall(pAccum, (const char*)pExpr->u.zToken); | ||||
| 32521 | sqlite3RecordErrorOffsetOfExpr(pAccum->db, pExpr); | ||||
| 32522 | } | ||||
| 32523 | }else{ | ||||
| 32524 | /* %T means a Token pointer */ | ||||
| 32525 | Token *pToken = va_arg(ap, Token*)__builtin_va_arg(ap, Token*); | ||||
| 32526 | assert( bArgList==0 )((void) (0)); | ||||
| 32527 | if( pToken && pToken->n ){ | ||||
| 32528 | sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n); | ||||
| 32529 | sqlite3RecordErrorByteOffset(pAccum->db, pToken->z); | ||||
| 32530 | } | ||||
| 32531 | } | ||||
| 32532 | length = width = 0; | ||||
| 32533 | break; | ||||
| 32534 | } | ||||
| 32535 | case etSRCITEM12: { | ||||
| 32536 | SrcItem *pItem; | ||||
| 32537 | if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL0x01)==0 ) return; | ||||
| 32538 | pItem = va_arg(ap, SrcItem*)__builtin_va_arg(ap, SrcItem*); | ||||
| 32539 | assert( bArgList==0 )((void) (0)); | ||||
| 32540 | if( pItem->zAlias && !flag_altform2 ){ | ||||
| 32541 | sqlite3_str_appendall(pAccum, pItem->zAlias); | ||||
| 32542 | }else if( pItem->zName ){ | ||||
| 32543 | if( pItem->fg.fixedSchema==0 | ||||
| 32544 | && pItem->fg.isSubquery==0 | ||||
| 32545 | && pItem->u4.zDatabase!=0 | ||||
| 32546 | ){ | ||||
| 32547 | sqlite3_str_appendall(pAccum, pItem->u4.zDatabase); | ||||
| 32548 | sqlite3_str_append(pAccum, ".", 1); | ||||
| 32549 | } | ||||
| 32550 | sqlite3_str_appendall(pAccum, pItem->zName); | ||||
| 32551 | }else if( pItem->zAlias ){ | ||||
| 32552 | sqlite3_str_appendall(pAccum, pItem->zAlias); | ||||
| 32553 | }else if( ALWAYS(pItem->fg.isSubquery)(pItem->fg.isSubquery) ){/* Because of tag-20240424-1 */ | ||||
| 32554 | Select *pSel = pItem->u4.pSubq->pSelect; | ||||
| 32555 | assert( pSel!=0 )((void) (0)); | ||||
| 32556 | if( pSel->selFlags & SF_NestedFrom0x0000800 ){ | ||||
| 32557 | sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId); | ||||
| 32558 | }else if( pSel->selFlags & SF_MultiValue0x0000400 ){ | ||||
| 32559 | assert( !pItem->fg.isTabFunc && !pItem->fg.isIndexedBy )((void) (0)); | ||||
| 32560 | sqlite3_str_appendf(pAccum, "%u-ROW VALUES CLAUSE", | ||||
| 32561 | pItem->u1.nRow); | ||||
| 32562 | }else{ | ||||
| 32563 | sqlite3_str_appendf(pAccum, "(subquery-%u)", pSel->selId); | ||||
| 32564 | } | ||||
| 32565 | } | ||||
| 32566 | length = width = 0; | ||||
| 32567 | break; | ||||
| 32568 | } | ||||
| 32569 | default: { | ||||
| 32570 | assert( xtype==etINVALID )((void) (0)); | ||||
| 32571 | return; | ||||
| 32572 | } | ||||
| 32573 | }/* End switch over the format type */ | ||||
| 32574 | /* | ||||
| 32575 | ** The text of the conversion is pointed to by "bufpt" and is | ||||
| 32576 | ** "length" characters long. The field width is "width". Do | ||||
| 32577 | ** the output. Both length and width are in bytes, not characters, | ||||
| 32578 | ** at this point. If the "!" flag was present on string conversions | ||||
| 32579 | ** indicating that width and precision should be expressed in characters, | ||||
| 32580 | ** then the values have been translated prior to reaching this point. | ||||
| 32581 | */ | ||||
| 32582 | width -= length; | ||||
| 32583 | if( width>0 ){ | ||||
| 32584 | if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' '); | ||||
| 32585 | sqlite3_str_append(pAccum, bufpt, length); | ||||
| 32586 | if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' '); | ||||
| 32587 | }else{ | ||||
| 32588 | sqlite3_str_append(pAccum, bufpt, length); | ||||
| 32589 | } | ||||
| 32590 | |||||
| 32591 | if( zExtra ){ | ||||
| 32592 | sqlite3DbFree(pAccum->db, zExtra); | ||||
| 32593 | zExtra = 0; | ||||
| 32594 | } | ||||
| 32595 | }/* End for loop over the format string */ | ||||
| 32596 | } /* End of function */ | ||||
| 32597 | |||||
| 32598 | |||||
| 32599 | /* | ||||
| 32600 | ** The z string points to the first character of a token that is | ||||
| 32601 | ** associated with an error. If db does not already have an error | ||||
| 32602 | ** byte offset recorded, try to compute the error byte offset for | ||||
| 32603 | ** z and set the error byte offset in db. | ||||
| 32604 | */ | ||||
| 32605 | SQLITE_PRIVATEstatic void sqlite3RecordErrorByteOffset(sqlite3 *db, const char *z){ | ||||
| 32606 | const Parse *pParse; | ||||
| 32607 | const char *zText; | ||||
| 32608 | const char *zEnd; | ||||
| 32609 | assert( z!=0 )((void) (0)); | ||||
| 32610 | if( NEVER(db==0)(db==0) ) return; | ||||
| 32611 | if( db->errByteOffset!=(-2) ) return; | ||||
| 32612 | pParse = db->pParse; | ||||
| 32613 | if( NEVER(pParse==0)(pParse==0) ) return; | ||||
| 32614 | zText =pParse->zTail; | ||||
| 32615 | if( NEVER(zText==0)(zText==0) ) return; | ||||
| 32616 | zEnd = &zText[strlen(zText)]; | ||||
| 32617 | if( SQLITE_WITHIN(z,zText,zEnd)(((uptr)(z)>=(uptr)(zText))&&((uptr)(z)<(uptr)( zEnd))) ){ | ||||
| 32618 | db->errByteOffset = (int)(z-zText); | ||||
| 32619 | } | ||||
| 32620 | } | ||||
| 32621 | |||||
| 32622 | /* | ||||
| 32623 | ** If pExpr has a byte offset for the start of a token, record that as | ||||
| 32624 | ** as the error offset. | ||||
| 32625 | */ | ||||
| 32626 | SQLITE_PRIVATEstatic void sqlite3RecordErrorOffsetOfExpr(sqlite3 *db, const Expr *pExpr){ | ||||
| 32627 | while( pExpr | ||||
| 32628 | && (ExprHasProperty(pExpr,EP_OuterON|EP_InnerON)(((pExpr)->flags&(u32)(0x000001|0x000002))!=0) || pExpr->w.iOfst<=0) | ||||
| 32629 | ){ | ||||
| 32630 | pExpr = pExpr->pLeft; | ||||
| 32631 | } | ||||
| 32632 | if( pExpr==0 ) return; | ||||
| 32633 | if( ExprHasProperty(pExpr, EP_FromDDL)(((pExpr)->flags&(u32)(0x40000000))!=0) ) return; | ||||
| 32634 | db->errByteOffset = pExpr->w.iOfst; | ||||
| 32635 | } | ||||
| 32636 | |||||
| 32637 | /* | ||||
| 32638 | ** Enlarge the memory allocation on a StrAccum object so that it is | ||||
| 32639 | ** able to accept at least N more bytes of text. | ||||
| 32640 | ** | ||||
| 32641 | ** Return the number of bytes of text that StrAccum is able to accept | ||||
| 32642 | ** after the attempted enlargement. The value returned might be zero. | ||||
| 32643 | */ | ||||
| 32644 | SQLITE_PRIVATEstatic int sqlite3StrAccumEnlarge(StrAccum *p, i64 N){ | ||||
| 32645 | char *zNew; | ||||
| 32646 | assert( p->nChar+N >= p->nAlloc )((void) (0)); /* Only called if really needed */ | ||||
| 32647 | if( p->accError ){ | ||||
| 32648 | testcase(p->accError==SQLITE_TOOBIG); | ||||
| 32649 | testcase(p->accError==SQLITE_NOMEM); | ||||
| 32650 | return 0; | ||||
| 32651 | } | ||||
| 32652 | if( p->mxAlloc==0 ){ | ||||
| 32653 | sqlite3StrAccumSetError(p, SQLITE_TOOBIG18); | ||||
| 32654 | return p->nAlloc - p->nChar - 1; | ||||
| 32655 | }else{ | ||||
| 32656 | char *zOld = isMalloced(p)(((p)->printfFlags & 0x04)!=0) ? p->zText : 0; | ||||
| 32657 | i64 szNew = p->nChar + N + 1; | ||||
| 32658 | if( szNew+p->nChar<=p->mxAlloc ){ | ||||
| 32659 | /* Force exponential buffer size growth as long as it does not overflow, | ||||
| 32660 | ** to avoid having to call this routine too often */ | ||||
| 32661 | szNew += p->nChar; | ||||
| 32662 | } | ||||
| 32663 | if( szNew > p->mxAlloc ){ | ||||
| 32664 | sqlite3_str_reset(p); | ||||
| 32665 | sqlite3StrAccumSetError(p, SQLITE_TOOBIG18); | ||||
| 32666 | return 0; | ||||
| 32667 | }else{ | ||||
| 32668 | p->nAlloc = (int)szNew; | ||||
| 32669 | } | ||||
| 32670 | if( p->db ){ | ||||
| 32671 | zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); | ||||
| 32672 | }else{ | ||||
| 32673 | zNew = sqlite3Realloc(zOld, p->nAlloc); | ||||
| 32674 | } | ||||
| 32675 | if( zNew ){ | ||||
| 32676 | assert( p->zText!=0 || p->nChar==0 )((void) (0)); | ||||
| 32677 | if( !isMalloced(p)(((p)->printfFlags & 0x04)!=0) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); | ||||
| 32678 | p->zText = zNew; | ||||
| 32679 | p->nAlloc = sqlite3DbMallocSize(p->db, zNew); | ||||
| 32680 | p->printfFlags |= SQLITE_PRINTF_MALLOCED0x04; | ||||
| 32681 | }else{ | ||||
| 32682 | sqlite3_str_reset(p); | ||||
| 32683 | sqlite3StrAccumSetError(p, SQLITE_NOMEM7); | ||||
| 32684 | return 0; | ||||
| 32685 | } | ||||
| 32686 | } | ||||
| 32687 | assert( N>=0 && N<=0x7fffffff )((void) (0)); | ||||
| 32688 | return (int)N; | ||||
| 32689 | } | ||||
| 32690 | |||||
| 32691 | /* | ||||
| 32692 | ** Append N copies of character c to the given string buffer. | ||||
| 32693 | */ | ||||
| 32694 | SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){ | ||||
| 32695 | testcase( p->nChar + (i64)N > 0x7fffffff ); | ||||
| 32696 | if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){ | ||||
| 32697 | return; | ||||
| 32698 | } | ||||
| 32699 | while( (N--)>0 ) p->zText[p->nChar++] = c; | ||||
| 32700 | } | ||||
| 32701 | |||||
| 32702 | /* | ||||
| 32703 | ** The StrAccum "p" is not large enough to accept N new bytes of z[]. | ||||
| 32704 | ** So enlarge if first, then do the append. | ||||
| 32705 | ** | ||||
| 32706 | ** This is a helper routine to sqlite3_str_append() that does special-case | ||||
| 32707 | ** work (enlarging the buffer) using tail recursion, so that the | ||||
| 32708 | ** sqlite3_str_append() routine can use fast calling semantics. | ||||
| 32709 | */ | ||||
| 32710 | static void SQLITE_NOINLINE__attribute__((noinline)) enlargeAndAppend(StrAccum *p, const char *z, int N){ | ||||
| 32711 | N = sqlite3StrAccumEnlarge(p, N); | ||||
| 32712 | if( N>0 ){ | ||||
| 32713 | memcpy(&p->zText[p->nChar], z, N); | ||||
| 32714 | p->nChar += N; | ||||
| 32715 | } | ||||
| 32716 | } | ||||
| 32717 | |||||
| 32718 | /* | ||||
| 32719 | ** Append N bytes of text from z to the StrAccum object. Increase the | ||||
| 32720 | ** size of the memory allocation for StrAccum if necessary. | ||||
| 32721 | */ | ||||
| 32722 | SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){ | ||||
| 32723 | assert( z!=0 || N==0 )((void) (0)); | ||||
| 32724 | assert( p->zText!=0 || p->nChar==0 || p->accError )((void) (0)); | ||||
| 32725 | assert( N>=0 )((void) (0)); | ||||
| 32726 | assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 )((void) (0)); | ||||
| 32727 | if( p->nChar+N >= p->nAlloc ){ | ||||
| 32728 | enlargeAndAppend(p,z,N); | ||||
| 32729 | }else if( N ){ | ||||
| 32730 | assert( p->zText )((void) (0)); | ||||
| 32731 | p->nChar += N; | ||||
| 32732 | memcpy(&p->zText[p->nChar-N], z, N); | ||||
| 32733 | } | ||||
| 32734 | } | ||||
| 32735 | |||||
| 32736 | /* | ||||
| 32737 | ** Append the complete text of zero-terminated string z[] to the p string. | ||||
| 32738 | */ | ||||
| 32739 | SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){ | ||||
| 32740 | sqlite3_str_append(p, z, sqlite3Strlen30(z)); | ||||
| 32741 | } | ||||
| 32742 | |||||
| 32743 | |||||
| 32744 | /* | ||||
| 32745 | ** Finish off a string by making sure it is zero-terminated. | ||||
| 32746 | ** Return a pointer to the resulting string. Return a NULL | ||||
| 32747 | ** pointer if any kind of error was encountered. | ||||
| 32748 | */ | ||||
| 32749 | static SQLITE_NOINLINE__attribute__((noinline)) char *strAccumFinishRealloc(StrAccum *p){ | ||||
| 32750 | char *zText; | ||||
| 32751 | assert( p->mxAlloc>0 && !isMalloced(p) )((void) (0)); | ||||
| 32752 | zText = sqlite3DbMallocRaw(p->db, 1+(u64)p->nChar ); | ||||
| 32753 | if( zText ){ | ||||
| 32754 | memcpy(zText, p->zText, p->nChar+1); | ||||
| 32755 | p->printfFlags |= SQLITE_PRINTF_MALLOCED0x04; | ||||
| 32756 | }else{ | ||||
| 32757 | sqlite3StrAccumSetError(p, SQLITE_NOMEM7); | ||||
| 32758 | } | ||||
| 32759 | p->zText = zText; | ||||
| 32760 | return zText; | ||||
| 32761 | } | ||||
| 32762 | SQLITE_PRIVATEstatic char *sqlite3StrAccumFinish(StrAccum *p){ | ||||
| 32763 | if( p->zText ){ | ||||
| 32764 | p->zText[p->nChar] = 0; | ||||
| 32765 | if( p->mxAlloc>0 && !isMalloced(p)(((p)->printfFlags & 0x04)!=0) ){ | ||||
| 32766 | return strAccumFinishRealloc(p); | ||||
| 32767 | } | ||||
| 32768 | } | ||||
| 32769 | return p->zText; | ||||
| 32770 | } | ||||
| 32771 | |||||
| 32772 | /* | ||||
| 32773 | ** Use the content of the StrAccum passed as the second argument | ||||
| 32774 | ** as the result of an SQL function. | ||||
| 32775 | */ | ||||
| 32776 | SQLITE_PRIVATEstatic void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){ | ||||
| 32777 | if( p->accError ){ | ||||
| 32778 | sqlite3_result_error_code(pCtx, p->accError); | ||||
| 32779 | sqlite3_str_reset(p); | ||||
| 32780 | }else if( isMalloced(p)(((p)->printfFlags & 0x04)!=0) ){ | ||||
| 32781 | sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC((sqlite3_destructor_type)sqlite3OomClear)); | ||||
| 32782 | }else{ | ||||
| 32783 | sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC((sqlite3_destructor_type)0)); | ||||
| 32784 | sqlite3_str_reset(p); | ||||
| 32785 | } | ||||
| 32786 | } | ||||
| 32787 | |||||
| 32788 | /* | ||||
| 32789 | ** This singleton is an sqlite3_str object that is returned if | ||||
| 32790 | ** sqlite3_malloc() fails to provide space for a real one. This | ||||
| 32791 | ** sqlite3_str object accepts no new text and always returns | ||||
| 32792 | ** an SQLITE_NOMEM error. | ||||
| 32793 | */ | ||||
| 32794 | static sqlite3_str sqlite3OomStr = { | ||||
| 32795 | 0, 0, 0, 0, 0, SQLITE_NOMEM7, 0 | ||||
| 32796 | }; | ||||
| 32797 | |||||
| 32798 | /* Finalize a string created using sqlite3_str_new(). | ||||
| 32799 | */ | ||||
| 32800 | SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){ | ||||
| 32801 | char *z; | ||||
| 32802 | if( p!=0 && p!=&sqlite3OomStr ){ | ||||
| 32803 | z = sqlite3StrAccumFinish(p); | ||||
| 32804 | sqlite3_free(p); | ||||
| 32805 | }else{ | ||||
| 32806 | z = 0; | ||||
| 32807 | } | ||||
| 32808 | return z; | ||||
| 32809 | } | ||||
| 32810 | |||||
| 32811 | /* Return any error code associated with p */ | ||||
| 32812 | SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){ | ||||
| 32813 | return p ? p->accError : SQLITE_NOMEM7; | ||||
| 32814 | } | ||||
| 32815 | |||||
| 32816 | /* Return the current length of p in bytes */ | ||||
| 32817 | SQLITE_API int sqlite3_str_length(sqlite3_str *p){ | ||||
| 32818 | return p ? p->nChar : 0; | ||||
| 32819 | } | ||||
| 32820 | |||||
| 32821 | /* Return the current value for p */ | ||||
| 32822 | SQLITE_API char *sqlite3_str_value(sqlite3_str *p){ | ||||
| 32823 | if( p==0 || p->nChar==0 ) return 0; | ||||
| 32824 | p->zText[p->nChar] = 0; | ||||
| 32825 | return p->zText; | ||||
| 32826 | } | ||||
| 32827 | |||||
| 32828 | /* | ||||
| 32829 | ** Reset an StrAccum string. Reclaim all malloced memory. | ||||
| 32830 | */ | ||||
| 32831 | SQLITE_API void sqlite3_str_reset(StrAccum *p){ | ||||
| 32832 | if( isMalloced(p)(((p)->printfFlags & 0x04)!=0) ){ | ||||
| 32833 | sqlite3DbFree(p->db, p->zText); | ||||
| 32834 | p->printfFlags &= ~SQLITE_PRINTF_MALLOCED0x04; | ||||
| 32835 | } | ||||
| 32836 | p->nAlloc = 0; | ||||
| 32837 | p->nChar = 0; | ||||
| 32838 | p->zText = 0; | ||||
| 32839 | } | ||||
| 32840 | |||||
| 32841 | /* | ||||
| 32842 | ** Initialize a string accumulator. | ||||
| 32843 | ** | ||||
| 32844 | ** p: The accumulator to be initialized. | ||||
| 32845 | ** db: Pointer to a database connection. May be NULL. Lookaside | ||||
| 32846 | ** memory is used if not NULL. db->mallocFailed is set appropriately | ||||
| 32847 | ** when not NULL. | ||||
| 32848 | ** zBase: An initial buffer. May be NULL in which case the initial buffer | ||||
| 32849 | ** is malloced. | ||||
| 32850 | ** n: Size of zBase in bytes. If total space requirements never exceed | ||||
| 32851 | ** n then no memory allocations ever occur. | ||||
| 32852 | ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory | ||||
| 32853 | ** allocations will ever occur. | ||||
| 32854 | */ | ||||
| 32855 | SQLITE_PRIVATEstatic void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){ | ||||
| 32856 | p->zText = zBase; | ||||
| 32857 | p->db = db; | ||||
| 32858 | p->nAlloc = n; | ||||
| 32859 | p->mxAlloc = mx; | ||||
| 32860 | p->nChar = 0; | ||||
| 32861 | p->accError = 0; | ||||
| 32862 | p->printfFlags = 0; | ||||
| 32863 | } | ||||
| 32864 | |||||
| 32865 | /* Allocate and initialize a new dynamic string object */ | ||||
| 32866 | SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){ | ||||
| 32867 | sqlite3_str *p = sqlite3_malloc64(sizeof(*p)); | ||||
| 32868 | if( p ){ | ||||
| 32869 | sqlite3StrAccumInit(p, 0, 0, 0, | ||||
| 32870 | db ? db->aLimit[SQLITE_LIMIT_LENGTH0] : SQLITE_MAX_LENGTH2147483645); | ||||
| 32871 | }else{ | ||||
| 32872 | p = &sqlite3OomStr; | ||||
| 32873 | } | ||||
| 32874 | return p; | ||||
| 32875 | } | ||||
| 32876 | |||||
| 32877 | /* | ||||
| 32878 | ** Print into memory obtained from sqliteMalloc(). Use the internal | ||||
| 32879 | ** %-conversion extensions. | ||||
| 32880 | */ | ||||
| 32881 | SQLITE_PRIVATEstatic char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ | ||||
| 32882 | char *z; | ||||
| 32883 | char zBase[SQLITE_PRINT_BUF_SIZE70]; | ||||
| 32884 | StrAccum acc; | ||||
| 32885 | assert( db!=0 )((void) (0)); | ||||
| 32886 | sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase), | ||||
| 32887 | db->aLimit[SQLITE_LIMIT_LENGTH0]); | ||||
| 32888 | acc.printfFlags = SQLITE_PRINTF_INTERNAL0x01; | ||||
| 32889 | sqlite3_str_vappendf(&acc, zFormat, ap); | ||||
| 32890 | z = sqlite3StrAccumFinish(&acc); | ||||
| 32891 | if( acc.accError==SQLITE_NOMEM7 ){ | ||||
| 32892 | sqlite3OomFault(db); | ||||
| 32893 | } | ||||
| 32894 | return z; | ||||
| 32895 | } | ||||
| 32896 | |||||
| 32897 | /* | ||||
| 32898 | ** Print into memory obtained from sqliteMalloc(). Use the internal | ||||
| 32899 | ** %-conversion extensions. | ||||
| 32900 | */ | ||||
| 32901 | SQLITE_PRIVATEstatic char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ | ||||
| 32902 | va_list ap; | ||||
| 32903 | char *z; | ||||
| 32904 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 32905 | z = sqlite3VMPrintf(db, zFormat, ap); | ||||
| 32906 | va_end(ap)__builtin_va_end(ap); | ||||
| 32907 | return z; | ||||
| 32908 | } | ||||
| 32909 | |||||
| 32910 | /* | ||||
| 32911 | ** Print into memory obtained from sqlite3_malloc(). Omit the internal | ||||
| 32912 | ** %-conversion extensions. | ||||
| 32913 | */ | ||||
| 32914 | SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){ | ||||
| 32915 | char *z; | ||||
| 32916 | char zBase[SQLITE_PRINT_BUF_SIZE70]; | ||||
| 32917 | StrAccum acc; | ||||
| 32918 | |||||
| 32919 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 32920 | if( zFormat==0 ){ | ||||
| 32921 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(32921); | ||||
| 32922 | return 0; | ||||
| 32923 | } | ||||
| 32924 | #endif | ||||
| 32925 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 32926 | if( sqlite3_initialize() ) return 0; | ||||
| 32927 | #endif | ||||
| 32928 | sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH2147483645); | ||||
| 32929 | sqlite3_str_vappendf(&acc, zFormat, ap); | ||||
| 32930 | z = sqlite3StrAccumFinish(&acc); | ||||
| 32931 | return z; | ||||
| 32932 | } | ||||
| 32933 | |||||
| 32934 | /* | ||||
| 32935 | ** Print into memory obtained from sqlite3_malloc()(). Omit the internal | ||||
| 32936 | ** %-conversion extensions. | ||||
| 32937 | */ | ||||
| 32938 | SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){ | ||||
| 32939 | va_list ap; | ||||
| 32940 | char *z; | ||||
| 32941 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 32942 | if( sqlite3_initialize() ) return 0; | ||||
| 32943 | #endif | ||||
| 32944 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 32945 | z = sqlite3_vmprintf(zFormat, ap); | ||||
| 32946 | va_end(ap)__builtin_va_end(ap); | ||||
| 32947 | return z; | ||||
| 32948 | } | ||||
| 32949 | |||||
| 32950 | /* | ||||
| 32951 | ** sqlite3_snprintf() works like snprintf() except that it ignores the | ||||
| 32952 | ** current locale settings. This is important for SQLite because we | ||||
| 32953 | ** are not able to use a "," as the decimal point in place of "." as | ||||
| 32954 | ** specified by some locales. | ||||
| 32955 | ** | ||||
| 32956 | ** Oops: The first two arguments of sqlite3_snprintf() are backwards | ||||
| 32957 | ** from the snprintf() standard. Unfortunately, it is too late to change | ||||
| 32958 | ** this without breaking compatibility, so we just have to live with the | ||||
| 32959 | ** mistake. | ||||
| 32960 | ** | ||||
| 32961 | ** sqlite3_vsnprintf() is the varargs version. | ||||
| 32962 | */ | ||||
| 32963 | SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ | ||||
| 32964 | StrAccum acc; | ||||
| 32965 | if( n<=0 ) return zBuf; | ||||
| 32966 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 32967 | if( zBuf==0 || zFormat==0 ) { | ||||
| 32968 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(32968); | ||||
| 32969 | if( zBuf ) zBuf[0] = 0; | ||||
| 32970 | return zBuf; | ||||
| 32971 | } | ||||
| 32972 | #endif | ||||
| 32973 | sqlite3StrAccumInit(&acc, 0, zBuf, n, 0); | ||||
| 32974 | sqlite3_str_vappendf(&acc, zFormat, ap); | ||||
| 32975 | zBuf[acc.nChar] = 0; | ||||
| 32976 | return zBuf; | ||||
| 32977 | } | ||||
| 32978 | SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ | ||||
| 32979 | StrAccum acc; | ||||
| 32980 | va_list ap; | ||||
| 32981 | if( n<=0 ) return zBuf; | ||||
| 32982 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 32983 | if( zBuf==0 || zFormat==0 ) { | ||||
| 32984 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(32984); | ||||
| 32985 | if( zBuf ) zBuf[0] = 0; | ||||
| 32986 | return zBuf; | ||||
| 32987 | } | ||||
| 32988 | #endif | ||||
| 32989 | sqlite3StrAccumInit(&acc, 0, zBuf, n, 0); | ||||
| 32990 | va_start(ap,zFormat)__builtin_va_start(ap, zFormat); | ||||
| 32991 | sqlite3_str_vappendf(&acc, zFormat, ap); | ||||
| 32992 | va_end(ap)__builtin_va_end(ap); | ||||
| 32993 | zBuf[acc.nChar] = 0; | ||||
| 32994 | return zBuf; | ||||
| 32995 | } | ||||
| 32996 | |||||
| 32997 | /* Maximum size of an sqlite3_log() message. */ | ||||
| 32998 | #if defined(SQLITE_MAX_LOG_MESSAGE(70*10)) | ||||
| 32999 | /* Leave the definition as supplied */ | ||||
| 33000 | #elif SQLITE_PRINT_BUF_SIZE70*10>10000 | ||||
| 33001 | # define SQLITE_MAX_LOG_MESSAGE(70*10) 10000 | ||||
| 33002 | #else | ||||
| 33003 | # define SQLITE_MAX_LOG_MESSAGE(70*10) (SQLITE_PRINT_BUF_SIZE70*10) | ||||
| 33004 | #endif | ||||
| 33005 | |||||
| 33006 | /* | ||||
| 33007 | ** This is the routine that actually formats the sqlite3_log() message. | ||||
| 33008 | ** We house it in a separate routine from sqlite3_log() to avoid using | ||||
| 33009 | ** stack space on small-stack systems when logging is disabled. | ||||
| 33010 | ** | ||||
| 33011 | ** sqlite3_log() must render into a static buffer. It cannot dynamically | ||||
| 33012 | ** allocate memory because it might be called while the memory allocator | ||||
| 33013 | ** mutex is held. | ||||
| 33014 | ** | ||||
| 33015 | ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for | ||||
| 33016 | ** certain format characters (%q) or for very large precisions or widths. | ||||
| 33017 | ** Care must be taken that any sqlite3_log() calls that occur while the | ||||
| 33018 | ** memory mutex is held do not use these mechanisms. | ||||
| 33019 | */ | ||||
| 33020 | static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ | ||||
| 33021 | StrAccum acc; /* String accumulator */ | ||||
| 33022 | char zMsg[SQLITE_MAX_LOG_MESSAGE(70*10)]; /* Complete log message */ | ||||
| 33023 | |||||
| 33024 | sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0); | ||||
| 33025 | sqlite3_str_vappendf(&acc, zFormat, ap); | ||||
| 33026 | sqlite3GlobalConfigsqlite3Config.xLog(sqlite3GlobalConfigsqlite3Config.pLogArg, iErrCode, | ||||
| 33027 | sqlite3StrAccumFinish(&acc)); | ||||
| 33028 | } | ||||
| 33029 | |||||
| 33030 | /* | ||||
| 33031 | ** Format and write a message to the log if logging is enabled. | ||||
| 33032 | */ | ||||
| 33033 | SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ | ||||
| 33034 | va_list ap; /* Vararg list */ | ||||
| 33035 | if( sqlite3GlobalConfigsqlite3Config.xLog ){ | ||||
| 33036 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 33037 | renderLogMsg(iErrCode, zFormat, ap); | ||||
| 33038 | va_end(ap)__builtin_va_end(ap); | ||||
| 33039 | } | ||||
| 33040 | } | ||||
| 33041 | |||||
| 33042 | #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) | ||||
| 33043 | /* | ||||
| 33044 | ** A version of printf() that understands %lld. Used for debugging. | ||||
| 33045 | ** The printf() built into some versions of windows does not understand %lld | ||||
| 33046 | ** and segfaults if you give it a long long int. | ||||
| 33047 | */ | ||||
| 33048 | SQLITE_PRIVATEstatic void sqlite3DebugPrintf(const char *zFormat, ...){ | ||||
| 33049 | va_list ap; | ||||
| 33050 | StrAccum acc; | ||||
| 33051 | char zBuf[SQLITE_PRINT_BUF_SIZE70*10]; | ||||
| 33052 | sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); | ||||
| 33053 | va_start(ap,zFormat)__builtin_va_start(ap, zFormat); | ||||
| 33054 | sqlite3_str_vappendf(&acc, zFormat, ap); | ||||
| 33055 | va_end(ap)__builtin_va_end(ap); | ||||
| 33056 | sqlite3StrAccumFinish(&acc); | ||||
| 33057 | #ifdef SQLITE_OS_TRACE_PROC | ||||
| 33058 | { | ||||
| 33059 | extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf); | ||||
| 33060 | SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf)); | ||||
| 33061 | } | ||||
| 33062 | #else | ||||
| 33063 | fprintf(stdoutstdout,"%s", zBuf); | ||||
| 33064 | fflush(stdoutstdout); | ||||
| 33065 | #endif | ||||
| 33066 | } | ||||
| 33067 | #endif | ||||
| 33068 | |||||
| 33069 | |||||
| 33070 | /* | ||||
| 33071 | ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument | ||||
| 33072 | ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats. | ||||
| 33073 | */ | ||||
| 33074 | SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){ | ||||
| 33075 | va_list ap; | ||||
| 33076 | va_start(ap,zFormat)__builtin_va_start(ap, zFormat); | ||||
| 33077 | sqlite3_str_vappendf(p, zFormat, ap); | ||||
| 33078 | va_end(ap)__builtin_va_end(ap); | ||||
| 33079 | } | ||||
| 33080 | |||||
| 33081 | |||||
| 33082 | /***************************************************************************** | ||||
| 33083 | ** Reference counted string/blob storage | ||||
| 33084 | *****************************************************************************/ | ||||
| 33085 | |||||
| 33086 | /* | ||||
| 33087 | ** Increase the reference count of the string by one. | ||||
| 33088 | ** | ||||
| 33089 | ** The input parameter is returned. | ||||
| 33090 | */ | ||||
| 33091 | SQLITE_PRIVATEstatic char *sqlite3RCStrRef(char *z){ | ||||
| 33092 | RCStr *p = (RCStr*)z; | ||||
| 33093 | assert( p!=0 )((void) (0)); | ||||
| 33094 | p--; | ||||
| 33095 | p->nRCRef++; | ||||
| 33096 | return z; | ||||
| 33097 | } | ||||
| 33098 | |||||
| 33099 | /* | ||||
| 33100 | ** Decrease the reference count by one. Free the string when the | ||||
| 33101 | ** reference count reaches zero. | ||||
| 33102 | */ | ||||
| 33103 | SQLITE_PRIVATEstatic void sqlite3RCStrUnref(void *z){ | ||||
| 33104 | RCStr *p = (RCStr*)z; | ||||
| 33105 | assert( p!=0 )((void) (0)); | ||||
| 33106 | p--; | ||||
| 33107 | assert( p->nRCRef>0 )((void) (0)); | ||||
| 33108 | if( p->nRCRef>=2 ){ | ||||
| 33109 | p->nRCRef--; | ||||
| 33110 | }else{ | ||||
| 33111 | sqlite3_free(p); | ||||
| 33112 | } | ||||
| 33113 | } | ||||
| 33114 | |||||
| 33115 | /* | ||||
| 33116 | ** Create a new string that is capable of holding N bytes of text, not counting | ||||
| 33117 | ** the zero byte at the end. The string is uninitialized. | ||||
| 33118 | ** | ||||
| 33119 | ** The reference count is initially 1. Call sqlite3RCStrUnref() to free the | ||||
| 33120 | ** newly allocated string. | ||||
| 33121 | ** | ||||
| 33122 | ** This routine returns 0 on an OOM. | ||||
| 33123 | */ | ||||
| 33124 | SQLITE_PRIVATEstatic char *sqlite3RCStrNew(u64 N){ | ||||
| 33125 | RCStr *p = sqlite3_malloc64( N + sizeof(*p) + 1 ); | ||||
| 33126 | if( p==0 ) return 0; | ||||
| 33127 | p->nRCRef = 1; | ||||
| 33128 | return (char*)&p[1]; | ||||
| 33129 | } | ||||
| 33130 | |||||
| 33131 | /* | ||||
| 33132 | ** Change the size of the string so that it is able to hold N bytes. | ||||
| 33133 | ** The string might be reallocated, so return the new allocation. | ||||
| 33134 | */ | ||||
| 33135 | SQLITE_PRIVATEstatic char *sqlite3RCStrResize(char *z, u64 N){ | ||||
| 33136 | RCStr *p = (RCStr*)z; | ||||
| 33137 | RCStr *pNew; | ||||
| 33138 | assert( p!=0 )((void) (0)); | ||||
| 33139 | p--; | ||||
| 33140 | assert( p->nRCRef==1 )((void) (0)); | ||||
| 33141 | pNew = sqlite3_realloc64(p, N+sizeof(RCStr)+1); | ||||
| 33142 | if( pNew==0 ){ | ||||
| 33143 | sqlite3_free(p); | ||||
| 33144 | return 0; | ||||
| 33145 | }else{ | ||||
| 33146 | return (char*)&pNew[1]; | ||||
| 33147 | } | ||||
| 33148 | } | ||||
| 33149 | |||||
| 33150 | /************** End of printf.c **********************************************/ | ||||
| 33151 | /************** Begin file treeview.c ****************************************/ | ||||
| 33152 | /* | ||||
| 33153 | ** 2015-06-08 | ||||
| 33154 | ** | ||||
| 33155 | ** The author disclaims copyright to this source code. In place of | ||||
| 33156 | ** a legal notice, here is a blessing: | ||||
| 33157 | ** | ||||
| 33158 | ** May you do good and not evil. | ||||
| 33159 | ** May you find forgiveness for yourself and forgive others. | ||||
| 33160 | ** May you share freely, never taking more than you give. | ||||
| 33161 | ** | ||||
| 33162 | ************************************************************************* | ||||
| 33163 | ** | ||||
| 33164 | ** This file contains C code to implement the TreeView debugging routines. | ||||
| 33165 | ** These routines print a parse tree to standard output for debugging and | ||||
| 33166 | ** analysis. | ||||
| 33167 | ** | ||||
| 33168 | ** The interfaces in this file is only available when compiling | ||||
| 33169 | ** with SQLITE_DEBUG. | ||||
| 33170 | */ | ||||
| 33171 | /* #include "sqliteInt.h" */ | ||||
| 33172 | #ifdef SQLITE_DEBUG | ||||
| 33173 | |||||
| 33174 | /* | ||||
| 33175 | ** Add a new subitem to the tree. The moreToFollow flag indicates that this | ||||
| 33176 | ** is not the last item in the tree. | ||||
| 33177 | */ | ||||
| 33178 | static void sqlite3TreeViewPush(TreeView **pp, u8 moreToFollow){ | ||||
| 33179 | TreeView *p = *pp; | ||||
| 33180 | if( p==0 ){ | ||||
| 33181 | *pp = p = sqlite3_malloc64( sizeof(*p) ); | ||||
| 33182 | if( p==0 ) return; | ||||
| 33183 | memset(p, 0, sizeof(*p)); | ||||
| 33184 | }else{ | ||||
| 33185 | p->iLevel++; | ||||
| 33186 | } | ||||
| 33187 | assert( moreToFollow==0 || moreToFollow==1 )((void) (0)); | ||||
| 33188 | if( p->iLevel<(int)sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow; | ||||
| 33189 | } | ||||
| 33190 | |||||
| 33191 | /* | ||||
| 33192 | ** Finished with one layer of the tree | ||||
| 33193 | */ | ||||
| 33194 | static void sqlite3TreeViewPop(TreeView **pp){ | ||||
| 33195 | TreeView *p = *pp; | ||||
| 33196 | if( p==0 ) return; | ||||
| 33197 | p->iLevel--; | ||||
| 33198 | if( p->iLevel<0 ){ | ||||
| 33199 | sqlite3_free(p); | ||||
| 33200 | *pp = 0; | ||||
| 33201 | } | ||||
| 33202 | } | ||||
| 33203 | |||||
| 33204 | /* | ||||
| 33205 | ** Generate a single line of output for the tree, with a prefix that contains | ||||
| 33206 | ** all the appropriate tree lines | ||||
| 33207 | */ | ||||
| 33208 | SQLITE_PRIVATEstatic void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){ | ||||
| 33209 | va_list ap; | ||||
| 33210 | int i; | ||||
| 33211 | StrAccum acc; | ||||
| 33212 | char zBuf[1000]; | ||||
| 33213 | sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); | ||||
| 33214 | if( p ){ | ||||
| 33215 | for(i=0; i<p->iLevel && i<(int)sizeof(p->bLine)-1; i++){ | ||||
| 33216 | sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4); | ||||
| 33217 | } | ||||
| 33218 | sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); | ||||
| 33219 | } | ||||
| 33220 | if( zFormat!=0 ){ | ||||
| 33221 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 33222 | sqlite3_str_vappendf(&acc, zFormat, ap); | ||||
| 33223 | va_end(ap)__builtin_va_end(ap); | ||||
| 33224 | assert( acc.nChar>0 || acc.accError )((void) (0)); | ||||
| 33225 | sqlite3_str_append(&acc, "\n", 1); | ||||
| 33226 | } | ||||
| 33227 | sqlite3StrAccumFinish(&acc); | ||||
| 33228 | fprintf(stdoutstdout,"%s", zBuf); | ||||
| 33229 | fflush(stdoutstdout); | ||||
| 33230 | } | ||||
| 33231 | |||||
| 33232 | /* | ||||
| 33233 | ** Shorthand for starting a new tree item that consists of a single label | ||||
| 33234 | */ | ||||
| 33235 | static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){ | ||||
| 33236 | sqlite3TreeViewPush(&p, moreFollows); | ||||
| 33237 | sqlite3TreeViewLine(p, "%s", zLabel); | ||||
| 33238 | } | ||||
| 33239 | |||||
| 33240 | /* | ||||
| 33241 | ** Show a list of Column objects in tree format. | ||||
| 33242 | */ | ||||
| 33243 | SQLITE_PRIVATEstatic void sqlite3TreeViewColumnList( | ||||
| 33244 | TreeView *pView, | ||||
| 33245 | const Column *aCol, | ||||
| 33246 | int nCol, | ||||
| 33247 | u8 moreToFollow | ||||
| 33248 | ){ | ||||
| 33249 | int i; | ||||
| 33250 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 33251 | sqlite3TreeViewLine(pView, "COLUMNS"); | ||||
| 33252 | for(i=0; i<nCol; i++){ | ||||
| 33253 | u16 flg = aCol[i].colFlags; | ||||
| 33254 | int colMoreToFollow = i<(nCol - 1); | ||||
| 33255 | sqlite3TreeViewPush(&pView, colMoreToFollow); | ||||
| 33256 | sqlite3TreeViewLine(pView, 0); | ||||
| 33257 | printf(" %s", aCol[i].zCnName); | ||||
| 33258 | switch( aCol[i].eCType ){ | ||||
| 33259 | case COLTYPE_ANY1: printf(" ANY"); break; | ||||
| 33260 | case COLTYPE_BLOB2: printf(" BLOB"); break; | ||||
| 33261 | case COLTYPE_INT3: printf(" INT"); break; | ||||
| 33262 | case COLTYPE_INTEGER4: printf(" INTEGER"); break; | ||||
| 33263 | case COLTYPE_REAL5: printf(" REAL"); break; | ||||
| 33264 | case COLTYPE_TEXT6: printf(" TEXT"); break; | ||||
| 33265 | case COLTYPE_CUSTOM0: { | ||||
| 33266 | if( flg & COLFLAG_HASTYPE0x0004 ){ | ||||
| 33267 | const char *z = aCol[i].zCnName; | ||||
| 33268 | z += strlen(z)+1; | ||||
| 33269 | printf(" X-%s", z); | ||||
| 33270 | break; | ||||
| 33271 | } | ||||
| 33272 | } | ||||
| 33273 | } | ||||
| 33274 | if( flg & COLFLAG_PRIMKEY0x0001 ) printf(" PRIMARY KEY"); | ||||
| 33275 | if( flg & COLFLAG_HIDDEN0x0002 ) printf(" HIDDEN"); | ||||
| 33276 | #ifdef COLFLAG_NOEXPAND0x0400 | ||||
| 33277 | if( flg & COLFLAG_NOEXPAND0x0400 ) printf(" NO-EXPAND"); | ||||
| 33278 | #endif | ||||
| 33279 | if( flg ) printf(" flags=%04x", flg); | ||||
| 33280 | printf("\n"); | ||||
| 33281 | fflush(stdoutstdout); | ||||
| 33282 | sqlite3TreeViewPop(&pView); | ||||
| 33283 | } | ||||
| 33284 | sqlite3TreeViewPop(&pView); | ||||
| 33285 | } | ||||
| 33286 | |||||
| 33287 | /* | ||||
| 33288 | ** Generate a human-readable description of a WITH clause. | ||||
| 33289 | */ | ||||
| 33290 | SQLITE_PRIVATEstatic void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){ | ||||
| 33291 | int i; | ||||
| 33292 | if( pWith==0 ) return; | ||||
| 33293 | if( pWith->nCte==0 ) return; | ||||
| 33294 | if( pWith->pOuter ){ | ||||
| 33295 | sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter); | ||||
| 33296 | }else{ | ||||
| 33297 | sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith); | ||||
| 33298 | } | ||||
| 33299 | if( pWith->nCte>0 ){ | ||||
| 33300 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 33301 | for(i=0; i<pWith->nCte; i++){ | ||||
| 33302 | StrAccum x; | ||||
| 33303 | char zLine[1000]; | ||||
| 33304 | const struct Cte *pCte = &pWith->a[i]; | ||||
| 33305 | sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); | ||||
| 33306 | sqlite3_str_appendf(&x, "%s", pCte->zName); | ||||
| 33307 | if( pCte->pCols && pCte->pCols->nExpr>0 ){ | ||||
| 33308 | char cSep = '('; | ||||
| 33309 | int j; | ||||
| 33310 | for(j=0; j<pCte->pCols->nExpr; j++){ | ||||
| 33311 | sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName); | ||||
| 33312 | cSep = ','; | ||||
| 33313 | } | ||||
| 33314 | sqlite3_str_appendf(&x, ")"); | ||||
| 33315 | } | ||||
| 33316 | if( pCte->eM10d!=M10d_Any1 ){ | ||||
| 33317 | sqlite3_str_appendf(&x, " %sMATERIALIZED", | ||||
| 33318 | pCte->eM10d==M10d_No2 ? "NOT " : ""); | ||||
| 33319 | } | ||||
| 33320 | if( pCte->pUse ){ | ||||
| 33321 | sqlite3_str_appendf(&x, " (pUse=0x%p, nUse=%d)", pCte->pUse, | ||||
| 33322 | pCte->pUse->nUse); | ||||
| 33323 | } | ||||
| 33324 | sqlite3StrAccumFinish(&x); | ||||
| 33325 | sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1); | ||||
| 33326 | sqlite3TreeViewSelect(pView, pCte->pSelect, 0); | ||||
| 33327 | sqlite3TreeViewPop(&pView); | ||||
| 33328 | } | ||||
| 33329 | sqlite3TreeViewPop(&pView); | ||||
| 33330 | } | ||||
| 33331 | } | ||||
| 33332 | |||||
| 33333 | /* | ||||
| 33334 | ** Generate a human-readable description of a SrcList object. | ||||
| 33335 | */ | ||||
| 33336 | SQLITE_PRIVATEstatic void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){ | ||||
| 33337 | int i; | ||||
| 33338 | if( pSrc==0 ) return; | ||||
| 33339 | for(i=0; i<pSrc->nSrc; i++){ | ||||
| 33340 | const SrcItem *pItem = &pSrc->a[i]; | ||||
| 33341 | StrAccum x; | ||||
| 33342 | int n = 0; | ||||
| 33343 | char zLine[1000]; | ||||
| 33344 | sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); | ||||
| 33345 | x.printfFlags |= SQLITE_PRINTF_INTERNAL0x01; | ||||
| 33346 | sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem); | ||||
| 33347 | if( pItem->pSTab ){ | ||||
| 33348 | sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx%s", | ||||
| 33349 | pItem->pSTab->zName, pItem->pSTab->nCol, pItem->pSTab, | ||||
| 33350 | pItem->colUsed, | ||||
| 33351 | pItem->fg.rowidUsed ? "+rowid" : ""); | ||||
| 33352 | } | ||||
| 33353 | if( (pItem->fg.jointype & (JT_LEFT0x08|JT_RIGHT0x10))==(JT_LEFT0x08|JT_RIGHT0x10) ){ | ||||
| 33354 | sqlite3_str_appendf(&x, " FULL-OUTER-JOIN"); | ||||
| 33355 | }else if( pItem->fg.jointype & JT_LEFT0x08 ){ | ||||
| 33356 | sqlite3_str_appendf(&x, " LEFT-JOIN"); | ||||
| 33357 | }else if( pItem->fg.jointype & JT_RIGHT0x10 ){ | ||||
| 33358 | sqlite3_str_appendf(&x, " RIGHT-JOIN"); | ||||
| 33359 | }else if( pItem->fg.jointype & JT_CROSS0x02 ){ | ||||
| 33360 | sqlite3_str_appendf(&x, " CROSS-JOIN"); | ||||
| 33361 | } | ||||
| 33362 | if( pItem->fg.jointype & JT_LTORJ0x40 ){ | ||||
| 33363 | sqlite3_str_appendf(&x, " LTORJ"); | ||||
| 33364 | } | ||||
| 33365 | if( pItem->fg.fromDDL ){ | ||||
| 33366 | sqlite3_str_appendf(&x, " DDL"); | ||||
| 33367 | } | ||||
| 33368 | if( pItem->fg.isCte ){ | ||||
| 33369 | static const char *aMat[] = {",MAT", "", ",NO-MAT"}; | ||||
| 33370 | sqlite3_str_appendf(&x, " CteUse=%d%s", | ||||
| 33371 | pItem->u2.pCteUse->nUse, | ||||
| 33372 | aMat[pItem->u2.pCteUse->eM10d]); | ||||
| 33373 | } | ||||
| 33374 | if( pItem->fg.isOn || (pItem->fg.isUsing==0 && pItem->u3.pOn!=0) ){ | ||||
| 33375 | sqlite3_str_appendf(&x, " isOn"); | ||||
| 33376 | } | ||||
| 33377 | if( pItem->fg.isTabFunc ) sqlite3_str_appendf(&x, " isTabFunc"); | ||||
| 33378 | if( pItem->fg.isCorrelated ) sqlite3_str_appendf(&x, " isCorrelated"); | ||||
| 33379 | if( pItem->fg.isMaterialized ) sqlite3_str_appendf(&x, " isMaterialized"); | ||||
| 33380 | if( pItem->fg.viaCoroutine ) sqlite3_str_appendf(&x, " viaCoroutine"); | ||||
| 33381 | if( pItem->fg.notCte ) sqlite3_str_appendf(&x, " notCte"); | ||||
| 33382 | if( pItem->fg.isNestedFrom ) sqlite3_str_appendf(&x, " isNestedFrom"); | ||||
| 33383 | if( pItem->fg.fixedSchema ) sqlite3_str_appendf(&x, " fixedSchema"); | ||||
| 33384 | if( pItem->fg.hadSchema ) sqlite3_str_appendf(&x, " hadSchema"); | ||||
| 33385 | if( pItem->fg.isSubquery ) sqlite3_str_appendf(&x, " isSubquery"); | ||||
| 33386 | |||||
| 33387 | sqlite3StrAccumFinish(&x); | ||||
| 33388 | sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1); | ||||
| 33389 | n = 0; | ||||
| 33390 | if( pItem->fg.isSubquery ) n++; | ||||
| 33391 | if( pItem->fg.isTabFunc ) n++; | ||||
| 33392 | if( pItem->fg.isUsing ) n++; | ||||
| 33393 | if( pItem->fg.isUsing ){ | ||||
| 33394 | sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING"); | ||||
| 33395 | } | ||||
| 33396 | if( pItem->fg.isSubquery ){ | ||||
| 33397 | assert( n==1 )((void) (0)); | ||||
| 33398 | if( pItem->pSTab ){ | ||||
| 33399 | Table *pTab = pItem->pSTab; | ||||
| 33400 | sqlite3TreeViewColumnList(pView, pTab->aCol, pTab->nCol, 1); | ||||
| 33401 | } | ||||
| 33402 | assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem) )((void) (0)); | ||||
| 33403 | sqlite3TreeViewSelect(pView, pItem->u4.pSubq->pSelect, 0); | ||||
| 33404 | } | ||||
| 33405 | if( pItem->fg.isTabFunc ){ | ||||
| 33406 | sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:"); | ||||
| 33407 | } | ||||
| 33408 | sqlite3TreeViewPop(&pView); | ||||
| 33409 | } | ||||
| 33410 | } | ||||
| 33411 | |||||
| 33412 | /* | ||||
| 33413 | ** Generate a human-readable description of a Select object. | ||||
| 33414 | */ | ||||
| 33415 | SQLITE_PRIVATEstatic void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){ | ||||
| 33416 | int n = 0; | ||||
| 33417 | int cnt = 0; | ||||
| 33418 | if( p==0 ){ | ||||
| 33419 | sqlite3TreeViewLine(pView, "nil-SELECT"); | ||||
| 33420 | return; | ||||
| 33421 | } | ||||
| 33422 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 33423 | if( p->pWith ){ | ||||
| 33424 | sqlite3TreeViewWith(pView, p->pWith, 1); | ||||
| 33425 | cnt = 1; | ||||
| 33426 | sqlite3TreeViewPush(&pView, 1); | ||||
| 33427 | } | ||||
| 33428 | do{ | ||||
| 33429 | if( p->selFlags & SF_WhereBegin0x0080000 ){ | ||||
| 33430 | sqlite3TreeViewLine(pView, "sqlite3WhereBegin()"); | ||||
| 33431 | }else{ | ||||
| 33432 | sqlite3TreeViewLine(pView, | ||||
| 33433 | "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d", | ||||
| 33434 | ((p->selFlags & SF_Distinct0x0000001) ? " DISTINCT" : ""), | ||||
| 33435 | ((p->selFlags & SF_Aggregate0x0000008) ? " agg_flag" : ""), | ||||
| 33436 | p->selId, p, p->selFlags, | ||||
| 33437 | (int)p->nSelectRow | ||||
| 33438 | ); | ||||
| 33439 | } | ||||
| 33440 | if( cnt++ ) sqlite3TreeViewPop(&pView); | ||||
| 33441 | if( p->pPrior ){ | ||||
| 33442 | n = 1000; | ||||
| 33443 | }else{ | ||||
| 33444 | n = 0; | ||||
| 33445 | if( p->pSrc && p->pSrc->nSrc && p->pSrc->nAlloc ) n++; | ||||
| 33446 | if( p->pWhere ) n++; | ||||
| 33447 | if( p->pGroupBy ) n++; | ||||
| 33448 | if( p->pHaving ) n++; | ||||
| 33449 | if( p->pOrderBy ) n++; | ||||
| 33450 | if( p->pLimit ) n++; | ||||
| 33451 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33452 | if( p->pWin ) n++; | ||||
| 33453 | if( p->pWinDefn ) n++; | ||||
| 33454 | #endif | ||||
| 33455 | } | ||||
| 33456 | if( p->pEList ){ | ||||
| 33457 | sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set"); | ||||
| 33458 | } | ||||
| 33459 | n--; | ||||
| 33460 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33461 | if( p->pWin ){ | ||||
| 33462 | Window *pX; | ||||
| 33463 | sqlite3TreeViewPush(&pView, (n--)>0); | ||||
| 33464 | sqlite3TreeViewLine(pView, "window-functions"); | ||||
| 33465 | for(pX=p->pWin; pX; pX=pX->pNextWin){ | ||||
| 33466 | sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0); | ||||
| 33467 | } | ||||
| 33468 | sqlite3TreeViewPop(&pView); | ||||
| 33469 | } | ||||
| 33470 | #endif | ||||
| 33471 | if( p->pSrc && p->pSrc->nSrc && p->pSrc->nAlloc ){ | ||||
| 33472 | sqlite3TreeViewPush(&pView, (n--)>0); | ||||
| 33473 | sqlite3TreeViewLine(pView, "FROM"); | ||||
| 33474 | sqlite3TreeViewSrcList(pView, p->pSrc); | ||||
| 33475 | sqlite3TreeViewPop(&pView); | ||||
| 33476 | } | ||||
| 33477 | if( p->pWhere ){ | ||||
| 33478 | sqlite3TreeViewItem(pView, "WHERE", (n--)>0); | ||||
| 33479 | sqlite3TreeViewExpr(pView, p->pWhere, 0); | ||||
| 33480 | sqlite3TreeViewPop(&pView); | ||||
| 33481 | } | ||||
| 33482 | if( p->pGroupBy ){ | ||||
| 33483 | sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY"); | ||||
| 33484 | } | ||||
| 33485 | if( p->pHaving ){ | ||||
| 33486 | sqlite3TreeViewItem(pView, "HAVING", (n--)>0); | ||||
| 33487 | sqlite3TreeViewExpr(pView, p->pHaving, 0); | ||||
| 33488 | sqlite3TreeViewPop(&pView); | ||||
| 33489 | } | ||||
| 33490 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33491 | if( p->pWinDefn ){ | ||||
| 33492 | Window *pX; | ||||
| 33493 | sqlite3TreeViewItem(pView, "WINDOW", (n--)>0); | ||||
| 33494 | for(pX=p->pWinDefn; pX; pX=pX->pNextWin){ | ||||
| 33495 | sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0); | ||||
| 33496 | } | ||||
| 33497 | sqlite3TreeViewPop(&pView); | ||||
| 33498 | } | ||||
| 33499 | #endif | ||||
| 33500 | if( p->pOrderBy ){ | ||||
| 33501 | sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); | ||||
| 33502 | } | ||||
| 33503 | if( p->pLimit ){ | ||||
| 33504 | sqlite3TreeViewItem(pView, "LIMIT", (n--)>0); | ||||
| 33505 | sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0); | ||||
| 33506 | if( p->pLimit->pRight ){ | ||||
| 33507 | sqlite3TreeViewItem(pView, "OFFSET", 0); | ||||
| 33508 | sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0); | ||||
| 33509 | sqlite3TreeViewPop(&pView); | ||||
| 33510 | } | ||||
| 33511 | sqlite3TreeViewPop(&pView); | ||||
| 33512 | } | ||||
| 33513 | if( p->pPrior ){ | ||||
| 33514 | const char *zOp = "UNION"; | ||||
| 33515 | switch( p->op ){ | ||||
| 33516 | case TK_ALL136: zOp = "UNION ALL"; break; | ||||
| 33517 | case TK_INTERSECT138: zOp = "INTERSECT"; break; | ||||
| 33518 | case TK_EXCEPT137: zOp = "EXCEPT"; break; | ||||
| 33519 | } | ||||
| 33520 | sqlite3TreeViewItem(pView, zOp, 1); | ||||
| 33521 | } | ||||
| 33522 | p = p->pPrior; | ||||
| 33523 | }while( p!=0 ); | ||||
| 33524 | sqlite3TreeViewPop(&pView); | ||||
| 33525 | } | ||||
| 33526 | |||||
| 33527 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33528 | /* | ||||
| 33529 | ** Generate a description of starting or stopping bounds | ||||
| 33530 | */ | ||||
| 33531 | SQLITE_PRIVATEstatic void sqlite3TreeViewBound( | ||||
| 33532 | TreeView *pView, /* View context */ | ||||
| 33533 | u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */ | ||||
| 33534 | Expr *pExpr, /* Value for PRECEDING or FOLLOWING */ | ||||
| 33535 | u8 moreToFollow /* True if more to follow */ | ||||
| 33536 | ){ | ||||
| 33537 | switch( eBound ){ | ||||
| 33538 | case TK_UNBOUNDED91: { | ||||
| 33539 | sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow); | ||||
| 33540 | sqlite3TreeViewPop(&pView); | ||||
| 33541 | break; | ||||
| 33542 | } | ||||
| 33543 | case TK_CURRENT86: { | ||||
| 33544 | sqlite3TreeViewItem(pView, "CURRENT", moreToFollow); | ||||
| 33545 | sqlite3TreeViewPop(&pView); | ||||
| 33546 | break; | ||||
| 33547 | } | ||||
| 33548 | case TK_PRECEDING89: { | ||||
| 33549 | sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow); | ||||
| 33550 | sqlite3TreeViewExpr(pView, pExpr, 0); | ||||
| 33551 | sqlite3TreeViewPop(&pView); | ||||
| 33552 | break; | ||||
| 33553 | } | ||||
| 33554 | case TK_FOLLOWING87: { | ||||
| 33555 | sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow); | ||||
| 33556 | sqlite3TreeViewExpr(pView, pExpr, 0); | ||||
| 33557 | sqlite3TreeViewPop(&pView); | ||||
| 33558 | break; | ||||
| 33559 | } | ||||
| 33560 | } | ||||
| 33561 | } | ||||
| 33562 | #endif /* SQLITE_OMIT_WINDOWFUNC */ | ||||
| 33563 | |||||
| 33564 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33565 | /* | ||||
| 33566 | ** Generate a human-readable explanation for a Window object | ||||
| 33567 | */ | ||||
| 33568 | SQLITE_PRIVATEstatic void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){ | ||||
| 33569 | int nElement = 0; | ||||
| 33570 | if( pWin==0 ) return; | ||||
| 33571 | if( pWin->pFilter ){ | ||||
| 33572 | sqlite3TreeViewItem(pView, "FILTER", 1); | ||||
| 33573 | sqlite3TreeViewExpr(pView, pWin->pFilter, 0); | ||||
| 33574 | sqlite3TreeViewPop(&pView); | ||||
| 33575 | if( pWin->eFrmType==TK_FILTER167 ) return; | ||||
| 33576 | } | ||||
| 33577 | sqlite3TreeViewPush(&pView, more); | ||||
| 33578 | if( pWin->zName ){ | ||||
| 33579 | sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin); | ||||
| 33580 | }else{ | ||||
| 33581 | sqlite3TreeViewLine(pView, "OVER (%p)", pWin); | ||||
| 33582 | } | ||||
| 33583 | if( pWin->zBase ) nElement++; | ||||
| 33584 | if( pWin->pOrderBy ) nElement++; | ||||
| 33585 | if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER167 ) nElement++; | ||||
| 33586 | if( pWin->eExclude ) nElement++; | ||||
| 33587 | if( pWin->zBase ){ | ||||
| 33588 | sqlite3TreeViewPush(&pView, (--nElement)>0); | ||||
| 33589 | sqlite3TreeViewLine(pView, "window: %s", pWin->zBase); | ||||
| 33590 | sqlite3TreeViewPop(&pView); | ||||
| 33591 | } | ||||
| 33592 | if( pWin->pPartition ){ | ||||
| 33593 | sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY"); | ||||
| 33594 | } | ||||
| 33595 | if( pWin->pOrderBy ){ | ||||
| 33596 | sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY"); | ||||
| 33597 | } | ||||
| 33598 | if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER167 ){ | ||||
| 33599 | char zBuf[30]; | ||||
| 33600 | const char *zFrmType = "ROWS"; | ||||
| 33601 | if( pWin->eFrmType==TK_RANGE90 ) zFrmType = "RANGE"; | ||||
| 33602 | if( pWin->eFrmType==TK_GROUPS93 ) zFrmType = "GROUPS"; | ||||
| 33603 | sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType, | ||||
| 33604 | pWin->bImplicitFrame ? " (implied)" : ""); | ||||
| 33605 | sqlite3TreeViewItem(pView, zBuf, (--nElement)>0); | ||||
| 33606 | sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1); | ||||
| 33607 | sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0); | ||||
| 33608 | sqlite3TreeViewPop(&pView); | ||||
| 33609 | } | ||||
| 33610 | if( pWin->eExclude ){ | ||||
| 33611 | char zBuf[30]; | ||||
| 33612 | const char *zExclude; | ||||
| 33613 | switch( pWin->eExclude ){ | ||||
| 33614 | case TK_NO67: zExclude = "NO OTHERS"; break; | ||||
| 33615 | case TK_CURRENT86: zExclude = "CURRENT ROW"; break; | ||||
| 33616 | case TK_GROUP147: zExclude = "GROUP"; break; | ||||
| 33617 | case TK_TIES95: zExclude = "TIES"; break; | ||||
| 33618 | default: | ||||
| 33619 | sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude); | ||||
| 33620 | zExclude = zBuf; | ||||
| 33621 | break; | ||||
| 33622 | } | ||||
| 33623 | sqlite3TreeViewPush(&pView, 0); | ||||
| 33624 | sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude); | ||||
| 33625 | sqlite3TreeViewPop(&pView); | ||||
| 33626 | } | ||||
| 33627 | sqlite3TreeViewPop(&pView); | ||||
| 33628 | } | ||||
| 33629 | #endif /* SQLITE_OMIT_WINDOWFUNC */ | ||||
| 33630 | |||||
| 33631 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33632 | /* | ||||
| 33633 | ** Generate a human-readable explanation for a Window Function object | ||||
| 33634 | */ | ||||
| 33635 | SQLITE_PRIVATEstatic void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){ | ||||
| 33636 | if( pWin==0 ) return; | ||||
| 33637 | sqlite3TreeViewPush(&pView, more); | ||||
| 33638 | sqlite3TreeViewLine(pView, "WINFUNC %s(%d)", | ||||
| 33639 | pWin->pWFunc->zName, pWin->pWFunc->nArg); | ||||
| 33640 | sqlite3TreeViewWindow(pView, pWin, 0); | ||||
| 33641 | sqlite3TreeViewPop(&pView); | ||||
| 33642 | } | ||||
| 33643 | #endif /* SQLITE_OMIT_WINDOWFUNC */ | ||||
| 33644 | |||||
| 33645 | /* | ||||
| 33646 | ** Generate a human-readable explanation of an expression tree. | ||||
| 33647 | */ | ||||
| 33648 | SQLITE_PRIVATEstatic void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){ | ||||
| 33649 | const char *zBinOp = 0; /* Binary operator */ | ||||
| 33650 | const char *zUniOp = 0; /* Unary operator */ | ||||
| 33651 | char zFlgs[200]; | ||||
| 33652 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 33653 | if( pExpr==0 ){ | ||||
| 33654 | sqlite3TreeViewLine(pView, "nil"); | ||||
| 33655 | sqlite3TreeViewPop(&pView); | ||||
| 33656 | return; | ||||
| 33657 | } | ||||
| 33658 | if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags || pExpr->pAggInfo ){ | ||||
| 33659 | StrAccum x; | ||||
| 33660 | sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0); | ||||
| 33661 | sqlite3_str_appendf(&x, " fg.af=%x.%c", | ||||
| 33662 | pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n'); | ||||
| 33663 | if( ExprHasProperty(pExpr, EP_OuterON)(((pExpr)->flags&(u32)(0x000001))!=0) ){ | ||||
| 33664 | sqlite3_str_appendf(&x, " outer.iJoin=%d", pExpr->w.iJoin); | ||||
| 33665 | } | ||||
| 33666 | if( ExprHasProperty(pExpr, EP_InnerON)(((pExpr)->flags&(u32)(0x000002))!=0) ){ | ||||
| 33667 | sqlite3_str_appendf(&x, " inner.iJoin=%d", pExpr->w.iJoin); | ||||
| 33668 | } | ||||
| 33669 | if( ExprHasProperty(pExpr, EP_FromDDL)(((pExpr)->flags&(u32)(0x40000000))!=0) ){ | ||||
| 33670 | sqlite3_str_appendf(&x, " DDL"); | ||||
| 33671 | } | ||||
| 33672 | if( ExprHasVVAProperty(pExpr, EP_Immutable)0 ){ | ||||
| 33673 | sqlite3_str_appendf(&x, " IMMUTABLE"); | ||||
| 33674 | } | ||||
| 33675 | if( pExpr->pAggInfo!=0 ){ | ||||
| 33676 | sqlite3_str_appendf(&x, " agg-column[%d]", pExpr->iAgg); | ||||
| 33677 | } | ||||
| 33678 | sqlite3StrAccumFinish(&x); | ||||
| 33679 | }else{ | ||||
| 33680 | zFlgs[0] = 0; | ||||
| 33681 | } | ||||
| 33682 | switch( pExpr->op ){ | ||||
| 33683 | case TK_AGG_COLUMN170: { | ||||
| 33684 | sqlite3TreeViewLine(pView, "AGG{%d:%d}%s", | ||||
| 33685 | pExpr->iTable, pExpr->iColumn, zFlgs); | ||||
| 33686 | break; | ||||
| 33687 | } | ||||
| 33688 | case TK_COLUMN168: { | ||||
| 33689 | if( pExpr->iTable<0 ){ | ||||
| 33690 | /* This only happens when coding check constraints */ | ||||
| 33691 | char zOp2[16]; | ||||
| 33692 | if( pExpr->op2 ){ | ||||
| 33693 | sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2); | ||||
| 33694 | }else{ | ||||
| 33695 | zOp2[0] = 0; | ||||
| 33696 | } | ||||
| 33697 | sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s", | ||||
| 33698 | pExpr->iColumn, zFlgs, zOp2); | ||||
| 33699 | }else{ | ||||
| 33700 | assert( ExprUseYTab(pExpr) )((void) (0)); | ||||
| 33701 | sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s", | ||||
| 33702 | pExpr->iTable, pExpr->iColumn, | ||||
| 33703 | pExpr->y.pTab, zFlgs); | ||||
| 33704 | } | ||||
| 33705 | if( ExprHasProperty(pExpr, EP_FixedCol)(((pExpr)->flags&(u32)(0x000020))!=0) ){ | ||||
| 33706 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); | ||||
| 33707 | } | ||||
| 33708 | break; | ||||
| 33709 | } | ||||
| 33710 | case TK_INTEGER156: { | ||||
| 33711 | if( pExpr->flags & EP_IntValue0x000800 ){ | ||||
| 33712 | sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue); | ||||
| 33713 | }else{ | ||||
| 33714 | sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken); | ||||
| 33715 | } | ||||
| 33716 | break; | ||||
| 33717 | } | ||||
| 33718 | #ifndef SQLITE_OMIT_FLOATING_POINT | ||||
| 33719 | case TK_FLOAT154: { | ||||
| 33720 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33721 | sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); | ||||
| 33722 | break; | ||||
| 33723 | } | ||||
| 33724 | #endif | ||||
| 33725 | case TK_STRING118: { | ||||
| 33726 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33727 | sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken); | ||||
| 33728 | break; | ||||
| 33729 | } | ||||
| 33730 | case TK_NULL122: { | ||||
| 33731 | sqlite3TreeViewLine(pView,"NULL"); | ||||
| 33732 | break; | ||||
| 33733 | } | ||||
| 33734 | case TK_TRUEFALSE171: { | ||||
| 33735 | sqlite3TreeViewLine(pView,"%s%s", | ||||
| 33736 | sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE", zFlgs); | ||||
| 33737 | break; | ||||
| 33738 | } | ||||
| 33739 | #ifndef SQLITE_OMIT_BLOB_LITERAL | ||||
| 33740 | case TK_BLOB155: { | ||||
| 33741 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33742 | sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); | ||||
| 33743 | break; | ||||
| 33744 | } | ||||
| 33745 | #endif | ||||
| 33746 | case TK_VARIABLE157: { | ||||
| 33747 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33748 | sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)", | ||||
| 33749 | pExpr->u.zToken, pExpr->iColumn); | ||||
| 33750 | break; | ||||
| 33751 | } | ||||
| 33752 | case TK_REGISTER176: { | ||||
| 33753 | sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable); | ||||
| 33754 | break; | ||||
| 33755 | } | ||||
| 33756 | case TK_ID60: { | ||||
| 33757 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33758 | sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); | ||||
| 33759 | break; | ||||
| 33760 | } | ||||
| 33761 | #ifndef SQLITE_OMIT_CAST | ||||
| 33762 | case TK_CAST36: { | ||||
| 33763 | /* Expressions of the form: CAST(pLeft AS token) */ | ||||
| 33764 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33765 | sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken); | ||||
| 33766 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); | ||||
| 33767 | break; | ||||
| 33768 | } | ||||
| 33769 | #endif /* SQLITE_OMIT_CAST */ | ||||
| 33770 | case TK_LT57: zBinOp = "LT"; break; | ||||
| 33771 | case TK_LE56: zBinOp = "LE"; break; | ||||
| 33772 | case TK_GT55: zBinOp = "GT"; break; | ||||
| 33773 | case TK_GE58: zBinOp = "GE"; break; | ||||
| 33774 | case TK_NE53: zBinOp = "NE"; break; | ||||
| 33775 | case TK_EQ54: zBinOp = "EQ"; break; | ||||
| 33776 | case TK_IS45: zBinOp = "IS"; break; | ||||
| 33777 | case TK_ISNOT46: zBinOp = "ISNOT"; break; | ||||
| 33778 | case TK_AND44: zBinOp = "AND"; break; | ||||
| 33779 | case TK_OR43: zBinOp = "OR"; break; | ||||
| 33780 | case TK_PLUS107: zBinOp = "ADD"; break; | ||||
| 33781 | case TK_STAR109: zBinOp = "MUL"; break; | ||||
| 33782 | case TK_MINUS108: zBinOp = "SUB"; break; | ||||
| 33783 | case TK_REM111: zBinOp = "REM"; break; | ||||
| 33784 | case TK_BITAND103: zBinOp = "BITAND"; break; | ||||
| 33785 | case TK_BITOR104: zBinOp = "BITOR"; break; | ||||
| 33786 | case TK_SLASH110: zBinOp = "DIV"; break; | ||||
| 33787 | case TK_LSHIFT105: zBinOp = "LSHIFT"; break; | ||||
| 33788 | case TK_RSHIFT106: zBinOp = "RSHIFT"; break; | ||||
| 33789 | case TK_CONCAT112: zBinOp = "CONCAT"; break; | ||||
| 33790 | case TK_DOT142: zBinOp = "DOT"; break; | ||||
| 33791 | case TK_LIMIT149: zBinOp = "LIMIT"; break; | ||||
| 33792 | |||||
| 33793 | case TK_UMINUS174: zUniOp = "UMINUS"; break; | ||||
| 33794 | case TK_UPLUS173: zUniOp = "UPLUS"; break; | ||||
| 33795 | case TK_BITNOT115: zUniOp = "BITNOT"; break; | ||||
| 33796 | case TK_NOT19: zUniOp = "NOT"; break; | ||||
| 33797 | case TK_ISNULL51: zUniOp = "ISNULL"; break; | ||||
| 33798 | case TK_NOTNULL52: zUniOp = "NOTNULL"; break; | ||||
| 33799 | |||||
| 33800 | case TK_TRUTH175: { | ||||
| 33801 | int x; | ||||
| 33802 | const char *azOp[] = { | ||||
| 33803 | "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE" | ||||
| 33804 | }; | ||||
| 33805 | assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT )((void) (0)); | ||||
| 33806 | assert( pExpr->pRight )((void) (0)); | ||||
| 33807 | assert( sqlite3ExprSkipCollateAndLikely(pExpr->pRight)->op((void) (0)) | ||||
| 33808 | == TK_TRUEFALSE )((void) (0)); | ||||
| 33809 | x = (pExpr->op2==TK_ISNOT46)*2 + sqlite3ExprTruthValue(pExpr->pRight); | ||||
| 33810 | zUniOp = azOp[x]; | ||||
| 33811 | break; | ||||
| 33812 | } | ||||
| 33813 | |||||
| 33814 | case TK_SPAN181: { | ||||
| 33815 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33816 | sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken); | ||||
| 33817 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); | ||||
| 33818 | break; | ||||
| 33819 | } | ||||
| 33820 | |||||
| 33821 | case TK_COLLATE114: { | ||||
| 33822 | /* COLLATE operators without the EP_Collate flag are intended to | ||||
| 33823 | ** emulate collation associated with a table column. These show | ||||
| 33824 | ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE | ||||
| 33825 | ** operators that appear in the original SQL always have the | ||||
| 33826 | ** EP_Collate bit set and appear in treeview output as just "COLLATE" */ | ||||
| 33827 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33828 | sqlite3TreeViewLine(pView, "%sCOLLATE %Q%s", | ||||
| 33829 | !ExprHasProperty(pExpr, EP_Collate)(((pExpr)->flags&(u32)(0x000200))!=0) ? "SOFT-" : "", | ||||
| 33830 | pExpr->u.zToken, zFlgs); | ||||
| 33831 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); | ||||
| 33832 | break; | ||||
| 33833 | } | ||||
| 33834 | |||||
| 33835 | case TK_AGG_FUNCTION169: | ||||
| 33836 | case TK_FUNCTION172: { | ||||
| 33837 | ExprList *pFarg; /* List of function arguments */ | ||||
| 33838 | Window *pWin; | ||||
| 33839 | if( ExprHasProperty(pExpr, EP_TokenOnly)(((pExpr)->flags&(u32)(0x010000))!=0) ){ | ||||
| 33840 | pFarg = 0; | ||||
| 33841 | pWin = 0; | ||||
| 33842 | }else{ | ||||
| 33843 | assert( ExprUseXList(pExpr) )((void) (0)); | ||||
| 33844 | pFarg = pExpr->x.pList; | ||||
| 33845 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33846 | pWin = IsWindowFunc(pExpr)( ((((pExpr))->flags&(u32)(0x1000000))!=0) && pExpr ->y.pWin->eFrmType!=167 ) ? pExpr->y.pWin : 0; | ||||
| 33847 | #else | ||||
| 33848 | pWin = 0; | ||||
| 33849 | #endif | ||||
| 33850 | } | ||||
| 33851 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33852 | if( pExpr->op==TK_AGG_FUNCTION169 ){ | ||||
| 33853 | sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s agg=%d[%d]/%p", | ||||
| 33854 | pExpr->op2, pExpr->u.zToken, zFlgs, | ||||
| 33855 | pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0, | ||||
| 33856 | pExpr->iAgg, pExpr->pAggInfo); | ||||
| 33857 | }else if( pExpr->op2!=0 ){ | ||||
| 33858 | const char *zOp2; | ||||
| 33859 | char zBuf[8]; | ||||
| 33860 | sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2); | ||||
| 33861 | zOp2 = zBuf; | ||||
| 33862 | if( pExpr->op2==NC_IsCheck0x000004 ) zOp2 = "NC_IsCheck"; | ||||
| 33863 | if( pExpr->op2==NC_IdxExpr0x000020 ) zOp2 = "NC_IdxExpr"; | ||||
| 33864 | if( pExpr->op2==NC_PartIdx0x000002 ) zOp2 = "NC_PartIdx"; | ||||
| 33865 | if( pExpr->op2==NC_GenCol0x000008 ) zOp2 = "NC_GenCol"; | ||||
| 33866 | sqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s", | ||||
| 33867 | pExpr->u.zToken, zFlgs, zOp2); | ||||
| 33868 | }else{ | ||||
| 33869 | sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs); | ||||
| 33870 | } | ||||
| 33871 | if( pFarg ){ | ||||
| 33872 | sqlite3TreeViewExprList(pView, pFarg, pWin!=0 || pExpr->pLeft, 0); | ||||
| 33873 | if( pExpr->pLeft ){ | ||||
| 33874 | Expr *pOB = pExpr->pLeft; | ||||
| 33875 | assert( pOB->op==TK_ORDER )((void) (0)); | ||||
| 33876 | assert( ExprUseXList(pOB) )((void) (0)); | ||||
| 33877 | sqlite3TreeViewExprList(pView, pOB->x.pList, pWin!=0, "ORDERBY"); | ||||
| 33878 | } | ||||
| 33879 | } | ||||
| 33880 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 33881 | if( pWin ){ | ||||
| 33882 | sqlite3TreeViewWindow(pView, pWin, 0); | ||||
| 33883 | } | ||||
| 33884 | #endif | ||||
| 33885 | break; | ||||
| 33886 | } | ||||
| 33887 | case TK_ORDER146: { | ||||
| 33888 | sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, "ORDERBY"); | ||||
| 33889 | break; | ||||
| 33890 | } | ||||
| 33891 | #ifndef SQLITE_OMIT_SUBQUERY | ||||
| 33892 | case TK_EXISTS20: { | ||||
| 33893 | assert( ExprUseXSelect(pExpr) )((void) (0)); | ||||
| 33894 | sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags); | ||||
| 33895 | sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); | ||||
| 33896 | break; | ||||
| 33897 | } | ||||
| 33898 | case TK_SELECT139: { | ||||
| 33899 | assert( ExprUseXSelect(pExpr) )((void) (0)); | ||||
| 33900 | sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags); | ||||
| 33901 | sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); | ||||
| 33902 | break; | ||||
| 33903 | } | ||||
| 33904 | case TK_IN50: { | ||||
| 33905 | sqlite3_str *pStr = sqlite3_str_new(0); | ||||
| 33906 | char *z; | ||||
| 33907 | sqlite3_str_appendf(pStr, "IN flags=0x%x", pExpr->flags); | ||||
| 33908 | if( pExpr->iTable ) sqlite3_str_appendf(pStr, " iTable=%d",pExpr->iTable); | ||||
| 33909 | if( ExprHasProperty(pExpr, EP_Subrtn)(((pExpr)->flags&(u32)(0x2000000))!=0) ){ | ||||
| 33910 | sqlite3_str_appendf(pStr, " subrtn(%d,%d)", | ||||
| 33911 | pExpr->y.sub.regReturn, pExpr->y.sub.iAddr); | ||||
| 33912 | } | ||||
| 33913 | z = sqlite3_str_finish(pStr); | ||||
| 33914 | sqlite3TreeViewLine(pView, z); | ||||
| 33915 | sqlite3_free(z); | ||||
| 33916 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); | ||||
| 33917 | if( ExprUseXSelect(pExpr)(((pExpr)->flags&0x001000)!=0) ){ | ||||
| 33918 | sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); | ||||
| 33919 | }else{ | ||||
| 33920 | sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); | ||||
| 33921 | } | ||||
| 33922 | break; | ||||
| 33923 | } | ||||
| 33924 | #endif /* SQLITE_OMIT_SUBQUERY */ | ||||
| 33925 | |||||
| 33926 | /* | ||||
| 33927 | ** x BETWEEN y AND z | ||||
| 33928 | ** | ||||
| 33929 | ** This is equivalent to | ||||
| 33930 | ** | ||||
| 33931 | ** x>=y AND x<=z | ||||
| 33932 | ** | ||||
| 33933 | ** X is stored in pExpr->pLeft. | ||||
| 33934 | ** Y is stored in pExpr->pList->a[0].pExpr. | ||||
| 33935 | ** Z is stored in pExpr->pList->a[1].pExpr. | ||||
| 33936 | */ | ||||
| 33937 | case TK_BETWEEN49: { | ||||
| 33938 | const Expr *pX, *pY, *pZ; | ||||
| 33939 | pX = pExpr->pLeft; | ||||
| 33940 | assert( ExprUseXList(pExpr) )((void) (0)); | ||||
| 33941 | assert( pExpr->x.pList->nExpr==2 )((void) (0)); | ||||
| 33942 | pY = pExpr->x.pList->a[0].pExpr; | ||||
| 33943 | pZ = pExpr->x.pList->a[1].pExpr; | ||||
| 33944 | sqlite3TreeViewLine(pView, "BETWEEN%s", zFlgs); | ||||
| 33945 | sqlite3TreeViewExpr(pView, pX, 1); | ||||
| 33946 | sqlite3TreeViewExpr(pView, pY, 1); | ||||
| 33947 | sqlite3TreeViewExpr(pView, pZ, 0); | ||||
| 33948 | break; | ||||
| 33949 | } | ||||
| 33950 | case TK_TRIGGER78: { | ||||
| 33951 | /* If the opcode is TK_TRIGGER, then the expression is a reference | ||||
| 33952 | ** to a column in the new.* or old.* pseudo-tables available to | ||||
| 33953 | ** trigger programs. In this case Expr.iTable is set to 1 for the | ||||
| 33954 | ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn | ||||
| 33955 | ** is set to the column of the pseudo-table to read, or to -1 to | ||||
| 33956 | ** read the rowid field. | ||||
| 33957 | */ | ||||
| 33958 | sqlite3TreeViewLine(pView, "%s(%d)", | ||||
| 33959 | pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); | ||||
| 33960 | break; | ||||
| 33961 | } | ||||
| 33962 | case TK_CASE158: { | ||||
| 33963 | sqlite3TreeViewLine(pView, "CASE"); | ||||
| 33964 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); | ||||
| 33965 | assert( ExprUseXList(pExpr) )((void) (0)); | ||||
| 33966 | sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); | ||||
| 33967 | break; | ||||
| 33968 | } | ||||
| 33969 | #ifndef SQLITE_OMIT_TRIGGER | ||||
| 33970 | case TK_RAISE72: { | ||||
| 33971 | const char *zType = "unk"; | ||||
| 33972 | switch( pExpr->affExpr ){ | ||||
| 33973 | case OE_Rollback1: zType = "rollback"; break; | ||||
| 33974 | case OE_Abort2: zType = "abort"; break; | ||||
| 33975 | case OE_Fail3: zType = "fail"; break; | ||||
| 33976 | case OE_Ignore4: zType = "ignore"; break; | ||||
| 33977 | } | ||||
| 33978 | assert( !ExprHasProperty(pExpr, EP_IntValue) )((void) (0)); | ||||
| 33979 | sqlite3TreeViewLine(pView, "RAISE %s", zType); | ||||
| 33980 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); | ||||
| 33981 | break; | ||||
| 33982 | } | ||||
| 33983 | #endif | ||||
| 33984 | case TK_MATCH47: { | ||||
| 33985 | sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s", | ||||
| 33986 | pExpr->iTable, pExpr->iColumn, zFlgs); | ||||
| 33987 | sqlite3TreeViewExpr(pView, pExpr->pRight, 0); | ||||
| 33988 | break; | ||||
| 33989 | } | ||||
| 33990 | case TK_VECTOR177: { | ||||
| 33991 | char *z = sqlite3_mprintf("VECTOR%s",zFlgs); | ||||
| 33992 | assert( ExprUseXList(pExpr) )((void) (0)); | ||||
| 33993 | sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z); | ||||
| 33994 | sqlite3_free(z); | ||||
| 33995 | break; | ||||
| 33996 | } | ||||
| 33997 | case TK_SELECT_COLUMN178: { | ||||
| 33998 | sqlite3TreeViewLine(pView, "SELECT-COLUMN %d of [0..%d]%s", | ||||
| 33999 | pExpr->iColumn, pExpr->iTable-1, | ||||
| 34000 | pExpr->pRight==pExpr->pLeft ? " (SELECT-owner)" : ""); | ||||
| 34001 | assert( ExprUseXSelect(pExpr->pLeft) )((void) (0)); | ||||
| 34002 | sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0); | ||||
| 34003 | break; | ||||
| 34004 | } | ||||
| 34005 | case TK_IF_NULL_ROW179: { | ||||
| 34006 | sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable); | ||||
| 34007 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); | ||||
| 34008 | break; | ||||
| 34009 | } | ||||
| 34010 | case TK_ERROR182: { | ||||
| 34011 | Expr tmp; | ||||
| 34012 | sqlite3TreeViewLine(pView, "ERROR"); | ||||
| 34013 | tmp = *pExpr; | ||||
| 34014 | tmp.op = pExpr->op2; | ||||
| 34015 | sqlite3TreeViewExpr(pView, &tmp, 0); | ||||
| 34016 | break; | ||||
| 34017 | } | ||||
| 34018 | case TK_ROW76: { | ||||
| 34019 | if( pExpr->iColumn<=0 ){ | ||||
| 34020 | sqlite3TreeViewLine(pView, "First FROM table rowid"); | ||||
| 34021 | }else{ | ||||
| 34022 | sqlite3TreeViewLine(pView, "First FROM table column %d", | ||||
| 34023 | pExpr->iColumn-1); | ||||
| 34024 | } | ||||
| 34025 | break; | ||||
| 34026 | } | ||||
| 34027 | default: { | ||||
| 34028 | sqlite3TreeViewLine(pView, "op=%d", pExpr->op); | ||||
| 34029 | break; | ||||
| 34030 | } | ||||
| 34031 | } | ||||
| 34032 | if( zBinOp ){ | ||||
| 34033 | sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs); | ||||
| 34034 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); | ||||
| 34035 | sqlite3TreeViewExpr(pView, pExpr->pRight, 0); | ||||
| 34036 | }else if( zUniOp ){ | ||||
| 34037 | sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs); | ||||
| 34038 | sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); | ||||
| 34039 | } | ||||
| 34040 | sqlite3TreeViewPop(&pView); | ||||
| 34041 | } | ||||
| 34042 | |||||
| 34043 | |||||
| 34044 | /* | ||||
| 34045 | ** Generate a human-readable explanation of an expression list. | ||||
| 34046 | */ | ||||
| 34047 | SQLITE_PRIVATEstatic void sqlite3TreeViewBareExprList( | ||||
| 34048 | TreeView *pView, | ||||
| 34049 | const ExprList *pList, | ||||
| 34050 | const char *zLabel | ||||
| 34051 | ){ | ||||
| 34052 | if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST"; | ||||
| 34053 | if( pList==0 ){ | ||||
| 34054 | sqlite3TreeViewLine(pView, "%s (empty)", zLabel); | ||||
| 34055 | }else{ | ||||
| 34056 | int i; | ||||
| 34057 | sqlite3TreeViewLine(pView, "%s", zLabel); | ||||
| 34058 | for(i=0; i<pList->nExpr; i++){ | ||||
| 34059 | int j = pList->a[i].u.x.iOrderByCol; | ||||
| 34060 | u8 sortFlags = pList->a[i].fg.sortFlags; | ||||
| 34061 | char *zName = pList->a[i].zEName; | ||||
| 34062 | int moreToFollow = i<pList->nExpr - 1; | ||||
| 34063 | if( j || zName || sortFlags ){ | ||||
| 34064 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 34065 | moreToFollow = 0; | ||||
| 34066 | sqlite3TreeViewLine(pView, 0); | ||||
| 34067 | if( zName ){ | ||||
| 34068 | switch( pList->a[i].fg.eEName ){ | ||||
| 34069 | default: | ||||
| 34070 | fprintf(stdoutstdout, "AS %s ", zName); | ||||
| 34071 | break; | ||||
| 34072 | case ENAME_TAB2: | ||||
| 34073 | fprintf(stdoutstdout, "TABLE-ALIAS-NAME(\"%s\") ", zName); | ||||
| 34074 | if( pList->a[i].fg.bUsed ) fprintf(stdoutstdout, "(used) "); | ||||
| 34075 | if( pList->a[i].fg.bUsingTerm ) fprintf(stdoutstdout, "(USING-term) "); | ||||
| 34076 | if( pList->a[i].fg.bNoExpand ) fprintf(stdoutstdout, "(NoExpand) "); | ||||
| 34077 | break; | ||||
| 34078 | case ENAME_SPAN1: | ||||
| 34079 | fprintf(stdoutstdout, "SPAN(\"%s\") ", zName); | ||||
| 34080 | break; | ||||
| 34081 | } | ||||
| 34082 | } | ||||
| 34083 | if( j ){ | ||||
| 34084 | fprintf(stdoutstdout, "iOrderByCol=%d ", j); | ||||
| 34085 | } | ||||
| 34086 | if( sortFlags & KEYINFO_ORDER_DESC0x01 ){ | ||||
| 34087 | fprintf(stdoutstdout, "DESC "); | ||||
| 34088 | }else if( sortFlags & KEYINFO_ORDER_BIGNULL0x02 ){ | ||||
| 34089 | fprintf(stdoutstdout, "NULLS-LAST"); | ||||
| 34090 | } | ||||
| 34091 | fprintf(stdoutstdout, "\n"); | ||||
| 34092 | fflush(stdoutstdout); | ||||
| 34093 | } | ||||
| 34094 | sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow); | ||||
| 34095 | if( j || zName || sortFlags ){ | ||||
| 34096 | sqlite3TreeViewPop(&pView); | ||||
| 34097 | } | ||||
| 34098 | } | ||||
| 34099 | } | ||||
| 34100 | } | ||||
| 34101 | SQLITE_PRIVATEstatic void sqlite3TreeViewExprList( | ||||
| 34102 | TreeView *pView, | ||||
| 34103 | const ExprList *pList, | ||||
| 34104 | u8 moreToFollow, | ||||
| 34105 | const char *zLabel | ||||
| 34106 | ){ | ||||
| 34107 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 34108 | sqlite3TreeViewBareExprList(pView, pList, zLabel); | ||||
| 34109 | sqlite3TreeViewPop(&pView); | ||||
| 34110 | } | ||||
| 34111 | |||||
| 34112 | /* | ||||
| 34113 | ** Generate a human-readable explanation of an id-list. | ||||
| 34114 | */ | ||||
| 34115 | SQLITE_PRIVATEstatic void sqlite3TreeViewBareIdList( | ||||
| 34116 | TreeView *pView, | ||||
| 34117 | const IdList *pList, | ||||
| 34118 | const char *zLabel | ||||
| 34119 | ){ | ||||
| 34120 | if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST"; | ||||
| 34121 | if( pList==0 ){ | ||||
| 34122 | sqlite3TreeViewLine(pView, "%s (empty)", zLabel); | ||||
| 34123 | }else{ | ||||
| 34124 | int i; | ||||
| 34125 | sqlite3TreeViewLine(pView, "%s", zLabel); | ||||
| 34126 | for(i=0; i<pList->nId; i++){ | ||||
| 34127 | char *zName = pList->a[i].zName; | ||||
| 34128 | int moreToFollow = i<pList->nId - 1; | ||||
| 34129 | if( zName==0 ) zName = "(null)"; | ||||
| 34130 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 34131 | sqlite3TreeViewLine(pView, 0); | ||||
| 34132 | fprintf(stdoutstdout, "%s\n", zName); | ||||
| 34133 | sqlite3TreeViewPop(&pView); | ||||
| 34134 | } | ||||
| 34135 | } | ||||
| 34136 | } | ||||
| 34137 | SQLITE_PRIVATEstatic void sqlite3TreeViewIdList( | ||||
| 34138 | TreeView *pView, | ||||
| 34139 | const IdList *pList, | ||||
| 34140 | u8 moreToFollow, | ||||
| 34141 | const char *zLabel | ||||
| 34142 | ){ | ||||
| 34143 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 34144 | sqlite3TreeViewBareIdList(pView, pList, zLabel); | ||||
| 34145 | sqlite3TreeViewPop(&pView); | ||||
| 34146 | } | ||||
| 34147 | |||||
| 34148 | /* | ||||
| 34149 | ** Generate a human-readable explanation of a list of Upsert objects | ||||
| 34150 | */ | ||||
| 34151 | SQLITE_PRIVATEstatic void sqlite3TreeViewUpsert( | ||||
| 34152 | TreeView *pView, | ||||
| 34153 | const Upsert *pUpsert, | ||||
| 34154 | u8 moreToFollow | ||||
| 34155 | ){ | ||||
| 34156 | if( pUpsert==0 ) return; | ||||
| 34157 | sqlite3TreeViewPush(&pView, moreToFollow); | ||||
| 34158 | while( pUpsert ){ | ||||
| 34159 | int n; | ||||
| 34160 | sqlite3TreeViewPush(&pView, pUpsert->pNextUpsert!=0 || moreToFollow); | ||||
| 34161 | sqlite3TreeViewLine(pView, "ON CONFLICT DO %s", | ||||
| 34162 | pUpsert->isDoUpdate ? "UPDATE" : "NOTHING"); | ||||
| 34163 | n = (pUpsert->pUpsertSet!=0) + (pUpsert->pUpsertWhere!=0); | ||||
| 34164 | sqlite3TreeViewExprList(pView, pUpsert->pUpsertTarget, (n--)>0, "TARGET"); | ||||
| 34165 | sqlite3TreeViewExprList(pView, pUpsert->pUpsertSet, (n--)>0, "SET"); | ||||
| 34166 | if( pUpsert->pUpsertWhere ){ | ||||
| 34167 | sqlite3TreeViewItem(pView, "WHERE", (n--)>0); | ||||
| 34168 | sqlite3TreeViewExpr(pView, pUpsert->pUpsertWhere, 0); | ||||
| 34169 | sqlite3TreeViewPop(&pView); | ||||
| 34170 | } | ||||
| 34171 | sqlite3TreeViewPop(&pView); | ||||
| 34172 | pUpsert = pUpsert->pNextUpsert; | ||||
| 34173 | } | ||||
| 34174 | sqlite3TreeViewPop(&pView); | ||||
| 34175 | } | ||||
| 34176 | |||||
| 34177 | #if TREETRACE_ENABLED0 | ||||
| 34178 | /* | ||||
| 34179 | ** Generate a human-readable diagram of the data structure that go | ||||
| 34180 | ** into generating an DELETE statement. | ||||
| 34181 | */ | ||||
| 34182 | SQLITE_PRIVATEstatic void sqlite3TreeViewDelete( | ||||
| 34183 | const With *pWith, | ||||
| 34184 | const SrcList *pTabList, | ||||
| 34185 | const Expr *pWhere, | ||||
| 34186 | const ExprList *pOrderBy, | ||||
| 34187 | const Expr *pLimit, | ||||
| 34188 | const Trigger *pTrigger | ||||
| 34189 | ){ | ||||
| 34190 | int n = 0; | ||||
| 34191 | TreeView *pView = 0; | ||||
| 34192 | sqlite3TreeViewPush(&pView, 0); | ||||
| 34193 | sqlite3TreeViewLine(pView, "DELETE"); | ||||
| 34194 | if( pWith ) n++; | ||||
| 34195 | if( pTabList ) n++; | ||||
| 34196 | if( pWhere ) n++; | ||||
| 34197 | if( pOrderBy ) n++; | ||||
| 34198 | if( pLimit ) n++; | ||||
| 34199 | if( pTrigger ) n++; | ||||
| 34200 | if( pWith ){ | ||||
| 34201 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34202 | sqlite3TreeViewWith(pView, pWith, 0); | ||||
| 34203 | sqlite3TreeViewPop(&pView); | ||||
| 34204 | } | ||||
| 34205 | if( pTabList ){ | ||||
| 34206 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34207 | sqlite3TreeViewLine(pView, "FROM"); | ||||
| 34208 | sqlite3TreeViewSrcList(pView, pTabList); | ||||
| 34209 | sqlite3TreeViewPop(&pView); | ||||
| 34210 | } | ||||
| 34211 | if( pWhere ){ | ||||
| 34212 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34213 | sqlite3TreeViewLine(pView, "WHERE"); | ||||
| 34214 | sqlite3TreeViewExpr(pView, pWhere, 0); | ||||
| 34215 | sqlite3TreeViewPop(&pView); | ||||
| 34216 | } | ||||
| 34217 | if( pOrderBy ){ | ||||
| 34218 | sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY"); | ||||
| 34219 | } | ||||
| 34220 | if( pLimit ){ | ||||
| 34221 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34222 | sqlite3TreeViewLine(pView, "LIMIT"); | ||||
| 34223 | sqlite3TreeViewExpr(pView, pLimit, 0); | ||||
| 34224 | sqlite3TreeViewPop(&pView); | ||||
| 34225 | } | ||||
| 34226 | if( pTrigger ){ | ||||
| 34227 | sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1); | ||||
| 34228 | } | ||||
| 34229 | sqlite3TreeViewPop(&pView); | ||||
| 34230 | } | ||||
| 34231 | #endif /* TREETRACE_ENABLED */ | ||||
| 34232 | |||||
| 34233 | #if TREETRACE_ENABLED0 | ||||
| 34234 | /* | ||||
| 34235 | ** Generate a human-readable diagram of the data structure that go | ||||
| 34236 | ** into generating an INSERT statement. | ||||
| 34237 | */ | ||||
| 34238 | SQLITE_PRIVATEstatic void sqlite3TreeViewInsert( | ||||
| 34239 | const With *pWith, | ||||
| 34240 | const SrcList *pTabList, | ||||
| 34241 | const IdList *pColumnList, | ||||
| 34242 | const Select *pSelect, | ||||
| 34243 | const ExprList *pExprList, | ||||
| 34244 | int onError, | ||||
| 34245 | const Upsert *pUpsert, | ||||
| 34246 | const Trigger *pTrigger | ||||
| 34247 | ){ | ||||
| 34248 | TreeView *pView = 0; | ||||
| 34249 | int n = 0; | ||||
| 34250 | const char *zLabel = "INSERT"; | ||||
| 34251 | switch( onError ){ | ||||
| 34252 | case OE_Replace5: zLabel = "REPLACE"; break; | ||||
| 34253 | case OE_Ignore4: zLabel = "INSERT OR IGNORE"; break; | ||||
| 34254 | case OE_Rollback1: zLabel = "INSERT OR ROLLBACK"; break; | ||||
| 34255 | case OE_Abort2: zLabel = "INSERT OR ABORT"; break; | ||||
| 34256 | case OE_Fail3: zLabel = "INSERT OR FAIL"; break; | ||||
| 34257 | } | ||||
| 34258 | sqlite3TreeViewPush(&pView, 0); | ||||
| 34259 | sqlite3TreeViewLine(pView, zLabel); | ||||
| 34260 | if( pWith ) n++; | ||||
| 34261 | if( pTabList ) n++; | ||||
| 34262 | if( pColumnList ) n++; | ||||
| 34263 | if( pSelect ) n++; | ||||
| 34264 | if( pExprList ) n++; | ||||
| 34265 | if( pUpsert ) n++; | ||||
| 34266 | if( pTrigger ) n++; | ||||
| 34267 | if( pWith ){ | ||||
| 34268 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34269 | sqlite3TreeViewWith(pView, pWith, 0); | ||||
| 34270 | sqlite3TreeViewPop(&pView); | ||||
| 34271 | } | ||||
| 34272 | if( pTabList ){ | ||||
| 34273 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34274 | sqlite3TreeViewLine(pView, "INTO"); | ||||
| 34275 | sqlite3TreeViewSrcList(pView, pTabList); | ||||
| 34276 | sqlite3TreeViewPop(&pView); | ||||
| 34277 | } | ||||
| 34278 | if( pColumnList ){ | ||||
| 34279 | sqlite3TreeViewIdList(pView, pColumnList, (--n)>0, "COLUMNS"); | ||||
| 34280 | } | ||||
| 34281 | if( pSelect ){ | ||||
| 34282 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34283 | sqlite3TreeViewLine(pView, "DATA-SOURCE"); | ||||
| 34284 | sqlite3TreeViewSelect(pView, pSelect, 0); | ||||
| 34285 | sqlite3TreeViewPop(&pView); | ||||
| 34286 | } | ||||
| 34287 | if( pExprList ){ | ||||
| 34288 | sqlite3TreeViewExprList(pView, pExprList, (--n)>0, "VALUES"); | ||||
| 34289 | } | ||||
| 34290 | if( pUpsert ){ | ||||
| 34291 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34292 | sqlite3TreeViewLine(pView, "UPSERT"); | ||||
| 34293 | sqlite3TreeViewUpsert(pView, pUpsert, 0); | ||||
| 34294 | sqlite3TreeViewPop(&pView); | ||||
| 34295 | } | ||||
| 34296 | if( pTrigger ){ | ||||
| 34297 | sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1); | ||||
| 34298 | } | ||||
| 34299 | sqlite3TreeViewPop(&pView); | ||||
| 34300 | } | ||||
| 34301 | #endif /* TREETRACE_ENABLED */ | ||||
| 34302 | |||||
| 34303 | #if TREETRACE_ENABLED0 | ||||
| 34304 | /* | ||||
| 34305 | ** Generate a human-readable diagram of the data structure that go | ||||
| 34306 | ** into generating an UPDATE statement. | ||||
| 34307 | */ | ||||
| 34308 | SQLITE_PRIVATEstatic void sqlite3TreeViewUpdate( | ||||
| 34309 | const With *pWith, | ||||
| 34310 | const SrcList *pTabList, | ||||
| 34311 | const ExprList *pChanges, | ||||
| 34312 | const Expr *pWhere, | ||||
| 34313 | int onError, | ||||
| 34314 | const ExprList *pOrderBy, | ||||
| 34315 | const Expr *pLimit, | ||||
| 34316 | const Upsert *pUpsert, | ||||
| 34317 | const Trigger *pTrigger | ||||
| 34318 | ){ | ||||
| 34319 | int n = 0; | ||||
| 34320 | TreeView *pView = 0; | ||||
| 34321 | const char *zLabel = "UPDATE"; | ||||
| 34322 | switch( onError ){ | ||||
| 34323 | case OE_Replace5: zLabel = "UPDATE OR REPLACE"; break; | ||||
| 34324 | case OE_Ignore4: zLabel = "UPDATE OR IGNORE"; break; | ||||
| 34325 | case OE_Rollback1: zLabel = "UPDATE OR ROLLBACK"; break; | ||||
| 34326 | case OE_Abort2: zLabel = "UPDATE OR ABORT"; break; | ||||
| 34327 | case OE_Fail3: zLabel = "UPDATE OR FAIL"; break; | ||||
| 34328 | } | ||||
| 34329 | sqlite3TreeViewPush(&pView, 0); | ||||
| 34330 | sqlite3TreeViewLine(pView, zLabel); | ||||
| 34331 | if( pWith ) n++; | ||||
| 34332 | if( pTabList ) n++; | ||||
| 34333 | if( pChanges ) n++; | ||||
| 34334 | if( pWhere ) n++; | ||||
| 34335 | if( pOrderBy ) n++; | ||||
| 34336 | if( pLimit ) n++; | ||||
| 34337 | if( pUpsert ) n++; | ||||
| 34338 | if( pTrigger ) n++; | ||||
| 34339 | if( pWith ){ | ||||
| 34340 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34341 | sqlite3TreeViewWith(pView, pWith, 0); | ||||
| 34342 | sqlite3TreeViewPop(&pView); | ||||
| 34343 | } | ||||
| 34344 | if( pTabList ){ | ||||
| 34345 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34346 | sqlite3TreeViewLine(pView, "FROM"); | ||||
| 34347 | sqlite3TreeViewSrcList(pView, pTabList); | ||||
| 34348 | sqlite3TreeViewPop(&pView); | ||||
| 34349 | } | ||||
| 34350 | if( pChanges ){ | ||||
| 34351 | sqlite3TreeViewExprList(pView, pChanges, (--n)>0, "SET"); | ||||
| 34352 | } | ||||
| 34353 | if( pWhere ){ | ||||
| 34354 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34355 | sqlite3TreeViewLine(pView, "WHERE"); | ||||
| 34356 | sqlite3TreeViewExpr(pView, pWhere, 0); | ||||
| 34357 | sqlite3TreeViewPop(&pView); | ||||
| 34358 | } | ||||
| 34359 | if( pOrderBy ){ | ||||
| 34360 | sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY"); | ||||
| 34361 | } | ||||
| 34362 | if( pLimit ){ | ||||
| 34363 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34364 | sqlite3TreeViewLine(pView, "LIMIT"); | ||||
| 34365 | sqlite3TreeViewExpr(pView, pLimit, 0); | ||||
| 34366 | sqlite3TreeViewPop(&pView); | ||||
| 34367 | } | ||||
| 34368 | if( pUpsert ){ | ||||
| 34369 | sqlite3TreeViewPush(&pView, (--n)>0); | ||||
| 34370 | sqlite3TreeViewLine(pView, "UPSERT"); | ||||
| 34371 | sqlite3TreeViewUpsert(pView, pUpsert, 0); | ||||
| 34372 | sqlite3TreeViewPop(&pView); | ||||
| 34373 | } | ||||
| 34374 | if( pTrigger ){ | ||||
| 34375 | sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1); | ||||
| 34376 | } | ||||
| 34377 | sqlite3TreeViewPop(&pView); | ||||
| 34378 | } | ||||
| 34379 | #endif /* TREETRACE_ENABLED */ | ||||
| 34380 | |||||
| 34381 | #ifndef SQLITE_OMIT_TRIGGER | ||||
| 34382 | /* | ||||
| 34383 | ** Show a human-readable graph of a TriggerStep | ||||
| 34384 | */ | ||||
| 34385 | SQLITE_PRIVATEstatic void sqlite3TreeViewTriggerStep( | ||||
| 34386 | TreeView *pView, | ||||
| 34387 | const TriggerStep *pStep, | ||||
| 34388 | u8 moreToFollow, | ||||
| 34389 | u8 showFullList | ||||
| 34390 | ){ | ||||
| 34391 | int cnt = 0; | ||||
| 34392 | if( pStep==0 ) return; | ||||
| 34393 | sqlite3TreeViewPush(&pView, | ||||
| 34394 | moreToFollow || (showFullList && pStep->pNext!=0)); | ||||
| 34395 | do{ | ||||
| 34396 | if( cnt++ && pStep->pNext==0 ){ | ||||
| 34397 | sqlite3TreeViewPop(&pView); | ||||
| 34398 | sqlite3TreeViewPush(&pView, 0); | ||||
| 34399 | } | ||||
| 34400 | sqlite3TreeViewLine(pView, "%s", pStep->zSpan ? pStep->zSpan : "RETURNING"); | ||||
| 34401 | }while( showFullList && (pStep = pStep->pNext)!=0 ); | ||||
| 34402 | sqlite3TreeViewPop(&pView); | ||||
| 34403 | } | ||||
| 34404 | |||||
| 34405 | /* | ||||
| 34406 | ** Show a human-readable graph of a Trigger | ||||
| 34407 | */ | ||||
| 34408 | SQLITE_PRIVATEstatic void sqlite3TreeViewTrigger( | ||||
| 34409 | TreeView *pView, | ||||
| 34410 | const Trigger *pTrigger, | ||||
| 34411 | u8 moreToFollow, | ||||
| 34412 | u8 showFullList | ||||
| 34413 | ){ | ||||
| 34414 | int cnt = 0; | ||||
| 34415 | if( pTrigger==0 ) return; | ||||
| 34416 | sqlite3TreeViewPush(&pView, | ||||
| 34417 | moreToFollow || (showFullList && pTrigger->pNext!=0)); | ||||
| 34418 | do{ | ||||
| 34419 | if( cnt++ && pTrigger->pNext==0 ){ | ||||
| 34420 | sqlite3TreeViewPop(&pView); | ||||
| 34421 | sqlite3TreeViewPush(&pView, 0); | ||||
| 34422 | } | ||||
| 34423 | sqlite3TreeViewLine(pView, "TRIGGER %s", pTrigger->zName); | ||||
| 34424 | sqlite3TreeViewPush(&pView, 0); | ||||
| 34425 | sqlite3TreeViewTriggerStep(pView, pTrigger->step_list, 0, 1); | ||||
| 34426 | sqlite3TreeViewPop(&pView); | ||||
| 34427 | }while( showFullList && (pTrigger = pTrigger->pNext)!=0 ); | ||||
| 34428 | sqlite3TreeViewPop(&pView); | ||||
| 34429 | } | ||||
| 34430 | #endif /* SQLITE_OMIT_TRIGGER */ | ||||
| 34431 | |||||
| 34432 | |||||
| 34433 | /* | ||||
| 34434 | ** These simplified versions of the tree-view routines omit unnecessary | ||||
| 34435 | ** parameters. These variants are intended to be used from a symbolic | ||||
| 34436 | ** debugger, such as "gdb", during interactive debugging sessions. | ||||
| 34437 | ** | ||||
| 34438 | ** This routines are given external linkage so that they will always be | ||||
| 34439 | ** accessible to the debugging, and to avoid warnings about unused | ||||
| 34440 | ** functions. But these routines only exist in debugging builds, so they | ||||
| 34441 | ** do not contaminate the interface. | ||||
| 34442 | ** | ||||
| 34443 | ** See Also: | ||||
| 34444 | ** | ||||
| 34445 | ** sqlite3ShowWhereTerm() in where.c | ||||
| 34446 | */ | ||||
| 34447 | SQLITE_PRIVATEstatic void sqlite3ShowExpr(const Expr *p){ sqlite3TreeViewExpr(0,p,0); } | ||||
| 34448 | SQLITE_PRIVATEstatic void sqlite3ShowExprList(const ExprList *p){ sqlite3TreeViewExprList(0,p,0,0);} | ||||
| 34449 | SQLITE_PRIVATEstatic void sqlite3ShowIdList(const IdList *p){ sqlite3TreeViewIdList(0,p,0,0); } | ||||
| 34450 | SQLITE_PRIVATEstatic void sqlite3ShowSrcList(const SrcList *p){ sqlite3TreeViewSrcList(0,p); } | ||||
| 34451 | SQLITE_PRIVATEstatic void sqlite3ShowSelect(const Select *p){ sqlite3TreeViewSelect(0,p,0); } | ||||
| 34452 | SQLITE_PRIVATEstatic void sqlite3ShowWith(const With *p){ sqlite3TreeViewWith(0,p,0); } | ||||
| 34453 | SQLITE_PRIVATEstatic void sqlite3ShowUpsert(const Upsert *p){ sqlite3TreeViewUpsert(0,p,0); } | ||||
| 34454 | #ifndef SQLITE_OMIT_TRIGGER | ||||
| 34455 | SQLITE_PRIVATEstatic void sqlite3ShowTriggerStep(const TriggerStep *p){ | ||||
| 34456 | sqlite3TreeViewTriggerStep(0,p,0,0); | ||||
| 34457 | } | ||||
| 34458 | SQLITE_PRIVATEstatic void sqlite3ShowTriggerStepList(const TriggerStep *p){ | ||||
| 34459 | sqlite3TreeViewTriggerStep(0,p,0,1); | ||||
| 34460 | } | ||||
| 34461 | SQLITE_PRIVATEstatic void sqlite3ShowTrigger(const Trigger *p){ sqlite3TreeViewTrigger(0,p,0,0); } | ||||
| 34462 | SQLITE_PRIVATEstatic void sqlite3ShowTriggerList(const Trigger *p){ sqlite3TreeViewTrigger(0,p,0,1);} | ||||
| 34463 | #endif | ||||
| 34464 | #ifndef SQLITE_OMIT_WINDOWFUNC | ||||
| 34465 | SQLITE_PRIVATEstatic void sqlite3ShowWindow(const Window *p){ sqlite3TreeViewWindow(0,p,0); } | ||||
| 34466 | SQLITE_PRIVATEstatic void sqlite3ShowWinFunc(const Window *p){ sqlite3TreeViewWinFunc(0,p,0); } | ||||
| 34467 | #endif | ||||
| 34468 | |||||
| 34469 | #endif /* SQLITE_DEBUG */ | ||||
| 34470 | |||||
| 34471 | /************** End of treeview.c ********************************************/ | ||||
| 34472 | /************** Begin file random.c ******************************************/ | ||||
| 34473 | /* | ||||
| 34474 | ** 2001 September 15 | ||||
| 34475 | ** | ||||
| 34476 | ** The author disclaims copyright to this source code. In place of | ||||
| 34477 | ** a legal notice, here is a blessing: | ||||
| 34478 | ** | ||||
| 34479 | ** May you do good and not evil. | ||||
| 34480 | ** May you find forgiveness for yourself and forgive others. | ||||
| 34481 | ** May you share freely, never taking more than you give. | ||||
| 34482 | ** | ||||
| 34483 | ************************************************************************* | ||||
| 34484 | ** This file contains code to implement a pseudo-random number | ||||
| 34485 | ** generator (PRNG) for SQLite. | ||||
| 34486 | ** | ||||
| 34487 | ** Random numbers are used by some of the database backends in order | ||||
| 34488 | ** to generate random integer keys for tables or random filenames. | ||||
| 34489 | */ | ||||
| 34490 | /* #include "sqliteInt.h" */ | ||||
| 34491 | |||||
| 34492 | |||||
| 34493 | /* All threads share a single random number generator. | ||||
| 34494 | ** This structure is the current state of the generator. | ||||
| 34495 | */ | ||||
| 34496 | static SQLITE_WSD struct sqlite3PrngType { | ||||
| 34497 | u32 s[16]; /* 64 bytes of chacha20 state */ | ||||
| 34498 | u8 out[64]; /* Output bytes */ | ||||
| 34499 | u8 n; /* Output bytes remaining */ | ||||
| 34500 | } sqlite3Prng; | ||||
| 34501 | |||||
| 34502 | |||||
| 34503 | /* The RFC-7539 ChaCha20 block function | ||||
| 34504 | */ | ||||
| 34505 | #define ROTL(a,b)(((a) << (b)) | ((a) >> (32 - (b)))) (((a) << (b)) | ((a) >> (32 - (b)))) | ||||
| 34506 | #define QR(a, b, c, d)( a += b, d ^= a, d = (((d) << (16)) | ((d) >> (32 - (16)))), c += d, b ^= c, b = (((b) << (12)) | ((b) >> (32 - (12)))), a += b, d ^= a, d = (((d) << (8)) | ((d ) >> (32 - (8)))), c += d, b ^= c, b = (((b) << ( 7)) | ((b) >> (32 - (7))))) ( \ | ||||
| 34507 | a += b, d ^= a, d = ROTL(d,16)(((d) << (16)) | ((d) >> (32 - (16)))), \ | ||||
| 34508 | c += d, b ^= c, b = ROTL(b,12)(((b) << (12)) | ((b) >> (32 - (12)))), \ | ||||
| 34509 | a += b, d ^= a, d = ROTL(d, 8)(((d) << (8)) | ((d) >> (32 - (8)))), \ | ||||
| 34510 | c += d, b ^= c, b = ROTL(b, 7)(((b) << (7)) | ((b) >> (32 - (7))))) | ||||
| 34511 | static void chacha_block(u32 *out, const u32 *in){ | ||||
| 34512 | int i; | ||||
| 34513 | u32 x[16]; | ||||
| 34514 | memcpy(x, in, 64); | ||||
| 34515 | for(i=0; i<10; i++){ | ||||
| 34516 | QR(x[0], x[4], x[ 8], x[12])( x[0] += x[4], x[12] ^= x[0], x[12] = (((x[12]) << (16 )) | ((x[12]) >> (32 - (16)))), x[ 8] += x[12], x[4] ^= x[ 8], x[4] = (((x[4]) << (12)) | ((x[4]) >> (32 - (12)))), x[0] += x[4], x[12] ^= x[0], x[12] = (((x[12]) << (8)) | ((x[12]) >> (32 - (8)))), x[ 8] += x[12], x[4] ^= x[ 8], x[4] = (((x[4]) << (7)) | ((x[4]) >> (32 - (7))))); | ||||
| 34517 | QR(x[1], x[5], x[ 9], x[13])( x[1] += x[5], x[13] ^= x[1], x[13] = (((x[13]) << (16 )) | ((x[13]) >> (32 - (16)))), x[ 9] += x[13], x[5] ^= x[ 9], x[5] = (((x[5]) << (12)) | ((x[5]) >> (32 - (12)))), x[1] += x[5], x[13] ^= x[1], x[13] = (((x[13]) << (8)) | ((x[13]) >> (32 - (8)))), x[ 9] += x[13], x[5] ^= x[ 9], x[5] = (((x[5]) << (7)) | ((x[5]) >> (32 - (7))))); | ||||
| 34518 | QR(x[2], x[6], x[10], x[14])( x[2] += x[6], x[14] ^= x[2], x[14] = (((x[14]) << (16 )) | ((x[14]) >> (32 - (16)))), x[10] += x[14], x[6] ^= x[10], x[6] = (((x[6]) << (12)) | ((x[6]) >> (32 - (12)))), x[2] += x[6], x[14] ^= x[2], x[14] = (((x[14]) << (8)) | ((x[14]) >> (32 - (8)))), x[10] += x[14], x[6] ^= x[10], x[6] = (((x[6]) << (7)) | ((x[6]) >> (32 - (7))))); | ||||
| 34519 | QR(x[3], x[7], x[11], x[15])( x[3] += x[7], x[15] ^= x[3], x[15] = (((x[15]) << (16 )) | ((x[15]) >> (32 - (16)))), x[11] += x[15], x[7] ^= x[11], x[7] = (((x[7]) << (12)) | ((x[7]) >> (32 - (12)))), x[3] += x[7], x[15] ^= x[3], x[15] = (((x[15]) << (8)) | ((x[15]) >> (32 - (8)))), x[11] += x[15], x[7] ^= x[11], x[7] = (((x[7]) << (7)) | ((x[7]) >> (32 - (7))))); | ||||
| 34520 | QR(x[0], x[5], x[10], x[15])( x[0] += x[5], x[15] ^= x[0], x[15] = (((x[15]) << (16 )) | ((x[15]) >> (32 - (16)))), x[10] += x[15], x[5] ^= x[10], x[5] = (((x[5]) << (12)) | ((x[5]) >> (32 - (12)))), x[0] += x[5], x[15] ^= x[0], x[15] = (((x[15]) << (8)) | ((x[15]) >> (32 - (8)))), x[10] += x[15], x[5] ^= x[10], x[5] = (((x[5]) << (7)) | ((x[5]) >> (32 - (7))))); | ||||
| 34521 | QR(x[1], x[6], x[11], x[12])( x[1] += x[6], x[12] ^= x[1], x[12] = (((x[12]) << (16 )) | ((x[12]) >> (32 - (16)))), x[11] += x[12], x[6] ^= x[11], x[6] = (((x[6]) << (12)) | ((x[6]) >> (32 - (12)))), x[1] += x[6], x[12] ^= x[1], x[12] = (((x[12]) << (8)) | ((x[12]) >> (32 - (8)))), x[11] += x[12], x[6] ^= x[11], x[6] = (((x[6]) << (7)) | ((x[6]) >> (32 - (7))))); | ||||
| 34522 | QR(x[2], x[7], x[ 8], x[13])( x[2] += x[7], x[13] ^= x[2], x[13] = (((x[13]) << (16 )) | ((x[13]) >> (32 - (16)))), x[ 8] += x[13], x[7] ^= x[ 8], x[7] = (((x[7]) << (12)) | ((x[7]) >> (32 - (12)))), x[2] += x[7], x[13] ^= x[2], x[13] = (((x[13]) << (8)) | ((x[13]) >> (32 - (8)))), x[ 8] += x[13], x[7] ^= x[ 8], x[7] = (((x[7]) << (7)) | ((x[7]) >> (32 - (7))))); | ||||
| 34523 | QR(x[3], x[4], x[ 9], x[14])( x[3] += x[4], x[14] ^= x[3], x[14] = (((x[14]) << (16 )) | ((x[14]) >> (32 - (16)))), x[ 9] += x[14], x[4] ^= x[ 9], x[4] = (((x[4]) << (12)) | ((x[4]) >> (32 - (12)))), x[3] += x[4], x[14] ^= x[3], x[14] = (((x[14]) << (8)) | ((x[14]) >> (32 - (8)))), x[ 9] += x[14], x[4] ^= x[ 9], x[4] = (((x[4]) << (7)) | ((x[4]) >> (32 - (7))))); | ||||
| 34524 | } | ||||
| 34525 | for(i=0; i<16; i++) out[i] = x[i]+in[i]; | ||||
| 34526 | } | ||||
| 34527 | |||||
| 34528 | /* | ||||
| 34529 | ** Return N random bytes. | ||||
| 34530 | */ | ||||
| 34531 | SQLITE_API void sqlite3_randomness(int N, void *pBuf){ | ||||
| 34532 | unsigned char *zBuf = pBuf; | ||||
| 34533 | |||||
| 34534 | /* The "wsdPrng" macro will resolve to the pseudo-random number generator | ||||
| 34535 | ** state vector. If writable static data is unsupported on the target, | ||||
| 34536 | ** we have to locate the state vector at run-time. In the more common | ||||
| 34537 | ** case where writable static data is supported, wsdPrng can refer directly | ||||
| 34538 | ** to the "sqlite3Prng" state vector declared above. | ||||
| 34539 | */ | ||||
| 34540 | #ifdef SQLITE_OMIT_WSD | ||||
| 34541 | struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng)sqlite3Prng; | ||||
| 34542 | # define wsdPrngsqlite3Prng p[0] | ||||
| 34543 | #else | ||||
| 34544 | # define wsdPrngsqlite3Prng sqlite3Prng | ||||
| 34545 | #endif | ||||
| 34546 | |||||
| 34547 | #if SQLITE_THREADSAFE2 | ||||
| 34548 | sqlite3_mutex *mutex; | ||||
| 34549 | #endif | ||||
| 34550 | |||||
| 34551 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 34552 | if( sqlite3_initialize() ) return; | ||||
| 34553 | #endif | ||||
| 34554 | |||||
| 34555 | #if SQLITE_THREADSAFE2 | ||||
| 34556 | mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG5); | ||||
| 34557 | #endif | ||||
| 34558 | |||||
| 34559 | sqlite3_mutex_enter(mutex); | ||||
| 34560 | if( N<=0 || pBuf==0 ){ | ||||
| 34561 | wsdPrngsqlite3Prng.s[0] = 0; | ||||
| 34562 | sqlite3_mutex_leave(mutex); | ||||
| 34563 | return; | ||||
| 34564 | } | ||||
| 34565 | |||||
| 34566 | /* Initialize the state of the random number generator once, | ||||
| 34567 | ** the first time this routine is called. | ||||
| 34568 | */ | ||||
| 34569 | if( wsdPrngsqlite3Prng.s[0]==0 ){ | ||||
| 34570 | sqlite3_vfs *pVfs = sqlite3_vfs_find(0); | ||||
| 34571 | static const u32 chacha20_init[] = { | ||||
| 34572 | 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 | ||||
| 34573 | }; | ||||
| 34574 | memcpy(&wsdPrngsqlite3Prng.s[0], chacha20_init, 16); | ||||
| 34575 | if( NEVER(pVfs==0)(pVfs==0) ){ | ||||
| 34576 | memset(&wsdPrngsqlite3Prng.s[4], 0, 44); | ||||
| 34577 | }else{ | ||||
| 34578 | sqlite3OsRandomness(pVfs, 44, (char*)&wsdPrngsqlite3Prng.s[4]); | ||||
| 34579 | } | ||||
| 34580 | wsdPrngsqlite3Prng.s[15] = wsdPrngsqlite3Prng.s[12]; | ||||
| 34581 | wsdPrngsqlite3Prng.s[12] = 0; | ||||
| 34582 | wsdPrngsqlite3Prng.n = 0; | ||||
| 34583 | } | ||||
| 34584 | |||||
| 34585 | assert( N>0 )((void) (0)); | ||||
| 34586 | while( 1 /* exit by break */ ){ | ||||
| 34587 | if( N<=wsdPrngsqlite3Prng.n ){ | ||||
| 34588 | memcpy(zBuf, &wsdPrngsqlite3Prng.out[wsdPrngsqlite3Prng.n-N], N); | ||||
| 34589 | wsdPrngsqlite3Prng.n -= N; | ||||
| 34590 | break; | ||||
| 34591 | } | ||||
| 34592 | if( wsdPrngsqlite3Prng.n>0 ){ | ||||
| 34593 | memcpy(zBuf, wsdPrngsqlite3Prng.out, wsdPrngsqlite3Prng.n); | ||||
| 34594 | N -= wsdPrngsqlite3Prng.n; | ||||
| 34595 | zBuf += wsdPrngsqlite3Prng.n; | ||||
| 34596 | } | ||||
| 34597 | wsdPrngsqlite3Prng.s[12]++; | ||||
| 34598 | chacha_block((u32*)wsdPrngsqlite3Prng.out, wsdPrngsqlite3Prng.s); | ||||
| 34599 | wsdPrngsqlite3Prng.n = 64; | ||||
| 34600 | } | ||||
| 34601 | sqlite3_mutex_leave(mutex); | ||||
| 34602 | } | ||||
| 34603 | |||||
| 34604 | #ifndef SQLITE_UNTESTABLE | ||||
| 34605 | /* | ||||
| 34606 | ** For testing purposes, we sometimes want to preserve the state of | ||||
| 34607 | ** PRNG and restore the PRNG to its saved state at a later time, or | ||||
| 34608 | ** to reset the PRNG to its initial state. These routines accomplish | ||||
| 34609 | ** those tasks. | ||||
| 34610 | ** | ||||
| 34611 | ** The sqlite3_test_control() interface calls these routines to | ||||
| 34612 | ** control the PRNG. | ||||
| 34613 | */ | ||||
| 34614 | static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; | ||||
| 34615 | SQLITE_PRIVATEstatic void sqlite3PrngSaveState(void){ | ||||
| 34616 | memcpy( | ||||
| 34617 | &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng)sqlite3SavedPrng, | ||||
| 34618 | &GLOBAL(struct sqlite3PrngType, sqlite3Prng)sqlite3Prng, | ||||
| 34619 | sizeof(sqlite3Prng) | ||||
| 34620 | ); | ||||
| 34621 | } | ||||
| 34622 | SQLITE_PRIVATEstatic void sqlite3PrngRestoreState(void){ | ||||
| 34623 | memcpy( | ||||
| 34624 | &GLOBAL(struct sqlite3PrngType, sqlite3Prng)sqlite3Prng, | ||||
| 34625 | &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng)sqlite3SavedPrng, | ||||
| 34626 | sizeof(sqlite3Prng) | ||||
| 34627 | ); | ||||
| 34628 | } | ||||
| 34629 | #endif /* SQLITE_UNTESTABLE */ | ||||
| 34630 | |||||
| 34631 | /************** End of random.c **********************************************/ | ||||
| 34632 | /************** Begin file threads.c *****************************************/ | ||||
| 34633 | /* | ||||
| 34634 | ** 2012 July 21 | ||||
| 34635 | ** | ||||
| 34636 | ** The author disclaims copyright to this source code. In place of | ||||
| 34637 | ** a legal notice, here is a blessing: | ||||
| 34638 | ** | ||||
| 34639 | ** May you do good and not evil. | ||||
| 34640 | ** May you find forgiveness for yourself and forgive others. | ||||
| 34641 | ** May you share freely, never taking more than you give. | ||||
| 34642 | ** | ||||
| 34643 | ****************************************************************************** | ||||
| 34644 | ** | ||||
| 34645 | ** This file presents a simple cross-platform threading interface for | ||||
| 34646 | ** use internally by SQLite. | ||||
| 34647 | ** | ||||
| 34648 | ** A "thread" can be created using sqlite3ThreadCreate(). This thread | ||||
| 34649 | ** runs independently of its creator until it is joined using | ||||
| 34650 | ** sqlite3ThreadJoin(), at which point it terminates. | ||||
| 34651 | ** | ||||
| 34652 | ** Threads do not have to be real. It could be that the work of the | ||||
| 34653 | ** "thread" is done by the main thread at either the sqlite3ThreadCreate() | ||||
| 34654 | ** or sqlite3ThreadJoin() call. This is, in fact, what happens in | ||||
| 34655 | ** single threaded systems. Nothing in SQLite requires multiple threads. | ||||
| 34656 | ** This interface exists so that applications that want to take advantage | ||||
| 34657 | ** of multiple cores can do so, while also allowing applications to stay | ||||
| 34658 | ** single-threaded if desired. | ||||
| 34659 | */ | ||||
| 34660 | /* #include "sqliteInt.h" */ | ||||
| 34661 | #if SQLITE_OS_WIN0 | ||||
| 34662 | /* # include "os_win.h" */ | ||||
| 34663 | #endif | ||||
| 34664 | |||||
| 34665 | #if SQLITE_MAX_WORKER_THREADS8>0 | ||||
| 34666 | |||||
| 34667 | /********************************* Unix Pthreads ****************************/ | ||||
| 34668 | #if SQLITE_OS_UNIX1 && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE2>0 | ||||
| 34669 | |||||
| 34670 | #define SQLITE_THREADS_IMPLEMENTED1 1 /* Prevent the single-thread code below */ | ||||
| 34671 | /* #include <pthread.h> */ | ||||
| 34672 | |||||
| 34673 | /* A running thread */ | ||||
| 34674 | struct SQLiteThread { | ||||
| 34675 | pthread_t tid; /* Thread ID */ | ||||
| 34676 | int done; /* Set to true when thread finishes */ | ||||
| 34677 | void *pOut; /* Result returned by the thread */ | ||||
| 34678 | void *(*xTask)(void*); /* The thread routine */ | ||||
| 34679 | void *pIn; /* Argument to the thread */ | ||||
| 34680 | }; | ||||
| 34681 | |||||
| 34682 | /* Create a new thread */ | ||||
| 34683 | SQLITE_PRIVATEstatic int sqlite3ThreadCreate( | ||||
| 34684 | SQLiteThread **ppThread, /* OUT: Write the thread object here */ | ||||
| 34685 | void *(*xTask)(void*), /* Routine to run in a separate thread */ | ||||
| 34686 | void *pIn /* Argument passed into xTask() */ | ||||
| 34687 | ){ | ||||
| 34688 | SQLiteThread *p; | ||||
| 34689 | int rc; | ||||
| 34690 | |||||
| 34691 | assert( ppThread!=0 )((void) (0)); | ||||
| 34692 | assert( xTask!=0 )((void) (0)); | ||||
| 34693 | /* This routine is never used in single-threaded mode */ | ||||
| 34694 | assert( sqlite3GlobalConfig.bCoreMutex!=0 )((void) (0)); | ||||
| 34695 | |||||
| 34696 | *ppThread = 0; | ||||
| 34697 | p = sqlite3Malloc(sizeof(*p)); | ||||
| 34698 | if( p==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 34699 | memset(p, 0, sizeof(*p)); | ||||
| 34700 | p->xTask = xTask; | ||||
| 34701 | p->pIn = pIn; | ||||
| 34702 | /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a | ||||
| 34703 | ** function that returns SQLITE_ERROR when passed the argument 200, that | ||||
| 34704 | ** forces worker threads to run sequentially and deterministically | ||||
| 34705 | ** for testing purposes. */ | ||||
| 34706 | if( sqlite3FaultSim(200) ){ | ||||
| 34707 | rc = 1; | ||||
| 34708 | }else{ | ||||
| 34709 | rc = pthread_create(&p->tid, 0, xTask, pIn); | ||||
| 34710 | } | ||||
| 34711 | if( rc ){ | ||||
| 34712 | p->done = 1; | ||||
| 34713 | p->pOut = xTask(pIn); | ||||
| 34714 | } | ||||
| 34715 | *ppThread = p; | ||||
| 34716 | return SQLITE_OK0; | ||||
| 34717 | } | ||||
| 34718 | |||||
| 34719 | /* Get the results of the thread */ | ||||
| 34720 | SQLITE_PRIVATEstatic int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ | ||||
| 34721 | int rc; | ||||
| 34722 | |||||
| 34723 | assert( ppOut!=0 )((void) (0)); | ||||
| 34724 | if( NEVER(p==0)(p==0) ) return SQLITE_NOMEM_BKPT7; | ||||
| 34725 | if( p->done ){ | ||||
| 34726 | *ppOut = p->pOut; | ||||
| 34727 | rc = SQLITE_OK0; | ||||
| 34728 | }else{ | ||||
| 34729 | rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR1 : SQLITE_OK0; | ||||
| 34730 | } | ||||
| 34731 | sqlite3_free(p); | ||||
| 34732 | return rc; | ||||
| 34733 | } | ||||
| 34734 | |||||
| 34735 | #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */ | ||||
| 34736 | /******************************** End Unix Pthreads *************************/ | ||||
| 34737 | |||||
| 34738 | |||||
| 34739 | /********************************* Win32 Threads ****************************/ | ||||
| 34740 | #if SQLITE_OS_WIN_THREADS | ||||
| 34741 | |||||
| 34742 | #define SQLITE_THREADS_IMPLEMENTED1 1 /* Prevent the single-thread code below */ | ||||
| 34743 | #include <process.h> | ||||
| 34744 | |||||
| 34745 | /* A running thread */ | ||||
| 34746 | struct SQLiteThread { | ||||
| 34747 | void *tid; /* The thread handle */ | ||||
| 34748 | unsigned id; /* The thread identifier */ | ||||
| 34749 | void *(*xTask)(void*); /* The routine to run as a thread */ | ||||
| 34750 | void *pIn; /* Argument to xTask */ | ||||
| 34751 | void *pResult; /* Result of xTask */ | ||||
| 34752 | }; | ||||
| 34753 | |||||
| 34754 | /* Thread procedure Win32 compatibility shim */ | ||||
| 34755 | static unsigned __stdcall sqlite3ThreadProc( | ||||
| 34756 | void *pArg /* IN: Pointer to the SQLiteThread structure */ | ||||
| 34757 | ){ | ||||
| 34758 | SQLiteThread *p = (SQLiteThread *)pArg; | ||||
| 34759 | |||||
| 34760 | assert( p!=0 )((void) (0)); | ||||
| 34761 | #if 0 | ||||
| 34762 | /* | ||||
| 34763 | ** This assert appears to trigger spuriously on certain | ||||
| 34764 | ** versions of Windows, possibly due to _beginthreadex() | ||||
| 34765 | ** and/or CreateThread() not fully setting their thread | ||||
| 34766 | ** ID parameter before starting the thread. | ||||
| 34767 | */ | ||||
| 34768 | assert( p->id==GetCurrentThreadId() )((void) (0)); | ||||
| 34769 | #endif | ||||
| 34770 | assert( p->xTask!=0 )((void) (0)); | ||||
| 34771 | p->pResult = p->xTask(p->pIn); | ||||
| 34772 | |||||
| 34773 | _endthreadex(0); | ||||
| 34774 | return 0; /* NOT REACHED */ | ||||
| 34775 | } | ||||
| 34776 | |||||
| 34777 | /* Create a new thread */ | ||||
| 34778 | SQLITE_PRIVATEstatic int sqlite3ThreadCreate( | ||||
| 34779 | SQLiteThread **ppThread, /* OUT: Write the thread object here */ | ||||
| 34780 | void *(*xTask)(void*), /* Routine to run in a separate thread */ | ||||
| 34781 | void *pIn /* Argument passed into xTask() */ | ||||
| 34782 | ){ | ||||
| 34783 | SQLiteThread *p; | ||||
| 34784 | |||||
| 34785 | assert( ppThread!=0 )((void) (0)); | ||||
| 34786 | assert( xTask!=0 )((void) (0)); | ||||
| 34787 | *ppThread = 0; | ||||
| 34788 | p = sqlite3Malloc(sizeof(*p)); | ||||
| 34789 | if( p==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 34790 | /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a | ||||
| 34791 | ** function that returns SQLITE_ERROR when passed the argument 200, that | ||||
| 34792 | ** forces worker threads to run sequentially and deterministically | ||||
| 34793 | ** (via the sqlite3FaultSim() term of the conditional) for testing | ||||
| 34794 | ** purposes. */ | ||||
| 34795 | if( sqlite3GlobalConfigsqlite3Config.bCoreMutex==0 || sqlite3FaultSim(200) ){ | ||||
| 34796 | memset(p, 0, sizeof(*p)); | ||||
| 34797 | }else{ | ||||
| 34798 | p->xTask = xTask; | ||||
| 34799 | p->pIn = pIn; | ||||
| 34800 | p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id); | ||||
| 34801 | if( p->tid==0 ){ | ||||
| 34802 | memset(p, 0, sizeof(*p)); | ||||
| 34803 | } | ||||
| 34804 | } | ||||
| 34805 | if( p->xTask==0 ){ | ||||
| 34806 | p->id = GetCurrentThreadId(); | ||||
| 34807 | p->pResult = xTask(pIn); | ||||
| 34808 | } | ||||
| 34809 | *ppThread = p; | ||||
| 34810 | return SQLITE_OK0; | ||||
| 34811 | } | ||||
| 34812 | |||||
| 34813 | SQLITE_PRIVATEstatic DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */ | ||||
| 34814 | |||||
| 34815 | /* Get the results of the thread */ | ||||
| 34816 | SQLITE_PRIVATEstatic int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ | ||||
| 34817 | DWORD rc; | ||||
| 34818 | BOOL bRc; | ||||
| 34819 | |||||
| 34820 | assert( ppOut!=0 )((void) (0)); | ||||
| 34821 | if( NEVER(p==0)(p==0) ) return SQLITE_NOMEM_BKPT7; | ||||
| 34822 | if( p->xTask==0 ){ | ||||
| 34823 | /* assert( p->id==GetCurrentThreadId() ); */ | ||||
| 34824 | rc = WAIT_OBJECT_0; | ||||
| 34825 | assert( p->tid==0 )((void) (0)); | ||||
| 34826 | }else{ | ||||
| 34827 | assert( p->id!=0 && p->id!=GetCurrentThreadId() )((void) (0)); | ||||
| 34828 | rc = sqlite3Win32Wait((HANDLE)p->tid); | ||||
| 34829 | assert( rc!=WAIT_IO_COMPLETION )((void) (0)); | ||||
| 34830 | bRc = CloseHandle((HANDLE)p->tid); | ||||
| 34831 | assert( bRc )((void) (0)); | ||||
| 34832 | } | ||||
| 34833 | if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; | ||||
| 34834 | sqlite3_free(p); | ||||
| 34835 | return (rc==WAIT_OBJECT_0) ? SQLITE_OK0 : SQLITE_ERROR1; | ||||
| 34836 | } | ||||
| 34837 | |||||
| 34838 | #endif /* SQLITE_OS_WIN_THREADS */ | ||||
| 34839 | /******************************** End Win32 Threads *************************/ | ||||
| 34840 | |||||
| 34841 | |||||
| 34842 | /********************************* Single-Threaded **************************/ | ||||
| 34843 | #ifndef SQLITE_THREADS_IMPLEMENTED1 | ||||
| 34844 | /* | ||||
| 34845 | ** This implementation does not actually create a new thread. It does the | ||||
| 34846 | ** work of the thread in the main thread, when either the thread is created | ||||
| 34847 | ** or when it is joined | ||||
| 34848 | */ | ||||
| 34849 | |||||
| 34850 | /* A running thread */ | ||||
| 34851 | struct SQLiteThread { | ||||
| 34852 | void *(*xTask)(void*); /* The routine to run as a thread */ | ||||
| 34853 | void *pIn; /* Argument to xTask */ | ||||
| 34854 | void *pResult; /* Result of xTask */ | ||||
| 34855 | }; | ||||
| 34856 | |||||
| 34857 | /* Create a new thread */ | ||||
| 34858 | SQLITE_PRIVATEstatic int sqlite3ThreadCreate( | ||||
| 34859 | SQLiteThread **ppThread, /* OUT: Write the thread object here */ | ||||
| 34860 | void *(*xTask)(void*), /* Routine to run in a separate thread */ | ||||
| 34861 | void *pIn /* Argument passed into xTask() */ | ||||
| 34862 | ){ | ||||
| 34863 | SQLiteThread *p; | ||||
| 34864 | |||||
| 34865 | assert( ppThread!=0 )((void) (0)); | ||||
| 34866 | assert( xTask!=0 )((void) (0)); | ||||
| 34867 | *ppThread = 0; | ||||
| 34868 | p = sqlite3Malloc(sizeof(*p)); | ||||
| 34869 | if( p==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 34870 | if( (SQLITE_PTR_TO_INT(p)((int)(long int)(p))/17)&1 ){ | ||||
| 34871 | p->xTask = xTask; | ||||
| 34872 | p->pIn = pIn; | ||||
| 34873 | }else{ | ||||
| 34874 | p->xTask = 0; | ||||
| 34875 | p->pResult = xTask(pIn); | ||||
| 34876 | } | ||||
| 34877 | *ppThread = p; | ||||
| 34878 | return SQLITE_OK0; | ||||
| 34879 | } | ||||
| 34880 | |||||
| 34881 | /* Get the results of the thread */ | ||||
| 34882 | SQLITE_PRIVATEstatic int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ | ||||
| 34883 | |||||
| 34884 | assert( ppOut!=0 )((void) (0)); | ||||
| 34885 | if( NEVER(p==0)(p==0) ) return SQLITE_NOMEM_BKPT7; | ||||
| 34886 | if( p->xTask ){ | ||||
| 34887 | *ppOut = p->xTask(p->pIn); | ||||
| 34888 | }else{ | ||||
| 34889 | *ppOut = p->pResult; | ||||
| 34890 | } | ||||
| 34891 | sqlite3_free(p); | ||||
| 34892 | |||||
| 34893 | #if defined(SQLITE_TEST) | ||||
| 34894 | { | ||||
| 34895 | void *pTstAlloc = sqlite3Malloc(10); | ||||
| 34896 | if (!pTstAlloc) return SQLITE_NOMEM_BKPT7; | ||||
| 34897 | sqlite3_free(pTstAlloc); | ||||
| 34898 | } | ||||
| 34899 | #endif | ||||
| 34900 | |||||
| 34901 | return SQLITE_OK0; | ||||
| 34902 | } | ||||
| 34903 | |||||
| 34904 | #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */ | ||||
| 34905 | /****************************** End Single-Threaded *************************/ | ||||
| 34906 | #endif /* SQLITE_MAX_WORKER_THREADS>0 */ | ||||
| 34907 | |||||
| 34908 | /************** End of threads.c *********************************************/ | ||||
| 34909 | /************** Begin file utf.c *********************************************/ | ||||
| 34910 | /* | ||||
| 34911 | ** 2004 April 13 | ||||
| 34912 | ** | ||||
| 34913 | ** The author disclaims copyright to this source code. In place of | ||||
| 34914 | ** a legal notice, here is a blessing: | ||||
| 34915 | ** | ||||
| 34916 | ** May you do good and not evil. | ||||
| 34917 | ** May you find forgiveness for yourself and forgive others. | ||||
| 34918 | ** May you share freely, never taking more than you give. | ||||
| 34919 | ** | ||||
| 34920 | ************************************************************************* | ||||
| 34921 | ** This file contains routines used to translate between UTF-8, | ||||
| 34922 | ** UTF-16, UTF-16BE, and UTF-16LE. | ||||
| 34923 | ** | ||||
| 34924 | ** Notes on UTF-8: | ||||
| 34925 | ** | ||||
| 34926 | ** Byte-0 Byte-1 Byte-2 Byte-3 Value | ||||
| 34927 | ** 0xxxxxxx 00000000 00000000 0xxxxxxx | ||||
| 34928 | ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx | ||||
| 34929 | ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx | ||||
| 34930 | ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx | ||||
| 34931 | ** | ||||
| 34932 | ** | ||||
| 34933 | ** Notes on UTF-16: (with wwww+1==uuuuu) | ||||
| 34934 | ** | ||||
| 34935 | ** Word-0 Word-1 Value | ||||
| 34936 | ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx | ||||
| 34937 | ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx | ||||
| 34938 | ** | ||||
| 34939 | ** | ||||
| 34940 | ** BOM or Byte Order Mark: | ||||
| 34941 | ** 0xff 0xfe little-endian utf-16 follows | ||||
| 34942 | ** 0xfe 0xff big-endian utf-16 follows | ||||
| 34943 | ** | ||||
| 34944 | */ | ||||
| 34945 | /* #include "sqliteInt.h" */ | ||||
| 34946 | /* #include <assert.h> */ | ||||
| 34947 | /* #include "vdbeInt.h" */ | ||||
| 34948 | |||||
| 34949 | #if !defined(SQLITE_AMALGAMATION1) && SQLITE_BYTEORDER1234==0 | ||||
| 34950 | /* | ||||
| 34951 | ** The following constant value is used by the SQLITE_BIGENDIAN and | ||||
| 34952 | ** SQLITE_LITTLEENDIAN macros. | ||||
| 34953 | */ | ||||
| 34954 | SQLITE_PRIVATEstatic const int sqlite3one = 1; | ||||
| 34955 | #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */ | ||||
| 34956 | |||||
| 34957 | /* | ||||
| 34958 | ** This lookup table is used to help decode the first byte of | ||||
| 34959 | ** a multi-byte UTF8 character. | ||||
| 34960 | */ | ||||
| 34961 | static const unsigned char sqlite3Utf8Trans1[] = { | ||||
| 34962 | 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, | ||||
| 34963 | 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, | ||||
| 34964 | 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, | ||||
| 34965 | 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, | ||||
| 34966 | 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, | ||||
| 34967 | 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, | ||||
| 34968 | 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, | ||||
| 34969 | 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, | ||||
| 34970 | }; | ||||
| 34971 | |||||
| 34972 | |||||
| 34973 | #define WRITE_UTF8(zOut, c){ if( c<0x00080 ){ *zOut++ = (u8)(c&0xFF); } else if( c <0x00800 ){ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); * zOut++ = 0x80 + (u8)(c & 0x3F); } else if( c<0x10000 ) { *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)(c & 0x3F); }else{ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07 ); *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)( c & 0x3F); } } { \ | ||||
| 34974 | if( c<0x00080 ){ \ | ||||
| 34975 | *zOut++ = (u8)(c&0xFF); \ | ||||
| 34976 | } \ | ||||
| 34977 | else if( c<0x00800 ){ \ | ||||
| 34978 | *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ | ||||
| 34979 | *zOut++ = 0x80 + (u8)(c & 0x3F); \ | ||||
| 34980 | } \ | ||||
| 34981 | else if( c<0x10000 ){ \ | ||||
| 34982 | *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ | ||||
| 34983 | *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ | ||||
| 34984 | *zOut++ = 0x80 + (u8)(c & 0x3F); \ | ||||
| 34985 | }else{ \ | ||||
| 34986 | *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ | ||||
| 34987 | *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ | ||||
| 34988 | *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ | ||||
| 34989 | *zOut++ = 0x80 + (u8)(c & 0x3F); \ | ||||
| 34990 | } \ | ||||
| 34991 | } | ||||
| 34992 | |||||
| 34993 | #define WRITE_UTF16LE(zOut, c){ if( c<=0xFFFF ){ *zOut++ = (u8)(c&0x00FF); *zOut++ = (u8)((c>>8)&0x00FF); }else{ *zOut++ = (u8)(((c>> 10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); *zOut ++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); *zOut ++ = (u8)(c&0x00FF); *zOut++ = (u8)(0x00DC + ((c>>8 )&0x03)); } } { \ | ||||
| 34994 | if( c<=0xFFFF ){ \ | ||||
| 34995 | *zOut++ = (u8)(c&0x00FF); \ | ||||
| 34996 | *zOut++ = (u8)((c>>8)&0x00FF); \ | ||||
| 34997 | }else{ \ | ||||
| 34998 | *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ | ||||
| 34999 | *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ | ||||
| 35000 | *zOut++ = (u8)(c&0x00FF); \ | ||||
| 35001 | *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ | ||||
| 35002 | } \ | ||||
| 35003 | } | ||||
| 35004 | |||||
| 35005 | #define WRITE_UTF16BE(zOut, c){ if( c<=0xFFFF ){ *zOut++ = (u8)((c>>8)&0x00FF) ; *zOut++ = (u8)(c&0x00FF); }else{ *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); *zOut++ = (u8)(((c>> 10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); *zOut ++ = (u8)(0x00DC + ((c>>8)&0x03)); *zOut++ = (u8)(c &0x00FF); } } { \ | ||||
| 35006 | if( c<=0xFFFF ){ \ | ||||
| 35007 | *zOut++ = (u8)((c>>8)&0x00FF); \ | ||||
| 35008 | *zOut++ = (u8)(c&0x00FF); \ | ||||
| 35009 | }else{ \ | ||||
| 35010 | *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ | ||||
| 35011 | *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ | ||||
| 35012 | *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ | ||||
| 35013 | *zOut++ = (u8)(c&0x00FF); \ | ||||
| 35014 | } \ | ||||
| 35015 | } | ||||
| 35016 | |||||
| 35017 | /* | ||||
| 35018 | ** Write a single UTF8 character whose value is v into the | ||||
| 35019 | ** buffer starting at zOut. zOut must be sized to hold at | ||||
| 35020 | ** least four bytes. Return the number of bytes needed | ||||
| 35021 | ** to encode the new character. | ||||
| 35022 | */ | ||||
| 35023 | SQLITE_PRIVATEstatic int sqlite3AppendOneUtf8Character(char *zOut, u32 v){ | ||||
| 35024 | if( v<0x00080 ){ | ||||
| 35025 | zOut[0] = (u8)(v & 0xff); | ||||
| 35026 | return 1; | ||||
| 35027 | } | ||||
| 35028 | if( v<0x00800 ){ | ||||
| 35029 | zOut[0] = 0xc0 + (u8)((v>>6) & 0x1f); | ||||
| 35030 | zOut[1] = 0x80 + (u8)(v & 0x3f); | ||||
| 35031 | return 2; | ||||
| 35032 | } | ||||
| 35033 | if( v<0x10000 ){ | ||||
| 35034 | zOut[0] = 0xe0 + (u8)((v>>12) & 0x0f); | ||||
| 35035 | zOut[1] = 0x80 + (u8)((v>>6) & 0x3f); | ||||
| 35036 | zOut[2] = 0x80 + (u8)(v & 0x3f); | ||||
| 35037 | return 3; | ||||
| 35038 | } | ||||
| 35039 | zOut[0] = 0xf0 + (u8)((v>>18) & 0x07); | ||||
| 35040 | zOut[1] = 0x80 + (u8)((v>>12) & 0x3f); | ||||
| 35041 | zOut[2] = 0x80 + (u8)((v>>6) & 0x3f); | ||||
| 35042 | zOut[3] = 0x80 + (u8)(v & 0x3f); | ||||
| 35043 | return 4; | ||||
| 35044 | } | ||||
| 35045 | |||||
| 35046 | /* | ||||
| 35047 | ** Translate a single UTF-8 character. Return the unicode value. | ||||
| 35048 | ** | ||||
| 35049 | ** During translation, assume that the byte that zTerm points | ||||
| 35050 | ** is a 0x00. | ||||
| 35051 | ** | ||||
| 35052 | ** Write a pointer to the next unread byte back into *pzNext. | ||||
| 35053 | ** | ||||
| 35054 | ** Notes On Invalid UTF-8: | ||||
| 35055 | ** | ||||
| 35056 | ** * This routine never allows a 7-bit character (0x00 through 0x7f) to | ||||
| 35057 | ** be encoded as a multi-byte character. Any multi-byte character that | ||||
| 35058 | ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. | ||||
| 35059 | ** | ||||
| 35060 | ** * This routine never allows a UTF16 surrogate value to be encoded. | ||||
| 35061 | ** If a multi-byte character attempts to encode a value between | ||||
| 35062 | ** 0xd800 and 0xe000 then it is rendered as 0xfffd. | ||||
| 35063 | ** | ||||
| 35064 | ** * Bytes in the range of 0x80 through 0xbf which occur as the first | ||||
| 35065 | ** byte of a character are interpreted as single-byte characters | ||||
| 35066 | ** and rendered as themselves even though they are technically | ||||
| 35067 | ** invalid characters. | ||||
| 35068 | ** | ||||
| 35069 | ** * This routine accepts over-length UTF8 encodings | ||||
| 35070 | ** for unicode values 0x80 and greater. It does not change over-length | ||||
| 35071 | ** encodings to 0xfffd as some systems recommend. | ||||
| 35072 | */ | ||||
| 35073 | #define READ_UTF8(zIn, zTerm, c)c = *(zIn++); if( c>=0xc0 ){ c = sqlite3Utf8Trans1[c-0xc0] ; while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){ c = (c<<6) + (0x3f & *(zIn++)); } if( c<0x80 || ( c&0xFFFFF800)==0xD800 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } } \ | ||||
| 35074 | c = *(zIn++); \ | ||||
| 35075 | if( c>=0xc0 ){ \ | ||||
| 35076 | c = sqlite3Utf8Trans1[c-0xc0]; \ | ||||
| 35077 | while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){ \ | ||||
| 35078 | c = (c<<6) + (0x3f & *(zIn++)); \ | ||||
| 35079 | } \ | ||||
| 35080 | if( c<0x80 \ | ||||
| 35081 | || (c&0xFFFFF800)==0xD800 \ | ||||
| 35082 | || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ | ||||
| 35083 | } | ||||
| 35084 | SQLITE_PRIVATEstatic u32 sqlite3Utf8Read( | ||||
| 35085 | const unsigned char **pz /* Pointer to string from which to read char */ | ||||
| 35086 | ){ | ||||
| 35087 | unsigned int c; | ||||
| 35088 | |||||
| 35089 | /* Same as READ_UTF8() above but without the zTerm parameter. | ||||
| 35090 | ** For this routine, we assume the UTF8 string is always zero-terminated. | ||||
| 35091 | */ | ||||
| 35092 | c = *((*pz)++); | ||||
| 35093 | if( c>=0xc0 ){ | ||||
| 35094 | c = sqlite3Utf8Trans1[c-0xc0]; | ||||
| 35095 | while( (*(*pz) & 0xc0)==0x80 ){ | ||||
| 35096 | c = (c<<6) + (0x3f & *((*pz)++)); | ||||
| 35097 | } | ||||
| 35098 | if( c<0x80 | ||||
| 35099 | || (c&0xFFFFF800)==0xD800 | ||||
| 35100 | || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } | ||||
| 35101 | } | ||||
| 35102 | return c; | ||||
| 35103 | } | ||||
| 35104 | |||||
| 35105 | /* | ||||
| 35106 | ** Read a single UTF8 character out of buffer z[], but reading no | ||||
| 35107 | ** more than n characters from the buffer. z[] is not zero-terminated. | ||||
| 35108 | ** | ||||
| 35109 | ** Return the number of bytes used to construct the character. | ||||
| 35110 | ** | ||||
| 35111 | ** Invalid UTF8 might generate a strange result. No effort is made | ||||
| 35112 | ** to detect invalid UTF8. | ||||
| 35113 | ** | ||||
| 35114 | ** At most 4 bytes will be read out of z[]. The return value will always | ||||
| 35115 | ** be between 1 and 4. | ||||
| 35116 | */ | ||||
| 35117 | SQLITE_PRIVATEstatic int sqlite3Utf8ReadLimited( | ||||
| 35118 | const u8 *z, | ||||
| 35119 | int n, | ||||
| 35120 | u32 *piOut | ||||
| 35121 | ){ | ||||
| 35122 | u32 c; | ||||
| 35123 | int i = 1; | ||||
| 35124 | assert( n>0 )((void) (0)); | ||||
| 35125 | c = z[0]; | ||||
| 35126 | if( c>=0xc0 ){ | ||||
| 35127 | c = sqlite3Utf8Trans1[c-0xc0]; | ||||
| 35128 | if( n>4 ) n = 4; | ||||
| 35129 | while( i<n && (z[i] & 0xc0)==0x80 ){ | ||||
| 35130 | c = (c<<6) + (0x3f & z[i]); | ||||
| 35131 | i++; | ||||
| 35132 | } | ||||
| 35133 | } | ||||
| 35134 | *piOut = c; | ||||
| 35135 | return i; | ||||
| 35136 | } | ||||
| 35137 | |||||
| 35138 | |||||
| 35139 | /* | ||||
| 35140 | ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is | ||||
| 35141 | ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). | ||||
| 35142 | */ | ||||
| 35143 | /* #define TRANSLATE_TRACE 1 */ | ||||
| 35144 | |||||
| 35145 | #ifndef SQLITE_OMIT_UTF16 | ||||
| 35146 | /* | ||||
| 35147 | ** This routine transforms the internal text encoding used by pMem to | ||||
| 35148 | ** desiredEnc. It is an error if the string is already of the desired | ||||
| 35149 | ** encoding, or if *pMem does not contain a string value. | ||||
| 35150 | */ | ||||
| 35151 | SQLITE_PRIVATEstatic SQLITE_NOINLINE__attribute__((noinline)) int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ | ||||
| 35152 | sqlite3_int64 len; /* Maximum length of output string in bytes */ | ||||
| 35153 | unsigned char *zOut; /* Output buffer */ | ||||
| 35154 | unsigned char *zIn; /* Input iterator */ | ||||
| 35155 | unsigned char *zTerm; /* End of input */ | ||||
| 35156 | unsigned char *z; /* Output iterator */ | ||||
| 35157 | unsigned int c; | ||||
| 35158 | |||||
| 35159 | assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) )((void) (0)); | ||||
| 35160 | assert( pMem->flags&MEM_Str )((void) (0)); | ||||
| 35161 | assert( pMem->enc!=desiredEnc )((void) (0)); | ||||
| 35162 | assert( pMem->enc!=0 )((void) (0)); | ||||
| 35163 | assert( pMem->n>=0 )((void) (0)); | ||||
| 35164 | |||||
| 35165 | #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) | ||||
| 35166 | { | ||||
| 35167 | StrAccum acc; | ||||
| 35168 | char zBuf[1000]; | ||||
| 35169 | sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); | ||||
| 35170 | sqlite3VdbeMemPrettyPrint(pMem, &acc); | ||||
| 35171 | fprintf(stderrstderr, "INPUT: %s\n", sqlite3StrAccumFinish(&acc)); | ||||
| 35172 | } | ||||
| 35173 | #endif | ||||
| 35174 | |||||
| 35175 | /* If the translation is between UTF-16 little and big endian, then | ||||
| 35176 | ** all that is required is to swap the byte order. This case is handled | ||||
| 35177 | ** differently from the others. | ||||
| 35178 | */ | ||||
| 35179 | if( pMem->enc!=SQLITE_UTF81 && desiredEnc!=SQLITE_UTF81 ){ | ||||
| 35180 | u8 temp; | ||||
| 35181 | int rc; | ||||
| 35182 | rc = sqlite3VdbeMemMakeWriteable(pMem); | ||||
| 35183 | if( rc!=SQLITE_OK0 ){ | ||||
| 35184 | assert( rc==SQLITE_NOMEM )((void) (0)); | ||||
| 35185 | return SQLITE_NOMEM_BKPT7; | ||||
| 35186 | } | ||||
| 35187 | zIn = (u8*)pMem->z; | ||||
| 35188 | zTerm = &zIn[pMem->n&~1]; | ||||
| 35189 | while( zIn<zTerm ){ | ||||
| 35190 | temp = *zIn; | ||||
| 35191 | *zIn = *(zIn+1); | ||||
| 35192 | zIn++; | ||||
| 35193 | *zIn++ = temp; | ||||
| 35194 | } | ||||
| 35195 | pMem->enc = desiredEnc; | ||||
| 35196 | goto translate_out; | ||||
| 35197 | } | ||||
| 35198 | |||||
| 35199 | /* Set len to the maximum number of bytes required in the output buffer. */ | ||||
| 35200 | if( desiredEnc==SQLITE_UTF81 ){ | ||||
| 35201 | /* When converting from UTF-16, the maximum growth results from | ||||
| 35202 | ** translating a 2-byte character to a 4-byte UTF-8 character. | ||||
| 35203 | ** A single byte is required for the output string | ||||
| 35204 | ** nul-terminator. | ||||
| 35205 | */ | ||||
| 35206 | pMem->n &= ~1; | ||||
| 35207 | len = 2 * (sqlite3_int64)pMem->n + 1; | ||||
| 35208 | }else{ | ||||
| 35209 | /* When converting from UTF-8 to UTF-16 the maximum growth is caused | ||||
| 35210 | ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 | ||||
| 35211 | ** character. Two bytes are required in the output buffer for the | ||||
| 35212 | ** nul-terminator. | ||||
| 35213 | */ | ||||
| 35214 | len = 2 * (sqlite3_int64)pMem->n + 2; | ||||
| 35215 | } | ||||
| 35216 | |||||
| 35217 | /* Set zIn to point at the start of the input buffer and zTerm to point 1 | ||||
| 35218 | ** byte past the end. | ||||
| 35219 | ** | ||||
| 35220 | ** Variable zOut is set to point at the output buffer, space obtained | ||||
| 35221 | ** from sqlite3_malloc(). | ||||
| 35222 | */ | ||||
| 35223 | zIn = (u8*)pMem->z; | ||||
| 35224 | zTerm = &zIn[pMem->n]; | ||||
| 35225 | zOut = sqlite3DbMallocRaw(pMem->db, len); | ||||
| 35226 | if( !zOut ){ | ||||
| 35227 | return SQLITE_NOMEM_BKPT7; | ||||
| 35228 | } | ||||
| 35229 | z = zOut; | ||||
| 35230 | |||||
| 35231 | if( pMem->enc==SQLITE_UTF81 ){ | ||||
| 35232 | if( desiredEnc==SQLITE_UTF16LE2 ){ | ||||
| 35233 | /* UTF-8 -> UTF-16 Little-endian */ | ||||
| 35234 | while( zIn<zTerm ){ | ||||
| 35235 | READ_UTF8(zIn, zTerm, c)c = *(zIn++); if( c>=0xc0 ){ c = sqlite3Utf8Trans1[c-0xc0] ; while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){ c = (c<<6) + (0x3f & *(zIn++)); } if( c<0x80 || ( c&0xFFFFF800)==0xD800 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } }; | ||||
| 35236 | WRITE_UTF16LE(z, c){ if( c<=0xFFFF ){ *z++ = (u8)(c&0x00FF); *z++ = (u8)( (c>>8)&0x00FF); }else{ *z++ = (u8)(((c>>10)& 0x003F) + (((c-0x10000)>>10)&0x00C0)); *z++ = (u8)( 0x00D8 + (((c-0x10000)>>18)&0x03)); *z++ = (u8)(c& 0x00FF); *z++ = (u8)(0x00DC + ((c>>8)&0x03)); } }; | ||||
| 35237 | } | ||||
| 35238 | }else{ | ||||
| 35239 | assert( desiredEnc==SQLITE_UTF16BE )((void) (0)); | ||||
| 35240 | /* UTF-8 -> UTF-16 Big-endian */ | ||||
| 35241 | while( zIn<zTerm ){ | ||||
| 35242 | READ_UTF8(zIn, zTerm, c)c = *(zIn++); if( c>=0xc0 ){ c = sqlite3Utf8Trans1[c-0xc0] ; while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){ c = (c<<6) + (0x3f & *(zIn++)); } if( c<0x80 || ( c&0xFFFFF800)==0xD800 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } }; | ||||
| 35243 | WRITE_UTF16BE(z, c){ if( c<=0xFFFF ){ *z++ = (u8)((c>>8)&0x00FF); * z++ = (u8)(c&0x00FF); }else{ *z++ = (u8)(0x00D8 + (((c-0x10000 )>>18)&0x03)); *z++ = (u8)(((c>>10)&0x003F ) + (((c-0x10000)>>10)&0x00C0)); *z++ = (u8)(0x00DC + ((c>>8)&0x03)); *z++ = (u8)(c&0x00FF); } }; | ||||
| 35244 | } | ||||
| 35245 | } | ||||
| 35246 | pMem->n = (int)(z - zOut); | ||||
| 35247 | *z++ = 0; | ||||
| 35248 | }else{ | ||||
| 35249 | assert( desiredEnc==SQLITE_UTF8 )((void) (0)); | ||||
| 35250 | if( pMem->enc==SQLITE_UTF16LE2 ){ | ||||
| 35251 | /* UTF-16 Little-endian -> UTF-8 */ | ||||
| 35252 | while( zIn<zTerm ){ | ||||
| 35253 | c = *(zIn++); | ||||
| 35254 | c += (*(zIn++))<<8; | ||||
| 35255 | if( c>=0xd800 && c<0xe000 ){ | ||||
| 35256 | #ifdef SQLITE_REPLACE_INVALID_UTF | ||||
| 35257 | if( c>=0xdc00 || zIn>=zTerm ){ | ||||
| 35258 | c = 0xfffd; | ||||
| 35259 | }else{ | ||||
| 35260 | int c2 = *(zIn++); | ||||
| 35261 | c2 += (*(zIn++))<<8; | ||||
| 35262 | if( c2<0xdc00 || c2>=0xe000 ){ | ||||
| 35263 | zIn -= 2; | ||||
| 35264 | c = 0xfffd; | ||||
| 35265 | }else{ | ||||
| 35266 | c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000; | ||||
| 35267 | } | ||||
| 35268 | } | ||||
| 35269 | #else | ||||
| 35270 | if( zIn<zTerm ){ | ||||
| 35271 | int c2 = (*zIn++); | ||||
| 35272 | c2 += ((*zIn++)<<8); | ||||
| 35273 | c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); | ||||
| 35274 | } | ||||
| 35275 | #endif | ||||
| 35276 | } | ||||
| 35277 | WRITE_UTF8(z, c){ if( c<0x00080 ){ *z++ = (u8)(c&0xFF); } else if( c< 0x00800 ){ *z++ = 0xC0 + (u8)((c>>6)&0x1F); *z++ = 0x80 + (u8)(c & 0x3F); } else if( c<0x10000 ){ *z++ = 0xE0 + (u8)((c>>12)&0x0F); *z++ = 0x80 + (u8)((c>> 6) & 0x3F); *z++ = 0x80 + (u8)(c & 0x3F); }else{ *z++ = 0xF0 + (u8)((c>>18) & 0x07); *z++ = 0x80 + (u8)( (c>>12) & 0x3F); *z++ = 0x80 + (u8)((c>>6) & 0x3F); *z++ = 0x80 + (u8)(c & 0x3F); } }; | ||||
| 35278 | } | ||||
| 35279 | }else{ | ||||
| 35280 | /* UTF-16 Big-endian -> UTF-8 */ | ||||
| 35281 | while( zIn<zTerm ){ | ||||
| 35282 | c = (*(zIn++))<<8; | ||||
| 35283 | c += *(zIn++); | ||||
| 35284 | if( c>=0xd800 && c<0xe000 ){ | ||||
| 35285 | #ifdef SQLITE_REPLACE_INVALID_UTF | ||||
| 35286 | if( c>=0xdc00 || zIn>=zTerm ){ | ||||
| 35287 | c = 0xfffd; | ||||
| 35288 | }else{ | ||||
| 35289 | int c2 = (*(zIn++))<<8; | ||||
| 35290 | c2 += *(zIn++); | ||||
| 35291 | if( c2<0xdc00 || c2>=0xe000 ){ | ||||
| 35292 | zIn -= 2; | ||||
| 35293 | c = 0xfffd; | ||||
| 35294 | }else{ | ||||
| 35295 | c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000; | ||||
| 35296 | } | ||||
| 35297 | } | ||||
| 35298 | #else | ||||
| 35299 | if( zIn<zTerm ){ | ||||
| 35300 | int c2 = ((*zIn++)<<8); | ||||
| 35301 | c2 += (*zIn++); | ||||
| 35302 | c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); | ||||
| 35303 | } | ||||
| 35304 | #endif | ||||
| 35305 | } | ||||
| 35306 | WRITE_UTF8(z, c){ if( c<0x00080 ){ *z++ = (u8)(c&0xFF); } else if( c< 0x00800 ){ *z++ = 0xC0 + (u8)((c>>6)&0x1F); *z++ = 0x80 + (u8)(c & 0x3F); } else if( c<0x10000 ){ *z++ = 0xE0 + (u8)((c>>12)&0x0F); *z++ = 0x80 + (u8)((c>> 6) & 0x3F); *z++ = 0x80 + (u8)(c & 0x3F); }else{ *z++ = 0xF0 + (u8)((c>>18) & 0x07); *z++ = 0x80 + (u8)( (c>>12) & 0x3F); *z++ = 0x80 + (u8)((c>>6) & 0x3F); *z++ = 0x80 + (u8)(c & 0x3F); } }; | ||||
| 35307 | } | ||||
| 35308 | } | ||||
| 35309 | pMem->n = (int)(z - zOut); | ||||
| 35310 | } | ||||
| 35311 | *z = 0; | ||||
| 35312 | assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len )((void) (0)); | ||||
| 35313 | |||||
| 35314 | c = MEM_Str0x0002|MEM_Term0x0200|(pMem->flags&(MEM_AffMask0x003f|MEM_Subtype0x0800)); | ||||
| 35315 | sqlite3VdbeMemRelease(pMem); | ||||
| 35316 | pMem->flags = c; | ||||
| 35317 | pMem->enc = desiredEnc; | ||||
| 35318 | pMem->z = (char*)zOut; | ||||
| 35319 | pMem->zMalloc = pMem->z; | ||||
| 35320 | pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z); | ||||
| 35321 | |||||
| 35322 | translate_out: | ||||
| 35323 | #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) | ||||
| 35324 | { | ||||
| 35325 | StrAccum acc; | ||||
| 35326 | char zBuf[1000]; | ||||
| 35327 | sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); | ||||
| 35328 | sqlite3VdbeMemPrettyPrint(pMem, &acc); | ||||
| 35329 | fprintf(stderrstderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc)); | ||||
| 35330 | } | ||||
| 35331 | #endif | ||||
| 35332 | return SQLITE_OK0; | ||||
| 35333 | } | ||||
| 35334 | #endif /* SQLITE_OMIT_UTF16 */ | ||||
| 35335 | |||||
| 35336 | #ifndef SQLITE_OMIT_UTF16 | ||||
| 35337 | /* | ||||
| 35338 | ** This routine checks for a byte-order mark at the beginning of the | ||||
| 35339 | ** UTF-16 string stored in *pMem. If one is present, it is removed and | ||||
| 35340 | ** the encoding of the Mem adjusted. This routine does not do any | ||||
| 35341 | ** byte-swapping, it just sets Mem.enc appropriately. | ||||
| 35342 | ** | ||||
| 35343 | ** The allocation (static, dynamic etc.) and encoding of the Mem may be | ||||
| 35344 | ** changed by this function. | ||||
| 35345 | */ | ||||
| 35346 | SQLITE_PRIVATEstatic int sqlite3VdbeMemHandleBom(Mem *pMem){ | ||||
| 35347 | int rc = SQLITE_OK0; | ||||
| 35348 | u8 bom = 0; | ||||
| 35349 | |||||
| 35350 | assert( pMem->n>=0 )((void) (0)); | ||||
| 35351 | if( pMem->n>1 ){ | ||||
| 35352 | u8 b1 = *(u8 *)pMem->z; | ||||
| 35353 | u8 b2 = *(((u8 *)pMem->z) + 1); | ||||
| 35354 | if( b1==0xFE && b2==0xFF ){ | ||||
| 35355 | bom = SQLITE_UTF16BE3; | ||||
| 35356 | } | ||||
| 35357 | if( b1==0xFF && b2==0xFE ){ | ||||
| 35358 | bom = SQLITE_UTF16LE2; | ||||
| 35359 | } | ||||
| 35360 | } | ||||
| 35361 | |||||
| 35362 | if( bom ){ | ||||
| 35363 | rc = sqlite3VdbeMemMakeWriteable(pMem); | ||||
| 35364 | if( rc==SQLITE_OK0 ){ | ||||
| 35365 | pMem->n -= 2; | ||||
| 35366 | memmove(pMem->z, &pMem->z[2], pMem->n); | ||||
| 35367 | pMem->z[pMem->n] = '\0'; | ||||
| 35368 | pMem->z[pMem->n+1] = '\0'; | ||||
| 35369 | pMem->flags |= MEM_Term0x0200; | ||||
| 35370 | pMem->enc = bom; | ||||
| 35371 | } | ||||
| 35372 | } | ||||
| 35373 | return rc; | ||||
| 35374 | } | ||||
| 35375 | #endif /* SQLITE_OMIT_UTF16 */ | ||||
| 35376 | |||||
| 35377 | /* | ||||
| 35378 | ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, | ||||
| 35379 | ** return the number of unicode characters in pZ up to (but not including) | ||||
| 35380 | ** the first 0x00 byte. If nByte is not less than zero, return the | ||||
| 35381 | ** number of unicode characters in the first nByte of pZ (or up to | ||||
| 35382 | ** the first 0x00, whichever comes first). | ||||
| 35383 | */ | ||||
| 35384 | SQLITE_PRIVATEstatic int sqlite3Utf8CharLen(const char *zIn, int nByte){ | ||||
| 35385 | int r = 0; | ||||
| 35386 | const u8 *z = (const u8*)zIn; | ||||
| 35387 | const u8 *zTerm; | ||||
| 35388 | if( nByte>=0 ){ | ||||
| 35389 | zTerm = &z[nByte]; | ||||
| 35390 | }else{ | ||||
| 35391 | zTerm = (const u8*)(-1); | ||||
| 35392 | } | ||||
| 35393 | assert( z<=zTerm )((void) (0)); | ||||
| 35394 | while( *z!=0 && z<zTerm ){ | ||||
| 35395 | SQLITE_SKIP_UTF8(z){ if( (*(z++))>=0xc0 ){ while( (*z & 0xc0)==0x80 ){ z++ ; } } }; | ||||
| 35396 | r++; | ||||
| 35397 | } | ||||
| 35398 | return r; | ||||
| 35399 | } | ||||
| 35400 | |||||
| 35401 | /* This test function is not currently used by the automated test-suite. | ||||
| 35402 | ** Hence it is only available in debug builds. | ||||
| 35403 | */ | ||||
| 35404 | #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) | ||||
| 35405 | /* | ||||
| 35406 | ** Translate UTF-8 to UTF-8. | ||||
| 35407 | ** | ||||
| 35408 | ** This has the effect of making sure that the string is well-formed | ||||
| 35409 | ** UTF-8. Miscoded characters are removed. | ||||
| 35410 | ** | ||||
| 35411 | ** The translation is done in-place and aborted if the output | ||||
| 35412 | ** overruns the input. | ||||
| 35413 | */ | ||||
| 35414 | SQLITE_PRIVATEstatic int sqlite3Utf8To8(unsigned char *zIn){ | ||||
| 35415 | unsigned char *zOut = zIn; | ||||
| 35416 | unsigned char *zStart = zIn; | ||||
| 35417 | u32 c; | ||||
| 35418 | |||||
| 35419 | while( zIn[0] && zOut<=zIn ){ | ||||
| 35420 | c = sqlite3Utf8Read((const u8**)&zIn); | ||||
| 35421 | if( c!=0xfffd ){ | ||||
| 35422 | WRITE_UTF8(zOut, c){ if( c<0x00080 ){ *zOut++ = (u8)(c&0xFF); } else if( c <0x00800 ){ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); * zOut++ = 0x80 + (u8)(c & 0x3F); } else if( c<0x10000 ) { *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)(c & 0x3F); }else{ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07 ); *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); *zOut++ = 0x80 + (u8)( c & 0x3F); } }; | ||||
| 35423 | } | ||||
| 35424 | } | ||||
| 35425 | *zOut = 0; | ||||
| 35426 | return (int)(zOut - zStart); | ||||
| 35427 | } | ||||
| 35428 | #endif | ||||
| 35429 | |||||
| 35430 | #ifndef SQLITE_OMIT_UTF16 | ||||
| 35431 | /* | ||||
| 35432 | ** Convert a UTF-16 string in the native encoding into a UTF-8 string. | ||||
| 35433 | ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must | ||||
| 35434 | ** be freed by the calling function. | ||||
| 35435 | ** | ||||
| 35436 | ** NULL is returned if there is an allocation error. | ||||
| 35437 | */ | ||||
| 35438 | SQLITE_PRIVATEstatic char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){ | ||||
| 35439 | Mem m; | ||||
| 35440 | memset(&m, 0, sizeof(m)); | ||||
| 35441 | m.db = db; | ||||
| 35442 | sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC((sqlite3_destructor_type)0)); | ||||
| 35443 | sqlite3VdbeChangeEncoding(&m, SQLITE_UTF81); | ||||
| 35444 | if( db->mallocFailed ){ | ||||
| 35445 | sqlite3VdbeMemRelease(&m); | ||||
| 35446 | m.z = 0; | ||||
| 35447 | } | ||||
| 35448 | assert( (m.flags & MEM_Term)!=0 || db->mallocFailed )((void) (0)); | ||||
| 35449 | assert( (m.flags & MEM_Str)!=0 || db->mallocFailed )((void) (0)); | ||||
| 35450 | assert( m.z || db->mallocFailed )((void) (0)); | ||||
| 35451 | return m.z; | ||||
| 35452 | } | ||||
| 35453 | |||||
| 35454 | /* | ||||
| 35455 | ** zIn is a UTF-16 encoded unicode string at least nByte bytes long. | ||||
| 35456 | ** Return the number of bytes in the first nChar unicode characters | ||||
| 35457 | ** in pZ. nChar must be non-negative. Surrogate pairs count as a single | ||||
| 35458 | ** character. | ||||
| 35459 | */ | ||||
| 35460 | SQLITE_PRIVATEstatic int sqlite3Utf16ByteLen(const void *zIn, int nByte, int nChar){ | ||||
| 35461 | int c; | ||||
| 35462 | unsigned char const *z = zIn; | ||||
| 35463 | unsigned char const *zEnd = &z[nByte-1]; | ||||
| 35464 | int n = 0; | ||||
| 35465 | |||||
| 35466 | if( SQLITE_UTF16NATIVE2==SQLITE_UTF16LE2 ) z++; | ||||
| 35467 | while( n<nChar && z<=zEnd ){ | ||||
| 35468 | c = z[0]; | ||||
| 35469 | z += 2; | ||||
| 35470 | if( c>=0xd8 && c<0xdc && z<=zEnd && z[0]>=0xdc && z[0]<0xe0 ) z += 2; | ||||
| 35471 | n++; | ||||
| 35472 | } | ||||
| 35473 | return (int)(z-(unsigned char const *)zIn) | ||||
| 35474 | - (SQLITE_UTF16NATIVE2==SQLITE_UTF16LE2); | ||||
| 35475 | } | ||||
| 35476 | |||||
| 35477 | #if defined(SQLITE_TEST) | ||||
| 35478 | /* | ||||
| 35479 | ** This routine is called from the TCL test function "translate_selftest". | ||||
| 35480 | ** It checks that the primitives for serializing and deserializing | ||||
| 35481 | ** characters in each encoding are inverses of each other. | ||||
| 35482 | */ | ||||
| 35483 | SQLITE_PRIVATEstatic void sqlite3UtfSelfTest(void){ | ||||
| 35484 | unsigned int i, t; | ||||
| 35485 | unsigned char zBuf[20]; | ||||
| 35486 | unsigned char *z; | ||||
| 35487 | int n; | ||||
| 35488 | unsigned int c; | ||||
| 35489 | |||||
| 35490 | for(i=0; i<0x00110000; i++){ | ||||
| 35491 | z = zBuf; | ||||
| 35492 | WRITE_UTF8(z, i){ if( i<0x00080 ){ *z++ = (u8)(i&0xFF); } else if( i< 0x00800 ){ *z++ = 0xC0 + (u8)((i>>6)&0x1F); *z++ = 0x80 + (u8)(i & 0x3F); } else if( i<0x10000 ){ *z++ = 0xE0 + (u8)((i>>12)&0x0F); *z++ = 0x80 + (u8)((i>> 6) & 0x3F); *z++ = 0x80 + (u8)(i & 0x3F); }else{ *z++ = 0xF0 + (u8)((i>>18) & 0x07); *z++ = 0x80 + (u8)( (i>>12) & 0x3F); *z++ = 0x80 + (u8)((i>>6) & 0x3F); *z++ = 0x80 + (u8)(i & 0x3F); } }; | ||||
| 35493 | n = (int)(z-zBuf); | ||||
| 35494 | assert( n>0 && n<=4 )((void) (0)); | ||||
| 35495 | z[0] = 0; | ||||
| 35496 | z = zBuf; | ||||
| 35497 | c = sqlite3Utf8Read((const u8**)&z); | ||||
| 35498 | t = i; | ||||
| 35499 | if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; | ||||
| 35500 | if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; | ||||
| 35501 | assert( c==t )((void) (0)); | ||||
| 35502 | assert( (z-zBuf)==n )((void) (0)); | ||||
| 35503 | } | ||||
| 35504 | } | ||||
| 35505 | #endif /* SQLITE_TEST */ | ||||
| 35506 | #endif /* SQLITE_OMIT_UTF16 */ | ||||
| 35507 | |||||
| 35508 | /************** End of utf.c *************************************************/ | ||||
| 35509 | /************** Begin file util.c ********************************************/ | ||||
| 35510 | /* | ||||
| 35511 | ** 2001 September 15 | ||||
| 35512 | ** | ||||
| 35513 | ** The author disclaims copyright to this source code. In place of | ||||
| 35514 | ** a legal notice, here is a blessing: | ||||
| 35515 | ** | ||||
| 35516 | ** May you do good and not evil. | ||||
| 35517 | ** May you find forgiveness for yourself and forgive others. | ||||
| 35518 | ** May you share freely, never taking more than you give. | ||||
| 35519 | ** | ||||
| 35520 | ************************************************************************* | ||||
| 35521 | ** Utility functions used throughout sqlite. | ||||
| 35522 | ** | ||||
| 35523 | ** This file contains functions for allocating memory, comparing | ||||
| 35524 | ** strings, and stuff like that. | ||||
| 35525 | ** | ||||
| 35526 | */ | ||||
| 35527 | /* #include "sqliteInt.h" */ | ||||
| 35528 | /* #include <stdarg.h> */ | ||||
| 35529 | #ifndef SQLITE_OMIT_FLOATING_POINT | ||||
| 35530 | #include <math.h> | ||||
| 35531 | #endif | ||||
| 35532 | |||||
| 35533 | /* | ||||
| 35534 | ** Calls to sqlite3FaultSim() are used to simulate a failure during testing, | ||||
| 35535 | ** or to bypass normal error detection during testing in order to let | ||||
| 35536 | ** execute proceed further downstream. | ||||
| 35537 | ** | ||||
| 35538 | ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The | ||||
| 35539 | ** sqlite3FaultSim() function only returns non-zero during testing. | ||||
| 35540 | ** | ||||
| 35541 | ** During testing, if the test harness has set a fault-sim callback using | ||||
| 35542 | ** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then | ||||
| 35543 | ** each call to sqlite3FaultSim() is relayed to that application-supplied | ||||
| 35544 | ** callback and the integer return value form the application-supplied | ||||
| 35545 | ** callback is returned by sqlite3FaultSim(). | ||||
| 35546 | ** | ||||
| 35547 | ** The integer argument to sqlite3FaultSim() is a code to identify which | ||||
| 35548 | ** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim() | ||||
| 35549 | ** should have a unique code. To prevent legacy testing applications from | ||||
| 35550 | ** breaking, the codes should not be changed or reused. | ||||
| 35551 | */ | ||||
| 35552 | #ifndef SQLITE_UNTESTABLE | ||||
| 35553 | SQLITE_PRIVATEstatic int sqlite3FaultSim(int iTest){ | ||||
| 35554 | int (*xCallback)(int) = sqlite3GlobalConfigsqlite3Config.xTestCallback; | ||||
| 35555 | return xCallback ? xCallback(iTest) : SQLITE_OK0; | ||||
| 35556 | } | ||||
| 35557 | #endif | ||||
| 35558 | |||||
| 35559 | #ifndef SQLITE_OMIT_FLOATING_POINT | ||||
| 35560 | /* | ||||
| 35561 | ** Return true if the floating point value is Not a Number (NaN). | ||||
| 35562 | ** | ||||
| 35563 | ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. | ||||
| 35564 | ** Otherwise, we have our own implementation that works on most systems. | ||||
| 35565 | */ | ||||
| 35566 | SQLITE_PRIVATEstatic int sqlite3IsNaN(double x){ | ||||
| 35567 | int rc; /* The value return */ | ||||
| 35568 | #if !SQLITE_HAVE_ISNAN1 && !HAVE_ISNAN | ||||
| 35569 | u64 y; | ||||
| 35570 | memcpy(&y,&x,sizeof(y)); | ||||
| 35571 | rc = IsNaN(y)(((y)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52) && ((y)&((((u64)1)<<52)-1))!=0); | ||||
| 35572 | #else | ||||
| 35573 | rc = isnan(x)__builtin_isnan (x); | ||||
| 35574 | #endif /* HAVE_ISNAN */ | ||||
| 35575 | testcase( rc ); | ||||
| 35576 | return rc; | ||||
| 35577 | } | ||||
| 35578 | #endif /* SQLITE_OMIT_FLOATING_POINT */ | ||||
| 35579 | |||||
| 35580 | #ifndef SQLITE_OMIT_FLOATING_POINT | ||||
| 35581 | /* | ||||
| 35582 | ** Return true if the floating point value is NaN or +Inf or -Inf. | ||||
| 35583 | */ | ||||
| 35584 | SQLITE_PRIVATEstatic int sqlite3IsOverflow(double x){ | ||||
| 35585 | int rc; /* The value return */ | ||||
| 35586 | u64 y; | ||||
| 35587 | memcpy(&y,&x,sizeof(y)); | ||||
| 35588 | rc = IsOvfl(y)(((y)&(((u64)0x7ff)<<52))==(((u64)0x7ff)<<52) ); | ||||
| 35589 | return rc; | ||||
| 35590 | } | ||||
| 35591 | #endif /* SQLITE_OMIT_FLOATING_POINT */ | ||||
| 35592 | |||||
| 35593 | /* | ||||
| 35594 | ** Compute a string length that is limited to what can be stored in | ||||
| 35595 | ** lower 30 bits of a 32-bit signed integer. | ||||
| 35596 | ** | ||||
| 35597 | ** The value returned will never be negative. Nor will it ever be greater | ||||
| 35598 | ** than the actual length of the string. For very long strings (greater | ||||
| 35599 | ** than 1GiB) the value returned might be less than the true string length. | ||||
| 35600 | */ | ||||
| 35601 | SQLITE_PRIVATEstatic int sqlite3Strlen30(const char *z){ | ||||
| 35602 | if( z==0 ) return 0; | ||||
| 35603 | return 0x3fffffff & (int)strlen(z); | ||||
| 35604 | } | ||||
| 35605 | |||||
| 35606 | /* | ||||
| 35607 | ** Return the declared type of a column. Or return zDflt if the column | ||||
| 35608 | ** has no declared type. | ||||
| 35609 | ** | ||||
| 35610 | ** The column type is an extra string stored after the zero-terminator on | ||||
| 35611 | ** the column name if and only if the COLFLAG_HASTYPE flag is set. | ||||
| 35612 | */ | ||||
| 35613 | SQLITE_PRIVATEstatic char *sqlite3ColumnType(Column *pCol, char *zDflt){ | ||||
| 35614 | if( pCol->colFlags & COLFLAG_HASTYPE0x0004 ){ | ||||
| 35615 | return pCol->zCnName + strlen(pCol->zCnName) + 1; | ||||
| 35616 | }else if( pCol->eCType ){ | ||||
| 35617 | assert( pCol->eCType<=SQLITE_N_STDTYPE )((void) (0)); | ||||
| 35618 | return (char*)sqlite3StdType[pCol->eCType-1]; | ||||
| 35619 | }else{ | ||||
| 35620 | return zDflt; | ||||
| 35621 | } | ||||
| 35622 | } | ||||
| 35623 | |||||
| 35624 | /* | ||||
| 35625 | ** Helper function for sqlite3Error() - called rarely. Broken out into | ||||
| 35626 | ** a separate routine to avoid unnecessary register saves on entry to | ||||
| 35627 | ** sqlite3Error(). | ||||
| 35628 | */ | ||||
| 35629 | static SQLITE_NOINLINE__attribute__((noinline)) void sqlite3ErrorFinish(sqlite3 *db, int err_code){ | ||||
| 35630 | if( db->pErr ) sqlite3ValueSetNull(db->pErr); | ||||
| 35631 | sqlite3SystemError(db, err_code); | ||||
| 35632 | } | ||||
| 35633 | |||||
| 35634 | /* | ||||
| 35635 | ** Set the current error code to err_code and clear any prior error message. | ||||
| 35636 | ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates | ||||
| 35637 | ** that would be appropriate. | ||||
| 35638 | */ | ||||
| 35639 | SQLITE_PRIVATEstatic void sqlite3Error(sqlite3 *db, int err_code){ | ||||
| 35640 | assert( db!=0 )((void) (0)); | ||||
| 35641 | db->errCode = err_code; | ||||
| 35642 | if( err_code || db->pErr ){ | ||||
| 35643 | sqlite3ErrorFinish(db, err_code); | ||||
| 35644 | }else{ | ||||
| 35645 | db->errByteOffset = -1; | ||||
| 35646 | } | ||||
| 35647 | } | ||||
| 35648 | |||||
| 35649 | /* | ||||
| 35650 | ** The equivalent of sqlite3Error(db, SQLITE_OK). Clear the error state | ||||
| 35651 | ** and error message. | ||||
| 35652 | */ | ||||
| 35653 | SQLITE_PRIVATEstatic void sqlite3ErrorClear(sqlite3 *db){ | ||||
| 35654 | assert( db!=0 )((void) (0)); | ||||
| 35655 | db->errCode = SQLITE_OK0; | ||||
| 35656 | db->errByteOffset = -1; | ||||
| 35657 | if( db->pErr ) sqlite3ValueSetNull(db->pErr); | ||||
| 35658 | } | ||||
| 35659 | |||||
| 35660 | /* | ||||
| 35661 | ** Load the sqlite3.iSysErrno field if that is an appropriate thing | ||||
| 35662 | ** to do based on the SQLite error code in rc. | ||||
| 35663 | */ | ||||
| 35664 | SQLITE_PRIVATEstatic void sqlite3SystemError(sqlite3 *db, int rc){ | ||||
| 35665 | if( rc==SQLITE_IOERR_NOMEM(10 | (12<<8)) ) return; | ||||
| 35666 | #if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL) | ||||
| 35667 | if( rc==SQLITE_IOERR_IN_PAGE(10 | (34<<8)) ){ | ||||
| 35668 | int ii; | ||||
| 35669 | int iErr; | ||||
| 35670 | sqlite3BtreeEnterAll(db); | ||||
| 35671 | for(ii=0; ii<db->nDb; ii++){ | ||||
| 35672 | if( db->aDb[ii].pBt ){ | ||||
| 35673 | iErr = sqlite3PagerWalSystemErrno(sqlite3BtreePager(db->aDb[ii].pBt)); | ||||
| 35674 | if( iErr ){ | ||||
| 35675 | db->iSysErrno = iErr; | ||||
| 35676 | } | ||||
| 35677 | } | ||||
| 35678 | } | ||||
| 35679 | sqlite3BtreeLeaveAll(db); | ||||
| 35680 | return; | ||||
| 35681 | } | ||||
| 35682 | #endif | ||||
| 35683 | rc &= 0xff; | ||||
| 35684 | if( rc==SQLITE_CANTOPEN14 || rc==SQLITE_IOERR10 ){ | ||||
| 35685 | db->iSysErrno = sqlite3OsGetLastError(db->pVfs); | ||||
| 35686 | } | ||||
| 35687 | } | ||||
| 35688 | |||||
| 35689 | /* | ||||
| 35690 | ** Set the most recent error code and error string for the sqlite | ||||
| 35691 | ** handle "db". The error code is set to "err_code". | ||||
| 35692 | ** | ||||
| 35693 | ** If it is not NULL, string zFormat specifies the format of the | ||||
| 35694 | ** error string. zFormat and any string tokens that follow it are | ||||
| 35695 | ** assumed to be encoded in UTF-8. | ||||
| 35696 | ** | ||||
| 35697 | ** To clear the most recent error for sqlite handle "db", sqlite3Error | ||||
| 35698 | ** should be called with err_code set to SQLITE_OK and zFormat set | ||||
| 35699 | ** to NULL. | ||||
| 35700 | */ | ||||
| 35701 | SQLITE_PRIVATEstatic void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){ | ||||
| 35702 | assert( db!=0 )((void) (0)); | ||||
| 35703 | db->errCode = err_code; | ||||
| 35704 | sqlite3SystemError(db, err_code); | ||||
| 35705 | if( zFormat==0 ){ | ||||
| 35706 | sqlite3Error(db, err_code); | ||||
| 35707 | }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){ | ||||
| 35708 | char *z; | ||||
| 35709 | va_list ap; | ||||
| 35710 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 35711 | z = sqlite3VMPrintf(db, zFormat, ap); | ||||
| 35712 | va_end(ap)__builtin_va_end(ap); | ||||
| 35713 | sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF81, SQLITE_DYNAMIC((sqlite3_destructor_type)sqlite3OomClear)); | ||||
| 35714 | } | ||||
| 35715 | } | ||||
| 35716 | |||||
| 35717 | /* | ||||
| 35718 | ** Check for interrupts and invoke progress callback. | ||||
| 35719 | */ | ||||
| 35720 | SQLITE_PRIVATEstatic void sqlite3ProgressCheck(Parse *p){ | ||||
| 35721 | sqlite3 *db = p->db; | ||||
| 35722 | if( AtomicLoad(&db->u1.isInterrupted)__atomic_load_n((&db->u1.isInterrupted),0) ){ | ||||
| 35723 | p->nErr++; | ||||
| 35724 | p->rc = SQLITE_INTERRUPT9; | ||||
| 35725 | } | ||||
| 35726 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK1 | ||||
| 35727 | if( db->xProgress ){ | ||||
| 35728 | if( p->rc==SQLITE_INTERRUPT9 ){ | ||||
| 35729 | p->nProgressSteps = 0; | ||||
| 35730 | }else if( (++p->nProgressSteps)>=db->nProgressOps ){ | ||||
| 35731 | if( db->xProgress(db->pProgressArg) ){ | ||||
| 35732 | p->nErr++; | ||||
| 35733 | p->rc = SQLITE_INTERRUPT9; | ||||
| 35734 | } | ||||
| 35735 | p->nProgressSteps = 0; | ||||
| 35736 | } | ||||
| 35737 | } | ||||
| 35738 | #endif | ||||
| 35739 | } | ||||
| 35740 | |||||
| 35741 | /* | ||||
| 35742 | ** Add an error message to pParse->zErrMsg and increment pParse->nErr. | ||||
| 35743 | ** | ||||
| 35744 | ** This function should be used to report any error that occurs while | ||||
| 35745 | ** compiling an SQL statement (i.e. within sqlite3_prepare()). The | ||||
| 35746 | ** last thing the sqlite3_prepare() function does is copy the error | ||||
| 35747 | ** stored by this function into the database handle using sqlite3Error(). | ||||
| 35748 | ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used | ||||
| 35749 | ** during statement execution (sqlite3_step() etc.). | ||||
| 35750 | */ | ||||
| 35751 | SQLITE_PRIVATEstatic void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ | ||||
| 35752 | char *zMsg; | ||||
| 35753 | va_list ap; | ||||
| 35754 | sqlite3 *db = pParse->db; | ||||
| 35755 | assert( db!=0 )((void) (0)); | ||||
| 35756 | assert( db->pParse==pParse || db->pParse->pToplevel==pParse )((void) (0)); | ||||
| 35757 | db->errByteOffset = -2; | ||||
| 35758 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 35759 | zMsg = sqlite3VMPrintf(db, zFormat, ap); | ||||
| 35760 | va_end(ap)__builtin_va_end(ap); | ||||
| 35761 | if( db->errByteOffset<-1 ) db->errByteOffset = -1; | ||||
| 35762 | if( db->suppressErr ){ | ||||
| 35763 | sqlite3DbFree(db, zMsg); | ||||
| 35764 | if( db->mallocFailed ){ | ||||
| 35765 | pParse->nErr++; | ||||
| 35766 | pParse->rc = SQLITE_NOMEM7; | ||||
| 35767 | } | ||||
| 35768 | }else{ | ||||
| 35769 | pParse->nErr++; | ||||
| 35770 | sqlite3DbFree(db, pParse->zErrMsg); | ||||
| 35771 | pParse->zErrMsg = zMsg; | ||||
| 35772 | pParse->rc = SQLITE_ERROR1; | ||||
| 35773 | pParse->pWith = 0; | ||||
| 35774 | } | ||||
| 35775 | } | ||||
| 35776 | |||||
| 35777 | /* | ||||
| 35778 | ** If database connection db is currently parsing SQL, then transfer | ||||
| 35779 | ** error code errCode to that parser if the parser has not already | ||||
| 35780 | ** encountered some other kind of error. | ||||
| 35781 | */ | ||||
| 35782 | SQLITE_PRIVATEstatic int sqlite3ErrorToParser(sqlite3 *db, int errCode){ | ||||
| 35783 | Parse *pParse; | ||||
| 35784 | if( db==0 || (pParse = db->pParse)==0 ) return errCode; | ||||
| 35785 | pParse->rc = errCode; | ||||
| 35786 | pParse->nErr++; | ||||
| 35787 | return errCode; | ||||
| 35788 | } | ||||
| 35789 | |||||
| 35790 | /* | ||||
| 35791 | ** Convert an SQL-style quoted string into a normal string by removing | ||||
| 35792 | ** the quote characters. The conversion is done in-place. If the | ||||
| 35793 | ** input does not begin with a quote character, then this routine | ||||
| 35794 | ** is a no-op. | ||||
| 35795 | ** | ||||
| 35796 | ** The input string must be zero-terminated. A new zero-terminator | ||||
| 35797 | ** is added to the dequoted string. | ||||
| 35798 | ** | ||||
| 35799 | ** The return value is -1 if no dequoting occurs or the length of the | ||||
| 35800 | ** dequoted string, exclusive of the zero terminator, if dequoting does | ||||
| 35801 | ** occur. | ||||
| 35802 | ** | ||||
| 35803 | ** 2002-02-14: This routine is extended to remove MS-Access style | ||||
| 35804 | ** brackets from around identifiers. For example: "[a-b-c]" becomes | ||||
| 35805 | ** "a-b-c". | ||||
| 35806 | */ | ||||
| 35807 | SQLITE_PRIVATEstatic void sqlite3Dequote(char *z){ | ||||
| 35808 | char quote; | ||||
| 35809 | int i, j; | ||||
| 35810 | if( z==0 ) return; | ||||
| 35811 | quote = z[0]; | ||||
| 35812 | if( !sqlite3Isquote(quote)(sqlite3CtypeMap[(unsigned char)(quote)]&0x80) ) return; | ||||
| 35813 | if( quote=='[' ) quote = ']'; | ||||
| 35814 | for(i=1, j=0;; i++){ | ||||
| 35815 | assert( z[i] )((void) (0)); | ||||
| 35816 | if( z[i]==quote ){ | ||||
| 35817 | if( z[i+1]==quote ){ | ||||
| 35818 | z[j++] = quote; | ||||
| 35819 | i++; | ||||
| 35820 | }else{ | ||||
| 35821 | break; | ||||
| 35822 | } | ||||
| 35823 | }else{ | ||||
| 35824 | z[j++] = z[i]; | ||||
| 35825 | } | ||||
| 35826 | } | ||||
| 35827 | z[j] = 0; | ||||
| 35828 | } | ||||
| 35829 | SQLITE_PRIVATEstatic void sqlite3DequoteExpr(Expr *p){ | ||||
| 35830 | assert( !ExprHasProperty(p, EP_IntValue) )((void) (0)); | ||||
| 35831 | assert( sqlite3Isquote(p->u.zToken[0]) )((void) (0)); | ||||
| 35832 | p->flags |= p->u.zToken[0]=='"' ? EP_Quoted0x4000000|EP_DblQuoted0x000080 : EP_Quoted0x4000000; | ||||
| 35833 | sqlite3Dequote(p->u.zToken); | ||||
| 35834 | } | ||||
| 35835 | |||||
| 35836 | /* | ||||
| 35837 | ** Expression p is a QNUMBER (quoted number). Dequote the value in p->u.zToken | ||||
| 35838 | ** and set the type to INTEGER or FLOAT. "Quoted" integers or floats are those | ||||
| 35839 | ** that contain '_' characters that must be removed before further processing. | ||||
| 35840 | */ | ||||
| 35841 | SQLITE_PRIVATEstatic void sqlite3DequoteNumber(Parse *pParse, Expr *p){ | ||||
| 35842 | assert( p!=0 || pParse->db->mallocFailed )((void) (0)); | ||||
| 35843 | if( p ){ | ||||
| 35844 | const char *pIn = p->u.zToken; | ||||
| 35845 | char *pOut = p->u.zToken; | ||||
| 35846 | int bHex = (pIn[0]=='0' && (pIn[1]=='x' || pIn[1]=='X')); | ||||
| 35847 | int iValue; | ||||
| 35848 | assert( p->op==TK_QNUMBER )((void) (0)); | ||||
| 35849 | p->op = TK_INTEGER156; | ||||
| 35850 | do { | ||||
| 35851 | if( *pIn!=SQLITE_DIGIT_SEPARATOR'_' ){ | ||||
| 35852 | *pOut++ = *pIn; | ||||
| 35853 | if( *pIn=='e' || *pIn=='E' || *pIn=='.' ) p->op = TK_FLOAT154; | ||||
| 35854 | }else{ | ||||
| 35855 | if( (bHex==0 && (!sqlite3Isdigit(pIn[-1])(sqlite3CtypeMap[(unsigned char)(pIn[-1])]&0x04) || !sqlite3Isdigit(pIn[1])(sqlite3CtypeMap[(unsigned char)(pIn[1])]&0x04))) | ||||
| 35856 | || (bHex==1 && (!sqlite3Isxdigit(pIn[-1])(sqlite3CtypeMap[(unsigned char)(pIn[-1])]&0x08) || !sqlite3Isxdigit(pIn[1])(sqlite3CtypeMap[(unsigned char)(pIn[1])]&0x08))) | ||||
| 35857 | ){ | ||||
| 35858 | sqlite3ErrorMsg(pParse, "unrecognized token: \"%s\"", p->u.zToken); | ||||
| 35859 | } | ||||
| 35860 | } | ||||
| 35861 | }while( *pIn++ ); | ||||
| 35862 | if( bHex ) p->op = TK_INTEGER156; | ||||
| 35863 | |||||
| 35864 | /* tag-20240227-a: If after dequoting, the number is an integer that | ||||
| 35865 | ** fits in 32 bits, then it must be converted into EP_IntValue. Other | ||||
| 35866 | ** parts of the code expect this. See also tag-20240227-b. */ | ||||
| 35867 | if( p->op==TK_INTEGER156 && sqlite3GetInt32(p->u.zToken, &iValue) ){ | ||||
| 35868 | p->u.iValue = iValue; | ||||
| 35869 | p->flags |= EP_IntValue0x000800; | ||||
| 35870 | } | ||||
| 35871 | } | ||||
| 35872 | } | ||||
| 35873 | |||||
| 35874 | /* | ||||
| 35875 | ** If the input token p is quoted, try to adjust the token to remove | ||||
| 35876 | ** the quotes. This is not always possible: | ||||
| 35877 | ** | ||||
| 35878 | ** "abc" -> abc | ||||
| 35879 | ** "ab""cd" -> (not possible because of the interior "") | ||||
| 35880 | ** | ||||
| 35881 | ** Remove the quotes if possible. This is a optimization. The overall | ||||
| 35882 | ** system should still return the correct answer even if this routine | ||||
| 35883 | ** is always a no-op. | ||||
| 35884 | */ | ||||
| 35885 | SQLITE_PRIVATEstatic void sqlite3DequoteToken(Token *p){ | ||||
| 35886 | unsigned int i; | ||||
| 35887 | if( p->n<2 ) return; | ||||
| 35888 | if( !sqlite3Isquote(p->z[0])(sqlite3CtypeMap[(unsigned char)(p->z[0])]&0x80) ) return; | ||||
| 35889 | for(i=1; i<p->n-1; i++){ | ||||
| 35890 | if( sqlite3Isquote(p->z[i])(sqlite3CtypeMap[(unsigned char)(p->z[i])]&0x80) ) return; | ||||
| 35891 | } | ||||
| 35892 | p->n -= 2; | ||||
| 35893 | p->z++; | ||||
| 35894 | } | ||||
| 35895 | |||||
| 35896 | /* | ||||
| 35897 | ** Generate a Token object from a string | ||||
| 35898 | */ | ||||
| 35899 | SQLITE_PRIVATEstatic void sqlite3TokenInit(Token *p, char *z){ | ||||
| 35900 | p->z = z; | ||||
| 35901 | p->n = sqlite3Strlen30(z); | ||||
| 35902 | } | ||||
| 35903 | |||||
| 35904 | /* Convenient short-hand */ | ||||
| 35905 | #define UpperToLowersqlite3UpperToLower sqlite3UpperToLower | ||||
| 35906 | |||||
| 35907 | /* | ||||
| 35908 | ** Some systems have stricmp(). Others have strcasecmp(). Because | ||||
| 35909 | ** there is no consistency, we will define our own. | ||||
| 35910 | ** | ||||
| 35911 | ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and | ||||
| 35912 | ** sqlite3_strnicmp() APIs allow applications and extensions to compare | ||||
| 35913 | ** the contents of two buffers containing UTF-8 strings in a | ||||
| 35914 | ** case-independent fashion, using the same definition of "case | ||||
| 35915 | ** independence" that SQLite uses internally when comparing identifiers. | ||||
| 35916 | */ | ||||
| 35917 | SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){ | ||||
| 35918 | if( zLeft==0 ){ | ||||
| 35919 | return zRight ? -1 : 0; | ||||
| 35920 | }else if( zRight==0 ){ | ||||
| 35921 | return 1; | ||||
| 35922 | } | ||||
| 35923 | return sqlite3StrICmp(zLeft, zRight); | ||||
| 35924 | } | ||||
| 35925 | SQLITE_PRIVATEstatic int sqlite3StrICmp(const char *zLeft, const char *zRight){ | ||||
| 35926 | unsigned char *a, *b; | ||||
| 35927 | int c, x; | ||||
| 35928 | a = (unsigned char *)zLeft; | ||||
| 35929 | b = (unsigned char *)zRight; | ||||
| 35930 | for(;;){ | ||||
| 35931 | c = *a; | ||||
| 35932 | x = *b; | ||||
| 35933 | if( c==x ){ | ||||
| 35934 | if( c==0 ) break; | ||||
| 35935 | }else{ | ||||
| 35936 | c = (int)UpperToLowersqlite3UpperToLower[c] - (int)UpperToLowersqlite3UpperToLower[x]; | ||||
| 35937 | if( c ) break; | ||||
| 35938 | } | ||||
| 35939 | a++; | ||||
| 35940 | b++; | ||||
| 35941 | } | ||||
| 35942 | return c; | ||||
| 35943 | } | ||||
| 35944 | SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){ | ||||
| 35945 | register unsigned char *a, *b; | ||||
| 35946 | if( zLeft==0 ){ | ||||
| 35947 | return zRight ? -1 : 0; | ||||
| 35948 | }else if( zRight==0 ){ | ||||
| 35949 | return 1; | ||||
| 35950 | } | ||||
| 35951 | a = (unsigned char *)zLeft; | ||||
| 35952 | b = (unsigned char *)zRight; | ||||
| 35953 | while( N-- > 0 && *a!=0 && UpperToLowersqlite3UpperToLower[*a]==UpperToLowersqlite3UpperToLower[*b]){ a++; b++; } | ||||
| 35954 | return N<0 ? 0 : UpperToLowersqlite3UpperToLower[*a] - UpperToLowersqlite3UpperToLower[*b]; | ||||
| 35955 | } | ||||
| 35956 | |||||
| 35957 | /* | ||||
| 35958 | ** Compute an 8-bit hash on a string that is insensitive to case differences | ||||
| 35959 | */ | ||||
| 35960 | SQLITE_PRIVATEstatic u8 sqlite3StrIHash(const char *z){ | ||||
| 35961 | u8 h = 0; | ||||
| 35962 | if( z==0 ) return 0; | ||||
| 35963 | while( z[0] ){ | ||||
| 35964 | h += UpperToLowersqlite3UpperToLower[(unsigned char)z[0]]; | ||||
| 35965 | z++; | ||||
| 35966 | } | ||||
| 35967 | return h; | ||||
| 35968 | } | ||||
| 35969 | |||||
| 35970 | /* Double-Double multiplication. (x[0],x[1]) *= (y,yy) | ||||
| 35971 | ** | ||||
| 35972 | ** Reference: | ||||
| 35973 | ** T. J. Dekker, "A Floating-Point Technique for Extending the | ||||
| 35974 | ** Available Precision". 1971-07-26. | ||||
| 35975 | */ | ||||
| 35976 | static void dekkerMul2(volatile double *x, double y, double yy){ | ||||
| 35977 | /* | ||||
| 35978 | ** The "volatile" keywords on parameter x[] and on local variables | ||||
| 35979 | ** below are needed force intermediate results to be truncated to | ||||
| 35980 | ** binary64 rather than be carried around in an extended-precision | ||||
| 35981 | ** format. The truncation is necessary for the Dekker algorithm to | ||||
| 35982 | ** work. Intel x86 floating point might omit the truncation without | ||||
| 35983 | ** the use of volatile. | ||||
| 35984 | */ | ||||
| 35985 | volatile double tx, ty, p, q, c, cc; | ||||
| 35986 | double hx, hy; | ||||
| 35987 | u64 m; | ||||
| 35988 | memcpy(&m, (void*)&x[0], 8); | ||||
| 35989 | m &= 0xfffffffffc000000LL; | ||||
| 35990 | memcpy(&hx, &m, 8); | ||||
| 35991 | tx = x[0] - hx; | ||||
| 35992 | memcpy(&m, &y, 8); | ||||
| 35993 | m &= 0xfffffffffc000000LL; | ||||
| 35994 | memcpy(&hy, &m, 8); | ||||
| 35995 | ty = y - hy; | ||||
| 35996 | p = hx*hy; | ||||
| 35997 | q = hx*ty + tx*hy; | ||||
| 35998 | c = p+q; | ||||
| 35999 | cc = p - c + q + tx*ty; | ||||
| 36000 | cc = x[0]*yy + x[1]*y + cc; | ||||
| 36001 | x[0] = c + cc; | ||||
| 36002 | x[1] = c - x[0]; | ||||
| 36003 | x[1] += cc; | ||||
| 36004 | } | ||||
| 36005 | |||||
| 36006 | /* | ||||
| 36007 | ** The string z[] is an text representation of a real number. | ||||
| 36008 | ** Convert this string to a double and write it into *pResult. | ||||
| 36009 | ** | ||||
| 36010 | ** The string z[] is length bytes in length (bytes, not characters) and | ||||
| 36011 | ** uses the encoding enc. The string is not necessarily zero-terminated. | ||||
| 36012 | ** | ||||
| 36013 | ** Return TRUE if the result is a valid real number (or integer) and FALSE | ||||
| 36014 | ** if the string is empty or contains extraneous text. More specifically | ||||
| 36015 | ** return | ||||
| 36016 | ** 1 => The input string is a pure integer | ||||
| 36017 | ** 2 or more => The input has a decimal point or eNNN clause | ||||
| 36018 | ** 0 or less => The input string is not a valid number | ||||
| 36019 | ** -1 => Not a valid number, but has a valid prefix which | ||||
| 36020 | ** includes a decimal point and/or an eNNN clause | ||||
| 36021 | ** | ||||
| 36022 | ** Valid numbers are in one of these formats: | ||||
| 36023 | ** | ||||
| 36024 | ** [+-]digits[E[+-]digits] | ||||
| 36025 | ** [+-]digits.[digits][E[+-]digits] | ||||
| 36026 | ** [+-].digits[E[+-]digits] | ||||
| 36027 | ** | ||||
| 36028 | ** Leading and trailing whitespace is ignored for the purpose of determining | ||||
| 36029 | ** validity. | ||||
| 36030 | ** | ||||
| 36031 | ** If some prefix of the input string is a valid number, this routine | ||||
| 36032 | ** returns FALSE but it still converts the prefix and writes the result | ||||
| 36033 | ** into *pResult. | ||||
| 36034 | */ | ||||
| 36035 | #if defined(_MSC_VER) | ||||
| 36036 | #pragma warning(disable : 4756) | ||||
| 36037 | #endif | ||||
| 36038 | SQLITE_PRIVATEstatic int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ | ||||
| 36039 | #ifndef SQLITE_OMIT_FLOATING_POINT | ||||
| 36040 | int incr; | ||||
| 36041 | const char *zEnd; | ||||
| 36042 | /* sign * significand * (10 ^ (esign * exponent)) */ | ||||
| 36043 | int sign = 1; /* sign of significand */ | ||||
| 36044 | u64 s = 0; /* significand */ | ||||
| 36045 | int d = 0; /* adjust exponent for shifting decimal point */ | ||||
| 36046 | int esign = 1; /* sign of exponent */ | ||||
| 36047 | int e = 0; /* exponent */ | ||||
| 36048 | int eValid = 1; /* True exponent is either not used or is well-formed */ | ||||
| 36049 | int nDigit = 0; /* Number of digits processed */ | ||||
| 36050 | int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */ | ||||
| 36051 | u64 s2; /* round-tripped significand */ | ||||
| 36052 | double rr[2]; | ||||
| 36053 | |||||
| 36054 | assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE )((void) (0)); | ||||
| 36055 | *pResult = 0.0; /* Default return value, in case of an error */ | ||||
| 36056 | if( length==0 ) return 0; | ||||
| 36057 | |||||
| 36058 | if( enc==SQLITE_UTF81 ){ | ||||
| 36059 | incr = 1; | ||||
| 36060 | zEnd = z + length; | ||||
| 36061 | }else{ | ||||
| 36062 | int i; | ||||
| 36063 | incr = 2; | ||||
| 36064 | length &= ~1; | ||||
| 36065 | assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 )((void) (0)); | ||||
| 36066 | testcase( enc==SQLITE_UTF16LE ); | ||||
| 36067 | testcase( enc==SQLITE_UTF16BE ); | ||||
| 36068 | for(i=3-enc; i<length && z[i]==0; i+=2){} | ||||
| 36069 | if( i<length ) eType = -100; | ||||
| 36070 | zEnd = &z[i^1]; | ||||
| 36071 | z += (enc&1); | ||||
| 36072 | } | ||||
| 36073 | |||||
| 36074 | /* skip leading spaces */ | ||||
| 36075 | while( z<zEnd && sqlite3Isspace(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x01) ) z+=incr; | ||||
| 36076 | if( z>=zEnd ) return 0; | ||||
| 36077 | |||||
| 36078 | /* get sign of significand */ | ||||
| 36079 | if( *z=='-' ){ | ||||
| 36080 | sign = -1; | ||||
| 36081 | z+=incr; | ||||
| 36082 | }else if( *z=='+' ){ | ||||
| 36083 | z+=incr; | ||||
| 36084 | } | ||||
| 36085 | |||||
| 36086 | /* copy max significant digits to significand */ | ||||
| 36087 | while( z<zEnd && sqlite3Isdigit(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x04) ){ | ||||
| 36088 | s = s*10 + (*z - '0'); | ||||
| 36089 | z+=incr; nDigit++; | ||||
| 36090 | if( s>=((LARGEST_UINT64(0xffffffff|(((u64)0xffffffff)<<32))-9)/10) ){ | ||||
| 36091 | /* skip non-significant significand digits | ||||
| 36092 | ** (increase exponent by d to shift decimal left) */ | ||||
| 36093 | while( z<zEnd && sqlite3Isdigit(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x04) ){ z+=incr; d++; } | ||||
| 36094 | } | ||||
| 36095 | } | ||||
| 36096 | if( z>=zEnd ) goto do_atof_calc; | ||||
| 36097 | |||||
| 36098 | /* if decimal point is present */ | ||||
| 36099 | if( *z=='.' ){ | ||||
| 36100 | z+=incr; | ||||
| 36101 | eType++; | ||||
| 36102 | /* copy digits from after decimal to significand | ||||
| 36103 | ** (decrease exponent by d to shift decimal right) */ | ||||
| 36104 | while( z<zEnd && sqlite3Isdigit(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x04) ){ | ||||
| 36105 | if( s<((LARGEST_UINT64(0xffffffff|(((u64)0xffffffff)<<32))-9)/10) ){ | ||||
| 36106 | s = s*10 + (*z - '0'); | ||||
| 36107 | d--; | ||||
| 36108 | nDigit++; | ||||
| 36109 | } | ||||
| 36110 | z+=incr; | ||||
| 36111 | } | ||||
| 36112 | } | ||||
| 36113 | if( z>=zEnd ) goto do_atof_calc; | ||||
| 36114 | |||||
| 36115 | /* if exponent is present */ | ||||
| 36116 | if( *z=='e' || *z=='E' ){ | ||||
| 36117 | z+=incr; | ||||
| 36118 | eValid = 0; | ||||
| 36119 | eType++; | ||||
| 36120 | |||||
| 36121 | /* This branch is needed to avoid a (harmless) buffer overread. The | ||||
| 36122 | ** special comment alerts the mutation tester that the correct answer | ||||
| 36123 | ** is obtained even if the branch is omitted */ | ||||
| 36124 | if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/ | ||||
| 36125 | |||||
| 36126 | /* get sign of exponent */ | ||||
| 36127 | if( *z=='-' ){ | ||||
| 36128 | esign = -1; | ||||
| 36129 | z+=incr; | ||||
| 36130 | }else if( *z=='+' ){ | ||||
| 36131 | z+=incr; | ||||
| 36132 | } | ||||
| 36133 | /* copy digits to exponent */ | ||||
| 36134 | while( z<zEnd && sqlite3Isdigit(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x04) ){ | ||||
| 36135 | e = e<10000 ? (e*10 + (*z - '0')) : 10000; | ||||
| 36136 | z+=incr; | ||||
| 36137 | eValid = 1; | ||||
| 36138 | } | ||||
| 36139 | } | ||||
| 36140 | |||||
| 36141 | /* skip trailing spaces */ | ||||
| 36142 | while( z<zEnd && sqlite3Isspace(*z)(sqlite3CtypeMap[(unsigned char)(*z)]&0x01) ) z+=incr; | ||||
| 36143 | |||||
| 36144 | do_atof_calc: | ||||
| 36145 | /* Zero is a special case */ | ||||
| 36146 | if( s==0 ){ | ||||
| 36147 | *pResult = sign<0 ? -0.0 : +0.0; | ||||
| 36148 | goto atof_return; | ||||
| 36149 | } | ||||
| 36150 | |||||
| 36151 | /* adjust exponent by d, and update sign */ | ||||
| 36152 | e = (e*esign) + d; | ||||
| 36153 | |||||
| 36154 | /* Try to adjust the exponent to make it smaller */ | ||||
| 36155 | while( e>0 && s<((LARGEST_UINT64(0xffffffff|(((u64)0xffffffff)<<32))-0x7ff)/10) ){ | ||||
| 36156 | s *= 10; | ||||
| 36157 | e--; | ||||
| 36158 | } | ||||
| 36159 | while( e<0 && (s%10)==0 ){ | ||||
| 36160 | s /= 10; | ||||
| 36161 | e++; | ||||
| 36162 | } | ||||
| 36163 | |||||
| 36164 | rr[0] = (double)s; | ||||
| 36165 | assert( sizeof(s2)==sizeof(rr[0]) )((void) (0)); | ||||
| 36166 | #ifdef SQLITE_DEBUG | ||||
| 36167 | rr[1] = 18446744073709549568.0; | ||||
| 36168 | memcpy(&s2, &rr[1], sizeof(s2)); | ||||
| 36169 | assert( s2==0x43efffffffffffffLL )((void) (0)); | ||||
| 36170 | #endif | ||||
| 36171 | /* Largest double that can be safely converted to u64 | ||||
| 36172 | ** vvvvvvvvvvvvvvvvvvvvvv */ | ||||
| 36173 | if( rr[0]<=18446744073709549568.0 ){ | ||||
| 36174 | s2 = (u64)rr[0]; | ||||
| 36175 | rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s); | ||||
| 36176 | }else{ | ||||
| 36177 | rr[1] = 0.0; | ||||
| 36178 | } | ||||
| 36179 | assert( rr[1]<=1.0e-10*rr[0] )((void) (0)); /* Equal only when rr[0]==0.0 */ | ||||
| 36180 | |||||
| 36181 | if( e>0 ){ | ||||
| 36182 | while( e>=100 ){ | ||||
| 36183 | e -= 100; | ||||
| 36184 | dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83); | ||||
| 36185 | } | ||||
| 36186 | while( e>=10 ){ | ||||
| 36187 | e -= 10; | ||||
| 36188 | dekkerMul2(rr, 1.0e+10, 0.0); | ||||
| 36189 | } | ||||
| 36190 | while( e>=1 ){ | ||||
| 36191 | e -= 1; | ||||
| 36192 | dekkerMul2(rr, 1.0e+01, 0.0); | ||||
| 36193 | } | ||||
| 36194 | }else{ | ||||
| 36195 | while( e<=-100 ){ | ||||
| 36196 | e += 100; | ||||
| 36197 | dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117); | ||||
| 36198 | } | ||||
| 36199 | while( e<=-10 ){ | ||||
| 36200 | e += 10; | ||||
| 36201 | dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27); | ||||
| 36202 | } | ||||
| 36203 | while( e<=-1 ){ | ||||
| 36204 | e += 1; | ||||
| 36205 | dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18); | ||||
| 36206 | } | ||||
| 36207 | } | ||||
| 36208 | *pResult = rr[0]+rr[1]; | ||||
| 36209 | if( sqlite3IsNaN(*pResult) ) *pResult = 1e300*1e300; | ||||
| 36210 | if( sign<0 ) *pResult = -*pResult; | ||||
| 36211 | assert( !sqlite3IsNaN(*pResult) )((void) (0)); | ||||
| 36212 | |||||
| 36213 | atof_return: | ||||
| 36214 | /* return true if number and no extra non-whitespace characters after */ | ||||
| 36215 | if( z==zEnd && nDigit>0 && eValid && eType>0 ){ | ||||
| 36216 | return eType; | ||||
| 36217 | }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){ | ||||
| 36218 | return -1; | ||||
| 36219 | }else{ | ||||
| 36220 | return 0; | ||||
| 36221 | } | ||||
| 36222 | #else | ||||
| 36223 | return !sqlite3Atoi64(z, pResult, length, enc); | ||||
| 36224 | #endif /* SQLITE_OMIT_FLOATING_POINT */ | ||||
| 36225 | } | ||||
| 36226 | #if defined(_MSC_VER) | ||||
| 36227 | #pragma warning(default : 4756) | ||||
| 36228 | #endif | ||||
| 36229 | |||||
| 36230 | /* | ||||
| 36231 | ** Render an signed 64-bit integer as text. Store the result in zOut[] and | ||||
| 36232 | ** return the length of the string that was stored, in bytes. The value | ||||
| 36233 | ** returned does not include the zero terminator at the end of the output | ||||
| 36234 | ** string. | ||||
| 36235 | ** | ||||
| 36236 | ** The caller must ensure that zOut[] is at least 21 bytes in size. | ||||
| 36237 | */ | ||||
| 36238 | SQLITE_PRIVATEstatic int sqlite3Int64ToText(i64 v, char *zOut){ | ||||
| 36239 | int i; | ||||
| 36240 | u64 x; | ||||
| 36241 | char zTemp[22]; | ||||
| 36242 | if( v<0 ){ | ||||
| 36243 | x = (v==SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32)))) ? ((u64)1)<<63 : (u64)-v; | ||||
| 36244 | }else{ | ||||
| 36245 | x = v; | ||||
| 36246 | } | ||||
| 36247 | i = sizeof(zTemp)-2; | ||||
| 36248 | zTemp[sizeof(zTemp)-1] = 0; | ||||
| 36249 | while( 1 /*exit-by-break*/ ){ | ||||
| 36250 | zTemp[i] = (x%10) + '0'; | ||||
| 36251 | x = x/10; | ||||
| 36252 | if( x==0 ) break; | ||||
| 36253 | i--; | ||||
| 36254 | }; | ||||
| 36255 | if( v<0 ) zTemp[--i] = '-'; | ||||
| 36256 | memcpy(zOut, &zTemp[i], sizeof(zTemp)-i); | ||||
| 36257 | return sizeof(zTemp)-1-i; | ||||
| 36258 | } | ||||
| 36259 | |||||
| 36260 | /* | ||||
| 36261 | ** Compare the 19-character string zNum against the text representation | ||||
| 36262 | ** value 2^63: 9223372036854775808. Return negative, zero, or positive | ||||
| 36263 | ** if zNum is less than, equal to, or greater than the string. | ||||
| 36264 | ** Note that zNum must contain exactly 19 characters. | ||||
| 36265 | ** | ||||
| 36266 | ** Unlike memcmp() this routine is guaranteed to return the difference | ||||
| 36267 | ** in the values of the last digit if the only difference is in the | ||||
| 36268 | ** last digit. So, for example, | ||||
| 36269 | ** | ||||
| 36270 | ** compare2pow63("9223372036854775800", 1) | ||||
| 36271 | ** | ||||
| 36272 | ** will return -8. | ||||
| 36273 | */ | ||||
| 36274 | static int compare2pow63(const char *zNum, int incr){ | ||||
| 36275 | int c = 0; | ||||
| 36276 | int i; | ||||
| 36277 | /* 012345678901234567 */ | ||||
| 36278 | const char *pow63 = "922337203685477580"; | ||||
| 36279 | for(i=0; c==0 && i<18; i++){ | ||||
| 36280 | c = (zNum[i*incr]-pow63[i])*10; | ||||
| 36281 | } | ||||
| 36282 | if( c==0 ){ | ||||
| 36283 | c = zNum[18*incr] - '8'; | ||||
| 36284 | testcase( c==(-1) ); | ||||
| 36285 | testcase( c==0 ); | ||||
| 36286 | testcase( c==(+1) ); | ||||
| 36287 | } | ||||
| 36288 | return c; | ||||
| 36289 | } | ||||
| 36290 | |||||
| 36291 | /* | ||||
| 36292 | ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This | ||||
| 36293 | ** routine does *not* accept hexadecimal notation. | ||||
| 36294 | ** | ||||
| 36295 | ** Returns: | ||||
| 36296 | ** | ||||
| 36297 | ** -1 Not even a prefix of the input text looks like an integer | ||||
| 36298 | ** 0 Successful transformation. Fits in a 64-bit signed integer. | ||||
| 36299 | ** 1 Excess non-space text after the integer value | ||||
| 36300 | ** 2 Integer too large for a 64-bit signed integer or is malformed | ||||
| 36301 | ** 3 Special case of 9223372036854775808 | ||||
| 36302 | ** | ||||
| 36303 | ** length is the number of bytes in the string (bytes, not characters). | ||||
| 36304 | ** The string is not necessarily zero-terminated. The encoding is | ||||
| 36305 | ** given by enc. | ||||
| 36306 | */ | ||||
| 36307 | SQLITE_PRIVATEstatic int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){ | ||||
| 36308 | int incr; | ||||
| 36309 | u64 u = 0; | ||||
| 36310 | int neg = 0; /* assume positive */ | ||||
| 36311 | int i; | ||||
| 36312 | int c = 0; | ||||
| 36313 | int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ | ||||
| 36314 | int rc; /* Baseline return code */ | ||||
| 36315 | const char *zStart; | ||||
| 36316 | const char *zEnd = zNum + length; | ||||
| 36317 | assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE )((void) (0)); | ||||
| 36318 | if( enc==SQLITE_UTF81 ){ | ||||
| 36319 | incr = 1; | ||||
| 36320 | }else{ | ||||
| 36321 | incr = 2; | ||||
| 36322 | length &= ~1; | ||||
| 36323 | assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 )((void) (0)); | ||||
| 36324 | for(i=3-enc; i<length && zNum[i]==0; i+=2){} | ||||
| 36325 | nonNum = i<length; | ||||
| 36326 | zEnd = &zNum[i^1]; | ||||
| 36327 | zNum += (enc&1); | ||||
| 36328 | } | ||||
| 36329 | while( zNum<zEnd && sqlite3Isspace(*zNum)(sqlite3CtypeMap[(unsigned char)(*zNum)]&0x01) ) zNum+=incr; | ||||
| 36330 | if( zNum<zEnd ){ | ||||
| 36331 | if( *zNum=='-' ){ | ||||
| 36332 | neg = 1; | ||||
| 36333 | zNum+=incr; | ||||
| 36334 | }else if( *zNum=='+' ){ | ||||
| 36335 | zNum+=incr; | ||||
| 36336 | } | ||||
| 36337 | } | ||||
| 36338 | zStart = zNum; | ||||
| 36339 | while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */ | ||||
| 36340 | for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){ | ||||
| 36341 | u = u*10 + c - '0'; | ||||
| 36342 | } | ||||
| 36343 | testcase( i==18*incr ); | ||||
| 36344 | testcase( i==19*incr ); | ||||
| 36345 | testcase( i==20*incr ); | ||||
| 36346 | if( u>LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)) ){ | ||||
| 36347 | /* This test and assignment is needed only to suppress UB warnings | ||||
| 36348 | ** from clang and -fsanitize=undefined. This test and assignment make | ||||
| 36349 | ** the code a little larger and slower, and no harm comes from omitting | ||||
| 36350 | ** them, but we must appease the undefined-behavior pharisees. */ | ||||
| 36351 | *pNum = neg ? SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32))) : LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)); | ||||
| 36352 | }else if( neg ){ | ||||
| 36353 | *pNum = -(i64)u; | ||||
| 36354 | }else{ | ||||
| 36355 | *pNum = (i64)u; | ||||
| 36356 | } | ||||
| 36357 | rc = 0; | ||||
| 36358 | if( i==0 && zStart==zNum ){ /* No digits */ | ||||
| 36359 | rc = -1; | ||||
| 36360 | }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */ | ||||
| 36361 | rc = 1; | ||||
| 36362 | }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */ | ||||
| 36363 | int jj = i; | ||||
| 36364 | do{ | ||||
| 36365 | if( !sqlite3Isspace(zNum[jj])(sqlite3CtypeMap[(unsigned char)(zNum[jj])]&0x01) ){ | ||||
| 36366 | rc = 1; /* Extra non-space text after the integer */ | ||||
| 36367 | break; | ||||
| 36368 | } | ||||
| 36369 | jj += incr; | ||||
| 36370 | }while( &zNum[jj]<zEnd ); | ||||
| 36371 | } | ||||
| 36372 | if( i<19*incr ){ | ||||
| 36373 | /* Less than 19 digits, so we know that it fits in 64 bits */ | ||||
| 36374 | assert( u<=LARGEST_INT64 )((void) (0)); | ||||
| 36375 | return rc; | ||||
| 36376 | }else{ | ||||
| 36377 | /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ | ||||
| 36378 | c = i>19*incr ? 1 : compare2pow63(zNum, incr); | ||||
| 36379 | if( c<0 ){ | ||||
| 36380 | /* zNum is less than 9223372036854775808 so it fits */ | ||||
| 36381 | assert( u<=LARGEST_INT64 )((void) (0)); | ||||
| 36382 | return rc; | ||||
| 36383 | }else{ | ||||
| 36384 | *pNum = neg ? SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32))) : LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)); | ||||
| 36385 | if( c>0 ){ | ||||
| 36386 | /* zNum is greater than 9223372036854775808 so it overflows */ | ||||
| 36387 | return 2; | ||||
| 36388 | }else{ | ||||
| 36389 | /* zNum is exactly 9223372036854775808. Fits if negative. The | ||||
| 36390 | ** special case 2 overflow if positive */ | ||||
| 36391 | assert( u-1==LARGEST_INT64 )((void) (0)); | ||||
| 36392 | return neg ? rc : 3; | ||||
| 36393 | } | ||||
| 36394 | } | ||||
| 36395 | } | ||||
| 36396 | } | ||||
| 36397 | |||||
| 36398 | /* | ||||
| 36399 | ** Transform a UTF-8 integer literal, in either decimal or hexadecimal, | ||||
| 36400 | ** into a 64-bit signed integer. This routine accepts hexadecimal literals, | ||||
| 36401 | ** whereas sqlite3Atoi64() does not. | ||||
| 36402 | ** | ||||
| 36403 | ** Returns: | ||||
| 36404 | ** | ||||
| 36405 | ** 0 Successful transformation. Fits in a 64-bit signed integer. | ||||
| 36406 | ** 1 Excess text after the integer value | ||||
| 36407 | ** 2 Integer too large for a 64-bit signed integer or is malformed | ||||
| 36408 | ** 3 Special case of 9223372036854775808 | ||||
| 36409 | */ | ||||
| 36410 | SQLITE_PRIVATEstatic int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ | ||||
| 36411 | #ifndef SQLITE_OMIT_HEX_INTEGER | ||||
| 36412 | if( z[0]=='0' | ||||
| 36413 | && (z[1]=='x' || z[1]=='X') | ||||
| 36414 | ){ | ||||
| 36415 | u64 u = 0; | ||||
| 36416 | int i, k; | ||||
| 36417 | for(i=2; z[i]=='0'; i++){} | ||||
| 36418 | for(k=i; sqlite3Isxdigit(z[k])(sqlite3CtypeMap[(unsigned char)(z[k])]&0x08); k++){ | ||||
| 36419 | u = u*16 + sqlite3HexToInt(z[k]); | ||||
| 36420 | } | ||||
| 36421 | memcpy(pOut, &u, 8); | ||||
| 36422 | if( k-i>16 ) return 2; | ||||
| 36423 | if( z[k]!=0 ) return 1; | ||||
| 36424 | return 0; | ||||
| 36425 | }else | ||||
| 36426 | #endif /* SQLITE_OMIT_HEX_INTEGER */ | ||||
| 36427 | { | ||||
| 36428 | int n = (int)(0x3fffffff&strspn(z,"+- \n\t0123456789")); | ||||
| 36429 | if( z[n] ) n++; | ||||
| 36430 | return sqlite3Atoi64(z, pOut, n, SQLITE_UTF81); | ||||
| 36431 | } | ||||
| 36432 | } | ||||
| 36433 | |||||
| 36434 | /* | ||||
| 36435 | ** If zNum represents an integer that will fit in 32-bits, then set | ||||
| 36436 | ** *pValue to that integer and return true. Otherwise return false. | ||||
| 36437 | ** | ||||
| 36438 | ** This routine accepts both decimal and hexadecimal notation for integers. | ||||
| 36439 | ** | ||||
| 36440 | ** Any non-numeric characters that following zNum are ignored. | ||||
| 36441 | ** This is different from sqlite3Atoi64() which requires the | ||||
| 36442 | ** input number to be zero-terminated. | ||||
| 36443 | */ | ||||
| 36444 | SQLITE_PRIVATEstatic int sqlite3GetInt32(const char *zNum, int *pValue){ | ||||
| 36445 | sqlite_int64 v = 0; | ||||
| 36446 | int i, c; | ||||
| 36447 | int neg = 0; | ||||
| 36448 | if( zNum[0]=='-' ){ | ||||
| 36449 | neg = 1; | ||||
| 36450 | zNum++; | ||||
| 36451 | }else if( zNum[0]=='+' ){ | ||||
| 36452 | zNum++; | ||||
| 36453 | } | ||||
| 36454 | #ifndef SQLITE_OMIT_HEX_INTEGER | ||||
| 36455 | else if( zNum[0]=='0' | ||||
| 36456 | && (zNum[1]=='x' || zNum[1]=='X') | ||||
| 36457 | && sqlite3Isxdigit(zNum[2])(sqlite3CtypeMap[(unsigned char)(zNum[2])]&0x08) | ||||
| 36458 | ){ | ||||
| 36459 | u32 u = 0; | ||||
| 36460 | zNum += 2; | ||||
| 36461 | while( zNum[0]=='0' ) zNum++; | ||||
| 36462 | for(i=0; i<8 && sqlite3Isxdigit(zNum[i])(sqlite3CtypeMap[(unsigned char)(zNum[i])]&0x08); i++){ | ||||
| 36463 | u = u*16 + sqlite3HexToInt(zNum[i]); | ||||
| 36464 | } | ||||
| 36465 | if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])(sqlite3CtypeMap[(unsigned char)(zNum[i])]&0x08)==0 ){ | ||||
| 36466 | memcpy(pValue, &u, 4); | ||||
| 36467 | return 1; | ||||
| 36468 | }else{ | ||||
| 36469 | return 0; | ||||
| 36470 | } | ||||
| 36471 | } | ||||
| 36472 | #endif | ||||
| 36473 | if( !sqlite3Isdigit(zNum[0])(sqlite3CtypeMap[(unsigned char)(zNum[0])]&0x04) ) return 0; | ||||
| 36474 | while( zNum[0]=='0' ) zNum++; | ||||
| 36475 | for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ | ||||
| 36476 | v = v*10 + c; | ||||
| 36477 | } | ||||
| 36478 | |||||
| 36479 | /* The longest decimal representation of a 32 bit integer is 10 digits: | ||||
| 36480 | ** | ||||
| 36481 | ** 1234567890 | ||||
| 36482 | ** 2^31 -> 2147483648 | ||||
| 36483 | */ | ||||
| 36484 | testcase( i==10 ); | ||||
| 36485 | if( i>10 ){ | ||||
| 36486 | return 0; | ||||
| 36487 | } | ||||
| 36488 | testcase( v-neg==2147483647 ); | ||||
| 36489 | if( v-neg>2147483647 ){ | ||||
| 36490 | return 0; | ||||
| 36491 | } | ||||
| 36492 | if( neg ){ | ||||
| 36493 | v = -v; | ||||
| 36494 | } | ||||
| 36495 | *pValue = (int)v; | ||||
| 36496 | return 1; | ||||
| 36497 | } | ||||
| 36498 | |||||
| 36499 | /* | ||||
| 36500 | ** Return a 32-bit integer value extracted from a string. If the | ||||
| 36501 | ** string is not an integer, just return 0. | ||||
| 36502 | */ | ||||
| 36503 | SQLITE_PRIVATEstatic int sqlite3Atoi(const char *z){ | ||||
| 36504 | int x = 0; | ||||
| 36505 | sqlite3GetInt32(z, &x); | ||||
| 36506 | return x; | ||||
| 36507 | } | ||||
| 36508 | |||||
| 36509 | /* | ||||
| 36510 | ** Decode a floating-point value into an approximate decimal | ||||
| 36511 | ** representation. | ||||
| 36512 | ** | ||||
| 36513 | ** If iRound<=0 then round to -iRound significant digits to the | ||||
| 36514 | ** the left of the decimal point, or to a maximum of mxRound total | ||||
| 36515 | ** significant digits. | ||||
| 36516 | ** | ||||
| 36517 | ** If iRound>0 round to min(iRound,mxRound) significant digits total. | ||||
| 36518 | ** | ||||
| 36519 | ** mxRound must be positive. | ||||
| 36520 | ** | ||||
| 36521 | ** The significant digits of the decimal representation are | ||||
| 36522 | ** stored in p->z[] which is a often (but not always) a pointer | ||||
| 36523 | ** into the middle of p->zBuf[]. There are p->n significant digits. | ||||
| 36524 | ** The p->z[] array is *not* zero-terminated. | ||||
| 36525 | */ | ||||
| 36526 | SQLITE_PRIVATEstatic void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){ | ||||
| 36527 | int i; | ||||
| 36528 | u64 v; | ||||
| 36529 | int e, exp = 0; | ||||
| 36530 | double rr[2]; | ||||
| 36531 | |||||
| 36532 | p->isSpecial = 0; | ||||
| 36533 | p->z = p->zBuf; | ||||
| 36534 | assert( mxRound>0 )((void) (0)); | ||||
| 36535 | |||||
| 36536 | /* Convert negative numbers to positive. Deal with Infinity, 0.0, and | ||||
| 36537 | ** NaN. */ | ||||
| 36538 | if( r<0.0 ){ | ||||
| 36539 | p->sign = '-'; | ||||
| 36540 | r = -r; | ||||
| 36541 | }else if( r==0.0 ){ | ||||
| 36542 | p->sign = '+'; | ||||
| 36543 | p->n = 1; | ||||
| 36544 | p->iDP = 1; | ||||
| 36545 | p->z = "0"; | ||||
| 36546 | return; | ||||
| 36547 | }else{ | ||||
| 36548 | p->sign = '+'; | ||||
| 36549 | } | ||||
| 36550 | memcpy(&v,&r,8); | ||||
| 36551 | e = v>>52; | ||||
| 36552 | if( (e&0x7ff)==0x7ff ){ | ||||
| 36553 | p->isSpecial = 1 + (v!=0x7ff0000000000000LL); | ||||
| 36554 | p->n = 0; | ||||
| 36555 | p->iDP = 0; | ||||
| 36556 | return; | ||||
| 36557 | } | ||||
| 36558 | |||||
| 36559 | /* Multiply r by powers of ten until it lands somewhere in between | ||||
| 36560 | ** 1.0e+19 and 1.0e+17. | ||||
| 36561 | ** | ||||
| 36562 | ** Use Dekker-style double-double computation to increase the | ||||
| 36563 | ** precision. | ||||
| 36564 | ** | ||||
| 36565 | ** The error terms on constants like 1.0e+100 computed using the | ||||
| 36566 | ** decimal extension, for example as follows: | ||||
| 36567 | ** | ||||
| 36568 | ** SELECT decimal_exp(decimal_sub('1.0e+100',decimal(1.0e+100))); | ||||
| 36569 | */ | ||||
| 36570 | rr[0] = r; | ||||
| 36571 | rr[1] = 0.0; | ||||
| 36572 | if( rr[0]>9.223372036854774784e+18 ){ | ||||
| 36573 | while( rr[0]>9.223372036854774784e+118 ){ | ||||
| 36574 | exp += 100; | ||||
| 36575 | dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117); | ||||
| 36576 | } | ||||
| 36577 | while( rr[0]>9.223372036854774784e+28 ){ | ||||
| 36578 | exp += 10; | ||||
| 36579 | dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27); | ||||
| 36580 | } | ||||
| 36581 | while( rr[0]>9.223372036854774784e+18 ){ | ||||
| 36582 | exp += 1; | ||||
| 36583 | dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18); | ||||
| 36584 | } | ||||
| 36585 | }else{ | ||||
| 36586 | while( rr[0]<9.223372036854774784e-83 ){ | ||||
| 36587 | exp -= 100; | ||||
| 36588 | dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83); | ||||
| 36589 | } | ||||
| 36590 | while( rr[0]<9.223372036854774784e+07 ){ | ||||
| 36591 | exp -= 10; | ||||
| 36592 | dekkerMul2(rr, 1.0e+10, 0.0); | ||||
| 36593 | } | ||||
| 36594 | while( rr[0]<9.22337203685477478e+17 ){ | ||||
| 36595 | exp -= 1; | ||||
| 36596 | dekkerMul2(rr, 1.0e+01, 0.0); | ||||
| 36597 | } | ||||
| 36598 | } | ||||
| 36599 | v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1]; | ||||
| 36600 | |||||
| 36601 | /* Extract significant digits. */ | ||||
| 36602 | i = sizeof(p->zBuf)-1; | ||||
| 36603 | assert( v>0 )((void) (0)); | ||||
| 36604 | while( v ){ p->zBuf[i--] = (v%10) + '0'; v /= 10; } | ||||
| 36605 | assert( i>=0 && i<sizeof(p->zBuf)-1 )((void) (0)); | ||||
| 36606 | p->n = sizeof(p->zBuf) - 1 - i; | ||||
| 36607 | assert( p->n>0 )((void) (0)); | ||||
| 36608 | assert( p->n<sizeof(p->zBuf) )((void) (0)); | ||||
| 36609 | p->iDP = p->n + exp; | ||||
| 36610 | if( iRound<=0 ){ | ||||
| 36611 | iRound = p->iDP - iRound; | ||||
| 36612 | if( iRound==0 && p->zBuf[i+1]>='5' ){ | ||||
| 36613 | iRound = 1; | ||||
| 36614 | p->zBuf[i--] = '0'; | ||||
| 36615 | p->n++; | ||||
| 36616 | p->iDP++; | ||||
| 36617 | } | ||||
| 36618 | } | ||||
| 36619 | if( iRound>0 && (iRound<p->n || p->n>mxRound) ){ | ||||
| 36620 | char *z = &p->zBuf[i+1]; | ||||
| 36621 | if( iRound>mxRound ) iRound = mxRound; | ||||
| 36622 | p->n = iRound; | ||||
| 36623 | if( z[iRound]>='5' ){ | ||||
| 36624 | int j = iRound-1; | ||||
| 36625 | while( 1 /*exit-by-break*/ ){ | ||||
| 36626 | z[j]++; | ||||
| 36627 | if( z[j]<='9' ) break; | ||||
| 36628 | z[j] = '0'; | ||||
| 36629 | if( j==0 ){ | ||||
| 36630 | p->z[i--] = '1'; | ||||
| 36631 | p->n++; | ||||
| 36632 | p->iDP++; | ||||
| 36633 | break; | ||||
| 36634 | }else{ | ||||
| 36635 | j--; | ||||
| 36636 | } | ||||
| 36637 | } | ||||
| 36638 | } | ||||
| 36639 | } | ||||
| 36640 | p->z = &p->zBuf[i+1]; | ||||
| 36641 | assert( i+p->n < sizeof(p->zBuf) )((void) (0)); | ||||
| 36642 | assert( p->n>0 )((void) (0)); | ||||
| 36643 | while( p->z[p->n-1]=='0' ){ | ||||
| 36644 | p->n--; | ||||
| 36645 | assert( p->n>0 )((void) (0)); | ||||
| 36646 | } | ||||
| 36647 | } | ||||
| 36648 | |||||
| 36649 | /* | ||||
| 36650 | ** Try to convert z into an unsigned 32-bit integer. Return true on | ||||
| 36651 | ** success and false if there is an error. | ||||
| 36652 | ** | ||||
| 36653 | ** Only decimal notation is accepted. | ||||
| 36654 | */ | ||||
| 36655 | SQLITE_PRIVATEstatic int sqlite3GetUInt32(const char *z, u32 *pI){ | ||||
| 36656 | u64 v = 0; | ||||
| 36657 | int i; | ||||
| 36658 | for(i=0; sqlite3Isdigit(z[i])(sqlite3CtypeMap[(unsigned char)(z[i])]&0x04); i++){ | ||||
| 36659 | v = v*10 + z[i] - '0'; | ||||
| 36660 | if( v>4294967296LL ){ *pI = 0; return 0; } | ||||
| 36661 | } | ||||
| 36662 | if( i==0 || z[i]!=0 ){ *pI = 0; return 0; } | ||||
| 36663 | *pI = (u32)v; | ||||
| 36664 | return 1; | ||||
| 36665 | } | ||||
| 36666 | |||||
| 36667 | /* | ||||
| 36668 | ** The variable-length integer encoding is as follows: | ||||
| 36669 | ** | ||||
| 36670 | ** KEY: | ||||
| 36671 | ** A = 0xxxxxxx 7 bits of data and one flag bit | ||||
| 36672 | ** B = 1xxxxxxx 7 bits of data and one flag bit | ||||
| 36673 | ** C = xxxxxxxx 8 bits of data | ||||
| 36674 | ** | ||||
| 36675 | ** 7 bits - A | ||||
| 36676 | ** 14 bits - BA | ||||
| 36677 | ** 21 bits - BBA | ||||
| 36678 | ** 28 bits - BBBA | ||||
| 36679 | ** 35 bits - BBBBA | ||||
| 36680 | ** 42 bits - BBBBBA | ||||
| 36681 | ** 49 bits - BBBBBBA | ||||
| 36682 | ** 56 bits - BBBBBBBA | ||||
| 36683 | ** 64 bits - BBBBBBBBC | ||||
| 36684 | */ | ||||
| 36685 | |||||
| 36686 | /* | ||||
| 36687 | ** Write a 64-bit variable-length integer to memory starting at p[0]. | ||||
| 36688 | ** The length of data write will be between 1 and 9 bytes. The number | ||||
| 36689 | ** of bytes written is returned. | ||||
| 36690 | ** | ||||
| 36691 | ** A variable-length integer consists of the lower 7 bits of each byte | ||||
| 36692 | ** for all bytes that have the 8th bit set and one byte with the 8th | ||||
| 36693 | ** bit clear. Except, if we get to the 9th byte, it stores the full | ||||
| 36694 | ** 8 bits and is the last byte. | ||||
| 36695 | */ | ||||
| 36696 | static int SQLITE_NOINLINE__attribute__((noinline)) putVarint64(unsigned char *p, u64 v){ | ||||
| 36697 | int i, j, n; | ||||
| 36698 | u8 buf[10]; | ||||
| 36699 | if( v & (((u64)0xff000000)<<32) ){ | ||||
| 36700 | p[8] = (u8)v; | ||||
| 36701 | v >>= 8; | ||||
| 36702 | for(i=7; i>=0; i--){ | ||||
| 36703 | p[i] = (u8)((v & 0x7f) | 0x80); | ||||
| 36704 | v >>= 7; | ||||
| 36705 | } | ||||
| 36706 | return 9; | ||||
| 36707 | } | ||||
| 36708 | n = 0; | ||||
| 36709 | do{ | ||||
| 36710 | buf[n++] = (u8)((v & 0x7f) | 0x80); | ||||
| 36711 | v >>= 7; | ||||
| 36712 | }while( v!=0 ); | ||||
| 36713 | buf[0] &= 0x7f; | ||||
| 36714 | assert( n<=9 )((void) (0)); | ||||
| 36715 | for(i=0, j=n-1; j>=0; j--, i++){ | ||||
| 36716 | p[i] = buf[j]; | ||||
| 36717 | } | ||||
| 36718 | return n; | ||||
| 36719 | } | ||||
| 36720 | SQLITE_PRIVATEstatic int sqlite3PutVarint(unsigned char *p, u64 v){ | ||||
| 36721 | if( v<=0x7f ){ | ||||
| 36722 | p[0] = v&0x7f; | ||||
| 36723 | return 1; | ||||
| 36724 | } | ||||
| 36725 | if( v<=0x3fff ){ | ||||
| 36726 | p[0] = ((v>>7)&0x7f)|0x80; | ||||
| 36727 | p[1] = v&0x7f; | ||||
| 36728 | return 2; | ||||
| 36729 | } | ||||
| 36730 | return putVarint64(p,v); | ||||
| 36731 | } | ||||
| 36732 | |||||
| 36733 | /* | ||||
| 36734 | ** Bitmasks used by sqlite3GetVarint(). These precomputed constants | ||||
| 36735 | ** are defined here rather than simply putting the constant expressions | ||||
| 36736 | ** inline in order to work around bugs in the RVT compiler. | ||||
| 36737 | ** | ||||
| 36738 | ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f | ||||
| 36739 | ** | ||||
| 36740 | ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 | ||||
| 36741 | */ | ||||
| 36742 | #define SLOT_2_00x001fc07f 0x001fc07f | ||||
| 36743 | #define SLOT_4_2_00xf01fc07f 0xf01fc07f | ||||
| 36744 | |||||
| 36745 | |||||
| 36746 | /* | ||||
| 36747 | ** Read a 64-bit variable-length integer from memory starting at p[0]. | ||||
| 36748 | ** Return the number of bytes read. The value is stored in *v. | ||||
| 36749 | */ | ||||
| 36750 | SQLITE_PRIVATEstatic u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ | ||||
| 36751 | u32 a,b,s; | ||||
| 36752 | |||||
| 36753 | if( ((signed char*)p)[0]>=0 ){ | ||||
| 36754 | *v = *p; | ||||
| 36755 | return 1; | ||||
| 36756 | } | ||||
| 36757 | if( ((signed char*)p)[1]>=0 ){ | ||||
| 36758 | *v = ((u32)(p[0]&0x7f)<<7) | p[1]; | ||||
| 36759 | return 2; | ||||
| 36760 | } | ||||
| 36761 | |||||
| 36762 | /* Verify that constants are precomputed correctly */ | ||||
| 36763 | assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) )((void) (0)); | ||||
| 36764 | assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) )((void) (0)); | ||||
| 36765 | |||||
| 36766 | a = ((u32)p[0])<<14; | ||||
| 36767 | b = p[1]; | ||||
| 36768 | p += 2; | ||||
| 36769 | a |= *p; | ||||
| 36770 | /* a: p0<<14 | p2 (unmasked) */ | ||||
| 36771 | if (!(a&0x80)) | ||||
| 36772 | { | ||||
| 36773 | a &= SLOT_2_00x001fc07f; | ||||
| 36774 | b &= 0x7f; | ||||
| 36775 | b = b<<7; | ||||
| 36776 | a |= b; | ||||
| 36777 | *v = a; | ||||
| 36778 | return 3; | ||||
| 36779 | } | ||||
| 36780 | |||||
| 36781 | /* CSE1 from below */ | ||||
| 36782 | a &= SLOT_2_00x001fc07f; | ||||
| 36783 | p++; | ||||
| 36784 | b = b<<14; | ||||
| 36785 | b |= *p; | ||||
| 36786 | /* b: p1<<14 | p3 (unmasked) */ | ||||
| 36787 | if (!(b&0x80)) | ||||
| 36788 | { | ||||
| 36789 | b &= SLOT_2_00x001fc07f; | ||||
| 36790 | /* moved CSE1 up */ | ||||
| 36791 | /* a &= (0x7f<<14)|(0x7f); */ | ||||
| 36792 | a = a<<7; | ||||
| 36793 | a |= b; | ||||
| 36794 | *v = a; | ||||
| 36795 | return 4; | ||||
| 36796 | } | ||||
| 36797 | |||||
| 36798 | /* a: p0<<14 | p2 (masked) */ | ||||
| 36799 | /* b: p1<<14 | p3 (unmasked) */ | ||||
| 36800 | /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ | ||||
| 36801 | /* moved CSE1 up */ | ||||
| 36802 | /* a &= (0x7f<<14)|(0x7f); */ | ||||
| 36803 | b &= SLOT_2_00x001fc07f; | ||||
| 36804 | s = a; | ||||
| 36805 | /* s: p0<<14 | p2 (masked) */ | ||||
| 36806 | |||||
| 36807 | p++; | ||||
| 36808 | a = a<<14; | ||||
| 36809 | a |= *p; | ||||
| 36810 | /* a: p0<<28 | p2<<14 | p4 (unmasked) */ | ||||
| 36811 | if (!(a&0x80)) | ||||
| 36812 | { | ||||
| 36813 | /* we can skip these cause they were (effectively) done above | ||||
| 36814 | ** while calculating s */ | ||||
| 36815 | /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ | ||||
| 36816 | /* b &= (0x7f<<14)|(0x7f); */ | ||||
| 36817 | b = b<<7; | ||||
| 36818 | a |= b; | ||||
| 36819 | s = s>>18; | ||||
| 36820 | *v = ((u64)s)<<32 | a; | ||||
| 36821 | return 5; | ||||
| 36822 | } | ||||
| 36823 | |||||
| 36824 | /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ | ||||
| 36825 | s = s<<7; | ||||
| 36826 | s |= b; | ||||
| 36827 | /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ | ||||
| 36828 | |||||
| 36829 | p++; | ||||
| 36830 | b = b<<14; | ||||
| 36831 | b |= *p; | ||||
| 36832 | /* b: p1<<28 | p3<<14 | p5 (unmasked) */ | ||||
| 36833 | if (!(b&0x80)) | ||||
| 36834 | { | ||||
| 36835 | /* we can skip this cause it was (effectively) done above in calc'ing s */ | ||||
| 36836 | /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ | ||||
| 36837 | a &= SLOT_2_00x001fc07f; | ||||
| 36838 | a = a<<7; | ||||
| 36839 | a |= b; | ||||
| 36840 | s = s>>18; | ||||
| 36841 | *v = ((u64)s)<<32 | a; | ||||
| 36842 | return 6; | ||||
| 36843 | } | ||||
| 36844 | |||||
| 36845 | p++; | ||||
| 36846 | a = a<<14; | ||||
| 36847 | a |= *p; | ||||
| 36848 | /* a: p2<<28 | p4<<14 | p6 (unmasked) */ | ||||
| 36849 | if (!(a&0x80)) | ||||
| 36850 | { | ||||
| 36851 | a &= SLOT_4_2_00xf01fc07f; | ||||
| 36852 | b &= SLOT_2_00x001fc07f; | ||||
| 36853 | b = b<<7; | ||||
| 36854 | a |= b; | ||||
| 36855 | s = s>>11; | ||||
| 36856 | *v = ((u64)s)<<32 | a; | ||||
| 36857 | return 7; | ||||
| 36858 | } | ||||
| 36859 | |||||
| 36860 | /* CSE2 from below */ | ||||
| 36861 | a &= SLOT_2_00x001fc07f; | ||||
| 36862 | p++; | ||||
| 36863 | b = b<<14; | ||||
| 36864 | b |= *p; | ||||
| 36865 | /* b: p3<<28 | p5<<14 | p7 (unmasked) */ | ||||
| 36866 | if (!(b&0x80)) | ||||
| 36867 | { | ||||
| 36868 | b &= SLOT_4_2_00xf01fc07f; | ||||
| 36869 | /* moved CSE2 up */ | ||||
| 36870 | /* a &= (0x7f<<14)|(0x7f); */ | ||||
| 36871 | a = a<<7; | ||||
| 36872 | a |= b; | ||||
| 36873 | s = s>>4; | ||||
| 36874 | *v = ((u64)s)<<32 | a; | ||||
| 36875 | return 8; | ||||
| 36876 | } | ||||
| 36877 | |||||
| 36878 | p++; | ||||
| 36879 | a = a<<15; | ||||
| 36880 | a |= *p; | ||||
| 36881 | /* a: p4<<29 | p6<<15 | p8 (unmasked) */ | ||||
| 36882 | |||||
| 36883 | /* moved CSE2 up */ | ||||
| 36884 | /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ | ||||
| 36885 | b &= SLOT_2_00x001fc07f; | ||||
| 36886 | b = b<<8; | ||||
| 36887 | a |= b; | ||||
| 36888 | |||||
| 36889 | s = s<<4; | ||||
| 36890 | b = p[-4]; | ||||
| 36891 | b &= 0x7f; | ||||
| 36892 | b = b>>3; | ||||
| 36893 | s |= b; | ||||
| 36894 | |||||
| 36895 | *v = ((u64)s)<<32 | a; | ||||
| 36896 | |||||
| 36897 | return 9; | ||||
| 36898 | } | ||||
| 36899 | |||||
| 36900 | /* | ||||
| 36901 | ** Read a 32-bit variable-length integer from memory starting at p[0]. | ||||
| 36902 | ** Return the number of bytes read. The value is stored in *v. | ||||
| 36903 | ** | ||||
| 36904 | ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned | ||||
| 36905 | ** integer, then set *v to 0xffffffff. | ||||
| 36906 | ** | ||||
| 36907 | ** A MACRO version, getVarint32, is provided which inlines the | ||||
| 36908 | ** single-byte case. All code should use the MACRO version as | ||||
| 36909 | ** this function assumes the single-byte case has already been handled. | ||||
| 36910 | */ | ||||
| 36911 | SQLITE_PRIVATEstatic u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ | ||||
| 36912 | u64 v64; | ||||
| 36913 | u8 n; | ||||
| 36914 | |||||
| 36915 | /* Assume that the single-byte case has already been handled by | ||||
| 36916 | ** the getVarint32() macro */ | ||||
| 36917 | assert( (p[0] & 0x80)!=0 )((void) (0)); | ||||
| 36918 | |||||
| 36919 | if( (p[1] & 0x80)==0 ){ | ||||
| 36920 | /* This is the two-byte case */ | ||||
| 36921 | *v = ((p[0]&0x7f)<<7) | p[1]; | ||||
| 36922 | return 2; | ||||
| 36923 | } | ||||
| 36924 | if( (p[2] & 0x80)==0 ){ | ||||
| 36925 | /* This is the three-byte case */ | ||||
| 36926 | *v = ((p[0]&0x7f)<<14) | ((p[1]&0x7f)<<7) | p[2]; | ||||
| 36927 | return 3; | ||||
| 36928 | } | ||||
| 36929 | /* four or more bytes */ | ||||
| 36930 | n = sqlite3GetVarint(p, &v64); | ||||
| 36931 | assert( n>3 && n<=9 )((void) (0)); | ||||
| 36932 | if( (v64 & SQLITE_MAX_U32((((u64)1)<<32)-1))!=v64 ){ | ||||
| 36933 | *v = 0xffffffff; | ||||
| 36934 | }else{ | ||||
| 36935 | *v = (u32)v64; | ||||
| 36936 | } | ||||
| 36937 | return n; | ||||
| 36938 | } | ||||
| 36939 | |||||
| 36940 | /* | ||||
| 36941 | ** Return the number of bytes that will be needed to store the given | ||||
| 36942 | ** 64-bit integer. | ||||
| 36943 | */ | ||||
| 36944 | SQLITE_PRIVATEstatic int sqlite3VarintLen(u64 v){ | ||||
| 36945 | int i; | ||||
| 36946 | for(i=1; (v >>= 7)!=0; i++){ assert( i<10 )((void) (0)); } | ||||
| 36947 | return i; | ||||
| 36948 | } | ||||
| 36949 | |||||
| 36950 | |||||
| 36951 | /* | ||||
| 36952 | ** Read or write a four-byte big-endian integer value. | ||||
| 36953 | */ | ||||
| 36954 | SQLITE_PRIVATEstatic u32 sqlite3Get4byte(const u8 *p){ | ||||
| 36955 | #if SQLITE_BYTEORDER1234==4321 | ||||
| 36956 | u32 x; | ||||
| 36957 | memcpy(&x,p,4); | ||||
| 36958 | return x; | ||||
| 36959 | #elif SQLITE_BYTEORDER1234==1234 && GCC_VERSION(4*1000000+2*1000+1)>=4003000 | ||||
| 36960 | u32 x; | ||||
| 36961 | memcpy(&x,p,4); | ||||
| 36962 | return __builtin_bswap32(x); | ||||
| 36963 | #elif SQLITE_BYTEORDER1234==1234 && MSVC_VERSION0>=1300 | ||||
| 36964 | u32 x; | ||||
| 36965 | memcpy(&x,p,4); | ||||
| 36966 | return _byteswap_ulong(x); | ||||
| 36967 | #else | ||||
| 36968 | testcase( p[0]&0x80 ); | ||||
| 36969 | return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; | ||||
| 36970 | #endif | ||||
| 36971 | } | ||||
| 36972 | SQLITE_PRIVATEstatic void sqlite3Put4byte(unsigned char *p, u32 v){ | ||||
| 36973 | #if SQLITE_BYTEORDER1234==4321 | ||||
| 36974 | memcpy(p,&v,4); | ||||
| 36975 | #elif SQLITE_BYTEORDER1234==1234 && GCC_VERSION(4*1000000+2*1000+1)>=4003000 | ||||
| 36976 | u32 x = __builtin_bswap32(v); | ||||
| 36977 | memcpy(p,&x,4); | ||||
| 36978 | #elif SQLITE_BYTEORDER1234==1234 && MSVC_VERSION0>=1300 | ||||
| 36979 | u32 x = _byteswap_ulong(v); | ||||
| 36980 | memcpy(p,&x,4); | ||||
| 36981 | #else | ||||
| 36982 | p[0] = (u8)(v>>24); | ||||
| 36983 | p[1] = (u8)(v>>16); | ||||
| 36984 | p[2] = (u8)(v>>8); | ||||
| 36985 | p[3] = (u8)v; | ||||
| 36986 | #endif | ||||
| 36987 | } | ||||
| 36988 | |||||
| 36989 | |||||
| 36990 | |||||
| 36991 | /* | ||||
| 36992 | ** Translate a single byte of Hex into an integer. | ||||
| 36993 | ** This routine only works if h really is a valid hexadecimal | ||||
| 36994 | ** character: 0..9a..fA..F | ||||
| 36995 | */ | ||||
| 36996 | SQLITE_PRIVATEstatic u8 sqlite3HexToInt(int h){ | ||||
| 36997 | assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') )((void) (0)); | ||||
| 36998 | #ifdef SQLITE_ASCII1 | ||||
| 36999 | h += 9*(1&(h>>6)); | ||||
| 37000 | #endif | ||||
| 37001 | #ifdef SQLITE_EBCDIC | ||||
| 37002 | h += 9*(1&~(h>>4)); | ||||
| 37003 | #endif | ||||
| 37004 | return (u8)(h & 0xf); | ||||
| 37005 | } | ||||
| 37006 | |||||
| 37007 | #if !defined(SQLITE_OMIT_BLOB_LITERAL) | ||||
| 37008 | /* | ||||
| 37009 | ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary | ||||
| 37010 | ** value. Return a pointer to its binary value. Space to hold the | ||||
| 37011 | ** binary value has been obtained from malloc and must be freed by | ||||
| 37012 | ** the calling routine. | ||||
| 37013 | */ | ||||
| 37014 | SQLITE_PRIVATEstatic void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ | ||||
| 37015 | char *zBlob; | ||||
| 37016 | int i; | ||||
| 37017 | |||||
| 37018 | zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1); | ||||
| 37019 | n--; | ||||
| 37020 | if( zBlob ){ | ||||
| 37021 | for(i=0; i<n; i+=2){ | ||||
| 37022 | zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]); | ||||
| 37023 | } | ||||
| 37024 | zBlob[i/2] = 0; | ||||
| 37025 | } | ||||
| 37026 | return zBlob; | ||||
| 37027 | } | ||||
| 37028 | #endif /* !SQLITE_OMIT_BLOB_LITERAL */ | ||||
| 37029 | |||||
| 37030 | /* | ||||
| 37031 | ** Log an error that is an API call on a connection pointer that should | ||||
| 37032 | ** not have been used. The "type" of connection pointer is given as the | ||||
| 37033 | ** argument. The zType is a word like "NULL" or "closed" or "invalid". | ||||
| 37034 | */ | ||||
| 37035 | static void logBadConnection(const char *zType){ | ||||
| 37036 | sqlite3_log(SQLITE_MISUSE21, | ||||
| 37037 | "API call with %s database connection pointer", | ||||
| 37038 | zType | ||||
| 37039 | ); | ||||
| 37040 | } | ||||
| 37041 | |||||
| 37042 | /* | ||||
| 37043 | ** Check to make sure we have a valid db pointer. This test is not | ||||
| 37044 | ** foolproof but it does provide some measure of protection against | ||||
| 37045 | ** misuse of the interface such as passing in db pointers that are | ||||
| 37046 | ** NULL or which have been previously closed. If this routine returns | ||||
| 37047 | ** 1 it means that the db pointer is valid and 0 if it should not be | ||||
| 37048 | ** dereferenced for any reason. The calling function should invoke | ||||
| 37049 | ** SQLITE_MISUSE immediately. | ||||
| 37050 | ** | ||||
| 37051 | ** sqlite3SafetyCheckOk() requires that the db pointer be valid for | ||||
| 37052 | ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to | ||||
| 37053 | ** open properly and is not fit for general use but which can be | ||||
| 37054 | ** used as an argument to sqlite3_errmsg() or sqlite3_close(). | ||||
| 37055 | */ | ||||
| 37056 | SQLITE_PRIVATEstatic int sqlite3SafetyCheckOk(sqlite3 *db){ | ||||
| 37057 | u8 eOpenState; | ||||
| 37058 | if( db==0 ){ | ||||
| 37059 | logBadConnection("NULL"); | ||||
| 37060 | return 0; | ||||
| 37061 | } | ||||
| 37062 | eOpenState = db->eOpenState; | ||||
| 37063 | if( eOpenState!=SQLITE_STATE_OPEN0x76 ){ | ||||
| 37064 | if( sqlite3SafetyCheckSickOrOk(db) ){ | ||||
| 37065 | testcase( sqlite3GlobalConfig.xLog!=0 ); | ||||
| 37066 | logBadConnection("unopened"); | ||||
| 37067 | } | ||||
| 37068 | return 0; | ||||
| 37069 | }else{ | ||||
| 37070 | return 1; | ||||
| 37071 | } | ||||
| 37072 | } | ||||
| 37073 | SQLITE_PRIVATEstatic int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ | ||||
| 37074 | u8 eOpenState; | ||||
| 37075 | eOpenState = db->eOpenState; | ||||
| 37076 | if( eOpenState!=SQLITE_STATE_SICK0xba && | ||||
| 37077 | eOpenState!=SQLITE_STATE_OPEN0x76 && | ||||
| 37078 | eOpenState!=SQLITE_STATE_BUSY0x6d ){ | ||||
| 37079 | testcase( sqlite3GlobalConfig.xLog!=0 ); | ||||
| 37080 | logBadConnection("invalid"); | ||||
| 37081 | return 0; | ||||
| 37082 | }else{ | ||||
| 37083 | return 1; | ||||
| 37084 | } | ||||
| 37085 | } | ||||
| 37086 | |||||
| 37087 | /* | ||||
| 37088 | ** Attempt to add, subtract, or multiply the 64-bit signed value iB against | ||||
| 37089 | ** the other 64-bit signed integer at *pA and store the result in *pA. | ||||
| 37090 | ** Return 0 on success. Or if the operation would have resulted in an | ||||
| 37091 | ** overflow, leave *pA unchanged and return 1. | ||||
| 37092 | */ | ||||
| 37093 | SQLITE_PRIVATEstatic int sqlite3AddInt64(i64 *pA, i64 iB){ | ||||
| 37094 | #if GCC_VERSION(4*1000000+2*1000+1)>=5004000 && !defined(__INTEL_COMPILER) | ||||
| 37095 | return __builtin_add_overflow(*pA, iB, pA); | ||||
| 37096 | #else | ||||
| 37097 | i64 iA = *pA; | ||||
| 37098 | testcase( iA==0 ); testcase( iA==1 ); | ||||
| 37099 | testcase( iB==-1 ); testcase( iB==0 ); | ||||
| 37100 | if( iB>=0 ){ | ||||
| 37101 | testcase( iA>0 && LARGEST_INT64 - iA == iB ); | ||||
| 37102 | testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 ); | ||||
| 37103 | if( iA>0 && LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)) - iA < iB ) return 1; | ||||
| 37104 | }else{ | ||||
| 37105 | testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 ); | ||||
| 37106 | testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 ); | ||||
| 37107 | if( iA<0 && -(iA + LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32))) > iB + 1 ) return 1; | ||||
| 37108 | } | ||||
| 37109 | *pA += iB; | ||||
| 37110 | return 0; | ||||
| 37111 | #endif | ||||
| 37112 | } | ||||
| 37113 | SQLITE_PRIVATEstatic int sqlite3SubInt64(i64 *pA, i64 iB){ | ||||
| 37114 | #if GCC_VERSION(4*1000000+2*1000+1)>=5004000 && !defined(__INTEL_COMPILER) | ||||
| 37115 | return __builtin_sub_overflow(*pA, iB, pA); | ||||
| 37116 | #else | ||||
| 37117 | testcase( iB==SMALLEST_INT64+1 ); | ||||
| 37118 | if( iB==SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32))) ){ | ||||
| 37119 | testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); | ||||
| 37120 | if( (*pA)>=0 ) return 1; | ||||
| 37121 | *pA -= iB; | ||||
| 37122 | return 0; | ||||
| 37123 | }else{ | ||||
| 37124 | return sqlite3AddInt64(pA, -iB); | ||||
| 37125 | } | ||||
| 37126 | #endif | ||||
| 37127 | } | ||||
| 37128 | SQLITE_PRIVATEstatic int sqlite3MulInt64(i64 *pA, i64 iB){ | ||||
| 37129 | #if GCC_VERSION(4*1000000+2*1000+1)>=5004000 && !defined(__INTEL_COMPILER) | ||||
| 37130 | return __builtin_mul_overflow(*pA, iB, pA); | ||||
| 37131 | #else | ||||
| 37132 | i64 iA = *pA; | ||||
| 37133 | if( iB>0 ){ | ||||
| 37134 | if( iA>LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32))/iB ) return 1; | ||||
| 37135 | if( iA<SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32)))/iB ) return 1; | ||||
| 37136 | }else if( iB<0 ){ | ||||
| 37137 | if( iA>0 ){ | ||||
| 37138 | if( iB<SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32)))/iA ) return 1; | ||||
| 37139 | }else if( iA<0 ){ | ||||
| 37140 | if( iB==SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32))) ) return 1; | ||||
| 37141 | if( iA==SMALLEST_INT64(((i64)-1) - (0xffffffff|(((i64)0x7fffffff)<<32))) ) return 1; | ||||
| 37142 | if( -iA>LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32))/-iB ) return 1; | ||||
| 37143 | } | ||||
| 37144 | } | ||||
| 37145 | *pA = iA*iB; | ||||
| 37146 | return 0; | ||||
| 37147 | #endif | ||||
| 37148 | } | ||||
| 37149 | |||||
| 37150 | /* | ||||
| 37151 | ** Compute the absolute value of a 32-bit signed integer, if possible. Or | ||||
| 37152 | ** if the integer has a value of -2147483648, return +2147483647 | ||||
| 37153 | */ | ||||
| 37154 | SQLITE_PRIVATEstatic int sqlite3AbsInt32(int x){ | ||||
| 37155 | if( x>=0 ) return x; | ||||
| 37156 | if( x==(int)0x80000000 ) return 0x7fffffff; | ||||
| 37157 | return -x; | ||||
| 37158 | } | ||||
| 37159 | |||||
| 37160 | #ifdef SQLITE_ENABLE_8_3_NAMES | ||||
| 37161 | /* | ||||
| 37162 | ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database | ||||
| 37163 | ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and | ||||
| 37164 | ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than | ||||
| 37165 | ** three characters, then shorten the suffix on z[] to be the last three | ||||
| 37166 | ** characters of the original suffix. | ||||
| 37167 | ** | ||||
| 37168 | ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always | ||||
| 37169 | ** do the suffix shortening regardless of URI parameter. | ||||
| 37170 | ** | ||||
| 37171 | ** Examples: | ||||
| 37172 | ** | ||||
| 37173 | ** test.db-journal => test.nal | ||||
| 37174 | ** test.db-wal => test.wal | ||||
| 37175 | ** test.db-shm => test.shm | ||||
| 37176 | ** test.db-mj7f3319fa => test.9fa | ||||
| 37177 | */ | ||||
| 37178 | SQLITE_PRIVATEstatic void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ | ||||
| 37179 | #if SQLITE_ENABLE_8_3_NAMES<2 | ||||
| 37180 | if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) | ||||
| 37181 | #endif | ||||
| 37182 | { | ||||
| 37183 | int i, sz; | ||||
| 37184 | sz = sqlite3Strlen30(z); | ||||
| 37185 | for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} | ||||
| 37186 | if( z[i]=='.' && ALWAYS(sz>i+4)(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); | ||||
| 37187 | } | ||||
| 37188 | } | ||||
| 37189 | #endif | ||||
| 37190 | |||||
| 37191 | /* | ||||
| 37192 | ** Find (an approximate) sum of two LogEst values. This computation is | ||||
| 37193 | ** not a simple "+" operator because LogEst is stored as a logarithmic | ||||
| 37194 | ** value. | ||||
| 37195 | ** | ||||
| 37196 | */ | ||||
| 37197 | SQLITE_PRIVATEstatic LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ | ||||
| 37198 | static const unsigned char x[] = { | ||||
| 37199 | 10, 10, /* 0,1 */ | ||||
| 37200 | 9, 9, /* 2,3 */ | ||||
| 37201 | 8, 8, /* 4,5 */ | ||||
| 37202 | 7, 7, 7, /* 6,7,8 */ | ||||
| 37203 | 6, 6, 6, /* 9,10,11 */ | ||||
| 37204 | 5, 5, 5, /* 12-14 */ | ||||
| 37205 | 4, 4, 4, 4, /* 15-18 */ | ||||
| 37206 | 3, 3, 3, 3, 3, 3, /* 19-24 */ | ||||
| 37207 | 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ | ||||
| 37208 | }; | ||||
| 37209 | if( a>=b ){ | ||||
| 37210 | if( a>b+49 ) return a; | ||||
| 37211 | if( a>b+31 ) return a+1; | ||||
| 37212 | return a+x[a-b]; | ||||
| 37213 | }else{ | ||||
| 37214 | if( b>a+49 ) return b; | ||||
| 37215 | if( b>a+31 ) return b+1; | ||||
| 37216 | return b+x[b-a]; | ||||
| 37217 | } | ||||
| 37218 | } | ||||
| 37219 | |||||
| 37220 | /* | ||||
| 37221 | ** Convert an integer into a LogEst. In other words, compute an | ||||
| 37222 | ** approximation for 10*log2(x). | ||||
| 37223 | */ | ||||
| 37224 | SQLITE_PRIVATEstatic LogEst sqlite3LogEst(u64 x){ | ||||
| 37225 | static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; | ||||
| 37226 | LogEst y = 40; | ||||
| 37227 | if( x<8 ){ | ||||
| 37228 | if( x<2 ) return 0; | ||||
| 37229 | while( x<8 ){ y -= 10; x <<= 1; } | ||||
| 37230 | }else{ | ||||
| 37231 | #if GCC_VERSION(4*1000000+2*1000+1)>=5004000 | ||||
| 37232 | int i = 60 - __builtin_clzll(x); | ||||
| 37233 | y += i*10; | ||||
| 37234 | x >>= i; | ||||
| 37235 | #else | ||||
| 37236 | while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/ | ||||
| 37237 | while( x>15 ){ y += 10; x >>= 1; } | ||||
| 37238 | #endif | ||||
| 37239 | } | ||||
| 37240 | return a[x&7] + y - 10; | ||||
| 37241 | } | ||||
| 37242 | |||||
| 37243 | /* | ||||
| 37244 | ** Convert a double into a LogEst | ||||
| 37245 | ** In other words, compute an approximation for 10*log2(x). | ||||
| 37246 | */ | ||||
| 37247 | SQLITE_PRIVATEstatic LogEst sqlite3LogEstFromDouble(double x){ | ||||
| 37248 | u64 a; | ||||
| 37249 | LogEst e; | ||||
| 37250 | assert( sizeof(x)==8 && sizeof(a)==8 )((void) (0)); | ||||
| 37251 | if( x<=1 ) return 0; | ||||
| 37252 | if( x<=2000000000 ) return sqlite3LogEst((u64)x); | ||||
| 37253 | memcpy(&a, &x, 8); | ||||
| 37254 | e = (a>>52) - 1022; | ||||
| 37255 | return e*10; | ||||
| 37256 | } | ||||
| 37257 | |||||
| 37258 | /* | ||||
| 37259 | ** Convert a LogEst into an integer. | ||||
| 37260 | */ | ||||
| 37261 | SQLITE_PRIVATEstatic u64 sqlite3LogEstToInt(LogEst x){ | ||||
| 37262 | u64 n; | ||||
| 37263 | n = x%10; | ||||
| 37264 | x /= 10; | ||||
| 37265 | if( n>=5 ) n -= 2; | ||||
| 37266 | else if( n>=1 ) n -= 1; | ||||
| 37267 | if( x>60 ) return (u64)LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)); | ||||
| 37268 | return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x); | ||||
| 37269 | } | ||||
| 37270 | |||||
| 37271 | /* | ||||
| 37272 | ** Add a new name/number pair to a VList. This might require that the | ||||
| 37273 | ** VList object be reallocated, so return the new VList. If an OOM | ||||
| 37274 | ** error occurs, the original VList returned and the | ||||
| 37275 | ** db->mallocFailed flag is set. | ||||
| 37276 | ** | ||||
| 37277 | ** A VList is really just an array of integers. To destroy a VList, | ||||
| 37278 | ** simply pass it to sqlite3DbFree(). | ||||
| 37279 | ** | ||||
| 37280 | ** The first integer is the number of integers allocated for the whole | ||||
| 37281 | ** VList. The second integer is the number of integers actually used. | ||||
| 37282 | ** Each name/number pair is encoded by subsequent groups of 3 or more | ||||
| 37283 | ** integers. | ||||
| 37284 | ** | ||||
| 37285 | ** Each name/number pair starts with two integers which are the numeric | ||||
| 37286 | ** value for the pair and the size of the name/number pair, respectively. | ||||
| 37287 | ** The text name overlays one or more following integers. The text name | ||||
| 37288 | ** is always zero-terminated. | ||||
| 37289 | ** | ||||
| 37290 | ** Conceptually: | ||||
| 37291 | ** | ||||
| 37292 | ** struct VList { | ||||
| 37293 | ** int nAlloc; // Number of allocated slots | ||||
| 37294 | ** int nUsed; // Number of used slots | ||||
| 37295 | ** struct VListEntry { | ||||
| 37296 | ** int iValue; // Value for this entry | ||||
| 37297 | ** int nSlot; // Slots used by this entry | ||||
| 37298 | ** // ... variable name goes here | ||||
| 37299 | ** } a[0]; | ||||
| 37300 | ** } | ||||
| 37301 | ** | ||||
| 37302 | ** During code generation, pointers to the variable names within the | ||||
| 37303 | ** VList are taken. When that happens, nAlloc is set to zero as an | ||||
| 37304 | ** indication that the VList may never again be enlarged, since the | ||||
| 37305 | ** accompanying realloc() would invalidate the pointers. | ||||
| 37306 | */ | ||||
| 37307 | SQLITE_PRIVATEstatic VList *sqlite3VListAdd( | ||||
| 37308 | sqlite3 *db, /* The database connection used for malloc() */ | ||||
| 37309 | VList *pIn, /* The input VList. Might be NULL */ | ||||
| 37310 | const char *zName, /* Name of symbol to add */ | ||||
| 37311 | int nName, /* Bytes of text in zName */ | ||||
| 37312 | int iVal /* Value to associate with zName */ | ||||
| 37313 | ){ | ||||
| 37314 | int nInt; /* number of sizeof(int) objects needed for zName */ | ||||
| 37315 | char *z; /* Pointer to where zName will be stored */ | ||||
| 37316 | int i; /* Index in pIn[] where zName is stored */ | ||||
| 37317 | |||||
| 37318 | nInt = nName/4 + 3; | ||||
| 37319 | assert( pIn==0 || pIn[0]>=3 )((void) (0)); /* Verify ok to add new elements */ | ||||
| 37320 | if( pIn==0 || pIn[1]+nInt > pIn[0] ){ | ||||
| 37321 | /* Enlarge the allocation */ | ||||
| 37322 | sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt; | ||||
| 37323 | VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int)); | ||||
| 37324 | if( pOut==0 ) return pIn; | ||||
| 37325 | if( pIn==0 ) pOut[1] = 2; | ||||
| 37326 | pIn = pOut; | ||||
| 37327 | pIn[0] = nAlloc; | ||||
| 37328 | } | ||||
| 37329 | i = pIn[1]; | ||||
| 37330 | pIn[i] = iVal; | ||||
| 37331 | pIn[i+1] = nInt; | ||||
| 37332 | z = (char*)&pIn[i+2]; | ||||
| 37333 | pIn[1] = i+nInt; | ||||
| 37334 | assert( pIn[1]<=pIn[0] )((void) (0)); | ||||
| 37335 | memcpy(z, zName, nName); | ||||
| 37336 | z[nName] = 0; | ||||
| 37337 | return pIn; | ||||
| 37338 | } | ||||
| 37339 | |||||
| 37340 | /* | ||||
| 37341 | ** Return a pointer to the name of a variable in the given VList that | ||||
| 37342 | ** has the value iVal. Or return a NULL if there is no such variable in | ||||
| 37343 | ** the list | ||||
| 37344 | */ | ||||
| 37345 | SQLITE_PRIVATEstatic const char *sqlite3VListNumToName(VList *pIn, int iVal){ | ||||
| 37346 | int i, mx; | ||||
| 37347 | if( pIn==0 ) return 0; | ||||
| 37348 | mx = pIn[1]; | ||||
| 37349 | i = 2; | ||||
| 37350 | do{ | ||||
| 37351 | if( pIn[i]==iVal ) return (char*)&pIn[i+2]; | ||||
| 37352 | i += pIn[i+1]; | ||||
| 37353 | }while( i<mx ); | ||||
| 37354 | return 0; | ||||
| 37355 | } | ||||
| 37356 | |||||
| 37357 | /* | ||||
| 37358 | ** Return the number of the variable named zName, if it is in VList. | ||||
| 37359 | ** or return 0 if there is no such variable. | ||||
| 37360 | */ | ||||
| 37361 | SQLITE_PRIVATEstatic int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){ | ||||
| 37362 | int i, mx; | ||||
| 37363 | if( pIn==0 ) return 0; | ||||
| 37364 | mx = pIn[1]; | ||||
| 37365 | i = 2; | ||||
| 37366 | do{ | ||||
| 37367 | const char *z = (const char*)&pIn[i+2]; | ||||
| 37368 | if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i]; | ||||
| 37369 | i += pIn[i+1]; | ||||
| 37370 | }while( i<mx ); | ||||
| 37371 | return 0; | ||||
| 37372 | } | ||||
| 37373 | |||||
| 37374 | /************** End of util.c ************************************************/ | ||||
| 37375 | /************** Begin file hash.c ********************************************/ | ||||
| 37376 | /* | ||||
| 37377 | ** 2001 September 22 | ||||
| 37378 | ** | ||||
| 37379 | ** The author disclaims copyright to this source code. In place of | ||||
| 37380 | ** a legal notice, here is a blessing: | ||||
| 37381 | ** | ||||
| 37382 | ** May you do good and not evil. | ||||
| 37383 | ** May you find forgiveness for yourself and forgive others. | ||||
| 37384 | ** May you share freely, never taking more than you give. | ||||
| 37385 | ** | ||||
| 37386 | ************************************************************************* | ||||
| 37387 | ** This is the implementation of generic hash-tables | ||||
| 37388 | ** used in SQLite. | ||||
| 37389 | */ | ||||
| 37390 | /* #include "sqliteInt.h" */ | ||||
| 37391 | /* #include <assert.h> */ | ||||
| 37392 | |||||
| 37393 | /* Turn bulk memory into a hash table object by initializing the | ||||
| 37394 | ** fields of the Hash structure. | ||||
| 37395 | ** | ||||
| 37396 | ** "pNew" is a pointer to the hash table that is to be initialized. | ||||
| 37397 | */ | ||||
| 37398 | SQLITE_PRIVATEstatic void sqlite3HashInit(Hash *pNew){ | ||||
| 37399 | assert( pNew!=0 )((void) (0)); | ||||
| 37400 | pNew->first = 0; | ||||
| 37401 | pNew->count = 0; | ||||
| 37402 | pNew->htsize = 0; | ||||
| 37403 | pNew->ht = 0; | ||||
| 37404 | } | ||||
| 37405 | |||||
| 37406 | /* Remove all entries from a hash table. Reclaim all memory. | ||||
| 37407 | ** Call this routine to delete a hash table or to reset a hash table | ||||
| 37408 | ** to the empty state. | ||||
| 37409 | */ | ||||
| 37410 | SQLITE_PRIVATEstatic void sqlite3HashClear(Hash *pH){ | ||||
| 37411 | HashElem *elem; /* For looping over all elements of the table */ | ||||
| 37412 | |||||
| 37413 | assert( pH!=0 )((void) (0)); | ||||
| 37414 | elem = pH->first; | ||||
| 37415 | pH->first = 0; | ||||
| 37416 | sqlite3_free(pH->ht); | ||||
| 37417 | pH->ht = 0; | ||||
| 37418 | pH->htsize = 0; | ||||
| 37419 | while( elem ){ | ||||
| 37420 | HashElem *next_elem = elem->next; | ||||
| 37421 | sqlite3_free(elem); | ||||
| 37422 | elem = next_elem; | ||||
| 37423 | } | ||||
| 37424 | pH->count = 0; | ||||
| 37425 | } | ||||
| 37426 | |||||
| 37427 | /* | ||||
| 37428 | ** The hashing function. | ||||
| 37429 | */ | ||||
| 37430 | static unsigned int strHash(const char *z){ | ||||
| 37431 | unsigned int h = 0; | ||||
| 37432 | while( z[0] ){ /*OPTIMIZATION-IF-TRUE*/ | ||||
| 37433 | /* Knuth multiplicative hashing. (Sorting & Searching, p. 510). | ||||
| 37434 | ** 0x9e3779b1 is 2654435761 which is the closest prime number to | ||||
| 37435 | ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. | ||||
| 37436 | ** | ||||
| 37437 | ** Only bits 0xdf for ASCII and bits 0xbf for EBCDIC each octet are | ||||
| 37438 | ** hashed since the omitted bits determine the upper/lower case difference. | ||||
| 37439 | */ | ||||
| 37440 | #ifdef SQLITE_EBCDIC | ||||
| 37441 | h += 0xbf & (unsigned char)*(z++); | ||||
| 37442 | #else | ||||
| 37443 | h += 0xdf & (unsigned char)*(z++); | ||||
| 37444 | #endif | ||||
| 37445 | h *= 0x9e3779b1; | ||||
| 37446 | } | ||||
| 37447 | return h; | ||||
| 37448 | } | ||||
| 37449 | |||||
| 37450 | |||||
| 37451 | /* Link pNew element into the hash table pH. If pEntry!=0 then also | ||||
| 37452 | ** insert pNew into the pEntry hash bucket. | ||||
| 37453 | */ | ||||
| 37454 | static void insertElement( | ||||
| 37455 | Hash *pH, /* The complete hash table */ | ||||
| 37456 | struct _ht *pEntry, /* The entry into which pNew is inserted */ | ||||
| 37457 | HashElem *pNew /* The element to be inserted */ | ||||
| 37458 | ){ | ||||
| 37459 | HashElem *pHead; /* First element already in pEntry */ | ||||
| 37460 | if( pEntry ){ | ||||
| 37461 | pHead = pEntry->count ? pEntry->chain : 0; | ||||
| 37462 | pEntry->count++; | ||||
| 37463 | pEntry->chain = pNew; | ||||
| 37464 | }else{ | ||||
| 37465 | pHead = 0; | ||||
| 37466 | } | ||||
| 37467 | if( pHead ){ | ||||
| 37468 | pNew->next = pHead; | ||||
| 37469 | pNew->prev = pHead->prev; | ||||
| 37470 | if( pHead->prev ){ pHead->prev->next = pNew; } | ||||
| 37471 | else { pH->first = pNew; } | ||||
| 37472 | pHead->prev = pNew; | ||||
| 37473 | }else{ | ||||
| 37474 | pNew->next = pH->first; | ||||
| 37475 | if( pH->first ){ pH->first->prev = pNew; } | ||||
| 37476 | pNew->prev = 0; | ||||
| 37477 | pH->first = pNew; | ||||
| 37478 | } | ||||
| 37479 | } | ||||
| 37480 | |||||
| 37481 | |||||
| 37482 | /* Resize the hash table so that it contains "new_size" buckets. | ||||
| 37483 | ** | ||||
| 37484 | ** The hash table might fail to resize if sqlite3_malloc() fails or | ||||
| 37485 | ** if the new size is the same as the prior size. | ||||
| 37486 | ** Return TRUE if the resize occurs and false if not. | ||||
| 37487 | */ | ||||
| 37488 | static int rehash(Hash *pH, unsigned int new_size){ | ||||
| 37489 | struct _ht *new_ht; /* The new hash table */ | ||||
| 37490 | HashElem *elem, *next_elem; /* For looping over existing elements */ | ||||
| 37491 | |||||
| 37492 | #if SQLITE_MALLOC_SOFT_LIMIT1024>0 | ||||
| 37493 | if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT1024 ){ | ||||
| 37494 | new_size = SQLITE_MALLOC_SOFT_LIMIT1024/sizeof(struct _ht); | ||||
| 37495 | } | ||||
| 37496 | if( new_size==pH->htsize ) return 0; | ||||
| 37497 | #endif | ||||
| 37498 | |||||
| 37499 | /* The inability to allocates space for a larger hash table is | ||||
| 37500 | ** a performance hit but it is not a fatal error. So mark the | ||||
| 37501 | ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of | ||||
| 37502 | ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero() | ||||
| 37503 | ** only zeroes the requested number of bytes whereas this module will | ||||
| 37504 | ** use the actual amount of space allocated for the hash table (which | ||||
| 37505 | ** may be larger than the requested amount). | ||||
| 37506 | */ | ||||
| 37507 | sqlite3BeginBenignMalloc(); | ||||
| 37508 | new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) ); | ||||
| 37509 | sqlite3EndBenignMalloc(); | ||||
| 37510 | |||||
| 37511 | if( new_ht==0 ) return 0; | ||||
| 37512 | sqlite3_free(pH->ht); | ||||
| 37513 | pH->ht = new_ht; | ||||
| 37514 | pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); | ||||
| 37515 | memset(new_ht, 0, new_size*sizeof(struct _ht)); | ||||
| 37516 | for(elem=pH->first, pH->first=0; elem; elem = next_elem){ | ||||
| 37517 | next_elem = elem->next; | ||||
| 37518 | insertElement(pH, &new_ht[elem->h % new_size], elem); | ||||
| 37519 | } | ||||
| 37520 | return 1; | ||||
| 37521 | } | ||||
| 37522 | |||||
| 37523 | /* This function (for internal use only) locates an element in an | ||||
| 37524 | ** hash table that matches the given key. If no element is found, | ||||
| 37525 | ** a pointer to a static null element with HashElem.data==0 is returned. | ||||
| 37526 | ** If pH is not NULL, then the hash for this key is written to *pH. | ||||
| 37527 | */ | ||||
| 37528 | static HashElem *findElementWithHash( | ||||
| 37529 | const Hash *pH, /* The pH to be searched */ | ||||
| 37530 | const char *pKey, /* The key we are searching for */ | ||||
| 37531 | unsigned int *pHash /* Write the hash value here */ | ||||
| 37532 | ){ | ||||
| 37533 | HashElem *elem; /* Used to loop thru the element list */ | ||||
| 37534 | unsigned int count; /* Number of elements left to test */ | ||||
| 37535 | unsigned int h; /* The computed hash */ | ||||
| 37536 | static HashElem nullElement = { 0, 0, 0, 0, 0 }; | ||||
| 37537 | |||||
| 37538 | h = strHash(pKey); | ||||
| 37539 | if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/ | ||||
| 37540 | struct _ht *pEntry; | ||||
| 37541 | pEntry = &pH->ht[h % pH->htsize]; | ||||
| 37542 | elem = pEntry->chain; | ||||
| 37543 | count = pEntry->count; | ||||
| 37544 | }else{ | ||||
| 37545 | elem = pH->first; | ||||
| 37546 | count = pH->count; | ||||
| 37547 | } | ||||
| 37548 | if( pHash ) *pHash = h; | ||||
| 37549 | while( count ){ | ||||
| 37550 | assert( elem!=0 )((void) (0)); | ||||
| 37551 | if( h==elem->h && sqlite3StrICmp(elem->pKey,pKey)==0 ){ | ||||
| 37552 | return elem; | ||||
| 37553 | } | ||||
| 37554 | elem = elem->next; | ||||
| 37555 | count--; | ||||
| 37556 | } | ||||
| 37557 | return &nullElement; | ||||
| 37558 | } | ||||
| 37559 | |||||
| 37560 | /* Remove a single entry from the hash table given a pointer to that | ||||
| 37561 | ** element and a hash on the element's key. | ||||
| 37562 | */ | ||||
| 37563 | static void removeElement( | ||||
| 37564 | Hash *pH, /* The pH containing "elem" */ | ||||
| 37565 | HashElem *elem /* The element to be removed from the pH */ | ||||
| 37566 | ){ | ||||
| 37567 | struct _ht *pEntry; | ||||
| 37568 | if( elem->prev ){ | ||||
| 37569 | elem->prev->next = elem->next; | ||||
| 37570 | }else{ | ||||
| 37571 | pH->first = elem->next; | ||||
| 37572 | } | ||||
| 37573 | if( elem->next ){ | ||||
| 37574 | elem->next->prev = elem->prev; | ||||
| 37575 | } | ||||
| 37576 | if( pH->ht ){ | ||||
| 37577 | pEntry = &pH->ht[elem->h % pH->htsize]; | ||||
| 37578 | if( pEntry->chain==elem ){ | ||||
| 37579 | pEntry->chain = elem->next; | ||||
| 37580 | } | ||||
| 37581 | assert( pEntry->count>0 )((void) (0)); | ||||
| 37582 | pEntry->count--; | ||||
| 37583 | } | ||||
| 37584 | sqlite3_free( elem ); | ||||
| 37585 | pH->count--; | ||||
| 37586 | if( pH->count==0 ){ | ||||
| 37587 | assert( pH->first==0 )((void) (0)); | ||||
| 37588 | assert( pH->count==0 )((void) (0)); | ||||
| 37589 | sqlite3HashClear(pH); | ||||
| 37590 | } | ||||
| 37591 | } | ||||
| 37592 | |||||
| 37593 | /* Attempt to locate an element of the hash table pH with a key | ||||
| 37594 | ** that matches pKey. Return the data for this element if it is | ||||
| 37595 | ** found, or NULL if there is no match. | ||||
| 37596 | */ | ||||
| 37597 | SQLITE_PRIVATEstatic void *sqlite3HashFind(const Hash *pH, const char *pKey){ | ||||
| 37598 | assert( pH!=0 )((void) (0)); | ||||
| 37599 | assert( pKey!=0 )((void) (0)); | ||||
| 37600 | return findElementWithHash(pH, pKey, 0)->data; | ||||
| 37601 | } | ||||
| 37602 | |||||
| 37603 | /* Insert an element into the hash table pH. The key is pKey | ||||
| 37604 | ** and the data is "data". | ||||
| 37605 | ** | ||||
| 37606 | ** If no element exists with a matching key, then a new | ||||
| 37607 | ** element is created and NULL is returned. | ||||
| 37608 | ** | ||||
| 37609 | ** If another element already exists with the same key, then the | ||||
| 37610 | ** new data replaces the old data and the old data is returned. | ||||
| 37611 | ** The key is not copied in this instance. If a malloc fails, then | ||||
| 37612 | ** the new data is returned and the hash table is unchanged. | ||||
| 37613 | ** | ||||
| 37614 | ** If the "data" parameter to this function is NULL, then the | ||||
| 37615 | ** element corresponding to "key" is removed from the hash table. | ||||
| 37616 | */ | ||||
| 37617 | SQLITE_PRIVATEstatic void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ | ||||
| 37618 | unsigned int h; /* the hash of the key modulo hash table size */ | ||||
| 37619 | HashElem *elem; /* Used to loop thru the element list */ | ||||
| 37620 | HashElem *new_elem; /* New element added to the pH */ | ||||
| 37621 | |||||
| 37622 | assert( pH!=0 )((void) (0)); | ||||
| 37623 | assert( pKey!=0 )((void) (0)); | ||||
| 37624 | elem = findElementWithHash(pH,pKey,&h); | ||||
| 37625 | if( elem->data ){ | ||||
| 37626 | void *old_data = elem->data; | ||||
| 37627 | if( data==0 ){ | ||||
| 37628 | removeElement(pH,elem); | ||||
| 37629 | }else{ | ||||
| 37630 | elem->data = data; | ||||
| 37631 | elem->pKey = pKey; | ||||
| 37632 | } | ||||
| 37633 | return old_data; | ||||
| 37634 | } | ||||
| 37635 | if( data==0 ) return 0; | ||||
| 37636 | new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) ); | ||||
| 37637 | if( new_elem==0 ) return data; | ||||
| 37638 | new_elem->pKey = pKey; | ||||
| 37639 | new_elem->h = h; | ||||
| 37640 | new_elem->data = data; | ||||
| 37641 | pH->count++; | ||||
| 37642 | if( pH->count>=5 && pH->count > 2*pH->htsize ){ | ||||
| 37643 | rehash(pH, pH->count*3); | ||||
| 37644 | } | ||||
| 37645 | insertElement(pH, pH->ht ? &pH->ht[new_elem->h % pH->htsize] : 0, new_elem); | ||||
| 37646 | return 0; | ||||
| 37647 | } | ||||
| 37648 | |||||
| 37649 | /************** End of hash.c ************************************************/ | ||||
| 37650 | /************** Begin file opcodes.c *****************************************/ | ||||
| 37651 | /* Automatically generated. Do not edit */ | ||||
| 37652 | /* See the tool/mkopcodec.tcl script for details. */ | ||||
| 37653 | #if !defined(SQLITE_OMIT_EXPLAIN) \ | ||||
| 37654 | || defined(VDBE_PROFILE) \ | ||||
| 37655 | || defined(SQLITE_DEBUG) | ||||
| 37656 | #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG) | ||||
| 37657 | # define OpHelp(X) "\0" X | ||||
| 37658 | #else | ||||
| 37659 | # define OpHelp(X) | ||||
| 37660 | #endif | ||||
| 37661 | SQLITE_PRIVATEstatic const char *sqlite3OpcodeName(int i){ | ||||
| 37662 | static const char *const azName[] = { | ||||
| 37663 | /* 0 */ "Savepoint" OpHelp(""), | ||||
| 37664 | /* 1 */ "AutoCommit" OpHelp(""), | ||||
| 37665 | /* 2 */ "Transaction" OpHelp(""), | ||||
| 37666 | /* 3 */ "Checkpoint" OpHelp(""), | ||||
| 37667 | /* 4 */ "JournalMode" OpHelp(""), | ||||
| 37668 | /* 5 */ "Vacuum" OpHelp(""), | ||||
| 37669 | /* 6 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"), | ||||
| 37670 | /* 7 */ "VUpdate" OpHelp("data=r[P3@P2]"), | ||||
| 37671 | /* 8 */ "Init" OpHelp("Start at P2"), | ||||
| 37672 | /* 9 */ "Goto" OpHelp(""), | ||||
| 37673 | /* 10 */ "Gosub" OpHelp(""), | ||||
| 37674 | /* 11 */ "InitCoroutine" OpHelp(""), | ||||
| 37675 | /* 12 */ "Yield" OpHelp(""), | ||||
| 37676 | /* 13 */ "MustBeInt" OpHelp(""), | ||||
| 37677 | /* 14 */ "Jump" OpHelp(""), | ||||
| 37678 | /* 15 */ "Once" OpHelp(""), | ||||
| 37679 | /* 16 */ "If" OpHelp(""), | ||||
| 37680 | /* 17 */ "IfNot" OpHelp(""), | ||||
| 37681 | /* 18 */ "IsType" OpHelp("if typeof(P1.P3) in P5 goto P2"), | ||||
| 37682 | /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"), | ||||
| 37683 | /* 20 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"), | ||||
| 37684 | /* 21 */ "SeekLT" OpHelp("key=r[P3@P4]"), | ||||
| 37685 | /* 22 */ "SeekLE" OpHelp("key=r[P3@P4]"), | ||||
| 37686 | /* 23 */ "SeekGE" OpHelp("key=r[P3@P4]"), | ||||
| 37687 | /* 24 */ "SeekGT" OpHelp("key=r[P3@P4]"), | ||||
| 37688 | /* 25 */ "IfNotOpen" OpHelp("if( !csr[P1] ) goto P2"), | ||||
| 37689 | /* 26 */ "IfNoHope" OpHelp("key=r[P3@P4]"), | ||||
| 37690 | /* 27 */ "NoConflict" OpHelp("key=r[P3@P4]"), | ||||
| 37691 | /* 28 */ "NotFound" OpHelp("key=r[P3@P4]"), | ||||
| 37692 | /* 29 */ "Found" OpHelp("key=r[P3@P4]"), | ||||
| 37693 | /* 30 */ "SeekRowid" OpHelp("intkey=r[P3]"), | ||||
| 37694 | /* 31 */ "NotExists" OpHelp("intkey=r[P3]"), | ||||
| 37695 | /* 32 */ "Last" OpHelp(""), | ||||
| 37696 | /* 33 */ "IfSizeBetween" OpHelp(""), | ||||
| 37697 | /* 34 */ "SorterSort" OpHelp(""), | ||||
| 37698 | /* 35 */ "Sort" OpHelp(""), | ||||
| 37699 | /* 36 */ "Rewind" OpHelp(""), | ||||
| 37700 | /* 37 */ "SorterNext" OpHelp(""), | ||||
| 37701 | /* 38 */ "Prev" OpHelp(""), | ||||
| 37702 | /* 39 */ "Next" OpHelp(""), | ||||
| 37703 | /* 40 */ "IdxLE" OpHelp("key=r[P3@P4]"), | ||||
| 37704 | /* 41 */ "IdxGT" OpHelp("key=r[P3@P4]"), | ||||
| 37705 | /* 42 */ "IdxLT" OpHelp("key=r[P3@P4]"), | ||||
| 37706 | /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"), | ||||
| 37707 | /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"), | ||||
| 37708 | /* 45 */ "IdxGE" OpHelp("key=r[P3@P4]"), | ||||
| 37709 | /* 46 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), | ||||
| 37710 | /* 47 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), | ||||
| 37711 | /* 48 */ "Program" OpHelp(""), | ||||
| 37712 | /* 49 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), | ||||
| 37713 | /* 50 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), | ||||
| 37714 | /* 51 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"), | ||||
| 37715 | /* 52 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"), | ||||
| 37716 | /* 53 */ "Ne" OpHelp("IF r[P3]!=r[P1]"), | ||||
| 37717 | /* 54 */ "Eq" OpHelp("IF r[P3]==r[P1]"), | ||||
| 37718 | /* 55 */ "Gt" OpHelp("IF r[P3]>r[P1]"), | ||||
| 37719 | /* 56 */ "Le" OpHelp("IF r[P3]<=r[P1]"), | ||||
| 37720 | /* 57 */ "Lt" OpHelp("IF r[P3]<r[P1]"), | ||||
| 37721 | /* 58 */ "Ge" OpHelp("IF r[P3]>=r[P1]"), | ||||
| 37722 | /* 59 */ "ElseEq" OpHelp(""), | ||||
| 37723 | /* 60 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"), | ||||
| 37724 | /* 61 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), | ||||
| 37725 | /* 62 */ "IncrVacuum" OpHelp(""), | ||||
| 37726 | /* 63 */ "VNext" OpHelp(""), | ||||
| 37727 | /* 64 */ "Filter" OpHelp("if key(P3@P4) not in filter(P1) goto P2"), | ||||
| 37728 | /* 65 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"), | ||||
| 37729 | /* 66 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"), | ||||
| 37730 | /* 67 */ "Return" OpHelp(""), | ||||
| 37731 | /* 68 */ "EndCoroutine" OpHelp(""), | ||||
| 37732 | /* 69 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), | ||||
| 37733 | /* 70 */ "Halt" OpHelp(""), | ||||
| 37734 | /* 71 */ "Integer" OpHelp("r[P2]=P1"), | ||||
| 37735 | /* 72 */ "Int64" OpHelp("r[P2]=P4"), | ||||
| 37736 | /* 73 */ "String" OpHelp("r[P2]='P4' (len=P1)"), | ||||
| 37737 | /* 74 */ "BeginSubrtn" OpHelp("r[P2]=NULL"), | ||||
| 37738 | /* 75 */ "Null" OpHelp("r[P2..P3]=NULL"), | ||||
| 37739 | /* 76 */ "SoftNull" OpHelp("r[P1]=NULL"), | ||||
| 37740 | /* 77 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), | ||||
| 37741 | /* 78 */ "Variable" OpHelp("r[P2]=parameter(P1)"), | ||||
| 37742 | /* 79 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), | ||||
| 37743 | /* 80 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), | ||||
| 37744 | /* 81 */ "SCopy" OpHelp("r[P2]=r[P1]"), | ||||
| 37745 | /* 82 */ "IntCopy" OpHelp("r[P2]=r[P1]"), | ||||
| 37746 | /* 83 */ "FkCheck" OpHelp(""), | ||||
| 37747 | /* 84 */ "ResultRow" OpHelp("output=r[P1@P2]"), | ||||
| 37748 | /* 85 */ "CollSeq" OpHelp(""), | ||||
| 37749 | /* 86 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), | ||||
| 37750 | /* 87 */ "RealAffinity" OpHelp(""), | ||||
| 37751 | /* 88 */ "Cast" OpHelp("affinity(r[P1])"), | ||||
| 37752 | /* 89 */ "Permutation" OpHelp(""), | ||||
| 37753 | /* 90 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), | ||||
| 37754 | /* 91 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"), | ||||
| 37755 | /* 92 */ "ZeroOrNull" OpHelp("r[P2] = 0 OR NULL"), | ||||
| 37756 | /* 93 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"), | ||||
| 37757 | /* 94 */ "Column" OpHelp("r[P3]=PX cursor P1 column P2"), | ||||
| 37758 | /* 95 */ "TypeCheck" OpHelp("typecheck(r[P1@P2])"), | ||||
| 37759 | /* 96 */ "Affinity" OpHelp("affinity(r[P1@P2])"), | ||||
| 37760 | /* 97 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), | ||||
| 37761 | /* 98 */ "Count" OpHelp("r[P2]=count()"), | ||||
| 37762 | /* 99 */ "ReadCookie" OpHelp(""), | ||||
| 37763 | /* 100 */ "SetCookie" OpHelp(""), | ||||
| 37764 | /* 101 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), | ||||
| 37765 | /* 102 */ "OpenRead" OpHelp("root=P2 iDb=P3"), | ||||
| 37766 | /* 103 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), | ||||
| 37767 | /* 104 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), | ||||
| 37768 | /* 105 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"), | ||||
| 37769 | /* 106 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"), | ||||
| 37770 | /* 107 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"), | ||||
| 37771 | /* 108 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), | ||||
| 37772 | /* 109 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"), | ||||
| 37773 | /* 110 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), | ||||
| 37774 | /* 111 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), | ||||
| 37775 | /* 112 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), | ||||
| 37776 | /* 113 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), | ||||
| 37777 | /* 114 */ "OpenDup" OpHelp(""), | ||||
| 37778 | /* 115 */ "BitNot" OpHelp("r[P2]= ~r[P1]"), | ||||
| 37779 | /* 116 */ "OpenAutoindex" OpHelp("nColumn=P2"), | ||||
| 37780 | /* 117 */ "OpenEphemeral" OpHelp("nColumn=P2"), | ||||
| 37781 | /* 118 */ "String8" OpHelp("r[P2]='P4'"), | ||||
| 37782 | /* 119 */ "SorterOpen" OpHelp(""), | ||||
| 37783 | /* 120 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), | ||||
| 37784 | /* 121 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), | ||||
| 37785 | /* 122 */ "Close" OpHelp(""), | ||||
| 37786 | /* 123 */ "ColumnsUsed" OpHelp(""), | ||||
| 37787 | /* 124 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"), | ||||
| 37788 | /* 125 */ "SeekHit" OpHelp("set P2<=seekHit<=P3"), | ||||
| 37789 | /* 126 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), | ||||
| 37790 | /* 127 */ "NewRowid" OpHelp("r[P2]=rowid"), | ||||
| 37791 | /* 128 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), | ||||
| 37792 | /* 129 */ "RowCell" OpHelp(""), | ||||
| 37793 | /* 130 */ "Delete" OpHelp(""), | ||||
| 37794 | /* 131 */ "ResetCount" OpHelp(""), | ||||
| 37795 | /* 132 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), | ||||
| 37796 | /* 133 */ "SorterData" OpHelp("r[P2]=data"), | ||||
| 37797 | /* 134 */ "RowData" OpHelp("r[P2]=data"), | ||||
| 37798 | /* 135 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"), | ||||
| 37799 | /* 136 */ "NullRow" OpHelp(""), | ||||
| 37800 | /* 137 */ "SeekEnd" OpHelp(""), | ||||
| 37801 | /* 138 */ "IdxInsert" OpHelp("key=r[P2]"), | ||||
| 37802 | /* 139 */ "SorterInsert" OpHelp("key=r[P2]"), | ||||
| 37803 | /* 140 */ "IdxDelete" OpHelp("key=r[P2@P3]"), | ||||
| 37804 | /* 141 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"), | ||||
| 37805 | /* 142 */ "IdxRowid" OpHelp("r[P2]=rowid"), | ||||
| 37806 | /* 143 */ "FinishSeek" OpHelp(""), | ||||
| 37807 | /* 144 */ "Destroy" OpHelp(""), | ||||
| 37808 | /* 145 */ "Clear" OpHelp(""), | ||||
| 37809 | /* 146 */ "ResetSorter" OpHelp(""), | ||||
| 37810 | /* 147 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"), | ||||
| 37811 | /* 148 */ "SqlExec" OpHelp(""), | ||||
| 37812 | /* 149 */ "ParseSchema" OpHelp(""), | ||||
| 37813 | /* 150 */ "LoadAnalysis" OpHelp(""), | ||||
| 37814 | /* 151 */ "DropTable" OpHelp(""), | ||||
| 37815 | /* 152 */ "DropIndex" OpHelp(""), | ||||
| 37816 | /* 153 */ "DropTrigger" OpHelp(""), | ||||
| 37817 | /* 154 */ "Real" OpHelp("r[P2]=P4"), | ||||
| 37818 | /* 155 */ "IntegrityCk" OpHelp(""), | ||||
| 37819 | /* 156 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), | ||||
| 37820 | /* 157 */ "Param" OpHelp(""), | ||||
| 37821 | /* 158 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), | ||||
| 37822 | /* 159 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), | ||||
| 37823 | /* 160 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), | ||||
| 37824 | /* 161 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"), | ||||
| 37825 | /* 162 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), | ||||
| 37826 | /* 163 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"), | ||||
| 37827 | /* 164 */ "AggValue" OpHelp("r[P3]=value N=P2"), | ||||
| 37828 | /* 165 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), | ||||
| 37829 | /* 166 */ "Expire" OpHelp(""), | ||||
| 37830 | /* 167 */ "CursorLock" OpHelp(""), | ||||
| 37831 | /* 168 */ "CursorUnlock" OpHelp(""), | ||||
| 37832 | /* 169 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), | ||||
| 37833 | /* 170 */ "VBegin" OpHelp(""), | ||||
| 37834 | /* 171 */ "VCreate" OpHelp(""), | ||||
| 37835 | /* 172 */ "VDestroy" OpHelp(""), | ||||
| 37836 | /* 173 */ "VOpen" OpHelp(""), | ||||
| 37837 | /* 174 */ "VCheck" OpHelp(""), | ||||
| 37838 | /* 175 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"), | ||||
| 37839 | /* 176 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), | ||||
| 37840 | /* 177 */ "VRename" OpHelp(""), | ||||
| 37841 | /* 178 */ "Pagecount" OpHelp(""), | ||||
| 37842 | /* 179 */ "MaxPgcnt" OpHelp(""), | ||||
| 37843 | /* 180 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"), | ||||
| 37844 | /* 181 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"), | ||||
| 37845 | /* 182 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"), | ||||
| 37846 | /* 183 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"), | ||||
| 37847 | /* 184 */ "Trace" OpHelp(""), | ||||
| 37848 | /* 185 */ "CursorHint" OpHelp(""), | ||||
| 37849 | /* 186 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"), | ||||
| 37850 | /* 187 */ "Noop" OpHelp(""), | ||||
| 37851 | /* 188 */ "Explain" OpHelp(""), | ||||
| 37852 | /* 189 */ "Abortable" OpHelp(""), | ||||
| 37853 | }; | ||||
| 37854 | return azName[i]; | ||||
| 37855 | } | ||||
| 37856 | #endif | ||||
| 37857 | |||||
| 37858 | /************** End of opcodes.c *********************************************/ | ||||
| 37859 | /************** Begin file os_kv.c *******************************************/ | ||||
| 37860 | /* | ||||
| 37861 | ** 2022-09-06 | ||||
| 37862 | ** | ||||
| 37863 | ** The author disclaims copyright to this source code. In place of | ||||
| 37864 | ** a legal notice, here is a blessing: | ||||
| 37865 | ** | ||||
| 37866 | ** May you do good and not evil. | ||||
| 37867 | ** May you find forgiveness for yourself and forgive others. | ||||
| 37868 | ** May you share freely, never taking more than you give. | ||||
| 37869 | ** | ||||
| 37870 | ****************************************************************************** | ||||
| 37871 | ** | ||||
| 37872 | ** This file contains an experimental VFS layer that operates on a | ||||
| 37873 | ** Key/Value storage engine where both keys and values must be pure | ||||
| 37874 | ** text. | ||||
| 37875 | */ | ||||
| 37876 | /* #include <sqliteInt.h> */ | ||||
| 37877 | #if SQLITE_OS_KV0 || (SQLITE_OS_UNIX1 && defined(SQLITE_OS_KV_OPTIONAL)) | ||||
| 37878 | |||||
| 37879 | /***************************************************************************** | ||||
| 37880 | ** Debugging logic | ||||
| 37881 | */ | ||||
| 37882 | |||||
| 37883 | /* SQLITE_KV_TRACE() is used for tracing calls to kvstorage routines. */ | ||||
| 37884 | #if 0 | ||||
| 37885 | #define SQLITE_KV_TRACE(X) printf X | ||||
| 37886 | #else | ||||
| 37887 | #define SQLITE_KV_TRACE(X) | ||||
| 37888 | #endif | ||||
| 37889 | |||||
| 37890 | /* SQLITE_KV_LOG() is used for tracing calls to the VFS interface */ | ||||
| 37891 | #if 0 | ||||
| 37892 | #define SQLITE_KV_LOG(X) printf X | ||||
| 37893 | #else | ||||
| 37894 | #define SQLITE_KV_LOG(X) | ||||
| 37895 | #endif | ||||
| 37896 | |||||
| 37897 | |||||
| 37898 | /* | ||||
| 37899 | ** Forward declaration of objects used by this VFS implementation | ||||
| 37900 | */ | ||||
| 37901 | typedef struct KVVfsFile KVVfsFile; | ||||
| 37902 | |||||
| 37903 | /* A single open file. There are only two files represented by this | ||||
| 37904 | ** VFS - the database and the rollback journal. | ||||
| 37905 | */ | ||||
| 37906 | struct KVVfsFile { | ||||
| 37907 | sqlite3_file base; /* IO methods */ | ||||
| 37908 | const char *zClass; /* Storage class */ | ||||
| 37909 | int isJournal; /* True if this is a journal file */ | ||||
| 37910 | unsigned int nJrnl; /* Space allocated for aJrnl[] */ | ||||
| 37911 | char *aJrnl; /* Journal content */ | ||||
| 37912 | int szPage; /* Last known page size */ | ||||
| 37913 | sqlite3_int64 szDb; /* Database file size. -1 means unknown */ | ||||
| 37914 | char *aData; /* Buffer to hold page data */ | ||||
| 37915 | }; | ||||
| 37916 | #define SQLITE_KVOS_SZ 133073 | ||||
| 37917 | |||||
| 37918 | /* | ||||
| 37919 | ** Methods for KVVfsFile | ||||
| 37920 | */ | ||||
| 37921 | static int kvvfsClose(sqlite3_file*); | ||||
| 37922 | static int kvvfsReadDb(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); | ||||
| 37923 | static int kvvfsReadJrnl(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); | ||||
| 37924 | static int kvvfsWriteDb(sqlite3_file*,const void*,int iAmt, sqlite3_int64); | ||||
| 37925 | static int kvvfsWriteJrnl(sqlite3_file*,const void*,int iAmt, sqlite3_int64); | ||||
| 37926 | static int kvvfsTruncateDb(sqlite3_file*, sqlite3_int64 size); | ||||
| 37927 | static int kvvfsTruncateJrnl(sqlite3_file*, sqlite3_int64 size); | ||||
| 37928 | static int kvvfsSyncDb(sqlite3_file*, int flags); | ||||
| 37929 | static int kvvfsSyncJrnl(sqlite3_file*, int flags); | ||||
| 37930 | static int kvvfsFileSizeDb(sqlite3_file*, sqlite3_int64 *pSize); | ||||
| 37931 | static int kvvfsFileSizeJrnl(sqlite3_file*, sqlite3_int64 *pSize); | ||||
| 37932 | static int kvvfsLock(sqlite3_file*, int); | ||||
| 37933 | static int kvvfsUnlock(sqlite3_file*, int); | ||||
| 37934 | static int kvvfsCheckReservedLock(sqlite3_file*, int *pResOut); | ||||
| 37935 | static int kvvfsFileControlDb(sqlite3_file*, int op, void *pArg); | ||||
| 37936 | static int kvvfsFileControlJrnl(sqlite3_file*, int op, void *pArg); | ||||
| 37937 | static int kvvfsSectorSize(sqlite3_file*); | ||||
| 37938 | static int kvvfsDeviceCharacteristics(sqlite3_file*); | ||||
| 37939 | |||||
| 37940 | /* | ||||
| 37941 | ** Methods for sqlite3_vfs | ||||
| 37942 | */ | ||||
| 37943 | static int kvvfsOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); | ||||
| 37944 | static int kvvfsDelete(sqlite3_vfs*, const char *zName, int syncDir); | ||||
| 37945 | static int kvvfsAccess(sqlite3_vfs*, const char *zName, int flags, int *); | ||||
| 37946 | static int kvvfsFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); | ||||
| 37947 | static void *kvvfsDlOpen(sqlite3_vfs*, const char *zFilename); | ||||
| 37948 | static int kvvfsRandomness(sqlite3_vfs*, int nByte, char *zOut); | ||||
| 37949 | static int kvvfsSleep(sqlite3_vfs*, int microseconds); | ||||
| 37950 | static int kvvfsCurrentTime(sqlite3_vfs*, double*); | ||||
| 37951 | static int kvvfsCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); | ||||
| 37952 | |||||
| 37953 | static sqlite3_vfs sqlite3OsKvvfsObject = { | ||||
| 37954 | 1, /* iVersion */ | ||||
| 37955 | sizeof(KVVfsFile), /* szOsFile */ | ||||
| 37956 | 1024, /* mxPathname */ | ||||
| 37957 | 0, /* pNext */ | ||||
| 37958 | "kvvfs", /* zName */ | ||||
| 37959 | 0, /* pAppData */ | ||||
| 37960 | kvvfsOpen, /* xOpen */ | ||||
| 37961 | kvvfsDelete, /* xDelete */ | ||||
| 37962 | kvvfsAccess, /* xAccess */ | ||||
| 37963 | kvvfsFullPathname, /* xFullPathname */ | ||||
| 37964 | kvvfsDlOpen, /* xDlOpen */ | ||||
| 37965 | 0, /* xDlError */ | ||||
| 37966 | 0, /* xDlSym */ | ||||
| 37967 | 0, /* xDlClose */ | ||||
| 37968 | kvvfsRandomness, /* xRandomness */ | ||||
| 37969 | kvvfsSleep, /* xSleep */ | ||||
| 37970 | kvvfsCurrentTime, /* xCurrentTime */ | ||||
| 37971 | 0, /* xGetLastError */ | ||||
| 37972 | kvvfsCurrentTimeInt64 /* xCurrentTimeInt64 */ | ||||
| 37973 | }; | ||||
| 37974 | |||||
| 37975 | /* Methods for sqlite3_file objects referencing a database file | ||||
| 37976 | */ | ||||
| 37977 | static sqlite3_io_methods kvvfs_db_io_methods = { | ||||
| 37978 | 1, /* iVersion */ | ||||
| 37979 | kvvfsClose, /* xClose */ | ||||
| 37980 | kvvfsReadDb, /* xRead */ | ||||
| 37981 | kvvfsWriteDb, /* xWrite */ | ||||
| 37982 | kvvfsTruncateDb, /* xTruncate */ | ||||
| 37983 | kvvfsSyncDb, /* xSync */ | ||||
| 37984 | kvvfsFileSizeDb, /* xFileSize */ | ||||
| 37985 | kvvfsLock, /* xLock */ | ||||
| 37986 | kvvfsUnlock, /* xUnlock */ | ||||
| 37987 | kvvfsCheckReservedLock, /* xCheckReservedLock */ | ||||
| 37988 | kvvfsFileControlDb, /* xFileControl */ | ||||
| 37989 | kvvfsSectorSize, /* xSectorSize */ | ||||
| 37990 | kvvfsDeviceCharacteristics, /* xDeviceCharacteristics */ | ||||
| 37991 | 0, /* xShmMap */ | ||||
| 37992 | 0, /* xShmLock */ | ||||
| 37993 | 0, /* xShmBarrier */ | ||||
| 37994 | 0, /* xShmUnmap */ | ||||
| 37995 | 0, /* xFetch */ | ||||
| 37996 | 0 /* xUnfetch */ | ||||
| 37997 | }; | ||||
| 37998 | |||||
| 37999 | /* Methods for sqlite3_file objects referencing a rollback journal | ||||
| 38000 | */ | ||||
| 38001 | static sqlite3_io_methods kvvfs_jrnl_io_methods = { | ||||
| 38002 | 1, /* iVersion */ | ||||
| 38003 | kvvfsClose, /* xClose */ | ||||
| 38004 | kvvfsReadJrnl, /* xRead */ | ||||
| 38005 | kvvfsWriteJrnl, /* xWrite */ | ||||
| 38006 | kvvfsTruncateJrnl, /* xTruncate */ | ||||
| 38007 | kvvfsSyncJrnl, /* xSync */ | ||||
| 38008 | kvvfsFileSizeJrnl, /* xFileSize */ | ||||
| 38009 | kvvfsLock, /* xLock */ | ||||
| 38010 | kvvfsUnlock, /* xUnlock */ | ||||
| 38011 | kvvfsCheckReservedLock, /* xCheckReservedLock */ | ||||
| 38012 | kvvfsFileControlJrnl, /* xFileControl */ | ||||
| 38013 | kvvfsSectorSize, /* xSectorSize */ | ||||
| 38014 | kvvfsDeviceCharacteristics, /* xDeviceCharacteristics */ | ||||
| 38015 | 0, /* xShmMap */ | ||||
| 38016 | 0, /* xShmLock */ | ||||
| 38017 | 0, /* xShmBarrier */ | ||||
| 38018 | 0, /* xShmUnmap */ | ||||
| 38019 | 0, /* xFetch */ | ||||
| 38020 | 0 /* xUnfetch */ | ||||
| 38021 | }; | ||||
| 38022 | |||||
| 38023 | /****** Storage subsystem **************************************************/ | ||||
| 38024 | #include <sys/types.h> | ||||
| 38025 | #include <sys/stat.h> | ||||
| 38026 | #include <unistd.h> | ||||
| 38027 | |||||
| 38028 | /* Forward declarations for the low-level storage engine | ||||
| 38029 | */ | ||||
| 38030 | static int kvstorageWrite(const char*, const char *zKey, const char *zData); | ||||
| 38031 | static int kvstorageDelete(const char*, const char *zKey); | ||||
| 38032 | static int kvstorageRead(const char*, const char *zKey, char *zBuf, int nBuf); | ||||
| 38033 | #define KVSTORAGE_KEY_SZ 32 | ||||
| 38034 | |||||
| 38035 | /* Expand the key name with an appropriate prefix and put the result | ||||
| 38036 | ** zKeyOut[]. The zKeyOut[] buffer is assumed to hold at least | ||||
| 38037 | ** KVSTORAGE_KEY_SZ bytes. | ||||
| 38038 | */ | ||||
| 38039 | static void kvstorageMakeKey( | ||||
| 38040 | const char *zClass, | ||||
| 38041 | const char *zKeyIn, | ||||
| 38042 | char *zKeyOut | ||||
| 38043 | ){ | ||||
| 38044 | sqlite3_snprintf(KVSTORAGE_KEY_SZ, zKeyOut, "kvvfs-%s-%s", zClass, zKeyIn); | ||||
| 38045 | } | ||||
| 38046 | |||||
| 38047 | /* Write content into a key. zClass is the particular namespace of the | ||||
| 38048 | ** underlying key/value store to use - either "local" or "session". | ||||
| 38049 | ** | ||||
| 38050 | ** Both zKey and zData are zero-terminated pure text strings. | ||||
| 38051 | ** | ||||
| 38052 | ** Return the number of errors. | ||||
| 38053 | */ | ||||
| 38054 | static int kvstorageWrite( | ||||
| 38055 | const char *zClass, | ||||
| 38056 | const char *zKey, | ||||
| 38057 | const char *zData | ||||
| 38058 | ){ | ||||
| 38059 | FILE *fd; | ||||
| 38060 | char zXKey[KVSTORAGE_KEY_SZ]; | ||||
| 38061 | kvstorageMakeKey(zClass, zKey, zXKey); | ||||
| 38062 | fd = fopen(zXKey, "wb"); | ||||
| 38063 | if( fd ){ | ||||
| 38064 | SQLITE_KV_TRACE(("KVVFS-WRITE %-15s (%d) %.50s%s\n", zXKey, | ||||
| 38065 | (int)strlen(zData), zData, | ||||
| 38066 | strlen(zData)>50 ? "..." : "")); | ||||
| 38067 | fputs(zData, fd); | ||||
| 38068 | fclose(fd); | ||||
| 38069 | return 0; | ||||
| 38070 | }else{ | ||||
| 38071 | return 1; | ||||
| 38072 | } | ||||
| 38073 | } | ||||
| 38074 | |||||
| 38075 | /* Delete a key (with its corresponding data) from the key/value | ||||
| 38076 | ** namespace given by zClass. If the key does not previously exist, | ||||
| 38077 | ** this routine is a no-op. | ||||
| 38078 | */ | ||||
| 38079 | static int kvstorageDelete(const char *zClass, const char *zKey){ | ||||
| 38080 | char zXKey[KVSTORAGE_KEY_SZ]; | ||||
| 38081 | kvstorageMakeKey(zClass, zKey, zXKey); | ||||
| 38082 | unlink(zXKey); | ||||
| 38083 | SQLITE_KV_TRACE(("KVVFS-DELETE %-15s\n", zXKey)); | ||||
| 38084 | return 0; | ||||
| 38085 | } | ||||
| 38086 | |||||
| 38087 | /* Read the value associated with a zKey from the key/value namespace given | ||||
| 38088 | ** by zClass and put the text data associated with that key in the first | ||||
| 38089 | ** nBuf bytes of zBuf[]. The value might be truncated if zBuf is not large | ||||
| 38090 | ** enough to hold it all. The value put into zBuf must always be zero | ||||
| 38091 | ** terminated, even if it gets truncated because nBuf is not large enough. | ||||
| 38092 | ** | ||||
| 38093 | ** Return the total number of bytes in the data, without truncation, and | ||||
| 38094 | ** not counting the final zero terminator. Return -1 if the key does | ||||
| 38095 | ** not exist. | ||||
| 38096 | ** | ||||
| 38097 | ** If nBuf<=0 then this routine simply returns the size of the data without | ||||
| 38098 | ** actually reading it. | ||||
| 38099 | */ | ||||
| 38100 | static int kvstorageRead( | ||||
| 38101 | const char *zClass, | ||||
| 38102 | const char *zKey, | ||||
| 38103 | char *zBuf, | ||||
| 38104 | int nBuf | ||||
| 38105 | ){ | ||||
| 38106 | FILE *fd; | ||||
| 38107 | struct stat buf; | ||||
| 38108 | char zXKey[KVSTORAGE_KEY_SZ]; | ||||
| 38109 | kvstorageMakeKey(zClass, zKey, zXKey); | ||||
| 38110 | if( access(zXKey, R_OK4)!=0 | ||||
| 38111 | || stat(zXKey, &buf)!=0 | ||||
| 38112 | || !S_ISREG(buf.st_mode)((((buf.st_mode)) & 0170000) == (0100000)) | ||||
| 38113 | ){ | ||||
| 38114 | SQLITE_KV_TRACE(("KVVFS-READ %-15s (-1)\n", zXKey)); | ||||
| 38115 | return -1; | ||||
| 38116 | } | ||||
| 38117 | if( nBuf<=0 ){ | ||||
| 38118 | return (int)buf.st_size; | ||||
| 38119 | }else if( nBuf==1 ){ | ||||
| 38120 | zBuf[0] = 0; | ||||
| 38121 | SQLITE_KV_TRACE(("KVVFS-READ %-15s (%d)\n", zXKey, | ||||
| 38122 | (int)buf.st_size)); | ||||
| 38123 | return (int)buf.st_size; | ||||
| 38124 | } | ||||
| 38125 | if( nBuf > buf.st_size + 1 ){ | ||||
| 38126 | nBuf = buf.st_size + 1; | ||||
| 38127 | } | ||||
| 38128 | fd = fopen(zXKey, "rb"); | ||||
| 38129 | if( fd==0 ){ | ||||
| 38130 | SQLITE_KV_TRACE(("KVVFS-READ %-15s (-1)\n", zXKey)); | ||||
| 38131 | return -1; | ||||
| 38132 | }else{ | ||||
| 38133 | sqlite3_int64 n = fread(zBuf, 1, nBuf-1, fd); | ||||
| 38134 | fclose(fd); | ||||
| 38135 | zBuf[n] = 0; | ||||
| 38136 | SQLITE_KV_TRACE(("KVVFS-READ %-15s (%lld) %.50s%s\n", zXKey, | ||||
| 38137 | n, zBuf, n>50 ? "..." : "")); | ||||
| 38138 | return (int)n; | ||||
| 38139 | } | ||||
| 38140 | } | ||||
| 38141 | |||||
| 38142 | /* | ||||
| 38143 | ** An internal level of indirection which enables us to replace the | ||||
| 38144 | ** kvvfs i/o methods with JavaScript implementations in WASM builds. | ||||
| 38145 | ** Maintenance reminder: if this struct changes in any way, the JSON | ||||
| 38146 | ** rendering of its structure must be updated in | ||||
| 38147 | ** sqlite3_wasm_enum_json(). There are no binary compatibility | ||||
| 38148 | ** concerns, so it does not need an iVersion member. This file is | ||||
| 38149 | ** necessarily always compiled together with sqlite3_wasm_enum_json(), | ||||
| 38150 | ** and JS code dynamically creates the mapping of members based on | ||||
| 38151 | ** that JSON description. | ||||
| 38152 | */ | ||||
| 38153 | typedef struct sqlite3_kvvfs_methods sqlite3_kvvfs_methods; | ||||
| 38154 | struct sqlite3_kvvfs_methods { | ||||
| 38155 | int (*xRead)(const char *zClass, const char *zKey, char *zBuf, int nBuf); | ||||
| 38156 | int (*xWrite)(const char *zClass, const char *zKey, const char *zData); | ||||
| 38157 | int (*xDelete)(const char *zClass, const char *zKey); | ||||
| 38158 | const int nKeySize; | ||||
| 38159 | }; | ||||
| 38160 | |||||
| 38161 | /* | ||||
| 38162 | ** This object holds the kvvfs I/O methods which may be swapped out | ||||
| 38163 | ** for JavaScript-side implementations in WASM builds. In such builds | ||||
| 38164 | ** it cannot be const, but in native builds it should be so that | ||||
| 38165 | ** the compiler can hopefully optimize this level of indirection out. | ||||
| 38166 | ** That said, kvvfs is intended primarily for use in WASM builds. | ||||
| 38167 | ** | ||||
| 38168 | ** Note that this is not explicitly flagged as static because the | ||||
| 38169 | ** amalgamation build will tag it with SQLITE_PRIVATE. | ||||
| 38170 | */ | ||||
| 38171 | #ifndef SQLITE_WASM | ||||
| 38172 | const | ||||
| 38173 | #endif | ||||
| 38174 | SQLITE_PRIVATEstatic sqlite3_kvvfs_methods sqlite3KvvfsMethods = { | ||||
| 38175 | kvstorageRead, | ||||
| 38176 | kvstorageWrite, | ||||
| 38177 | kvstorageDelete, | ||||
| 38178 | KVSTORAGE_KEY_SZ | ||||
| 38179 | }; | ||||
| 38180 | |||||
| 38181 | /****** Utility subroutines ************************************************/ | ||||
| 38182 | |||||
| 38183 | /* | ||||
| 38184 | ** Encode binary into the text encoded used to persist on disk. | ||||
| 38185 | ** The output text is stored in aOut[], which must be at least | ||||
| 38186 | ** nData+1 bytes in length. | ||||
| 38187 | ** | ||||
| 38188 | ** Return the actual length of the encoded text, not counting the | ||||
| 38189 | ** zero terminator at the end. | ||||
| 38190 | ** | ||||
| 38191 | ** Encoding format | ||||
| 38192 | ** --------------- | ||||
| 38193 | ** | ||||
| 38194 | ** * Non-zero bytes are encoded as upper-case hexadecimal | ||||
| 38195 | ** | ||||
| 38196 | ** * A sequence of one or more zero-bytes that are not at the | ||||
| 38197 | ** beginning of the buffer are encoded as a little-endian | ||||
| 38198 | ** base-26 number using a..z. "a" means 0. "b" means 1, | ||||
| 38199 | ** "z" means 25. "ab" means 26. "ac" means 52. And so forth. | ||||
| 38200 | ** | ||||
| 38201 | ** * Because there is no overlap between the encoding characters | ||||
| 38202 | ** of hexadecimal and base-26 numbers, it is always clear where | ||||
| 38203 | ** one stops and the next begins. | ||||
| 38204 | */ | ||||
| 38205 | static int kvvfsEncode(const char *aData, int nData, char *aOut){ | ||||
| 38206 | int i, j; | ||||
| 38207 | const unsigned char *a = (const unsigned char*)aData; | ||||
| 38208 | for(i=j=0; i<nData; i++){ | ||||
| 38209 | unsigned char c = a[i]; | ||||
| 38210 | if( c!=0 ){ | ||||
| 38211 | aOut[j++] = "0123456789ABCDEF"[c>>4]; | ||||
| 38212 | aOut[j++] = "0123456789ABCDEF"[c&0xf]; | ||||
| 38213 | }else{ | ||||
| 38214 | /* A sequence of 1 or more zeros is stored as a little-endian | ||||
| 38215 | ** base-26 number using a..z as the digits. So one zero is "b". | ||||
| 38216 | ** Two zeros is "c". 25 zeros is "z", 26 zeros is "ab", 27 is "bb", | ||||
| 38217 | ** and so forth. | ||||
| 38218 | */ | ||||
| 38219 | int k; | ||||
| 38220 | for(k=1; i+k<nData && a[i+k]==0; k++){} | ||||
| 38221 | i += k-1; | ||||
| 38222 | while( k>0 ){ | ||||
| 38223 | aOut[j++] = 'a'+(k%26); | ||||
| 38224 | k /= 26; | ||||
| 38225 | } | ||||
| 38226 | } | ||||
| 38227 | } | ||||
| 38228 | aOut[j] = 0; | ||||
| 38229 | return j; | ||||
| 38230 | } | ||||
| 38231 | |||||
| 38232 | static const signed char kvvfsHexValue[256] = { | ||||
| 38233 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38234 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38235 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38236 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, | ||||
| 38237 | -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38238 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38239 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38240 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38241 | |||||
| 38242 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38243 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38244 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38245 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38246 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38247 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38248 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, | ||||
| 38249 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 | ||||
| 38250 | }; | ||||
| 38251 | |||||
| 38252 | /* | ||||
| 38253 | ** Decode the text encoding back to binary. The binary content is | ||||
| 38254 | ** written into pOut, which must be at least nOut bytes in length. | ||||
| 38255 | ** | ||||
| 38256 | ** The return value is the number of bytes actually written into aOut[]. | ||||
| 38257 | */ | ||||
| 38258 | static int kvvfsDecode(const char *a, char *aOut, int nOut){ | ||||
| 38259 | int i, j; | ||||
| 38260 | int c; | ||||
| 38261 | const unsigned char *aIn = (const unsigned char*)a; | ||||
| 38262 | i = 0; | ||||
| 38263 | j = 0; | ||||
| 38264 | while( 1 ){ | ||||
| 38265 | c = kvvfsHexValue[aIn[i]]; | ||||
| 38266 | if( c<0 ){ | ||||
| 38267 | int n = 0; | ||||
| 38268 | int mult = 1; | ||||
| 38269 | c = aIn[i]; | ||||
| 38270 | if( c==0 ) break; | ||||
| 38271 | while( c>='a' && c<='z' ){ | ||||
| 38272 | n += (c - 'a')*mult; | ||||
| 38273 | mult *= 26; | ||||
| 38274 | c = aIn[++i]; | ||||
| 38275 | } | ||||
| 38276 | if( j+n>nOut ) return -1; | ||||
| 38277 | memset(&aOut[j], 0, n); | ||||
| 38278 | j += n; | ||||
| 38279 | if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */ | ||||
| 38280 | }else{ | ||||
| 38281 | aOut[j] = c<<4; | ||||
| 38282 | c = kvvfsHexValue[aIn[++i]]; | ||||
| 38283 | if( c<0 ) break; | ||||
| 38284 | aOut[j++] += c; | ||||
| 38285 | i++; | ||||
| 38286 | } | ||||
| 38287 | } | ||||
| 38288 | return j; | ||||
| 38289 | } | ||||
| 38290 | |||||
| 38291 | /* | ||||
| 38292 | ** Decode a complete journal file. Allocate space in pFile->aJrnl | ||||
| 38293 | ** and store the decoding there. Or leave pFile->aJrnl set to NULL | ||||
| 38294 | ** if an error is encountered. | ||||
| 38295 | ** | ||||
| 38296 | ** The first few characters of the text encoding will be a little-endian | ||||
| 38297 | ** base-26 number (digits a..z) that is the total number of bytes | ||||
| 38298 | ** in the decoded journal file image. This base-26 number is followed | ||||
| 38299 | ** by a single space, then the encoding of the journal. The space | ||||
| 38300 | ** separator is required to act as a terminator for the base-26 number. | ||||
| 38301 | */ | ||||
| 38302 | static void kvvfsDecodeJournal( | ||||
| 38303 | KVVfsFile *pFile, /* Store decoding in pFile->aJrnl */ | ||||
| 38304 | const char *zTxt, /* Text encoding. Zero-terminated */ | ||||
| 38305 | int nTxt /* Bytes in zTxt, excluding zero terminator */ | ||||
| 38306 | ){ | ||||
| 38307 | unsigned int n = 0; | ||||
| 38308 | int c, i, mult; | ||||
| 38309 | i = 0; | ||||
| 38310 | mult = 1; | ||||
| 38311 | while( (c = zTxt[i++])>='a' && c<='z' ){ | ||||
| 38312 | n += (zTxt[i] - 'a')*mult; | ||||
| 38313 | mult *= 26; | ||||
| 38314 | } | ||||
| 38315 | sqlite3_free(pFile->aJrnl); | ||||
| 38316 | pFile->aJrnl = sqlite3_malloc64( n ); | ||||
| 38317 | if( pFile->aJrnl==0 ){ | ||||
| 38318 | pFile->nJrnl = 0; | ||||
| 38319 | return; | ||||
| 38320 | } | ||||
| 38321 | pFile->nJrnl = n; | ||||
| 38322 | n = kvvfsDecode(zTxt+i, pFile->aJrnl, pFile->nJrnl); | ||||
| 38323 | if( n<pFile->nJrnl ){ | ||||
| 38324 | sqlite3_free(pFile->aJrnl); | ||||
| 38325 | pFile->aJrnl = 0; | ||||
| 38326 | pFile->nJrnl = 0; | ||||
| 38327 | } | ||||
| 38328 | } | ||||
| 38329 | |||||
| 38330 | /* | ||||
| 38331 | ** Read or write the "sz" element, containing the database file size. | ||||
| 38332 | */ | ||||
| 38333 | static sqlite3_int64 kvvfsReadFileSize(KVVfsFile *pFile){ | ||||
| 38334 | char zData[50]; | ||||
| 38335 | zData[0] = 0; | ||||
| 38336 | sqlite3KvvfsMethods.xRead(pFile->zClass, "sz", zData, sizeof(zData)-1); | ||||
| 38337 | return strtoll(zData, 0, 0); | ||||
| 38338 | } | ||||
| 38339 | static int kvvfsWriteFileSize(KVVfsFile *pFile, sqlite3_int64 sz){ | ||||
| 38340 | char zData[50]; | ||||
| 38341 | sqlite3_snprintf(sizeof(zData), zData, "%lld", sz); | ||||
| 38342 | return sqlite3KvvfsMethods.xWrite(pFile->zClass, "sz", zData); | ||||
| 38343 | } | ||||
| 38344 | |||||
| 38345 | /****** sqlite3_io_methods methods ******************************************/ | ||||
| 38346 | |||||
| 38347 | /* | ||||
| 38348 | ** Close an kvvfs-file. | ||||
| 38349 | */ | ||||
| 38350 | static int kvvfsClose(sqlite3_file *pProtoFile){ | ||||
| 38351 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38352 | |||||
| 38353 | SQLITE_KV_LOG(("xClose %s %s\n", pFile->zClass, | ||||
| 38354 | pFile->isJournal ? "journal" : "db")); | ||||
| 38355 | sqlite3_free(pFile->aJrnl); | ||||
| 38356 | sqlite3_free(pFile->aData); | ||||
| 38357 | return SQLITE_OK0; | ||||
| 38358 | } | ||||
| 38359 | |||||
| 38360 | /* | ||||
| 38361 | ** Read from the -journal file. | ||||
| 38362 | */ | ||||
| 38363 | static int kvvfsReadJrnl( | ||||
| 38364 | sqlite3_file *pProtoFile, | ||||
| 38365 | void *zBuf, | ||||
| 38366 | int iAmt, | ||||
| 38367 | sqlite_int64 iOfst | ||||
| 38368 | ){ | ||||
| 38369 | KVVfsFile *pFile = (KVVfsFile*)pProtoFile; | ||||
| 38370 | assert( pFile->isJournal )((void) (0)); | ||||
| 38371 | SQLITE_KV_LOG(("xRead('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); | ||||
| 38372 | if( pFile->aJrnl==0 ){ | ||||
| 38373 | int szTxt = kvstorageRead(pFile->zClass, "jrnl", 0, 0); | ||||
| 38374 | char *aTxt; | ||||
| 38375 | if( szTxt<=4 ){ | ||||
| 38376 | return SQLITE_IOERR10; | ||||
| 38377 | } | ||||
| 38378 | aTxt = sqlite3_malloc64( szTxt+1 ); | ||||
| 38379 | if( aTxt==0 ) return SQLITE_NOMEM7; | ||||
| 38380 | kvstorageRead(pFile->zClass, "jrnl", aTxt, szTxt+1); | ||||
| 38381 | kvvfsDecodeJournal(pFile, aTxt, szTxt); | ||||
| 38382 | sqlite3_free(aTxt); | ||||
| 38383 | if( pFile->aJrnl==0 ) return SQLITE_IOERR10; | ||||
| 38384 | } | ||||
| 38385 | if( iOfst+iAmt>pFile->nJrnl ){ | ||||
| 38386 | return SQLITE_IOERR_SHORT_READ(10 | (2<<8)); | ||||
| 38387 | } | ||||
| 38388 | memcpy(zBuf, pFile->aJrnl+iOfst, iAmt); | ||||
| 38389 | return SQLITE_OK0; | ||||
| 38390 | } | ||||
| 38391 | |||||
| 38392 | /* | ||||
| 38393 | ** Read from the database file. | ||||
| 38394 | */ | ||||
| 38395 | static int kvvfsReadDb( | ||||
| 38396 | sqlite3_file *pProtoFile, | ||||
| 38397 | void *zBuf, | ||||
| 38398 | int iAmt, | ||||
| 38399 | sqlite_int64 iOfst | ||||
| 38400 | ){ | ||||
| 38401 | KVVfsFile *pFile = (KVVfsFile*)pProtoFile; | ||||
| 38402 | unsigned int pgno; | ||||
| 38403 | int got, n; | ||||
| 38404 | char zKey[30]; | ||||
| 38405 | char *aData = pFile->aData; | ||||
| 38406 | assert( iOfst>=0 )((void) (0)); | ||||
| 38407 | assert( iAmt>=0 )((void) (0)); | ||||
| 38408 | SQLITE_KV_LOG(("xRead('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); | ||||
| 38409 | if( iOfst+iAmt>=512 ){ | ||||
| 38410 | if( (iOfst % iAmt)!=0 ){ | ||||
| 38411 | return SQLITE_IOERR_READ(10 | (1<<8)); | ||||
| 38412 | } | ||||
| 38413 | if( (iAmt & (iAmt-1))!=0 || iAmt<512 || iAmt>65536 ){ | ||||
| 38414 | return SQLITE_IOERR_READ(10 | (1<<8)); | ||||
| 38415 | } | ||||
| 38416 | pFile->szPage = iAmt; | ||||
| 38417 | pgno = 1 + iOfst/iAmt; | ||||
| 38418 | }else{ | ||||
| 38419 | pgno = 1; | ||||
| 38420 | } | ||||
| 38421 | sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno); | ||||
| 38422 | got = sqlite3KvvfsMethods.xRead(pFile->zClass, zKey, | ||||
| 38423 | aData, SQLITE_KVOS_SZ-1); | ||||
| 38424 | if( got<0 ){ | ||||
| 38425 | n = 0; | ||||
| 38426 | }else{ | ||||
| 38427 | aData[got] = 0; | ||||
| 38428 | if( iOfst+iAmt<512 ){ | ||||
| 38429 | int k = iOfst+iAmt; | ||||
| 38430 | aData[k*2] = 0; | ||||
| 38431 | n = kvvfsDecode(aData, &aData[2000], SQLITE_KVOS_SZ-2000); | ||||
| 38432 | if( n>=iOfst+iAmt ){ | ||||
| 38433 | memcpy(zBuf, &aData[2000+iOfst], iAmt); | ||||
| 38434 | n = iAmt; | ||||
| 38435 | }else{ | ||||
| 38436 | n = 0; | ||||
| 38437 | } | ||||
| 38438 | }else{ | ||||
| 38439 | n = kvvfsDecode(aData, zBuf, iAmt); | ||||
| 38440 | } | ||||
| 38441 | } | ||||
| 38442 | if( n<iAmt ){ | ||||
| 38443 | memset(zBuf+n, 0, iAmt-n); | ||||
| 38444 | return SQLITE_IOERR_SHORT_READ(10 | (2<<8)); | ||||
| 38445 | } | ||||
| 38446 | return SQLITE_OK0; | ||||
| 38447 | } | ||||
| 38448 | |||||
| 38449 | |||||
| 38450 | /* | ||||
| 38451 | ** Write into the -journal file. | ||||
| 38452 | */ | ||||
| 38453 | static int kvvfsWriteJrnl( | ||||
| 38454 | sqlite3_file *pProtoFile, | ||||
| 38455 | const void *zBuf, | ||||
| 38456 | int iAmt, | ||||
| 38457 | sqlite_int64 iOfst | ||||
| 38458 | ){ | ||||
| 38459 | KVVfsFile *pFile = (KVVfsFile*)pProtoFile; | ||||
| 38460 | sqlite3_int64 iEnd = iOfst+iAmt; | ||||
| 38461 | SQLITE_KV_LOG(("xWrite('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); | ||||
| 38462 | if( iEnd>=0x10000000 ) return SQLITE_FULL13; | ||||
| 38463 | if( pFile->aJrnl==0 || pFile->nJrnl<iEnd ){ | ||||
| 38464 | char *aNew = sqlite3_realloc(pFile->aJrnl, iEnd); | ||||
| 38465 | if( aNew==0 ){ | ||||
| 38466 | return SQLITE_IOERR_NOMEM(10 | (12<<8)); | ||||
| 38467 | } | ||||
| 38468 | pFile->aJrnl = aNew; | ||||
| 38469 | if( pFile->nJrnl<iOfst ){ | ||||
| 38470 | memset(pFile->aJrnl+pFile->nJrnl, 0, iOfst-pFile->nJrnl); | ||||
| 38471 | } | ||||
| 38472 | pFile->nJrnl = iEnd; | ||||
| 38473 | } | ||||
| 38474 | memcpy(pFile->aJrnl+iOfst, zBuf, iAmt); | ||||
| 38475 | return SQLITE_OK0; | ||||
| 38476 | } | ||||
| 38477 | |||||
| 38478 | /* | ||||
| 38479 | ** Write into the database file. | ||||
| 38480 | */ | ||||
| 38481 | static int kvvfsWriteDb( | ||||
| 38482 | sqlite3_file *pProtoFile, | ||||
| 38483 | const void *zBuf, | ||||
| 38484 | int iAmt, | ||||
| 38485 | sqlite_int64 iOfst | ||||
| 38486 | ){ | ||||
| 38487 | KVVfsFile *pFile = (KVVfsFile*)pProtoFile; | ||||
| 38488 | unsigned int pgno; | ||||
| 38489 | char zKey[30]; | ||||
| 38490 | char *aData = pFile->aData; | ||||
| 38491 | SQLITE_KV_LOG(("xWrite('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); | ||||
| 38492 | assert( iAmt>=512 && iAmt<=65536 )((void) (0)); | ||||
| 38493 | assert( (iAmt & (iAmt-1))==0 )((void) (0)); | ||||
| 38494 | assert( pFile->szPage<0 || pFile->szPage==iAmt )((void) (0)); | ||||
| 38495 | pFile->szPage = iAmt; | ||||
| 38496 | pgno = 1 + iOfst/iAmt; | ||||
| 38497 | sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno); | ||||
| 38498 | kvvfsEncode(zBuf, iAmt, aData); | ||||
| 38499 | if( sqlite3KvvfsMethods.xWrite(pFile->zClass, zKey, aData) ){ | ||||
| 38500 | return SQLITE_IOERR10; | ||||
| 38501 | } | ||||
| 38502 | if( iOfst+iAmt > pFile->szDb ){ | ||||
| 38503 | pFile->szDb = iOfst + iAmt; | ||||
| 38504 | } | ||||
| 38505 | return SQLITE_OK0; | ||||
| 38506 | } | ||||
| 38507 | |||||
| 38508 | /* | ||||
| 38509 | ** Truncate an kvvfs-file. | ||||
| 38510 | */ | ||||
| 38511 | static int kvvfsTruncateJrnl(sqlite3_file *pProtoFile, sqlite_int64 size){ | ||||
| 38512 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38513 | SQLITE_KV_LOG(("xTruncate('%s-journal',%lld)\n", pFile->zClass, size)); | ||||
| 38514 | assert( size==0 )((void) (0)); | ||||
| 38515 | sqlite3KvvfsMethods.xDelete(pFile->zClass, "jrnl"); | ||||
| 38516 | sqlite3_free(pFile->aJrnl); | ||||
| 38517 | pFile->aJrnl = 0; | ||||
| 38518 | pFile->nJrnl = 0; | ||||
| 38519 | return SQLITE_OK0; | ||||
| 38520 | } | ||||
| 38521 | static int kvvfsTruncateDb(sqlite3_file *pProtoFile, sqlite_int64 size){ | ||||
| 38522 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38523 | if( pFile->szDb>size | ||||
| 38524 | && pFile->szPage>0 | ||||
| 38525 | && (size % pFile->szPage)==0 | ||||
| 38526 | ){ | ||||
| 38527 | char zKey[50]; | ||||
| 38528 | unsigned int pgno, pgnoMax; | ||||
| 38529 | SQLITE_KV_LOG(("xTruncate('%s-db',%lld)\n", pFile->zClass, size)); | ||||
| 38530 | pgno = 1 + size/pFile->szPage; | ||||
| 38531 | pgnoMax = 2 + pFile->szDb/pFile->szPage; | ||||
| 38532 | while( pgno<=pgnoMax ){ | ||||
| 38533 | sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno); | ||||
| 38534 | sqlite3KvvfsMethods.xDelete(pFile->zClass, zKey); | ||||
| 38535 | pgno++; | ||||
| 38536 | } | ||||
| 38537 | pFile->szDb = size; | ||||
| 38538 | return kvvfsWriteFileSize(pFile, size) ? SQLITE_IOERR10 : SQLITE_OK0; | ||||
| 38539 | } | ||||
| 38540 | return SQLITE_IOERR10; | ||||
| 38541 | } | ||||
| 38542 | |||||
| 38543 | /* | ||||
| 38544 | ** Sync an kvvfs-file. | ||||
| 38545 | */ | ||||
| 38546 | static int kvvfsSyncJrnl(sqlite3_file *pProtoFile, int flags){ | ||||
| 38547 | int i, n; | ||||
| 38548 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38549 | char *zOut; | ||||
| 38550 | SQLITE_KV_LOG(("xSync('%s-journal')\n", pFile->zClass)); | ||||
| 38551 | if( pFile->nJrnl<=0 ){ | ||||
| 38552 | return kvvfsTruncateJrnl(pProtoFile, 0); | ||||
| 38553 | } | ||||
| 38554 | zOut = sqlite3_malloc64( pFile->nJrnl*2 + 50 ); | ||||
| 38555 | if( zOut==0 ){ | ||||
| 38556 | return SQLITE_IOERR_NOMEM(10 | (12<<8)); | ||||
| 38557 | } | ||||
| 38558 | n = pFile->nJrnl; | ||||
| 38559 | i = 0; | ||||
| 38560 | do{ | ||||
| 38561 | zOut[i++] = 'a' + (n%26); | ||||
| 38562 | n /= 26; | ||||
| 38563 | }while( n>0 ); | ||||
| 38564 | zOut[i++] = ' '; | ||||
| 38565 | kvvfsEncode(pFile->aJrnl, pFile->nJrnl, &zOut[i]); | ||||
| 38566 | i = sqlite3KvvfsMethods.xWrite(pFile->zClass, "jrnl", zOut); | ||||
| 38567 | sqlite3_free(zOut); | ||||
| 38568 | return i ? SQLITE_IOERR10 : SQLITE_OK0; | ||||
| 38569 | } | ||||
| 38570 | static int kvvfsSyncDb(sqlite3_file *pProtoFile, int flags){ | ||||
| 38571 | return SQLITE_OK0; | ||||
| 38572 | } | ||||
| 38573 | |||||
| 38574 | /* | ||||
| 38575 | ** Return the current file-size of an kvvfs-file. | ||||
| 38576 | */ | ||||
| 38577 | static int kvvfsFileSizeJrnl(sqlite3_file *pProtoFile, sqlite_int64 *pSize){ | ||||
| 38578 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38579 | SQLITE_KV_LOG(("xFileSize('%s-journal')\n", pFile->zClass)); | ||||
| 38580 | *pSize = pFile->nJrnl; | ||||
| 38581 | return SQLITE_OK0; | ||||
| 38582 | } | ||||
| 38583 | static int kvvfsFileSizeDb(sqlite3_file *pProtoFile, sqlite_int64 *pSize){ | ||||
| 38584 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38585 | SQLITE_KV_LOG(("xFileSize('%s-db')\n", pFile->zClass)); | ||||
| 38586 | if( pFile->szDb>=0 ){ | ||||
| 38587 | *pSize = pFile->szDb; | ||||
| 38588 | }else{ | ||||
| 38589 | *pSize = kvvfsReadFileSize(pFile); | ||||
| 38590 | } | ||||
| 38591 | return SQLITE_OK0; | ||||
| 38592 | } | ||||
| 38593 | |||||
| 38594 | /* | ||||
| 38595 | ** Lock an kvvfs-file. | ||||
| 38596 | */ | ||||
| 38597 | static int kvvfsLock(sqlite3_file *pProtoFile, int eLock){ | ||||
| 38598 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38599 | assert( !pFile->isJournal )((void) (0)); | ||||
| 38600 | SQLITE_KV_LOG(("xLock(%s,%d)\n", pFile->zClass, eLock)); | ||||
| 38601 | |||||
| 38602 | if( eLock!=SQLITE_LOCK_NONE0 ){ | ||||
| 38603 | pFile->szDb = kvvfsReadFileSize(pFile); | ||||
| 38604 | } | ||||
| 38605 | return SQLITE_OK0; | ||||
| 38606 | } | ||||
| 38607 | |||||
| 38608 | /* | ||||
| 38609 | ** Unlock an kvvfs-file. | ||||
| 38610 | */ | ||||
| 38611 | static int kvvfsUnlock(sqlite3_file *pProtoFile, int eLock){ | ||||
| 38612 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38613 | assert( !pFile->isJournal )((void) (0)); | ||||
| 38614 | SQLITE_KV_LOG(("xUnlock(%s,%d)\n", pFile->zClass, eLock)); | ||||
| 38615 | if( eLock==SQLITE_LOCK_NONE0 ){ | ||||
| 38616 | pFile->szDb = -1; | ||||
| 38617 | } | ||||
| 38618 | return SQLITE_OK0; | ||||
| 38619 | } | ||||
| 38620 | |||||
| 38621 | /* | ||||
| 38622 | ** Check if another file-handle holds a RESERVED lock on an kvvfs-file. | ||||
| 38623 | */ | ||||
| 38624 | static int kvvfsCheckReservedLock(sqlite3_file *pProtoFile, int *pResOut){ | ||||
| 38625 | SQLITE_KV_LOG(("xCheckReservedLock\n")); | ||||
| 38626 | *pResOut = 0; | ||||
| 38627 | return SQLITE_OK0; | ||||
| 38628 | } | ||||
| 38629 | |||||
| 38630 | /* | ||||
| 38631 | ** File control method. For custom operations on an kvvfs-file. | ||||
| 38632 | */ | ||||
| 38633 | static int kvvfsFileControlJrnl(sqlite3_file *pProtoFile, int op, void *pArg){ | ||||
| 38634 | SQLITE_KV_LOG(("xFileControl(%d) on journal\n", op)); | ||||
| 38635 | return SQLITE_NOTFOUND12; | ||||
| 38636 | } | ||||
| 38637 | static int kvvfsFileControlDb(sqlite3_file *pProtoFile, int op, void *pArg){ | ||||
| 38638 | SQLITE_KV_LOG(("xFileControl(%d) on database\n", op)); | ||||
| 38639 | if( op==SQLITE_FCNTL_SYNC21 ){ | ||||
| 38640 | KVVfsFile *pFile = (KVVfsFile *)pProtoFile; | ||||
| 38641 | int rc = SQLITE_OK0; | ||||
| 38642 | SQLITE_KV_LOG(("xSync('%s-db')\n", pFile->zClass)); | ||||
| 38643 | if( pFile->szDb>0 && 0!=kvvfsWriteFileSize(pFile, pFile->szDb) ){ | ||||
| 38644 | rc = SQLITE_IOERR10; | ||||
| 38645 | } | ||||
| 38646 | return rc; | ||||
| 38647 | } | ||||
| 38648 | return SQLITE_NOTFOUND12; | ||||
| 38649 | } | ||||
| 38650 | |||||
| 38651 | /* | ||||
| 38652 | ** Return the sector-size in bytes for an kvvfs-file. | ||||
| 38653 | */ | ||||
| 38654 | static int kvvfsSectorSize(sqlite3_file *pFile){ | ||||
| 38655 | return 512; | ||||
| 38656 | } | ||||
| 38657 | |||||
| 38658 | /* | ||||
| 38659 | ** Return the device characteristic flags supported by an kvvfs-file. | ||||
| 38660 | */ | ||||
| 38661 | static int kvvfsDeviceCharacteristics(sqlite3_file *pProtoFile){ | ||||
| 38662 | return 0; | ||||
| 38663 | } | ||||
| 38664 | |||||
| 38665 | /****** sqlite3_vfs methods *************************************************/ | ||||
| 38666 | |||||
| 38667 | /* | ||||
| 38668 | ** Open an kvvfs file handle. | ||||
| 38669 | */ | ||||
| 38670 | static int kvvfsOpen( | ||||
| 38671 | sqlite3_vfs *pProtoVfs, | ||||
| 38672 | const char *zName, | ||||
| 38673 | sqlite3_file *pProtoFile, | ||||
| 38674 | int flags, | ||||
| 38675 | int *pOutFlags | ||||
| 38676 | ){ | ||||
| 38677 | KVVfsFile *pFile = (KVVfsFile*)pProtoFile; | ||||
| 38678 | if( zName==0 ) zName = ""; | ||||
| 38679 | SQLITE_KV_LOG(("xOpen(\"%s\")\n", zName)); | ||||
| 38680 | if( strcmp(zName, "local")==0 | ||||
| 38681 | || strcmp(zName, "session")==0 | ||||
| 38682 | ){ | ||||
| 38683 | pFile->isJournal = 0; | ||||
| 38684 | pFile->base.pMethods = &kvvfs_db_io_methods; | ||||
| 38685 | }else | ||||
| 38686 | if( strcmp(zName, "local-journal")==0 | ||||
| 38687 | || strcmp(zName, "session-journal")==0 | ||||
| 38688 | ){ | ||||
| 38689 | pFile->isJournal = 1; | ||||
| 38690 | pFile->base.pMethods = &kvvfs_jrnl_io_methods; | ||||
| 38691 | }else{ | ||||
| 38692 | return SQLITE_CANTOPEN14; | ||||
| 38693 | } | ||||
| 38694 | if( zName[0]=='s' ){ | ||||
| 38695 | pFile->zClass = "session"; | ||||
| 38696 | }else{ | ||||
| 38697 | pFile->zClass = "local"; | ||||
| 38698 | } | ||||
| 38699 | pFile->aData = sqlite3_malloc64(SQLITE_KVOS_SZ); | ||||
| 38700 | if( pFile->aData==0 ){ | ||||
| 38701 | return SQLITE_NOMEM7; | ||||
| 38702 | } | ||||
| 38703 | pFile->aJrnl = 0; | ||||
| 38704 | pFile->nJrnl = 0; | ||||
| 38705 | pFile->szPage = -1; | ||||
| 38706 | pFile->szDb = -1; | ||||
| 38707 | return SQLITE_OK0; | ||||
| 38708 | } | ||||
| 38709 | |||||
| 38710 | /* | ||||
| 38711 | ** Delete the file located at zPath. If the dirSync argument is true, | ||||
| 38712 | ** ensure the file-system modifications are synced to disk before | ||||
| 38713 | ** returning. | ||||
| 38714 | */ | ||||
| 38715 | static int kvvfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ | ||||
| 38716 | if( strcmp(zPath, "local-journal")==0 ){ | ||||
| 38717 | sqlite3KvvfsMethods.xDelete("local", "jrnl"); | ||||
| 38718 | }else | ||||
| 38719 | if( strcmp(zPath, "session-journal")==0 ){ | ||||
| 38720 | sqlite3KvvfsMethods.xDelete("session", "jrnl"); | ||||
| 38721 | } | ||||
| 38722 | return SQLITE_OK0; | ||||
| 38723 | } | ||||
| 38724 | |||||
| 38725 | /* | ||||
| 38726 | ** Test for access permissions. Return true if the requested permission | ||||
| 38727 | ** is available, or false otherwise. | ||||
| 38728 | */ | ||||
| 38729 | static int kvvfsAccess( | ||||
| 38730 | sqlite3_vfs *pProtoVfs, | ||||
| 38731 | const char *zPath, | ||||
| 38732 | int flags, | ||||
| 38733 | int *pResOut | ||||
| 38734 | ){ | ||||
| 38735 | SQLITE_KV_LOG(("xAccess(\"%s\")\n", zPath)); | ||||
| 38736 | if( strcmp(zPath, "local-journal")==0 ){ | ||||
| 38737 | *pResOut = sqlite3KvvfsMethods.xRead("local", "jrnl", 0, 0)>0; | ||||
| 38738 | }else | ||||
| 38739 | if( strcmp(zPath, "session-journal")==0 ){ | ||||
| 38740 | *pResOut = sqlite3KvvfsMethods.xRead("session", "jrnl", 0, 0)>0; | ||||
| 38741 | }else | ||||
| 38742 | if( strcmp(zPath, "local")==0 ){ | ||||
| 38743 | *pResOut = sqlite3KvvfsMethods.xRead("local", "sz", 0, 0)>0; | ||||
| 38744 | }else | ||||
| 38745 | if( strcmp(zPath, "session")==0 ){ | ||||
| 38746 | *pResOut = sqlite3KvvfsMethods.xRead("session", "sz", 0, 0)>0; | ||||
| 38747 | }else | ||||
| 38748 | { | ||||
| 38749 | *pResOut = 0; | ||||
| 38750 | } | ||||
| 38751 | SQLITE_KV_LOG(("xAccess returns %d\n",*pResOut)); | ||||
| 38752 | return SQLITE_OK0; | ||||
| 38753 | } | ||||
| 38754 | |||||
| 38755 | /* | ||||
| 38756 | ** Populate buffer zOut with the full canonical pathname corresponding | ||||
| 38757 | ** to the pathname in zPath. zOut is guaranteed to point to a buffer | ||||
| 38758 | ** of at least (INST_MAX_PATHNAME+1) bytes. | ||||
| 38759 | */ | ||||
| 38760 | static int kvvfsFullPathname( | ||||
| 38761 | sqlite3_vfs *pVfs, | ||||
| 38762 | const char *zPath, | ||||
| 38763 | int nOut, | ||||
| 38764 | char *zOut | ||||
| 38765 | ){ | ||||
| 38766 | size_t nPath; | ||||
| 38767 | #ifdef SQLITE_OS_KV_ALWAYS_LOCAL | ||||
| 38768 | zPath = "local"; | ||||
| 38769 | #endif | ||||
| 38770 | nPath = strlen(zPath); | ||||
| 38771 | SQLITE_KV_LOG(("xFullPathname(\"%s\")\n", zPath)); | ||||
| 38772 | if( nOut<nPath+1 ) nPath = nOut - 1; | ||||
| 38773 | memcpy(zOut, zPath, nPath); | ||||
| 38774 | zOut[nPath] = 0; | ||||
| 38775 | return SQLITE_OK0; | ||||
| 38776 | } | ||||
| 38777 | |||||
| 38778 | /* | ||||
| 38779 | ** Open the dynamic library located at zPath and return a handle. | ||||
| 38780 | */ | ||||
| 38781 | static void *kvvfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ | ||||
| 38782 | return 0; | ||||
| 38783 | } | ||||
| 38784 | |||||
| 38785 | /* | ||||
| 38786 | ** Populate the buffer pointed to by zBufOut with nByte bytes of | ||||
| 38787 | ** random data. | ||||
| 38788 | */ | ||||
| 38789 | static int kvvfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ | ||||
| 38790 | memset(zBufOut, 0, nByte); | ||||
| 38791 | return nByte; | ||||
| 38792 | } | ||||
| 38793 | |||||
| 38794 | /* | ||||
| 38795 | ** Sleep for nMicro microseconds. Return the number of microseconds | ||||
| 38796 | ** actually slept. | ||||
| 38797 | */ | ||||
| 38798 | static int kvvfsSleep(sqlite3_vfs *pVfs, int nMicro){ | ||||
| 38799 | return SQLITE_OK0; | ||||
| 38800 | } | ||||
| 38801 | |||||
| 38802 | /* | ||||
| 38803 | ** Return the current time as a Julian Day number in *pTimeOut. | ||||
| 38804 | */ | ||||
| 38805 | static int kvvfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ | ||||
| 38806 | sqlite3_int64 i = 0; | ||||
| 38807 | int rc; | ||||
| 38808 | rc = kvvfsCurrentTimeInt64(0, &i); | ||||
| 38809 | *pTimeOut = i/86400000.0; | ||||
| 38810 | return rc; | ||||
| 38811 | } | ||||
| 38812 | #include <sys/time.h> | ||||
| 38813 | static int kvvfsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ | ||||
| 38814 | static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; | ||||
| 38815 | struct timeval sNow; | ||||
| 38816 | (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */ | ||||
| 38817 | *pTimeOut = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; | ||||
| 38818 | return SQLITE_OK0; | ||||
| 38819 | } | ||||
| 38820 | #endif /* SQLITE_OS_KV || SQLITE_OS_UNIX */ | ||||
| 38821 | |||||
| 38822 | #if SQLITE_OS_KV0 | ||||
| 38823 | /* | ||||
| 38824 | ** This routine is called initialize the KV-vfs as the default VFS. | ||||
| 38825 | */ | ||||
| 38826 | SQLITE_API int sqlite3_os_init(void){ | ||||
| 38827 | return sqlite3_vfs_register(&sqlite3OsKvvfsObject, 1); | ||||
| 38828 | } | ||||
| 38829 | SQLITE_API int sqlite3_os_end(void){ | ||||
| 38830 | return SQLITE_OK0; | ||||
| 38831 | } | ||||
| 38832 | #endif /* SQLITE_OS_KV */ | ||||
| 38833 | |||||
| 38834 | #if SQLITE_OS_UNIX1 && defined(SQLITE_OS_KV_OPTIONAL) | ||||
| 38835 | SQLITE_PRIVATEstatic int sqlite3KvvfsInit(void){ | ||||
| 38836 | return sqlite3_vfs_register(&sqlite3OsKvvfsObject, 0); | ||||
| 38837 | } | ||||
| 38838 | #endif | ||||
| 38839 | |||||
| 38840 | /************** End of os_kv.c ***********************************************/ | ||||
| 38841 | /************** Begin file os_unix.c *****************************************/ | ||||
| 38842 | /* | ||||
| 38843 | ** 2004 May 22 | ||||
| 38844 | ** | ||||
| 38845 | ** The author disclaims copyright to this source code. In place of | ||||
| 38846 | ** a legal notice, here is a blessing: | ||||
| 38847 | ** | ||||
| 38848 | ** May you do good and not evil. | ||||
| 38849 | ** May you find forgiveness for yourself and forgive others. | ||||
| 38850 | ** May you share freely, never taking more than you give. | ||||
| 38851 | ** | ||||
| 38852 | ****************************************************************************** | ||||
| 38853 | ** | ||||
| 38854 | ** This file contains the VFS implementation for unix-like operating systems | ||||
| 38855 | ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others. | ||||
| 38856 | ** | ||||
| 38857 | ** There are actually several different VFS implementations in this file. | ||||
| 38858 | ** The differences are in the way that file locking is done. The default | ||||
| 38859 | ** implementation uses Posix Advisory Locks. Alternative implementations | ||||
| 38860 | ** use flock(), dot-files, various proprietary locking schemas, or simply | ||||
| 38861 | ** skip locking all together. | ||||
| 38862 | ** | ||||
| 38863 | ** This source file is organized into divisions where the logic for various | ||||
| 38864 | ** subfunctions is contained within the appropriate division. PLEASE | ||||
| 38865 | ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed | ||||
| 38866 | ** in the correct division and should be clearly labelled. | ||||
| 38867 | ** | ||||
| 38868 | ** The layout of divisions is as follows: | ||||
| 38869 | ** | ||||
| 38870 | ** * General-purpose declarations and utility functions. | ||||
| 38871 | ** * Unique file ID logic used by VxWorks. | ||||
| 38872 | ** * Various locking primitive implementations (all except proxy locking): | ||||
| 38873 | ** + for Posix Advisory Locks | ||||
| 38874 | ** + for no-op locks | ||||
| 38875 | ** + for dot-file locks | ||||
| 38876 | ** + for flock() locking | ||||
| 38877 | ** + for named semaphore locks (VxWorks only) | ||||
| 38878 | ** + for AFP filesystem locks (MacOSX only) | ||||
| 38879 | ** * sqlite3_file methods not associated with locking. | ||||
| 38880 | ** * Definitions of sqlite3_io_methods objects for all locking | ||||
| 38881 | ** methods plus "finder" functions for each locking method. | ||||
| 38882 | ** * sqlite3_vfs method implementations. | ||||
| 38883 | ** * Locking primitives for the proxy uber-locking-method. (MacOSX only) | ||||
| 38884 | ** * Definitions of sqlite3_vfs objects for all locking methods | ||||
| 38885 | ** plus implementations of sqlite3_os_init() and sqlite3_os_end(). | ||||
| 38886 | */ | ||||
| 38887 | /* #include "sqliteInt.h" */ | ||||
| 38888 | #if SQLITE_OS_UNIX1 /* This file is used on unix only */ | ||||
| 38889 | |||||
| 38890 | /* | ||||
| 38891 | ** There are various methods for file locking used for concurrency | ||||
| 38892 | ** control: | ||||
| 38893 | ** | ||||
| 38894 | ** 1. POSIX locking (the default), | ||||
| 38895 | ** 2. No locking, | ||||
| 38896 | ** 3. Dot-file locking, | ||||
| 38897 | ** 4. flock() locking, | ||||
| 38898 | ** 5. AFP locking (OSX only), | ||||
| 38899 | ** 6. Named POSIX semaphores (VXWorks only), | ||||
| 38900 | ** 7. proxy locking. (OSX only) | ||||
| 38901 | ** | ||||
| 38902 | ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE | ||||
| 38903 | ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic | ||||
| 38904 | ** selection of the appropriate locking style based on the filesystem | ||||
| 38905 | ** where the database is located. | ||||
| 38906 | */ | ||||
| 38907 | #if !defined(SQLITE_ENABLE_LOCKING_STYLE0) | ||||
| 38908 | # if defined(__APPLE__) | ||||
| 38909 | # define SQLITE_ENABLE_LOCKING_STYLE0 1 | ||||
| 38910 | # else | ||||
| 38911 | # define SQLITE_ENABLE_LOCKING_STYLE0 0 | ||||
| 38912 | # endif | ||||
| 38913 | #endif | ||||
| 38914 | |||||
| 38915 | /* Use pread() and pwrite() if they are available */ | ||||
| 38916 | #if defined(__APPLE__) || defined(__linux__1) | ||||
| 38917 | # define HAVE_PREAD1 1 | ||||
| 38918 | # define HAVE_PWRITE1 1 | ||||
| 38919 | #endif | ||||
| 38920 | #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64) | ||||
| 38921 | # undef USE_PREAD1 | ||||
| 38922 | # define USE_PREAD64 1 | ||||
| 38923 | #elif defined(HAVE_PREAD1) && defined(HAVE_PWRITE1) | ||||
| 38924 | # undef USE_PREAD64 | ||||
| 38925 | # define USE_PREAD1 1 | ||||
| 38926 | #endif | ||||
| 38927 | |||||
| 38928 | /* | ||||
| 38929 | ** standard include files. | ||||
| 38930 | */ | ||||
| 38931 | #include <sys/types.h> /* amalgamator: keep */ | ||||
| 38932 | #include <sys/stat.h> /* amalgamator: keep */ | ||||
| 38933 | #include <fcntl.h> | ||||
| 38934 | #include <sys/ioctl.h> | ||||
| 38935 | #include <unistd.h> /* amalgamator: keep */ | ||||
| 38936 | /* #include <time.h> */ | ||||
| 38937 | #include <sys/time.h> /* amalgamator: keep */ | ||||
| 38938 | #include <errno(*__errno_location ()).h> | ||||
| 38939 | #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) \ | ||||
| 38940 | && !defined(SQLITE_WASI) | ||||
| 38941 | # include <sys/mman.h> | ||||
| 38942 | #endif | ||||
| 38943 | |||||
| 38944 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 38945 | /* # include <sys/ioctl.h> */ | ||||
| 38946 | # include <sys/file.h> | ||||
| 38947 | # include <sys/param.h> | ||||
| 38948 | #endif /* SQLITE_ENABLE_LOCKING_STYLE */ | ||||
| 38949 | |||||
| 38950 | /* | ||||
| 38951 | ** Try to determine if gethostuuid() is available based on standard | ||||
| 38952 | ** macros. This might sometimes compute the wrong value for some | ||||
| 38953 | ** obscure platforms. For those cases, simply compile with one of | ||||
| 38954 | ** the following: | ||||
| 38955 | ** | ||||
| 38956 | ** -DHAVE_GETHOSTUUID=0 | ||||
| 38957 | ** -DHAVE_GETHOSTUUID=1 | ||||
| 38958 | ** | ||||
| 38959 | ** None if this matters except when building on Apple products with | ||||
| 38960 | ** -DSQLITE_ENABLE_LOCKING_STYLE. | ||||
| 38961 | */ | ||||
| 38962 | #ifndef HAVE_GETHOSTUUID0 | ||||
| 38963 | # define HAVE_GETHOSTUUID0 0 | ||||
| 38964 | # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \ | ||||
| 38965 | (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000)) | ||||
| 38966 | # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \ | ||||
| 38967 | && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\ | ||||
| 38968 | && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0)) | ||||
| 38969 | # undef HAVE_GETHOSTUUID0 | ||||
| 38970 | # define HAVE_GETHOSTUUID0 1 | ||||
| 38971 | # else | ||||
| 38972 | # warning "gethostuuid() is disabled." | ||||
| 38973 | # endif | ||||
| 38974 | # endif | ||||
| 38975 | #endif | ||||
| 38976 | |||||
| 38977 | |||||
| 38978 | #if OS_VXWORKS0 | ||||
| 38979 | /* # include <sys/ioctl.h> */ | ||||
| 38980 | # include <semaphore.h> | ||||
| 38981 | # include <limits.h> | ||||
| 38982 | #endif /* OS_VXWORKS */ | ||||
| 38983 | |||||
| 38984 | #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 38985 | # include <sys/mount.h> | ||||
| 38986 | #endif | ||||
| 38987 | |||||
| 38988 | #ifdef HAVE_UTIME | ||||
| 38989 | # include <utime.h> | ||||
| 38990 | #endif | ||||
| 38991 | |||||
| 38992 | /* | ||||
| 38993 | ** Allowed values of unixFile.fsFlags | ||||
| 38994 | */ | ||||
| 38995 | #define SQLITE_FSFLAGS_IS_MSDOS0x1 0x1 | ||||
| 38996 | |||||
| 38997 | /* | ||||
| 38998 | ** If we are to be thread-safe, include the pthreads header. | ||||
| 38999 | */ | ||||
| 39000 | #if SQLITE_THREADSAFE2 | ||||
| 39001 | /* # include <pthread.h> */ | ||||
| 39002 | #endif | ||||
| 39003 | |||||
| 39004 | /* | ||||
| 39005 | ** Default permissions when creating a new file | ||||
| 39006 | */ | ||||
| 39007 | #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS0644 | ||||
| 39008 | # define SQLITE_DEFAULT_FILE_PERMISSIONS0644 0644 | ||||
| 39009 | #endif | ||||
| 39010 | |||||
| 39011 | /* | ||||
| 39012 | ** Default permissions when creating auto proxy dir | ||||
| 39013 | */ | ||||
| 39014 | #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS0755 | ||||
| 39015 | # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS0755 0755 | ||||
| 39016 | #endif | ||||
| 39017 | |||||
| 39018 | /* | ||||
| 39019 | ** Maximum supported path-length. | ||||
| 39020 | */ | ||||
| 39021 | #define MAX_PATHNAME512 512 | ||||
| 39022 | |||||
| 39023 | /* | ||||
| 39024 | ** Maximum supported symbolic links | ||||
| 39025 | */ | ||||
| 39026 | #define SQLITE_MAX_SYMLINKS100 100 | ||||
| 39027 | |||||
| 39028 | /* | ||||
| 39029 | ** Remove and stub certain info for WASI (WebAssembly System | ||||
| 39030 | ** Interface) builds. | ||||
| 39031 | */ | ||||
| 39032 | #ifdef SQLITE_WASI | ||||
| 39033 | # undef HAVE_FCHMOD1 | ||||
| 39034 | # undef HAVE_FCHOWN1 | ||||
| 39035 | # undef HAVE_MREMAP1 | ||||
| 39036 | # define HAVE_MREMAP1 0 | ||||
| 39037 | # ifndef SQLITE_DEFAULT_UNIX_VFS | ||||
| 39038 | # define SQLITE_DEFAULT_UNIX_VFS "unix-dotfile" | ||||
| 39039 | /* ^^^ should SQLITE_DEFAULT_UNIX_VFS be "unix-none"? */ | ||||
| 39040 | # endif | ||||
| 39041 | # ifndef F_RDLCK0 | ||||
| 39042 | # define F_RDLCK0 0 | ||||
| 39043 | # define F_WRLCK1 1 | ||||
| 39044 | # define F_UNLCK2 2 | ||||
| 39045 | # if __LONG_MAX == 0x7fffffffL | ||||
| 39046 | # define F_GETLK5 12 | ||||
| 39047 | # define F_SETLK6 13 | ||||
| 39048 | # define F_SETLKW7 14 | ||||
| 39049 | # else | ||||
| 39050 | # define F_GETLK5 5 | ||||
| 39051 | # define F_SETLK6 6 | ||||
| 39052 | # define F_SETLKW7 7 | ||||
| 39053 | # endif | ||||
| 39054 | # endif | ||||
| 39055 | #else /* !SQLITE_WASI */ | ||||
| 39056 | # ifndef HAVE_FCHMOD1 | ||||
| 39057 | # define HAVE_FCHMOD1 1 | ||||
| 39058 | # endif | ||||
| 39059 | #endif /* SQLITE_WASI */ | ||||
| 39060 | |||||
| 39061 | #ifdef SQLITE_WASI | ||||
| 39062 | # define osGetpid(X)(pid_t)getpid() (pid_t)1 | ||||
| 39063 | #else | ||||
| 39064 | /* Always cast the getpid() return type for compatibility with | ||||
| 39065 | ** kernel modules in VxWorks. */ | ||||
| 39066 | # define osGetpid(X)(pid_t)getpid() (pid_t)getpid() | ||||
| 39067 | #endif | ||||
| 39068 | |||||
| 39069 | /* | ||||
| 39070 | ** Only set the lastErrno if the error code is a real error and not | ||||
| 39071 | ** a normal expected return code of SQLITE_BUSY or SQLITE_OK | ||||
| 39072 | */ | ||||
| 39073 | #define IS_LOCK_ERROR(x)((x != 0) && (x != 5)) ((x != SQLITE_OK0) && (x != SQLITE_BUSY5)) | ||||
| 39074 | |||||
| 39075 | /* Forward references */ | ||||
| 39076 | typedef struct unixShm unixShm; /* Connection shared memory */ | ||||
| 39077 | typedef struct unixShmNode unixShmNode; /* Shared memory instance */ | ||||
| 39078 | typedef struct unixInodeInfo unixInodeInfo; /* An i-node */ | ||||
| 39079 | typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */ | ||||
| 39080 | |||||
| 39081 | /* | ||||
| 39082 | ** Sometimes, after a file handle is closed by SQLite, the file descriptor | ||||
| 39083 | ** cannot be closed immediately. In these cases, instances of the following | ||||
| 39084 | ** structure are used to store the file descriptor while waiting for an | ||||
| 39085 | ** opportunity to either close or reuse it. | ||||
| 39086 | */ | ||||
| 39087 | struct UnixUnusedFd { | ||||
| 39088 | int fd; /* File descriptor to close */ | ||||
| 39089 | int flags; /* Flags this file descriptor was opened with */ | ||||
| 39090 | UnixUnusedFd *pNext; /* Next unused file descriptor on same file */ | ||||
| 39091 | }; | ||||
| 39092 | |||||
| 39093 | /* | ||||
| 39094 | ** The unixFile structure is subclass of sqlite3_file specific to the unix | ||||
| 39095 | ** VFS implementations. | ||||
| 39096 | */ | ||||
| 39097 | typedef struct unixFile unixFile; | ||||
| 39098 | struct unixFile { | ||||
| 39099 | sqlite3_io_methods const *pMethod; /* Always the first entry */ | ||||
| 39100 | sqlite3_vfs *pVfs; /* The VFS that created this unixFile */ | ||||
| 39101 | unixInodeInfo *pInode; /* Info about locks on this inode */ | ||||
| 39102 | int h; /* The file descriptor */ | ||||
| 39103 | unsigned char eFileLock; /* The type of lock held on this fd */ | ||||
| 39104 | unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */ | ||||
| 39105 | int lastErrno; /* The unix errno from last I/O error */ | ||||
| 39106 | void *lockingContext; /* Locking style specific state */ | ||||
| 39107 | UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */ | ||||
| 39108 | const char *zPath; /* Name of the file */ | ||||
| 39109 | unixShm *pShm; /* Shared memory segment information */ | ||||
| 39110 | int szChunk; /* Configured by FCNTL_CHUNK_SIZE */ | ||||
| 39111 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 39112 | int nFetchOut; /* Number of outstanding xFetch refs */ | ||||
| 39113 | sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */ | ||||
| 39114 | sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */ | ||||
| 39115 | sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ | ||||
| 39116 | void *pMapRegion; /* Memory mapped region */ | ||||
| 39117 | #endif | ||||
| 39118 | int sectorSize; /* Device sector size */ | ||||
| 39119 | int deviceCharacteristics; /* Precomputed device characteristics */ | ||||
| 39120 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 39121 | int openFlags; /* The flags specified at open() */ | ||||
| 39122 | #endif | ||||
| 39123 | #if SQLITE_ENABLE_LOCKING_STYLE0 || defined(__APPLE__) | ||||
| 39124 | unsigned fsFlags; /* cached details from statfs() */ | ||||
| 39125 | #endif | ||||
| 39126 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 39127 | unsigned iBusyTimeout; /* Wait this many millisec on locks */ | ||||
| 39128 | int bBlockOnConnect; /* True to block for SHARED locks */ | ||||
| 39129 | #endif | ||||
| 39130 | #if OS_VXWORKS0 | ||||
| 39131 | struct vxworksFileId *pId; /* Unique file ID */ | ||||
| 39132 | #endif | ||||
| 39133 | #ifdef SQLITE_DEBUG | ||||
| 39134 | /* The next group of variables are used to track whether or not the | ||||
| 39135 | ** transaction counter in bytes 24-27 of database files are updated | ||||
| 39136 | ** whenever any part of the database changes. An assertion fault will | ||||
| 39137 | ** occur if a file is updated without also updating the transaction | ||||
| 39138 | ** counter. This test is made to avoid new problems similar to the | ||||
| 39139 | ** one described by ticket #3584. | ||||
| 39140 | */ | ||||
| 39141 | unsigned char transCntrChng; /* True if the transaction counter changed */ | ||||
| 39142 | unsigned char dbUpdate; /* True if any part of database file changed */ | ||||
| 39143 | unsigned char inNormalWrite; /* True if in a normal write operation */ | ||||
| 39144 | |||||
| 39145 | #endif | ||||
| 39146 | |||||
| 39147 | #ifdef SQLITE_TEST | ||||
| 39148 | /* In test mode, increase the size of this structure a bit so that | ||||
| 39149 | ** it is larger than the struct CrashFile defined in test6.c. | ||||
| 39150 | */ | ||||
| 39151 | char aPadding[32]; | ||||
| 39152 | #endif | ||||
| 39153 | }; | ||||
| 39154 | |||||
| 39155 | /* This variable holds the process id (pid) from when the xRandomness() | ||||
| 39156 | ** method was called. If xOpen() is called from a different process id, | ||||
| 39157 | ** indicating that a fork() has occurred, the PRNG will be reset. | ||||
| 39158 | */ | ||||
| 39159 | static pid_t randomnessPid = 0; | ||||
| 39160 | |||||
| 39161 | /* | ||||
| 39162 | ** Allowed values for the unixFile.ctrlFlags bitmask: | ||||
| 39163 | */ | ||||
| 39164 | #define UNIXFILE_EXCL0x01 0x01 /* Connections from one process only */ | ||||
| 39165 | #define UNIXFILE_RDONLY0x02 0x02 /* Connection is read only */ | ||||
| 39166 | #define UNIXFILE_PERSIST_WAL0x04 0x04 /* Persistent WAL mode */ | ||||
| 39167 | #if !defined(SQLITE_DISABLE_DIRSYNC) && !defined(_AIX) | ||||
| 39168 | # define UNIXFILE_DIRSYNC0x08 0x08 /* Directory sync needed */ | ||||
| 39169 | #else | ||||
| 39170 | # define UNIXFILE_DIRSYNC0x08 0x00 | ||||
| 39171 | #endif | ||||
| 39172 | #define UNIXFILE_PSOW0x10 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ | ||||
| 39173 | #define UNIXFILE_DELETE0x20 0x20 /* Delete on close */ | ||||
| 39174 | #define UNIXFILE_URI0x40 0x40 /* Filename might have query parameters */ | ||||
| 39175 | #define UNIXFILE_NOLOCK0x80 0x80 /* Do no file locking */ | ||||
| 39176 | |||||
| 39177 | /* | ||||
| 39178 | ** Include code that is common to all os_*.c files | ||||
| 39179 | */ | ||||
| 39180 | /* #include "os_common.h" */ | ||||
| 39181 | |||||
| 39182 | /* | ||||
| 39183 | ** Define various macros that are missing from some systems. | ||||
| 39184 | */ | ||||
| 39185 | #ifndef O_LARGEFILE0 | ||||
| 39186 | # define O_LARGEFILE0 0 | ||||
| 39187 | #endif | ||||
| 39188 | #ifdef SQLITE_DISABLE_LFS | ||||
| 39189 | # undef O_LARGEFILE0 | ||||
| 39190 | # define O_LARGEFILE0 0 | ||||
| 39191 | #endif | ||||
| 39192 | #ifndef O_NOFOLLOW0400000 | ||||
| 39193 | # define O_NOFOLLOW0400000 0 | ||||
| 39194 | #endif | ||||
| 39195 | #ifndef O_BINARY0 | ||||
| 39196 | # define O_BINARY0 0 | ||||
| 39197 | #endif | ||||
| 39198 | |||||
| 39199 | /* | ||||
| 39200 | ** The threadid macro resolves to the thread-id or to 0. Used for | ||||
| 39201 | ** testing and debugging only. | ||||
| 39202 | */ | ||||
| 39203 | #if SQLITE_THREADSAFE2 | ||||
| 39204 | #define threadidpthread_self() pthread_self() | ||||
| 39205 | #else | ||||
| 39206 | #define threadidpthread_self() 0 | ||||
| 39207 | #endif | ||||
| 39208 | |||||
| 39209 | /* | ||||
| 39210 | ** HAVE_MREMAP defaults to true on Linux and false everywhere else. | ||||
| 39211 | */ | ||||
| 39212 | #if !defined(HAVE_MREMAP1) | ||||
| 39213 | # if defined(__linux__1) && defined(_GNU_SOURCE) | ||||
| 39214 | # define HAVE_MREMAP1 1 | ||||
| 39215 | # else | ||||
| 39216 | # define HAVE_MREMAP1 0 | ||||
| 39217 | # endif | ||||
| 39218 | #endif | ||||
| 39219 | |||||
| 39220 | /* | ||||
| 39221 | ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek() | ||||
| 39222 | ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined. | ||||
| 39223 | */ | ||||
| 39224 | #ifdef __ANDROID__ | ||||
| 39225 | # define lseek lseek64 | ||||
| 39226 | #endif | ||||
| 39227 | |||||
| 39228 | #ifdef __linux__1 | ||||
| 39229 | /* | ||||
| 39230 | ** Linux-specific IOCTL magic numbers used for controlling F2FS | ||||
| 39231 | */ | ||||
| 39232 | #define F2FS_IOCTL_MAGIC0xf5 0xf5 | ||||
| 39233 | #define F2FS_IOC_START_ATOMIC_WRITE(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((1)) << 0) | ((0) << ((0 +8)+8))) _IO(F2FS_IOCTL_MAGIC, 1)(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((1)) << 0) | ((0) << ((0 +8)+8))) | ||||
| 39234 | #define F2FS_IOC_COMMIT_ATOMIC_WRITE(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((2)) << 0) | ((0) << ((0 +8)+8))) _IO(F2FS_IOCTL_MAGIC, 2)(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((2)) << 0) | ((0) << ((0 +8)+8))) | ||||
| 39235 | #define F2FS_IOC_START_VOLATILE_WRITE(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((3)) << 0) | ((0) << ((0 +8)+8))) _IO(F2FS_IOCTL_MAGIC, 3)(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((3)) << 0) | ((0) << ((0 +8)+8))) | ||||
| 39236 | #define F2FS_IOC_ABORT_VOLATILE_WRITE(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((5)) << 0) | ((0) << ((0 +8)+8))) _IO(F2FS_IOCTL_MAGIC, 5)(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((5)) << 0) | ((0) << ((0 +8)+8))) | ||||
| 39237 | #define F2FS_IOC_GET_FEATURES(((2U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((12)) << 0) | ((((sizeof(u32)))) << ((0 +8)+ 8))) _IOR(F2FS_IOCTL_MAGIC, 12, u32)(((2U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((12)) << 0) | ((((sizeof(u32)))) << ((0 +8)+ 8))) | ||||
| 39238 | #define F2FS_FEATURE_ATOMIC_WRITE0x0004 0x0004 | ||||
| 39239 | #endif /* __linux__ */ | ||||
| 39240 | |||||
| 39241 | |||||
| 39242 | /* | ||||
| 39243 | ** Different Unix systems declare open() in different ways. Same use | ||||
| 39244 | ** open(const char*,int,mode_t). Others use open(const char*,int,...). | ||||
| 39245 | ** The difference is important when using a pointer to the function. | ||||
| 39246 | ** | ||||
| 39247 | ** The safest way to deal with the problem is to always use this wrapper | ||||
| 39248 | ** which always has the same well-defined interface. | ||||
| 39249 | */ | ||||
| 39250 | static int posixOpen(const char *zFile, int flags, int mode){ | ||||
| 39251 | return open(zFile, flags, mode); | ||||
| 39252 | } | ||||
| 39253 | |||||
| 39254 | /* Forward reference */ | ||||
| 39255 | static int openDirectory(const char*, int*); | ||||
| 39256 | static int unixGetpagesize(void); | ||||
| 39257 | |||||
| 39258 | /* | ||||
| 39259 | ** Many system calls are accessed through pointer-to-functions so that | ||||
| 39260 | ** they may be overridden at runtime to facilitate fault injection during | ||||
| 39261 | ** testing and sandboxing. The following array holds the names and pointers | ||||
| 39262 | ** to all overrideable system calls. | ||||
| 39263 | */ | ||||
| 39264 | static struct unix_syscall { | ||||
| 39265 | const char *zName; /* Name of the system call */ | ||||
| 39266 | sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ | ||||
| 39267 | sqlite3_syscall_ptr pDefault; /* Default value */ | ||||
| 39268 | } aSyscall[] = { | ||||
| 39269 | { "open", (sqlite3_syscall_ptr)posixOpen, 0 }, | ||||
| 39270 | #define osOpen((int(*)(const char*,int,int))aSyscall[0].pCurrent) ((int(*)(const char*,int,int))aSyscall[0].pCurrent) | ||||
| 39271 | |||||
| 39272 | { "close", (sqlite3_syscall_ptr)close, 0 }, | ||||
| 39273 | #define osClose((int(*)(int))aSyscall[1].pCurrent) ((int(*)(int))aSyscall[1].pCurrent) | ||||
| 39274 | |||||
| 39275 | { "access", (sqlite3_syscall_ptr)access, 0 }, | ||||
| 39276 | #define osAccess((int(*)(const char*,int))aSyscall[2].pCurrent) ((int(*)(const char*,int))aSyscall[2].pCurrent) | ||||
| 39277 | |||||
| 39278 | { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, | ||||
| 39279 | #define osGetcwd((char*(*)(char*,size_t))aSyscall[3].pCurrent) ((char*(*)(char*,size_t))aSyscall[3].pCurrent) | ||||
| 39280 | |||||
| 39281 | { "stat", (sqlite3_syscall_ptr)stat, 0 }, | ||||
| 39282 | #define osStat((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) | ||||
| 39283 | |||||
| 39284 | /* | ||||
| 39285 | ** The DJGPP compiler environment looks mostly like Unix, but it | ||||
| 39286 | ** lacks the fcntl() system call. So redefine fcntl() to be something | ||||
| 39287 | ** that always succeeds. This means that locking does not occur under | ||||
| 39288 | ** DJGPP. But it is DOS - what did you expect? | ||||
| 39289 | */ | ||||
| 39290 | #ifdef __DJGPP__ | ||||
| 39291 | { "fstat", 0, 0 }, | ||||
| 39292 | #define osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(a,b,c) 0 | ||||
| 39293 | #else | ||||
| 39294 | { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, | ||||
| 39295 | #define osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent) ((int(*)(int,struct stat*))aSyscall[5].pCurrent) | ||||
| 39296 | #endif | ||||
| 39297 | |||||
| 39298 | { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 }, | ||||
| 39299 | #define osFtruncate((int(*)(int,off_t))aSyscall[6].pCurrent) ((int(*)(int,off_t))aSyscall[6].pCurrent) | ||||
| 39300 | |||||
| 39301 | { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 }, | ||||
| 39302 | #define osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent) ((int(*)(int,int,...))aSyscall[7].pCurrent) | ||||
| 39303 | |||||
| 39304 | { "read", (sqlite3_syscall_ptr)read, 0 }, | ||||
| 39305 | #define osRead((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) | ||||
| 39306 | |||||
| 39307 | #if defined(USE_PREAD1) || SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 39308 | { "pread", (sqlite3_syscall_ptr)pread, 0 }, | ||||
| 39309 | #else | ||||
| 39310 | { "pread", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39311 | #endif | ||||
| 39312 | #define osPread((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) | ||||
| 39313 | |||||
| 39314 | #if defined(USE_PREAD64) | ||||
| 39315 | { "pread64", (sqlite3_syscall_ptr)pread64, 0 }, | ||||
| 39316 | #else | ||||
| 39317 | { "pread64", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39318 | #endif | ||||
| 39319 | #define osPread64((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent) ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent) | ||||
| 39320 | |||||
| 39321 | { "write", (sqlite3_syscall_ptr)write, 0 }, | ||||
| 39322 | #define osWrite((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) | ||||
| 39323 | |||||
| 39324 | #if defined(USE_PREAD1) || SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 39325 | { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 }, | ||||
| 39326 | #else | ||||
| 39327 | { "pwrite", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39328 | #endif | ||||
| 39329 | #define osPwrite((ssize_t(*)(int,const void*,size_t,off_t)) aSyscall[12].pCurrent ) ((ssize_t(*)(int,const void*,size_t,off_t))\ | ||||
| 39330 | aSyscall[12].pCurrent) | ||||
| 39331 | |||||
| 39332 | #if defined(USE_PREAD64) | ||||
| 39333 | { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 }, | ||||
| 39334 | #else | ||||
| 39335 | { "pwrite64", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39336 | #endif | ||||
| 39337 | #define osPwrite64((ssize_t(*)(int,const void*,size_t,off64_t)) aSyscall[13].pCurrent ) ((ssize_t(*)(int,const void*,size_t,off64_t))\ | ||||
| 39338 | aSyscall[13].pCurrent) | ||||
| 39339 | |||||
| 39340 | #if defined(HAVE_FCHMOD1) | ||||
| 39341 | { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, | ||||
| 39342 | #else | ||||
| 39343 | { "fchmod", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39344 | #endif | ||||
| 39345 | #define osFchmod((int(*)(int,mode_t))aSyscall[14].pCurrent) ((int(*)(int,mode_t))aSyscall[14].pCurrent) | ||||
| 39346 | |||||
| 39347 | #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE | ||||
| 39348 | { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, | ||||
| 39349 | #else | ||||
| 39350 | { "fallocate", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39351 | #endif | ||||
| 39352 | #define osFallocate((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) | ||||
| 39353 | |||||
| 39354 | { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, | ||||
| 39355 | #define osUnlink((int(*)(const char*))aSyscall[16].pCurrent) ((int(*)(const char*))aSyscall[16].pCurrent) | ||||
| 39356 | |||||
| 39357 | { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, | ||||
| 39358 | #define osOpenDirectory((int(*)(const char*,int*))aSyscall[17].pCurrent) ((int(*)(const char*,int*))aSyscall[17].pCurrent) | ||||
| 39359 | |||||
| 39360 | { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, | ||||
| 39361 | #define osMkdir((int(*)(const char*,mode_t))aSyscall[18].pCurrent) ((int(*)(const char*,mode_t))aSyscall[18].pCurrent) | ||||
| 39362 | |||||
| 39363 | { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, | ||||
| 39364 | #define osRmdir((int(*)(const char*))aSyscall[19].pCurrent) ((int(*)(const char*))aSyscall[19].pCurrent) | ||||
| 39365 | |||||
| 39366 | #if defined(HAVE_FCHOWN1) | ||||
| 39367 | { "fchown", (sqlite3_syscall_ptr)fchown, 0 }, | ||||
| 39368 | #else | ||||
| 39369 | { "fchown", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39370 | #endif | ||||
| 39371 | #define osFchown((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) | ||||
| 39372 | |||||
| 39373 | #if defined(HAVE_FCHOWN1) | ||||
| 39374 | { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 }, | ||||
| 39375 | #else | ||||
| 39376 | { "geteuid", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39377 | #endif | ||||
| 39378 | #define osGeteuid((uid_t(*)(void))aSyscall[21].pCurrent) ((uid_t(*)(void))aSyscall[21].pCurrent) | ||||
| 39379 | |||||
| 39380 | #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) \ | ||||
| 39381 | && !defined(SQLITE_WASI) | ||||
| 39382 | { "mmap", (sqlite3_syscall_ptr)mmap, 0 }, | ||||
| 39383 | #else | ||||
| 39384 | { "mmap", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39385 | #endif | ||||
| 39386 | #define osMmap((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent ) ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent) | ||||
| 39387 | |||||
| 39388 | #if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) \ | ||||
| 39389 | && !defined(SQLITE_WASI) | ||||
| 39390 | { "munmap", (sqlite3_syscall_ptr)munmap, 0 }, | ||||
| 39391 | #else | ||||
| 39392 | { "munmap", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39393 | #endif | ||||
| 39394 | #define osMunmap((int(*)(void*,size_t))aSyscall[23].pCurrent) ((int(*)(void*,size_t))aSyscall[23].pCurrent) | ||||
| 39395 | |||||
| 39396 | #if HAVE_MREMAP1 && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) | ||||
| 39397 | { "mremap", (sqlite3_syscall_ptr)mremap, 0 }, | ||||
| 39398 | #else | ||||
| 39399 | { "mremap", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39400 | #endif | ||||
| 39401 | #define osMremap((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent ) ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent) | ||||
| 39402 | |||||
| 39403 | #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 39404 | { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 }, | ||||
| 39405 | #else | ||||
| 39406 | { "getpagesize", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39407 | #endif | ||||
| 39408 | #define osGetpagesize((int(*)(void))aSyscall[25].pCurrent) ((int(*)(void))aSyscall[25].pCurrent) | ||||
| 39409 | |||||
| 39410 | #if defined(HAVE_READLINK1) | ||||
| 39411 | { "readlink", (sqlite3_syscall_ptr)readlink, 0 }, | ||||
| 39412 | #else | ||||
| 39413 | { "readlink", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39414 | #endif | ||||
| 39415 | #define osReadlink((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) | ||||
| 39416 | |||||
| 39417 | #if defined(HAVE_LSTAT1) | ||||
| 39418 | { "lstat", (sqlite3_syscall_ptr)lstat, 0 }, | ||||
| 39419 | #else | ||||
| 39420 | { "lstat", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39421 | #endif | ||||
| 39422 | #define osLstat((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) | ||||
| 39423 | |||||
| 39424 | #if defined(__linux__1) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) | ||||
| 39425 | # ifdef __ANDROID__ | ||||
| 39426 | { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 }, | ||||
| 39427 | #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent) | ||||
| 39428 | # else | ||||
| 39429 | { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 }, | ||||
| 39430 | #define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent) | ||||
| 39431 | # endif | ||||
| 39432 | #else | ||||
| 39433 | { "ioctl", (sqlite3_syscall_ptr)0, 0 }, | ||||
| 39434 | #endif | ||||
| 39435 | |||||
| 39436 | }; /* End of the overrideable system calls */ | ||||
| 39437 | |||||
| 39438 | |||||
| 39439 | /* | ||||
| 39440 | ** On some systems, calls to fchown() will trigger a message in a security | ||||
| 39441 | ** log if they come from non-root processes. So avoid calling fchown() if | ||||
| 39442 | ** we are not running as root. | ||||
| 39443 | */ | ||||
| 39444 | static int robustFchown(int fd, uid_t uid, gid_t gid){ | ||||
| 39445 | #if defined(HAVE_FCHOWN1) | ||||
| 39446 | return osGeteuid((uid_t(*)(void))aSyscall[21].pCurrent)() ? 0 : osFchown((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)(fd,uid,gid); | ||||
| 39447 | #else | ||||
| 39448 | return 0; | ||||
| 39449 | #endif | ||||
| 39450 | } | ||||
| 39451 | |||||
| 39452 | /* | ||||
| 39453 | ** This is the xSetSystemCall() method of sqlite3_vfs for all of the | ||||
| 39454 | ** "unix" VFSes. Return SQLITE_OK upon successfully updating the | ||||
| 39455 | ** system call pointer, or SQLITE_NOTFOUND if there is no configurable | ||||
| 39456 | ** system call named zName. | ||||
| 39457 | */ | ||||
| 39458 | static int unixSetSystemCall( | ||||
| 39459 | sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ | ||||
| 39460 | const char *zName, /* Name of system call to override */ | ||||
| 39461 | sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ | ||||
| 39462 | ){ | ||||
| 39463 | unsigned int i; | ||||
| 39464 | int rc = SQLITE_NOTFOUND12; | ||||
| 39465 | |||||
| 39466 | UNUSED_PARAMETER(pNotUsed)(void)(pNotUsed); | ||||
| 39467 | if( zName==0 ){ | ||||
| 39468 | /* If no zName is given, restore all system calls to their default | ||||
| 39469 | ** settings and return NULL | ||||
| 39470 | */ | ||||
| 39471 | rc = SQLITE_OK0; | ||||
| 39472 | for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ | ||||
| 39473 | if( aSyscall[i].pDefault ){ | ||||
| 39474 | aSyscall[i].pCurrent = aSyscall[i].pDefault; | ||||
| 39475 | } | ||||
| 39476 | } | ||||
| 39477 | }else{ | ||||
| 39478 | /* If zName is specified, operate on only the one system call | ||||
| 39479 | ** specified. | ||||
| 39480 | */ | ||||
| 39481 | for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ | ||||
| 39482 | if( strcmp(zName, aSyscall[i].zName)==0 ){ | ||||
| 39483 | if( aSyscall[i].pDefault==0 ){ | ||||
| 39484 | aSyscall[i].pDefault = aSyscall[i].pCurrent; | ||||
| 39485 | } | ||||
| 39486 | rc = SQLITE_OK0; | ||||
| 39487 | if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault; | ||||
| 39488 | aSyscall[i].pCurrent = pNewFunc; | ||||
| 39489 | break; | ||||
| 39490 | } | ||||
| 39491 | } | ||||
| 39492 | } | ||||
| 39493 | return rc; | ||||
| 39494 | } | ||||
| 39495 | |||||
| 39496 | /* | ||||
| 39497 | ** Return the value of a system call. Return NULL if zName is not a | ||||
| 39498 | ** recognized system call name. NULL is also returned if the system call | ||||
| 39499 | ** is currently undefined. | ||||
| 39500 | */ | ||||
| 39501 | static sqlite3_syscall_ptr unixGetSystemCall( | ||||
| 39502 | sqlite3_vfs *pNotUsed, | ||||
| 39503 | const char *zName | ||||
| 39504 | ){ | ||||
| 39505 | unsigned int i; | ||||
| 39506 | |||||
| 39507 | UNUSED_PARAMETER(pNotUsed)(void)(pNotUsed); | ||||
| 39508 | for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ | ||||
| 39509 | if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent; | ||||
| 39510 | } | ||||
| 39511 | return 0; | ||||
| 39512 | } | ||||
| 39513 | |||||
| 39514 | /* | ||||
| 39515 | ** Return the name of the first system call after zName. If zName==NULL | ||||
| 39516 | ** then return the name of the first system call. Return NULL if zName | ||||
| 39517 | ** is the last system call or if zName is not the name of a valid | ||||
| 39518 | ** system call. | ||||
| 39519 | */ | ||||
| 39520 | static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){ | ||||
| 39521 | int i = -1; | ||||
| 39522 | |||||
| 39523 | UNUSED_PARAMETER(p)(void)(p); | ||||
| 39524 | if( zName ){ | ||||
| 39525 | for(i=0; i<ArraySize(aSyscall)((int)(sizeof(aSyscall)/sizeof(aSyscall[0])))-1; i++){ | ||||
| 39526 | if( strcmp(zName, aSyscall[i].zName)==0 ) break; | ||||
| 39527 | } | ||||
| 39528 | } | ||||
| 39529 | for(i++; i<ArraySize(aSyscall)((int)(sizeof(aSyscall)/sizeof(aSyscall[0]))); i++){ | ||||
| 39530 | if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName; | ||||
| 39531 | } | ||||
| 39532 | return 0; | ||||
| 39533 | } | ||||
| 39534 | |||||
| 39535 | /* | ||||
| 39536 | ** Do not accept any file descriptor less than this value, in order to avoid | ||||
| 39537 | ** opening database file using file descriptors that are commonly used for | ||||
| 39538 | ** standard input, output, and error. | ||||
| 39539 | */ | ||||
| 39540 | #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR3 | ||||
| 39541 | # define SQLITE_MINIMUM_FILE_DESCRIPTOR3 3 | ||||
| 39542 | #endif | ||||
| 39543 | |||||
| 39544 | /* | ||||
| 39545 | ** Invoke open(). Do so multiple times, until it either succeeds or | ||||
| 39546 | ** fails for some reason other than EINTR. | ||||
| 39547 | ** | ||||
| 39548 | ** If the file creation mode "m" is 0 then set it to the default for | ||||
| 39549 | ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally | ||||
| 39550 | ** 0644) as modified by the system umask. If m is not 0, then | ||||
| 39551 | ** make the file creation mode be exactly m ignoring the umask. | ||||
| 39552 | ** | ||||
| 39553 | ** The m parameter will be non-zero only when creating -wal, -journal, | ||||
| 39554 | ** and -shm files. We want those files to have *exactly* the same | ||||
| 39555 | ** permissions as their original database, unadulterated by the umask. | ||||
| 39556 | ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a | ||||
| 39557 | ** transaction crashes and leaves behind hot journals, then any | ||||
| 39558 | ** process that is able to write to the database will also be able to | ||||
| 39559 | ** recover the hot journals. | ||||
| 39560 | */ | ||||
| 39561 | static int robust_open(const char *z, int f, mode_t m){ | ||||
| 39562 | int fd; | ||||
| 39563 | mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS0644; | ||||
| 39564 | while(1){ | ||||
| 39565 | #if defined(O_CLOEXEC02000000) | ||||
| 39566 | fd = osOpen((int(*)(const char*,int,int))aSyscall[0].pCurrent)(z,f|O_CLOEXEC02000000,m2); | ||||
| 39567 | #else | ||||
| 39568 | fd = osOpen((int(*)(const char*,int,int))aSyscall[0].pCurrent)(z,f,m2); | ||||
| 39569 | #endif | ||||
| 39570 | if( fd<0 ){ | ||||
| 39571 | if( errno(*__errno_location ())==EINTR4 ) continue; | ||||
| 39572 | break; | ||||
| 39573 | } | ||||
| 39574 | if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR3 ) break; | ||||
| 39575 | if( (f & (O_EXCL0200|O_CREAT0100))==(O_EXCL0200|O_CREAT0100) ){ | ||||
| 39576 | (void)osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(z); | ||||
| 39577 | } | ||||
| 39578 | osClose((int(*)(int))aSyscall[1].pCurrent)(fd); | ||||
| 39579 | sqlite3_log(SQLITE_WARNING28, | ||||
| 39580 | "attempt to open \"%s\" as file descriptor %d", z, fd); | ||||
| 39581 | fd = -1; | ||||
| 39582 | if( osOpen((int(*)(const char*,int,int))aSyscall[0].pCurrent)("/dev/null", O_RDONLY00, m)<0 ) break; | ||||
| 39583 | } | ||||
| 39584 | if( fd>=0 ){ | ||||
| 39585 | if( m!=0 ){ | ||||
| 39586 | struct stat statbuf; | ||||
| 39587 | if( osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(fd, &statbuf)==0 | ||||
| 39588 | && statbuf.st_size==0 | ||||
| 39589 | && (statbuf.st_mode&0777)!=m | ||||
| 39590 | ){ | ||||
| 39591 | osFchmod((int(*)(int,mode_t))aSyscall[14].pCurrent)(fd, m); | ||||
| 39592 | } | ||||
| 39593 | } | ||||
| 39594 | #if defined(FD_CLOEXEC1) && (!defined(O_CLOEXEC02000000) || O_CLOEXEC02000000==0) | ||||
| 39595 | osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(fd, F_SETFD2, osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(fd, F_GETFD1, 0) | FD_CLOEXEC1); | ||||
| 39596 | #endif | ||||
| 39597 | } | ||||
| 39598 | return fd; | ||||
| 39599 | } | ||||
| 39600 | |||||
| 39601 | /* | ||||
| 39602 | ** Helper functions to obtain and relinquish the global mutex. The | ||||
| 39603 | ** global mutex is used to protect the unixInodeInfo and | ||||
| 39604 | ** vxworksFileId objects used by this file, all of which may be | ||||
| 39605 | ** shared by multiple threads. | ||||
| 39606 | ** | ||||
| 39607 | ** Function unixMutexHeld() is used to assert() that the global mutex | ||||
| 39608 | ** is held when required. This function is only used as part of assert() | ||||
| 39609 | ** statements. e.g. | ||||
| 39610 | ** | ||||
| 39611 | ** unixEnterMutex() | ||||
| 39612 | ** assert( unixMutexHeld() ); | ||||
| 39613 | ** unixEnterLeave() | ||||
| 39614 | ** | ||||
| 39615 | ** To prevent deadlock, the global unixBigLock must must be acquired | ||||
| 39616 | ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is | ||||
| 39617 | ** OK to get the pLockMutex without holding unixBigLock first, but if | ||||
| 39618 | ** that happens, the unixBigLock mutex must not be acquired until after | ||||
| 39619 | ** pLockMutex is released. | ||||
| 39620 | ** | ||||
| 39621 | ** OK: enter(unixBigLock), enter(pLockInfo) | ||||
| 39622 | ** OK: enter(unixBigLock) | ||||
| 39623 | ** OK: enter(pLockInfo) | ||||
| 39624 | ** ERROR: enter(pLockInfo), enter(unixBigLock) | ||||
| 39625 | */ | ||||
| 39626 | static sqlite3_mutex *unixBigLock = 0; | ||||
| 39627 | static void unixEnterMutex(void){ | ||||
| 39628 | assert( sqlite3_mutex_notheld(unixBigLock) )((void) (0)); /* Not a recursive mutex */ | ||||
| 39629 | sqlite3_mutex_enter(unixBigLock); | ||||
| 39630 | } | ||||
| 39631 | static void unixLeaveMutex(void){ | ||||
| 39632 | assert( sqlite3_mutex_held(unixBigLock) )((void) (0)); | ||||
| 39633 | sqlite3_mutex_leave(unixBigLock); | ||||
| 39634 | } | ||||
| 39635 | #ifdef SQLITE_DEBUG | ||||
| 39636 | static int unixMutexHeld(void) { | ||||
| 39637 | return sqlite3_mutex_held(unixBigLock); | ||||
| 39638 | } | ||||
| 39639 | #endif | ||||
| 39640 | |||||
| 39641 | |||||
| 39642 | #ifdef SQLITE_HAVE_OS_TRACE | ||||
| 39643 | /* | ||||
| 39644 | ** Helper function for printing out trace information from debugging | ||||
| 39645 | ** binaries. This returns the string representation of the supplied | ||||
| 39646 | ** integer lock-type. | ||||
| 39647 | */ | ||||
| 39648 | static const char *azFileLock(int eFileLock){ | ||||
| 39649 | switch( eFileLock ){ | ||||
| 39650 | case NO_LOCK0: return "NONE"; | ||||
| 39651 | case SHARED_LOCK1: return "SHARED"; | ||||
| 39652 | case RESERVED_LOCK2: return "RESERVED"; | ||||
| 39653 | case PENDING_LOCK3: return "PENDING"; | ||||
| 39654 | case EXCLUSIVE_LOCK4: return "EXCLUSIVE"; | ||||
| 39655 | } | ||||
| 39656 | return "ERROR"; | ||||
| 39657 | } | ||||
| 39658 | #endif | ||||
| 39659 | |||||
| 39660 | #ifdef SQLITE_LOCK_TRACE | ||||
| 39661 | /* | ||||
| 39662 | ** Print out information about all locking operations. | ||||
| 39663 | ** | ||||
| 39664 | ** This routine is used for troubleshooting locks on multithreaded | ||||
| 39665 | ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE | ||||
| 39666 | ** command-line option on the compiler. This code is normally | ||||
| 39667 | ** turned off. | ||||
| 39668 | */ | ||||
| 39669 | static int lockTrace(int fd, int op, struct flock *p){ | ||||
| 39670 | char *zOpName, *zType; | ||||
| 39671 | int s; | ||||
| 39672 | int savedErrno; | ||||
| 39673 | if( op==F_GETLK5 ){ | ||||
| 39674 | zOpName = "GETLK"; | ||||
| 39675 | }else if( op==F_SETLK6 ){ | ||||
| 39676 | zOpName = "SETLK"; | ||||
| 39677 | }else{ | ||||
| 39678 | s = osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(fd, op, p); | ||||
| 39679 | sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s); | ||||
| 39680 | return s; | ||||
| 39681 | } | ||||
| 39682 | if( p->l_type==F_RDLCK0 ){ | ||||
| 39683 | zType = "RDLCK"; | ||||
| 39684 | }else if( p->l_type==F_WRLCK1 ){ | ||||
| 39685 | zType = "WRLCK"; | ||||
| 39686 | }else if( p->l_type==F_UNLCK2 ){ | ||||
| 39687 | zType = "UNLCK"; | ||||
| 39688 | }else{ | ||||
| 39689 | assert( 0 )((void) (0)); | ||||
| 39690 | } | ||||
| 39691 | assert( p->l_whence==SEEK_SET )((void) (0)); | ||||
| 39692 | s = osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(fd, op, p); | ||||
| 39693 | savedErrno = errno(*__errno_location ()); | ||||
| 39694 | sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n", | ||||
| 39695 | threadidpthread_self(), fd, zOpName, zType, (int)p->l_start, (int)p->l_len, | ||||
| 39696 | (int)p->l_pid, s); | ||||
| 39697 | if( s==(-1) && op==F_SETLK6 && (p->l_type==F_RDLCK0 || p->l_type==F_WRLCK1) ){ | ||||
| 39698 | struct flock l2; | ||||
| 39699 | l2 = *p; | ||||
| 39700 | osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(fd, F_GETLK5, &l2); | ||||
| 39701 | if( l2.l_type==F_RDLCK0 ){ | ||||
| 39702 | zType = "RDLCK"; | ||||
| 39703 | }else if( l2.l_type==F_WRLCK1 ){ | ||||
| 39704 | zType = "WRLCK"; | ||||
| 39705 | }else if( l2.l_type==F_UNLCK2 ){ | ||||
| 39706 | zType = "UNLCK"; | ||||
| 39707 | }else{ | ||||
| 39708 | assert( 0 )((void) (0)); | ||||
| 39709 | } | ||||
| 39710 | sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", | ||||
| 39711 | zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid); | ||||
| 39712 | } | ||||
| 39713 | errno(*__errno_location ()) = savedErrno; | ||||
| 39714 | return s; | ||||
| 39715 | } | ||||
| 39716 | #undef osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent) | ||||
| 39717 | #define osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent) lockTrace | ||||
| 39718 | #endif /* SQLITE_LOCK_TRACE */ | ||||
| 39719 | |||||
| 39720 | /* | ||||
| 39721 | ** Retry ftruncate() calls that fail due to EINTR | ||||
| 39722 | ** | ||||
| 39723 | ** All calls to ftruncate() within this file should be made through | ||||
| 39724 | ** this wrapper. On the Android platform, bypassing the logic below | ||||
| 39725 | ** could lead to a corrupt database. | ||||
| 39726 | */ | ||||
| 39727 | static int robust_ftruncate(int h, sqlite3_int64 sz){ | ||||
| 39728 | int rc; | ||||
| 39729 | #ifdef __ANDROID__ | ||||
| 39730 | /* On Android, ftruncate() always uses 32-bit offsets, even if | ||||
| 39731 | ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to | ||||
| 39732 | ** truncate a file to any size larger than 2GiB. Silently ignore any | ||||
| 39733 | ** such attempts. */ | ||||
| 39734 | if( sz>(sqlite3_int64)0x7FFFFFFF ){ | ||||
| 39735 | rc = SQLITE_OK0; | ||||
| 39736 | }else | ||||
| 39737 | #endif | ||||
| 39738 | do{ rc = osFtruncate((int(*)(int,off_t))aSyscall[6].pCurrent)(h,sz); }while( rc<0 && errno(*__errno_location ())==EINTR4 ); | ||||
| 39739 | return rc; | ||||
| 39740 | } | ||||
| 39741 | |||||
| 39742 | /* | ||||
| 39743 | ** This routine translates a standard POSIX errno code into something | ||||
| 39744 | ** useful to the clients of the sqlite3 functions. Specifically, it is | ||||
| 39745 | ** intended to translate a variety of "try again" errors into SQLITE_BUSY | ||||
| 39746 | ** and a variety of "please close the file descriptor NOW" errors into | ||||
| 39747 | ** SQLITE_IOERR | ||||
| 39748 | ** | ||||
| 39749 | ** Errors during initialization of locks, or file system support for locks, | ||||
| 39750 | ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately. | ||||
| 39751 | */ | ||||
| 39752 | static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) { | ||||
| 39753 | assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||((void) (0)) | ||||
| 39754 | (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||((void) (0)) | ||||
| 39755 | (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||((void) (0)) | ||||
| 39756 | (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) )((void) (0)); | ||||
| 39757 | switch (posixError) { | ||||
| 39758 | case EACCES13: | ||||
| 39759 | case EAGAIN11: | ||||
| 39760 | case ETIMEDOUT110: | ||||
| 39761 | case EBUSY16: | ||||
| 39762 | case EINTR4: | ||||
| 39763 | case ENOLCK37: | ||||
| 39764 | /* random NFS retry error, unless during file system support | ||||
| 39765 | * introspection, in which it actually means what it says */ | ||||
| 39766 | return SQLITE_BUSY5; | ||||
| 39767 | |||||
| 39768 | case EPERM1: | ||||
| 39769 | return SQLITE_PERM3; | ||||
| 39770 | |||||
| 39771 | default: | ||||
| 39772 | return sqliteIOErr; | ||||
| 39773 | } | ||||
| 39774 | } | ||||
| 39775 | |||||
| 39776 | |||||
| 39777 | /****************************************************************************** | ||||
| 39778 | ****************** Begin Unique File ID Utility Used By VxWorks *************** | ||||
| 39779 | ** | ||||
| 39780 | ** On most versions of unix, we can get a unique ID for a file by concatenating | ||||
| 39781 | ** the device number and the inode number. But this does not work on VxWorks. | ||||
| 39782 | ** On VxWorks, a unique file id must be based on the canonical filename. | ||||
| 39783 | ** | ||||
| 39784 | ** A pointer to an instance of the following structure can be used as a | ||||
| 39785 | ** unique file ID in VxWorks. Each instance of this structure contains | ||||
| 39786 | ** a copy of the canonical filename. There is also a reference count. | ||||
| 39787 | ** The structure is reclaimed when the number of pointers to it drops to | ||||
| 39788 | ** zero. | ||||
| 39789 | ** | ||||
| 39790 | ** There are never very many files open at one time and lookups are not | ||||
| 39791 | ** a performance-critical path, so it is sufficient to put these | ||||
| 39792 | ** structures on a linked list. | ||||
| 39793 | */ | ||||
| 39794 | struct vxworksFileId { | ||||
| 39795 | struct vxworksFileId *pNext; /* Next in a list of them all */ | ||||
| 39796 | int nRef; /* Number of references to this one */ | ||||
| 39797 | int nName; /* Length of the zCanonicalName[] string */ | ||||
| 39798 | char *zCanonicalName; /* Canonical filename */ | ||||
| 39799 | }; | ||||
| 39800 | |||||
| 39801 | #if OS_VXWORKS0 | ||||
| 39802 | /* | ||||
| 39803 | ** All unique filenames are held on a linked list headed by this | ||||
| 39804 | ** variable: | ||||
| 39805 | */ | ||||
| 39806 | static struct vxworksFileId *vxworksFileList = 0; | ||||
| 39807 | |||||
| 39808 | /* | ||||
| 39809 | ** Simplify a filename into its canonical form | ||||
| 39810 | ** by making the following changes: | ||||
| 39811 | ** | ||||
| 39812 | ** * removing any trailing and duplicate / | ||||
| 39813 | ** * convert /./ into just / | ||||
| 39814 | ** * convert /A/../ where A is any simple name into just / | ||||
| 39815 | ** | ||||
| 39816 | ** Changes are made in-place. Return the new name length. | ||||
| 39817 | ** | ||||
| 39818 | ** The original filename is in z[0..n-1]. Return the number of | ||||
| 39819 | ** characters in the simplified name. | ||||
| 39820 | */ | ||||
| 39821 | static int vxworksSimplifyName(char *z, int n){ | ||||
| 39822 | int i, j; | ||||
| 39823 | while( n>1 && z[n-1]=='/' ){ n--; } | ||||
| 39824 | for(i=j=0; i<n; i++){ | ||||
| 39825 | if( z[i]=='/' ){ | ||||
| 39826 | if( z[i+1]=='/' ) continue; | ||||
| 39827 | if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){ | ||||
| 39828 | i += 1; | ||||
| 39829 | continue; | ||||
| 39830 | } | ||||
| 39831 | if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){ | ||||
| 39832 | while( j>0 && z[j-1]!='/' ){ j--; } | ||||
| 39833 | if( j>0 ){ j--; } | ||||
| 39834 | i += 2; | ||||
| 39835 | continue; | ||||
| 39836 | } | ||||
| 39837 | } | ||||
| 39838 | z[j++] = z[i]; | ||||
| 39839 | } | ||||
| 39840 | z[j] = 0; | ||||
| 39841 | return j; | ||||
| 39842 | } | ||||
| 39843 | |||||
| 39844 | /* | ||||
| 39845 | ** Find a unique file ID for the given absolute pathname. Return | ||||
| 39846 | ** a pointer to the vxworksFileId object. This pointer is the unique | ||||
| 39847 | ** file ID. | ||||
| 39848 | ** | ||||
| 39849 | ** The nRef field of the vxworksFileId object is incremented before | ||||
| 39850 | ** the object is returned. A new vxworksFileId object is created | ||||
| 39851 | ** and added to the global list if necessary. | ||||
| 39852 | ** | ||||
| 39853 | ** If a memory allocation error occurs, return NULL. | ||||
| 39854 | */ | ||||
| 39855 | static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ | ||||
| 39856 | struct vxworksFileId *pNew; /* search key and new file ID */ | ||||
| 39857 | struct vxworksFileId *pCandidate; /* For looping over existing file IDs */ | ||||
| 39858 | int n; /* Length of zAbsoluteName string */ | ||||
| 39859 | |||||
| 39860 | assert( zAbsoluteName[0]=='/' )((void) (0)); | ||||
| 39861 | n = (int)strlen(zAbsoluteName); | ||||
| 39862 | pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) ); | ||||
| 39863 | if( pNew==0 ) return 0; | ||||
| 39864 | pNew->zCanonicalName = (char*)&pNew[1]; | ||||
| 39865 | memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); | ||||
| 39866 | n = vxworksSimplifyName(pNew->zCanonicalName, n); | ||||
| 39867 | |||||
| 39868 | /* Search for an existing entry that matching the canonical name. | ||||
| 39869 | ** If found, increment the reference count and return a pointer to | ||||
| 39870 | ** the existing file ID. | ||||
| 39871 | */ | ||||
| 39872 | unixEnterMutex(); | ||||
| 39873 | for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){ | ||||
| 39874 | if( pCandidate->nName==n | ||||
| 39875 | && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 | ||||
| 39876 | ){ | ||||
| 39877 | sqlite3_free(pNew); | ||||
| 39878 | pCandidate->nRef++; | ||||
| 39879 | unixLeaveMutex(); | ||||
| 39880 | return pCandidate; | ||||
| 39881 | } | ||||
| 39882 | } | ||||
| 39883 | |||||
| 39884 | /* No match was found. We will make a new file ID */ | ||||
| 39885 | pNew->nRef = 1; | ||||
| 39886 | pNew->nName = n; | ||||
| 39887 | pNew->pNext = vxworksFileList; | ||||
| 39888 | vxworksFileList = pNew; | ||||
| 39889 | unixLeaveMutex(); | ||||
| 39890 | return pNew; | ||||
| 39891 | } | ||||
| 39892 | |||||
| 39893 | /* | ||||
| 39894 | ** Decrement the reference count on a vxworksFileId object. Free | ||||
| 39895 | ** the object when the reference count reaches zero. | ||||
| 39896 | */ | ||||
| 39897 | static void vxworksReleaseFileId(struct vxworksFileId *pId){ | ||||
| 39898 | unixEnterMutex(); | ||||
| 39899 | assert( pId->nRef>0 )((void) (0)); | ||||
| 39900 | pId->nRef--; | ||||
| 39901 | if( pId->nRef==0 ){ | ||||
| 39902 | struct vxworksFileId **pp; | ||||
| 39903 | for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){} | ||||
| 39904 | assert( *pp==pId )((void) (0)); | ||||
| 39905 | *pp = pId->pNext; | ||||
| 39906 | sqlite3_free(pId); | ||||
| 39907 | } | ||||
| 39908 | unixLeaveMutex(); | ||||
| 39909 | } | ||||
| 39910 | #endif /* OS_VXWORKS */ | ||||
| 39911 | /*************** End of Unique File ID Utility Used By VxWorks **************** | ||||
| 39912 | ******************************************************************************/ | ||||
| 39913 | |||||
| 39914 | |||||
| 39915 | /****************************************************************************** | ||||
| 39916 | *************************** Posix Advisory Locking **************************** | ||||
| 39917 | ** | ||||
| 39918 | ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996) | ||||
| 39919 | ** section 6.5.2.2 lines 483 through 490 specify that when a process | ||||
| 39920 | ** sets or clears a lock, that operation overrides any prior locks set | ||||
| 39921 | ** by the same process. It does not explicitly say so, but this implies | ||||
| 39922 | ** that it overrides locks set by the same process using a different | ||||
| 39923 | ** file descriptor. Consider this test case: | ||||
| 39924 | ** | ||||
| 39925 | ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644); | ||||
| 39926 | ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644); | ||||
| 39927 | ** | ||||
| 39928 | ** Suppose ./file1 and ./file2 are really the same file (because | ||||
| 39929 | ** one is a hard or symbolic link to the other) then if you set | ||||
| 39930 | ** an exclusive lock on fd1, then try to get an exclusive lock | ||||
| 39931 | ** on fd2, it works. I would have expected the second lock to | ||||
| 39932 | ** fail since there was already a lock on the file due to fd1. | ||||
| 39933 | ** But not so. Since both locks came from the same process, the | ||||
| 39934 | ** second overrides the first, even though they were on different | ||||
| 39935 | ** file descriptors opened on different file names. | ||||
| 39936 | ** | ||||
| 39937 | ** This means that we cannot use POSIX locks to synchronize file access | ||||
| 39938 | ** among competing threads of the same process. POSIX locks will work fine | ||||
| 39939 | ** to synchronize access for threads in separate processes, but not | ||||
| 39940 | ** threads within the same process. | ||||
| 39941 | ** | ||||
| 39942 | ** To work around the problem, SQLite has to manage file locks internally | ||||
| 39943 | ** on its own. Whenever a new database is opened, we have to find the | ||||
| 39944 | ** specific inode of the database file (the inode is determined by the | ||||
| 39945 | ** st_dev and st_ino fields of the stat structure that fstat() fills in) | ||||
| 39946 | ** and check for locks already existing on that inode. When locks are | ||||
| 39947 | ** created or removed, we have to look at our own internal record of the | ||||
| 39948 | ** locks to see if another thread has previously set a lock on that same | ||||
| 39949 | ** inode. | ||||
| 39950 | ** | ||||
| 39951 | ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks. | ||||
| 39952 | ** For VxWorks, we have to use the alternative unique ID system based on | ||||
| 39953 | ** canonical filename and implemented in the previous division.) | ||||
| 39954 | ** | ||||
| 39955 | ** The sqlite3_file structure for POSIX is no longer just an integer file | ||||
| 39956 | ** descriptor. It is now a structure that holds the integer file | ||||
| 39957 | ** descriptor and a pointer to a structure that describes the internal | ||||
| 39958 | ** locks on the corresponding inode. There is one locking structure | ||||
| 39959 | ** per inode, so if the same inode is opened twice, both unixFile structures | ||||
| 39960 | ** point to the same locking structure. The locking structure keeps | ||||
| 39961 | ** a reference count (so we will know when to delete it) and a "cnt" | ||||
| 39962 | ** field that tells us its internal lock status. cnt==0 means the | ||||
| 39963 | ** file is unlocked. cnt==-1 means the file has an exclusive lock. | ||||
| 39964 | ** cnt>0 means there are cnt shared locks on the file. | ||||
| 39965 | ** | ||||
| 39966 | ** Any attempt to lock or unlock a file first checks the locking | ||||
| 39967 | ** structure. The fcntl() system call is only invoked to set a | ||||
| 39968 | ** POSIX lock if the internal lock structure transitions between | ||||
| 39969 | ** a locked and an unlocked state. | ||||
| 39970 | ** | ||||
| 39971 | ** But wait: there are yet more problems with POSIX advisory locks. | ||||
| 39972 | ** | ||||
| 39973 | ** If you close a file descriptor that points to a file that has locks, | ||||
| 39974 | ** all locks on that file that are owned by the current process are | ||||
| 39975 | ** released. To work around this problem, each unixInodeInfo object | ||||
| 39976 | ** maintains a count of the number of pending locks on the inode. | ||||
| 39977 | ** When an attempt is made to close an unixFile, if there are | ||||
| 39978 | ** other unixFile open on the same inode that are holding locks, the call | ||||
| 39979 | ** to close() the file descriptor is deferred until all of the locks clear. | ||||
| 39980 | ** The unixInodeInfo structure keeps a list of file descriptors that need to | ||||
| 39981 | ** be closed and that list is walked (and cleared) when the last lock | ||||
| 39982 | ** clears. | ||||
| 39983 | ** | ||||
| 39984 | ** Yet another problem: LinuxThreads do not play well with posix locks. | ||||
| 39985 | ** | ||||
| 39986 | ** Many older versions of linux use the LinuxThreads library which is | ||||
| 39987 | ** not posix compliant. Under LinuxThreads, a lock created by thread | ||||
| 39988 | ** A cannot be modified or overridden by a different thread B. | ||||
| 39989 | ** Only thread A can modify the lock. Locking behavior is correct | ||||
| 39990 | ** if the application uses the newer Native Posix Thread Library (NPTL) | ||||
| 39991 | ** on linux - with NPTL a lock created by thread A can override locks | ||||
| 39992 | ** in thread B. But there is no way to know at compile-time which | ||||
| 39993 | ** threading library is being used. So there is no way to know at | ||||
| 39994 | ** compile-time whether or not thread A can override locks on thread B. | ||||
| 39995 | ** One has to do a run-time check to discover the behavior of the | ||||
| 39996 | ** current process. | ||||
| 39997 | ** | ||||
| 39998 | ** SQLite used to support LinuxThreads. But support for LinuxThreads | ||||
| 39999 | ** was dropped beginning with version 3.7.0. SQLite will still work with | ||||
| 40000 | ** LinuxThreads provided that (1) there is no more than one connection | ||||
| 40001 | ** per database file in the same process and (2) database connections | ||||
| 40002 | ** do not move across threads. | ||||
| 40003 | */ | ||||
| 40004 | |||||
| 40005 | /* | ||||
| 40006 | ** An instance of the following structure serves as the key used | ||||
| 40007 | ** to locate a particular unixInodeInfo object. | ||||
| 40008 | */ | ||||
| 40009 | struct unixFileId { | ||||
| 40010 | dev_t dev; /* Device number */ | ||||
| 40011 | #if OS_VXWORKS0 | ||||
| 40012 | struct vxworksFileId *pId; /* Unique file ID for vxworks. */ | ||||
| 40013 | #else | ||||
| 40014 | /* We are told that some versions of Android contain a bug that | ||||
| 40015 | ** sizes ino_t at only 32-bits instead of 64-bits. (See | ||||
| 40016 | ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c) | ||||
| 40017 | ** To work around this, always allocate 64-bits for the inode number. | ||||
| 40018 | ** On small machines that only have 32-bit inodes, this wastes 4 bytes, | ||||
| 40019 | ** but that should not be a big deal. */ | ||||
| 40020 | /* WAS: ino_t ino; */ | ||||
| 40021 | u64 ino; /* Inode number */ | ||||
| 40022 | #endif | ||||
| 40023 | }; | ||||
| 40024 | |||||
| 40025 | /* | ||||
| 40026 | ** An instance of the following structure is allocated for each open | ||||
| 40027 | ** inode. | ||||
| 40028 | ** | ||||
| 40029 | ** A single inode can have multiple file descriptors, so each unixFile | ||||
| 40030 | ** structure contains a pointer to an instance of this object and this | ||||
| 40031 | ** object keeps a count of the number of unixFile pointing to it. | ||||
| 40032 | ** | ||||
| 40033 | ** Mutex rules: | ||||
| 40034 | ** | ||||
| 40035 | ** (1) Only the pLockMutex mutex must be held in order to read or write | ||||
| 40036 | ** any of the locking fields: | ||||
| 40037 | ** nShared, nLock, eFileLock, bProcessLock, pUnused | ||||
| 40038 | ** | ||||
| 40039 | ** (2) When nRef>0, then the following fields are unchanging and can | ||||
| 40040 | ** be read (but not written) without holding any mutex: | ||||
| 40041 | ** fileId, pLockMutex | ||||
| 40042 | ** | ||||
| 40043 | ** (3) With the exceptions above, all the fields may only be read | ||||
| 40044 | ** or written while holding the global unixBigLock mutex. | ||||
| 40045 | ** | ||||
| 40046 | ** Deadlock prevention: The global unixBigLock mutex may not | ||||
| 40047 | ** be acquired while holding the pLockMutex mutex. If both unixBigLock | ||||
| 40048 | ** and pLockMutex are needed, then unixBigLock must be acquired first. | ||||
| 40049 | */ | ||||
| 40050 | struct unixInodeInfo { | ||||
| 40051 | struct unixFileId fileId; /* The lookup key */ | ||||
| 40052 | sqlite3_mutex *pLockMutex; /* Hold this mutex for... */ | ||||
| 40053 | int nShared; /* Number of SHARED locks held */ | ||||
| 40054 | int nLock; /* Number of outstanding file locks */ | ||||
| 40055 | unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ | ||||
| 40056 | unsigned char bProcessLock; /* An exclusive process lock is held */ | ||||
| 40057 | UnixUnusedFd *pUnused; /* Unused file descriptors to close */ | ||||
| 40058 | int nRef; /* Number of pointers to this structure */ | ||||
| 40059 | unixShmNode *pShmNode; /* Shared memory associated with this inode */ | ||||
| 40060 | unixInodeInfo *pNext; /* List of all unixInodeInfo objects */ | ||||
| 40061 | unixInodeInfo *pPrev; /* .... doubly linked */ | ||||
| 40062 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 40063 | unsigned long long sharedByte; /* for AFP simulated shared lock */ | ||||
| 40064 | #endif | ||||
| 40065 | #if OS_VXWORKS0 | ||||
| 40066 | sem_t *pSem; /* Named POSIX semaphore */ | ||||
| 40067 | char aSemName[MAX_PATHNAME512+2]; /* Name of that semaphore */ | ||||
| 40068 | #endif | ||||
| 40069 | }; | ||||
| 40070 | |||||
| 40071 | /* | ||||
| 40072 | ** A lists of all unixInodeInfo objects. | ||||
| 40073 | ** | ||||
| 40074 | ** Must hold unixBigLock in order to read or write this variable. | ||||
| 40075 | */ | ||||
| 40076 | static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */ | ||||
| 40077 | |||||
| 40078 | #ifdef SQLITE_DEBUG | ||||
| 40079 | /* | ||||
| 40080 | ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not. | ||||
| 40081 | ** This routine is used only within assert() to help verify correct mutex | ||||
| 40082 | ** usage. | ||||
| 40083 | */ | ||||
| 40084 | int unixFileMutexHeld(unixFile *pFile){ | ||||
| 40085 | assert( pFile->pInode )((void) (0)); | ||||
| 40086 | return sqlite3_mutex_held(pFile->pInode->pLockMutex); | ||||
| 40087 | } | ||||
| 40088 | int unixFileMutexNotheld(unixFile *pFile){ | ||||
| 40089 | assert( pFile->pInode )((void) (0)); | ||||
| 40090 | return sqlite3_mutex_notheld(pFile->pInode->pLockMutex); | ||||
| 40091 | } | ||||
| 40092 | #endif | ||||
| 40093 | |||||
| 40094 | /* | ||||
| 40095 | ** | ||||
| 40096 | ** This function - unixLogErrorAtLine(), is only ever called via the macro | ||||
| 40097 | ** unixLogError(). | ||||
| 40098 | ** | ||||
| 40099 | ** It is invoked after an error occurs in an OS function and errno has been | ||||
| 40100 | ** set. It logs a message using sqlite3_log() containing the current value of | ||||
| 40101 | ** errno and, if possible, the human-readable equivalent from strerror() or | ||||
| 40102 | ** strerror_r(). | ||||
| 40103 | ** | ||||
| 40104 | ** The first argument passed to the macro should be the error code that | ||||
| 40105 | ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). | ||||
| 40106 | ** The two subsequent arguments should be the name of the OS function that | ||||
| 40107 | ** failed (e.g. "unlink", "open") and the associated file-system path, | ||||
| 40108 | ** if any. | ||||
| 40109 | */ | ||||
| 40110 | #define unixLogError(a,b,c)unixLogErrorAtLine(a,b,c,40110) unixLogErrorAtLine(a,b,c,__LINE__40110) | ||||
| 40111 | static int unixLogErrorAtLine( | ||||
| 40112 | int errcode, /* SQLite error code */ | ||||
| 40113 | const char *zFunc, /* Name of OS function that failed */ | ||||
| 40114 | const char *zPath, /* File path associated with error */ | ||||
| 40115 | int iLine /* Source line number where error occurred */ | ||||
| 40116 | ){ | ||||
| 40117 | char *zErr; /* Message from strerror() or equivalent */ | ||||
| 40118 | int iErrno = errno(*__errno_location ()); /* Saved syscall error number */ | ||||
| 40119 | |||||
| 40120 | /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use | ||||
| 40121 | ** the strerror() function to obtain the human-readable error message | ||||
| 40122 | ** equivalent to errno. Otherwise, use strerror_r(). | ||||
| 40123 | */ | ||||
| 40124 | #if SQLITE_THREADSAFE2 && defined(HAVE_STRERROR_R) | ||||
| 40125 | char aErr[80]; | ||||
| 40126 | memset(aErr, 0, sizeof(aErr)); | ||||
| 40127 | zErr = aErr; | ||||
| 40128 | |||||
| 40129 | /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined, | ||||
| 40130 | ** assume that the system provides the GNU version of strerror_r() that | ||||
| 40131 | ** returns a pointer to a buffer containing the error message. That pointer | ||||
| 40132 | ** may point to aErr[], or it may point to some static storage somewhere. | ||||
| 40133 | ** Otherwise, assume that the system provides the POSIX version of | ||||
| 40134 | ** strerror_r(), which always writes an error message into aErr[]. | ||||
| 40135 | ** | ||||
| 40136 | ** If the code incorrectly assumes that it is the POSIX version that is | ||||
| 40137 | ** available, the error message will often be an empty string. Not a | ||||
| 40138 | ** huge problem. Incorrectly concluding that the GNU version is available | ||||
| 40139 | ** could lead to a segfault though. | ||||
| 40140 | ** | ||||
| 40141 | ** Forum post 3f13857fa4062301 reports that the Android SDK may use | ||||
| 40142 | ** int-type return, depending on its version. | ||||
| 40143 | */ | ||||
| 40144 | #if (defined(STRERROR_R_CHAR_P) || defined(__USE_GNU1)) \ | ||||
| 40145 | && !defined(ANDROID) && !defined(__ANDROID__) | ||||
| 40146 | zErr = | ||||
| 40147 | # endif | ||||
| 40148 | strerror_r(iErrno, aErr, sizeof(aErr)-1); | ||||
| 40149 | |||||
| 40150 | #elif SQLITE_THREADSAFE2 | ||||
| 40151 | /* This is a threadsafe build, but strerror_r() is not available. */ | ||||
| 40152 | zErr = ""; | ||||
| 40153 | #else | ||||
| 40154 | /* Non-threadsafe build, use strerror(). */ | ||||
| 40155 | zErr = strerror(iErrno); | ||||
| 40156 | #endif | ||||
| 40157 | |||||
| 40158 | if( zPath==0 ) zPath = ""; | ||||
| 40159 | sqlite3_log(errcode, | ||||
| 40160 | "os_unix.c:%d: (%d) %s(%s) - %s", | ||||
| 40161 | iLine, iErrno, zFunc, zPath, zErr | ||||
| 40162 | ); | ||||
| 40163 | |||||
| 40164 | return errcode; | ||||
| 40165 | } | ||||
| 40166 | |||||
| 40167 | /* | ||||
| 40168 | ** Close a file descriptor. | ||||
| 40169 | ** | ||||
| 40170 | ** We assume that close() almost always works, since it is only in a | ||||
| 40171 | ** very sick application or on a very sick platform that it might fail. | ||||
| 40172 | ** If it does fail, simply leak the file descriptor, but do log the | ||||
| 40173 | ** error. | ||||
| 40174 | ** | ||||
| 40175 | ** Note that it is not safe to retry close() after EINTR since the | ||||
| 40176 | ** file descriptor might have already been reused by another thread. | ||||
| 40177 | ** So we don't even try to recover from an EINTR. Just log the error | ||||
| 40178 | ** and move on. | ||||
| 40179 | */ | ||||
| 40180 | static void robust_close(unixFile *pFile, int h, int lineno){ | ||||
| 40181 | if( osClose((int(*)(int))aSyscall[1].pCurrent)(h) ){ | ||||
| 40182 | unixLogErrorAtLine(SQLITE_IOERR_CLOSE(10 | (16<<8)), "close", | ||||
| 40183 | pFile ? pFile->zPath : 0, lineno); | ||||
| 40184 | } | ||||
| 40185 | } | ||||
| 40186 | |||||
| 40187 | /* | ||||
| 40188 | ** Set the pFile->lastErrno. Do this in a subroutine as that provides | ||||
| 40189 | ** a convenient place to set a breakpoint. | ||||
| 40190 | */ | ||||
| 40191 | static void storeLastErrno(unixFile *pFile, int error){ | ||||
| 40192 | pFile->lastErrno = error; | ||||
| 40193 | } | ||||
| 40194 | |||||
| 40195 | /* | ||||
| 40196 | ** Close all file descriptors accumulated in the unixInodeInfo->pUnused list. | ||||
| 40197 | */ | ||||
| 40198 | static void closePendingFds(unixFile *pFile){ | ||||
| 40199 | unixInodeInfo *pInode = pFile->pInode; | ||||
| 40200 | UnixUnusedFd *p; | ||||
| 40201 | UnixUnusedFd *pNext; | ||||
| 40202 | assert( unixFileMutexHeld(pFile) )((void) (0)); | ||||
| 40203 | for(p=pInode->pUnused; p; p=pNext){ | ||||
| 40204 | pNext = p->pNext; | ||||
| 40205 | robust_close(pFile, p->fd, __LINE__40205); | ||||
| 40206 | sqlite3_free(p); | ||||
| 40207 | } | ||||
| 40208 | pInode->pUnused = 0; | ||||
| 40209 | } | ||||
| 40210 | |||||
| 40211 | /* | ||||
| 40212 | ** Release a unixInodeInfo structure previously allocated by findInodeInfo(). | ||||
| 40213 | ** | ||||
| 40214 | ** The global mutex must be held when this routine is called, but the mutex | ||||
| 40215 | ** on the inode being deleted must NOT be held. | ||||
| 40216 | */ | ||||
| 40217 | static void releaseInodeInfo(unixFile *pFile){ | ||||
| 40218 | unixInodeInfo *pInode = pFile->pInode; | ||||
| 40219 | assert( unixMutexHeld() )((void) (0)); | ||||
| 40220 | assert( unixFileMutexNotheld(pFile) )((void) (0)); | ||||
| 40221 | if( ALWAYS(pInode)(pInode) ){ | ||||
| 40222 | pInode->nRef--; | ||||
| 40223 | if( pInode->nRef==0 ){ | ||||
| 40224 | assert( pInode->pShmNode==0 )((void) (0)); | ||||
| 40225 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 40226 | closePendingFds(pFile); | ||||
| 40227 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 40228 | if( pInode->pPrev ){ | ||||
| 40229 | assert( pInode->pPrev->pNext==pInode )((void) (0)); | ||||
| 40230 | pInode->pPrev->pNext = pInode->pNext; | ||||
| 40231 | }else{ | ||||
| 40232 | assert( inodeList==pInode )((void) (0)); | ||||
| 40233 | inodeList = pInode->pNext; | ||||
| 40234 | } | ||||
| 40235 | if( pInode->pNext ){ | ||||
| 40236 | assert( pInode->pNext->pPrev==pInode )((void) (0)); | ||||
| 40237 | pInode->pNext->pPrev = pInode->pPrev; | ||||
| 40238 | } | ||||
| 40239 | sqlite3_mutex_free(pInode->pLockMutex); | ||||
| 40240 | sqlite3_free(pInode); | ||||
| 40241 | } | ||||
| 40242 | } | ||||
| 40243 | } | ||||
| 40244 | |||||
| 40245 | /* | ||||
| 40246 | ** Given a file descriptor, locate the unixInodeInfo object that | ||||
| 40247 | ** describes that file descriptor. Create a new one if necessary. The | ||||
| 40248 | ** return value might be uninitialized if an error occurs. | ||||
| 40249 | ** | ||||
| 40250 | ** The global mutex must held when calling this routine. | ||||
| 40251 | ** | ||||
| 40252 | ** Return an appropriate error code. | ||||
| 40253 | */ | ||||
| 40254 | static int findInodeInfo( | ||||
| 40255 | unixFile *pFile, /* Unix file with file desc used in the key */ | ||||
| 40256 | unixInodeInfo **ppInode /* Return the unixInodeInfo object here */ | ||||
| 40257 | ){ | ||||
| 40258 | int rc; /* System call return code */ | ||||
| 40259 | int fd; /* The file descriptor for pFile */ | ||||
| 40260 | struct unixFileId fileId; /* Lookup key for the unixInodeInfo */ | ||||
| 40261 | struct stat statbuf; /* Low-level file information */ | ||||
| 40262 | unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */ | ||||
| 40263 | |||||
| 40264 | assert( unixMutexHeld() )((void) (0)); | ||||
| 40265 | |||||
| 40266 | /* Get low-level information about the file that we can used to | ||||
| 40267 | ** create a unique name for the file. | ||||
| 40268 | */ | ||||
| 40269 | fd = pFile->h; | ||||
| 40270 | rc = osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(fd, &statbuf); | ||||
| 40271 | if( rc!=0 ){ | ||||
| 40272 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 40273 | #if defined(EOVERFLOW75) && defined(SQLITE_DISABLE_LFS) | ||||
| 40274 | if( pFile->lastErrno==EOVERFLOW75 ) return SQLITE_NOLFS22; | ||||
| 40275 | #endif | ||||
| 40276 | return SQLITE_IOERR10; | ||||
| 40277 | } | ||||
| 40278 | |||||
| 40279 | #ifdef __APPLE__ | ||||
| 40280 | /* On OS X on an msdos filesystem, the inode number is reported | ||||
| 40281 | ** incorrectly for zero-size files. See ticket #3260. To work | ||||
| 40282 | ** around this problem (we consider it a bug in OS X, not SQLite) | ||||
| 40283 | ** we always increase the file size to 1 by writing a single byte | ||||
| 40284 | ** prior to accessing the inode number. The one byte written is | ||||
| 40285 | ** an ASCII 'S' character which also happens to be the first byte | ||||
| 40286 | ** in the header of every SQLite database. In this way, if there | ||||
| 40287 | ** is a race condition such that another thread has already populated | ||||
| 40288 | ** the first page of the database, no damage is done. | ||||
| 40289 | */ | ||||
| 40290 | if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS0x1)!=0 ){ | ||||
| 40291 | do{ rc = osWrite((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)(fd, "S", 1); }while( rc<0 && errno(*__errno_location ())==EINTR4 ); | ||||
| 40292 | if( rc!=1 ){ | ||||
| 40293 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 40294 | return SQLITE_IOERR10; | ||||
| 40295 | } | ||||
| 40296 | rc = osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(fd, &statbuf); | ||||
| 40297 | if( rc!=0 ){ | ||||
| 40298 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 40299 | return SQLITE_IOERR10; | ||||
| 40300 | } | ||||
| 40301 | } | ||||
| 40302 | #endif | ||||
| 40303 | |||||
| 40304 | memset(&fileId, 0, sizeof(fileId)); | ||||
| 40305 | fileId.dev = statbuf.st_dev; | ||||
| 40306 | #if OS_VXWORKS0 | ||||
| 40307 | fileId.pId = pFile->pId; | ||||
| 40308 | #else | ||||
| 40309 | fileId.ino = (u64)statbuf.st_ino; | ||||
| 40310 | #endif | ||||
| 40311 | assert( unixMutexHeld() )((void) (0)); | ||||
| 40312 | pInode = inodeList; | ||||
| 40313 | while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){ | ||||
| 40314 | pInode = pInode->pNext; | ||||
| 40315 | } | ||||
| 40316 | if( pInode==0 ){ | ||||
| 40317 | pInode = sqlite3_malloc64( sizeof(*pInode) ); | ||||
| 40318 | if( pInode==0 ){ | ||||
| 40319 | return SQLITE_NOMEM_BKPT7; | ||||
| 40320 | } | ||||
| 40321 | memset(pInode, 0, sizeof(*pInode)); | ||||
| 40322 | memcpy(&pInode->fileId, &fileId, sizeof(fileId)); | ||||
| 40323 | if( sqlite3GlobalConfigsqlite3Config.bCoreMutex ){ | ||||
| 40324 | pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST0); | ||||
| 40325 | if( pInode->pLockMutex==0 ){ | ||||
| 40326 | sqlite3_free(pInode); | ||||
| 40327 | return SQLITE_NOMEM_BKPT7; | ||||
| 40328 | } | ||||
| 40329 | } | ||||
| 40330 | pInode->nRef = 1; | ||||
| 40331 | assert( unixMutexHeld() )((void) (0)); | ||||
| 40332 | pInode->pNext = inodeList; | ||||
| 40333 | pInode->pPrev = 0; | ||||
| 40334 | if( inodeList ) inodeList->pPrev = pInode; | ||||
| 40335 | inodeList = pInode; | ||||
| 40336 | }else{ | ||||
| 40337 | pInode->nRef++; | ||||
| 40338 | } | ||||
| 40339 | *ppInode = pInode; | ||||
| 40340 | return SQLITE_OK0; | ||||
| 40341 | } | ||||
| 40342 | |||||
| 40343 | /* | ||||
| 40344 | ** Return TRUE if pFile has been renamed or unlinked since it was first opened. | ||||
| 40345 | */ | ||||
| 40346 | static int fileHasMoved(unixFile *pFile){ | ||||
| 40347 | #if OS_VXWORKS0 | ||||
| 40348 | return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId; | ||||
| 40349 | #else | ||||
| 40350 | struct stat buf; | ||||
| 40351 | return pFile->pInode!=0 && | ||||
| 40352 | (osStat((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)(pFile->zPath, &buf)!=0 | ||||
| 40353 | || (u64)buf.st_ino!=pFile->pInode->fileId.ino); | ||||
| 40354 | #endif | ||||
| 40355 | } | ||||
| 40356 | |||||
| 40357 | |||||
| 40358 | /* | ||||
| 40359 | ** Check a unixFile that is a database. Verify the following: | ||||
| 40360 | ** | ||||
| 40361 | ** (1) There is exactly one hard link on the file | ||||
| 40362 | ** (2) The file is not a symbolic link | ||||
| 40363 | ** (3) The file has not been renamed or unlinked | ||||
| 40364 | ** | ||||
| 40365 | ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right. | ||||
| 40366 | */ | ||||
| 40367 | static void verifyDbFile(unixFile *pFile){ | ||||
| 40368 | struct stat buf; | ||||
| 40369 | int rc; | ||||
| 40370 | |||||
| 40371 | /* These verifications occurs for the main database only */ | ||||
| 40372 | if( pFile->ctrlFlags & UNIXFILE_NOLOCK0x80 ) return; | ||||
| 40373 | |||||
| 40374 | rc = osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(pFile->h, &buf); | ||||
| 40375 | if( rc!=0 ){ | ||||
| 40376 | sqlite3_log(SQLITE_WARNING28, "cannot fstat db file %s", pFile->zPath); | ||||
| 40377 | return; | ||||
| 40378 | } | ||||
| 40379 | if( buf.st_nlink==0 ){ | ||||
| 40380 | sqlite3_log(SQLITE_WARNING28, "file unlinked while open: %s", pFile->zPath); | ||||
| 40381 | return; | ||||
| 40382 | } | ||||
| 40383 | if( buf.st_nlink>1 ){ | ||||
| 40384 | sqlite3_log(SQLITE_WARNING28, "multiple links to file: %s", pFile->zPath); | ||||
| 40385 | return; | ||||
| 40386 | } | ||||
| 40387 | if( fileHasMoved(pFile) ){ | ||||
| 40388 | sqlite3_log(SQLITE_WARNING28, "file renamed while open: %s", pFile->zPath); | ||||
| 40389 | return; | ||||
| 40390 | } | ||||
| 40391 | } | ||||
| 40392 | |||||
| 40393 | |||||
| 40394 | /* | ||||
| 40395 | ** This routine checks if there is a RESERVED lock held on the specified | ||||
| 40396 | ** file by this or any other process. If such a lock is held, set *pResOut | ||||
| 40397 | ** to a non-zero value otherwise *pResOut is set to zero. The return value | ||||
| 40398 | ** is set to SQLITE_OK unless an I/O error occurs during lock checking. | ||||
| 40399 | */ | ||||
| 40400 | static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ | ||||
| 40401 | int rc = SQLITE_OK0; | ||||
| 40402 | int reserved = 0; | ||||
| 40403 | unixFile *pFile = (unixFile*)id; | ||||
| 40404 | |||||
| 40405 | SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); | ||||
| 40406 | |||||
| 40407 | assert( pFile )((void) (0)); | ||||
| 40408 | assert( pFile->eFileLock<=SHARED_LOCK )((void) (0)); | ||||
| 40409 | sqlite3_mutex_enter(pFile->pInode->pLockMutex); | ||||
| 40410 | |||||
| 40411 | /* Check if a thread in this process holds such a lock */ | ||||
| 40412 | if( pFile->pInode->eFileLock>SHARED_LOCK1 ){ | ||||
| 40413 | reserved = 1; | ||||
| 40414 | } | ||||
| 40415 | |||||
| 40416 | /* Otherwise see if some other process holds it. | ||||
| 40417 | */ | ||||
| 40418 | #ifndef __DJGPP__ | ||||
| 40419 | if( !reserved && !pFile->pInode->bProcessLock ){ | ||||
| 40420 | struct flock lock; | ||||
| 40421 | lock.l_whence = SEEK_SET0; | ||||
| 40422 | lock.l_start = RESERVED_BYTE(sqlite3PendingByte+1); | ||||
| 40423 | lock.l_len = 1; | ||||
| 40424 | lock.l_type = F_WRLCK1; | ||||
| 40425 | if( osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(pFile->h, F_GETLK5, &lock) ){ | ||||
| 40426 | rc = SQLITE_IOERR_CHECKRESERVEDLOCK(10 | (14<<8)); | ||||
| 40427 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 40428 | } else if( lock.l_type!=F_UNLCK2 ){ | ||||
| 40429 | reserved = 1; | ||||
| 40430 | } | ||||
| 40431 | } | ||||
| 40432 | #endif | ||||
| 40433 | |||||
| 40434 | sqlite3_mutex_leave(pFile->pInode->pLockMutex); | ||||
| 40435 | OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); | ||||
| 40436 | |||||
| 40437 | *pResOut = reserved; | ||||
| 40438 | return rc; | ||||
| 40439 | } | ||||
| 40440 | |||||
| 40441 | /* Forward declaration*/ | ||||
| 40442 | static int unixSleep(sqlite3_vfs*,int); | ||||
| 40443 | |||||
| 40444 | /* | ||||
| 40445 | ** Set a posix-advisory-lock. | ||||
| 40446 | ** | ||||
| 40447 | ** There are two versions of this routine. If compiled with | ||||
| 40448 | ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter | ||||
| 40449 | ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout | ||||
| 40450 | ** value is set, then it is the number of milliseconds to wait before | ||||
| 40451 | ** failing the lock. The iBusyTimeout value is always reset back to | ||||
| 40452 | ** zero on each call. | ||||
| 40453 | ** | ||||
| 40454 | ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking | ||||
| 40455 | ** attempt to set the lock. | ||||
| 40456 | */ | ||||
| 40457 | #ifndef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 40458 | # define osSetPosixAdvisoryLock(h,x,t)((int(*)(int,int,...))aSyscall[7].pCurrent)(h,6,x) osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(h,F_SETLK6,x) | ||||
| 40459 | #else | ||||
| 40460 | static int osSetPosixAdvisoryLock(((int(*)(int,int,...))aSyscall[7].pCurrent)(int h,6,struct flock *pLock) | ||||
| 40461 | int h, /* The file descriptor on which to take the lock */((int(*)(int,int,...))aSyscall[7].pCurrent)(int h,6,struct flock *pLock) | ||||
| 40462 | struct flock *pLock, /* The description of the lock */((int(*)(int,int,...))aSyscall[7].pCurrent)(int h,6,struct flock *pLock) | ||||
| 40463 | unixFile *pFile /* Structure holding timeout value */((int(*)(int,int,...))aSyscall[7].pCurrent)(int h,6,struct flock *pLock) | ||||
| 40464 | )((int(*)(int,int,...))aSyscall[7].pCurrent)(int h,6,struct flock *pLock){ | ||||
| 40465 | int tm = pFile->iBusyTimeout; | ||||
| 40466 | int rc = osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(h,F_SETLK6,pLock); | ||||
| 40467 | while( rc<0 && tm>0 ){ | ||||
| 40468 | /* On systems that support some kind of blocking file lock with a timeout, | ||||
| 40469 | ** make appropriate changes here to invoke that blocking file lock. On | ||||
| 40470 | ** generic posix, however, there is no such API. So we simply try the | ||||
| 40471 | ** lock once every millisecond until either the timeout expires, or until | ||||
| 40472 | ** the lock is obtained. */ | ||||
| 40473 | unixSleep(0,1000); | ||||
| 40474 | rc = osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(h,F_SETLK6,pLock); | ||||
| 40475 | tm--; | ||||
| 40476 | } | ||||
| 40477 | return rc; | ||||
| 40478 | } | ||||
| 40479 | #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ | ||||
| 40480 | |||||
| 40481 | |||||
| 40482 | /* | ||||
| 40483 | ** Attempt to set a system-lock on the file pFile. The lock is | ||||
| 40484 | ** described by pLock. | ||||
| 40485 | ** | ||||
| 40486 | ** If the pFile was opened read/write from unix-excl, then the only lock | ||||
| 40487 | ** ever obtained is an exclusive lock, and it is obtained exactly once | ||||
| 40488 | ** the first time any lock is attempted. All subsequent system locking | ||||
| 40489 | ** operations become no-ops. Locking operations still happen internally, | ||||
| 40490 | ** in order to coordinate access between separate database connections | ||||
| 40491 | ** within this process, but all of that is handled in memory and the | ||||
| 40492 | ** operating system does not participate. | ||||
| 40493 | ** | ||||
| 40494 | ** This function is a pass-through to fcntl(F_SETLK) if pFile is using | ||||
| 40495 | ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl" | ||||
| 40496 | ** and is read-only. | ||||
| 40497 | ** | ||||
| 40498 | ** Zero is returned if the call completes successfully, or -1 if a call | ||||
| 40499 | ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()). | ||||
| 40500 | */ | ||||
| 40501 | static int unixFileLock(unixFile *pFile, struct flock *pLock){ | ||||
| 40502 | int rc; | ||||
| 40503 | unixInodeInfo *pInode = pFile->pInode; | ||||
| 40504 | assert( pInode!=0 )((void) (0)); | ||||
| 40505 | assert( sqlite3_mutex_held(pInode->pLockMutex) )((void) (0)); | ||||
| 40506 | if( (pFile->ctrlFlags & (UNIXFILE_EXCL0x01|UNIXFILE_RDONLY0x02))==UNIXFILE_EXCL0x01 ){ | ||||
| 40507 | if( pInode->bProcessLock==0 ){ | ||||
| 40508 | struct flock lock; | ||||
| 40509 | /* assert( pInode->nLock==0 ); <-- Not true if unix-excl READONLY used */ | ||||
| 40510 | lock.l_whence = SEEK_SET0; | ||||
| 40511 | lock.l_start = SHARED_FIRST(sqlite3PendingByte+2); | ||||
| 40512 | lock.l_len = SHARED_SIZE510; | ||||
| 40513 | lock.l_type = F_WRLCK1; | ||||
| 40514 | rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile)((int(*)(int,int,...))aSyscall[7].pCurrent)(pFile->h,6,& lock); | ||||
| 40515 | if( rc<0 ) return rc; | ||||
| 40516 | pInode->bProcessLock = 1; | ||||
| 40517 | pInode->nLock++; | ||||
| 40518 | }else{ | ||||
| 40519 | rc = 0; | ||||
| 40520 | } | ||||
| 40521 | }else{ | ||||
| 40522 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 40523 | if( pFile->bBlockOnConnect && pLock->l_type==F_RDLCK0 | ||||
| 40524 | && pLock->l_start==SHARED_FIRST(sqlite3PendingByte+2) && pLock->l_len==SHARED_SIZE510 | ||||
| 40525 | ){ | ||||
| 40526 | rc = osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(pFile->h, F_SETLKW7, pLock); | ||||
| 40527 | }else | ||||
| 40528 | #endif | ||||
| 40529 | rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile)((int(*)(int,int,...))aSyscall[7].pCurrent)(pFile->h,6,pLock ); | ||||
| 40530 | } | ||||
| 40531 | return rc; | ||||
| 40532 | } | ||||
| 40533 | |||||
| 40534 | /* | ||||
| 40535 | ** Lock the file with the lock specified by parameter eFileLock - one | ||||
| 40536 | ** of the following: | ||||
| 40537 | ** | ||||
| 40538 | ** (1) SHARED_LOCK | ||||
| 40539 | ** (2) RESERVED_LOCK | ||||
| 40540 | ** (3) PENDING_LOCK | ||||
| 40541 | ** (4) EXCLUSIVE_LOCK | ||||
| 40542 | ** | ||||
| 40543 | ** Sometimes when requesting one lock state, additional lock states | ||||
| 40544 | ** are inserted in between. The locking might fail on one of the later | ||||
| 40545 | ** transitions leaving the lock state different from what it started but | ||||
| 40546 | ** still short of its goal. The following chart shows the allowed | ||||
| 40547 | ** transitions and the inserted intermediate states: | ||||
| 40548 | ** | ||||
| 40549 | ** UNLOCKED -> SHARED | ||||
| 40550 | ** SHARED -> RESERVED | ||||
| 40551 | ** SHARED -> EXCLUSIVE | ||||
| 40552 | ** RESERVED -> (PENDING) -> EXCLUSIVE | ||||
| 40553 | ** PENDING -> EXCLUSIVE | ||||
| 40554 | ** | ||||
| 40555 | ** This routine will only increase a lock. Use the sqlite3OsUnlock() | ||||
| 40556 | ** routine to lower a locking level. | ||||
| 40557 | */ | ||||
| 40558 | static int unixLock(sqlite3_file *id, int eFileLock){ | ||||
| 40559 | /* The following describes the implementation of the various locks and | ||||
| 40560 | ** lock transitions in terms of the POSIX advisory shared and exclusive | ||||
| 40561 | ** lock primitives (called read-locks and write-locks below, to avoid | ||||
| 40562 | ** confusion with SQLite lock names). The algorithms are complicated | ||||
| 40563 | ** slightly in order to be compatible with Windows95 systems simultaneously | ||||
| 40564 | ** accessing the same database file, in case that is ever required. | ||||
| 40565 | ** | ||||
| 40566 | ** Symbols defined in os.h identify the 'pending byte' and the 'reserved | ||||
| 40567 | ** byte', each single bytes at well known offsets, and the 'shared byte | ||||
| 40568 | ** range', a range of 510 bytes at a well known offset. | ||||
| 40569 | ** | ||||
| 40570 | ** To obtain a SHARED lock, a read-lock is obtained on the 'pending | ||||
| 40571 | ** byte'. If this is successful, 'shared byte range' is read-locked | ||||
| 40572 | ** and the lock on the 'pending byte' released. (Legacy note: When | ||||
| 40573 | ** SQLite was first developed, Windows95 systems were still very common, | ||||
| 40574 | ** and Windows95 lacks a shared-lock capability. So on Windows95, a | ||||
| 40575 | ** single randomly selected by from the 'shared byte range' is locked. | ||||
| 40576 | ** Windows95 is now pretty much extinct, but this work-around for the | ||||
| 40577 | ** lack of shared-locks on Windows95 lives on, for backwards | ||||
| 40578 | ** compatibility.) | ||||
| 40579 | ** | ||||
| 40580 | ** A process may only obtain a RESERVED lock after it has a SHARED lock. | ||||
| 40581 | ** A RESERVED lock is implemented by grabbing a write-lock on the | ||||
| 40582 | ** 'reserved byte'. | ||||
| 40583 | ** | ||||
| 40584 | ** An EXCLUSIVE lock may only be requested after either a SHARED or | ||||
| 40585 | ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining | ||||
| 40586 | ** a write-lock on the entire 'shared byte range'. Since all other locks | ||||
| 40587 | ** require a read-lock on one of the bytes within this range, this ensures | ||||
| 40588 | ** that no other locks are held on the database. | ||||
| 40589 | ** | ||||
| 40590 | ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then | ||||
| 40591 | ** a PENDING lock is obtained first. A PENDING lock is implemented by | ||||
| 40592 | ** obtaining a write-lock on the 'pending byte'. This ensures that no new | ||||
| 40593 | ** SHARED locks can be obtained, but existing SHARED locks are allowed to | ||||
| 40594 | ** persist. If the call to this function fails to obtain the EXCLUSIVE | ||||
| 40595 | ** lock in this case, it holds the PENDING lock instead. The client may | ||||
| 40596 | ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED | ||||
| 40597 | ** locks have cleared. | ||||
| 40598 | */ | ||||
| 40599 | int rc = SQLITE_OK0; | ||||
| 40600 | unixFile *pFile = (unixFile*)id; | ||||
| 40601 | unixInodeInfo *pInode; | ||||
| 40602 | struct flock lock; | ||||
| 40603 | int tErrno = 0; | ||||
| 40604 | |||||
| 40605 | assert( pFile )((void) (0)); | ||||
| 40606 | OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, | ||||
| 40607 | azFileLock(eFileLock), azFileLock(pFile->eFileLock), | ||||
| 40608 | azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared, | ||||
| 40609 | osGetpid(0))); | ||||
| 40610 | |||||
| 40611 | /* If there is already a lock of this type or more restrictive on the | ||||
| 40612 | ** unixFile, do nothing. Don't use the end_lock: exit path, as | ||||
| 40613 | ** unixEnterMutex() hasn't been called yet. | ||||
| 40614 | */ | ||||
| 40615 | if( pFile->eFileLock>=eFileLock ){ | ||||
| 40616 | OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h, | ||||
| 40617 | azFileLock(eFileLock))); | ||||
| 40618 | return SQLITE_OK0; | ||||
| 40619 | } | ||||
| 40620 | |||||
| 40621 | /* Make sure the locking sequence is correct. | ||||
| 40622 | ** (1) We never move from unlocked to anything higher than shared lock. | ||||
| 40623 | ** (2) SQLite never explicitly requests a pending lock. | ||||
| 40624 | ** (3) A shared lock is always held when a reserve lock is requested. | ||||
| 40625 | */ | ||||
| 40626 | assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK )((void) (0)); | ||||
| 40627 | assert( eFileLock!=PENDING_LOCK )((void) (0)); | ||||
| 40628 | assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK )((void) (0)); | ||||
| 40629 | |||||
| 40630 | /* This mutex is needed because pFile->pInode is shared across threads | ||||
| 40631 | */ | ||||
| 40632 | pInode = pFile->pInode; | ||||
| 40633 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 40634 | |||||
| 40635 | /* If some thread using this PID has a lock via a different unixFile* | ||||
| 40636 | ** handle that precludes the requested lock, return BUSY. | ||||
| 40637 | */ | ||||
| 40638 | if( (pFile->eFileLock!=pInode->eFileLock && | ||||
| 40639 | (pInode->eFileLock>=PENDING_LOCK3 || eFileLock>SHARED_LOCK1)) | ||||
| 40640 | ){ | ||||
| 40641 | rc = SQLITE_BUSY5; | ||||
| 40642 | goto end_lock; | ||||
| 40643 | } | ||||
| 40644 | |||||
| 40645 | /* If a SHARED lock is requested, and some thread using this PID already | ||||
| 40646 | ** has a SHARED or RESERVED lock, then increment reference counts and | ||||
| 40647 | ** return SQLITE_OK. | ||||
| 40648 | */ | ||||
| 40649 | if( eFileLock==SHARED_LOCK1 && | ||||
| 40650 | (pInode->eFileLock==SHARED_LOCK1 || pInode->eFileLock==RESERVED_LOCK2) ){ | ||||
| 40651 | assert( eFileLock==SHARED_LOCK )((void) (0)); | ||||
| 40652 | assert( pFile->eFileLock==0 )((void) (0)); | ||||
| 40653 | assert( pInode->nShared>0 )((void) (0)); | ||||
| 40654 | pFile->eFileLock = SHARED_LOCK1; | ||||
| 40655 | pInode->nShared++; | ||||
| 40656 | pInode->nLock++; | ||||
| 40657 | goto end_lock; | ||||
| 40658 | } | ||||
| 40659 | |||||
| 40660 | |||||
| 40661 | /* A PENDING lock is needed before acquiring a SHARED lock and before | ||||
| 40662 | ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will | ||||
| 40663 | ** be released. | ||||
| 40664 | */ | ||||
| 40665 | lock.l_len = 1L; | ||||
| 40666 | lock.l_whence = SEEK_SET0; | ||||
| 40667 | if( eFileLock==SHARED_LOCK1 | ||||
| 40668 | || (eFileLock==EXCLUSIVE_LOCK4 && pFile->eFileLock==RESERVED_LOCK2) | ||||
| 40669 | ){ | ||||
| 40670 | lock.l_type = (eFileLock==SHARED_LOCK1?F_RDLCK0:F_WRLCK1); | ||||
| 40671 | lock.l_start = PENDING_BYTEsqlite3PendingByte; | ||||
| 40672 | if( unixFileLock(pFile, &lock) ){ | ||||
| 40673 | tErrno = errno(*__errno_location ()); | ||||
| 40674 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK(10 | (15<<8))); | ||||
| 40675 | if( rc!=SQLITE_BUSY5 ){ | ||||
| 40676 | storeLastErrno(pFile, tErrno); | ||||
| 40677 | } | ||||
| 40678 | goto end_lock; | ||||
| 40679 | }else if( eFileLock==EXCLUSIVE_LOCK4 ){ | ||||
| 40680 | pFile->eFileLock = PENDING_LOCK3; | ||||
| 40681 | pInode->eFileLock = PENDING_LOCK3; | ||||
| 40682 | } | ||||
| 40683 | } | ||||
| 40684 | |||||
| 40685 | |||||
| 40686 | /* If control gets to this point, then actually go ahead and make | ||||
| 40687 | ** operating system calls for the specified lock. | ||||
| 40688 | */ | ||||
| 40689 | if( eFileLock==SHARED_LOCK1 ){ | ||||
| 40690 | assert( pInode->nShared==0 )((void) (0)); | ||||
| 40691 | assert( pInode->eFileLock==0 )((void) (0)); | ||||
| 40692 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 40693 | |||||
| 40694 | /* Now get the read-lock */ | ||||
| 40695 | lock.l_start = SHARED_FIRST(sqlite3PendingByte+2); | ||||
| 40696 | lock.l_len = SHARED_SIZE510; | ||||
| 40697 | if( unixFileLock(pFile, &lock) ){ | ||||
| 40698 | tErrno = errno(*__errno_location ()); | ||||
| 40699 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK(10 | (15<<8))); | ||||
| 40700 | } | ||||
| 40701 | |||||
| 40702 | /* Drop the temporary PENDING lock */ | ||||
| 40703 | lock.l_start = PENDING_BYTEsqlite3PendingByte; | ||||
| 40704 | lock.l_len = 1L; | ||||
| 40705 | lock.l_type = F_UNLCK2; | ||||
| 40706 | if( unixFileLock(pFile, &lock) && rc==SQLITE_OK0 ){ | ||||
| 40707 | /* This could happen with a network mount */ | ||||
| 40708 | tErrno = errno(*__errno_location ()); | ||||
| 40709 | rc = SQLITE_IOERR_UNLOCK(10 | (8<<8)); | ||||
| 40710 | } | ||||
| 40711 | |||||
| 40712 | if( rc ){ | ||||
| 40713 | if( rc!=SQLITE_BUSY5 ){ | ||||
| 40714 | storeLastErrno(pFile, tErrno); | ||||
| 40715 | } | ||||
| 40716 | goto end_lock; | ||||
| 40717 | }else{ | ||||
| 40718 | pFile->eFileLock = SHARED_LOCK1; | ||||
| 40719 | pInode->nLock++; | ||||
| 40720 | pInode->nShared = 1; | ||||
| 40721 | } | ||||
| 40722 | }else if( eFileLock==EXCLUSIVE_LOCK4 && pInode->nShared>1 ){ | ||||
| 40723 | /* We are trying for an exclusive lock but another thread in this | ||||
| 40724 | ** same process is still holding a shared lock. */ | ||||
| 40725 | rc = SQLITE_BUSY5; | ||||
| 40726 | }else{ | ||||
| 40727 | /* The request was for a RESERVED or EXCLUSIVE lock. It is | ||||
| 40728 | ** assumed that there is a SHARED or greater lock on the file | ||||
| 40729 | ** already. | ||||
| 40730 | */ | ||||
| 40731 | assert( 0!=pFile->eFileLock )((void) (0)); | ||||
| 40732 | lock.l_type = F_WRLCK1; | ||||
| 40733 | |||||
| 40734 | assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 40735 | if( eFileLock==RESERVED_LOCK2 ){ | ||||
| 40736 | lock.l_start = RESERVED_BYTE(sqlite3PendingByte+1); | ||||
| 40737 | lock.l_len = 1L; | ||||
| 40738 | }else{ | ||||
| 40739 | lock.l_start = SHARED_FIRST(sqlite3PendingByte+2); | ||||
| 40740 | lock.l_len = SHARED_SIZE510; | ||||
| 40741 | } | ||||
| 40742 | |||||
| 40743 | if( unixFileLock(pFile, &lock) ){ | ||||
| 40744 | tErrno = errno(*__errno_location ()); | ||||
| 40745 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK(10 | (15<<8))); | ||||
| 40746 | if( rc!=SQLITE_BUSY5 ){ | ||||
| 40747 | storeLastErrno(pFile, tErrno); | ||||
| 40748 | } | ||||
| 40749 | } | ||||
| 40750 | } | ||||
| 40751 | |||||
| 40752 | |||||
| 40753 | #ifdef SQLITE_DEBUG | ||||
| 40754 | /* Set up the transaction-counter change checking flags when | ||||
| 40755 | ** transitioning from a SHARED to a RESERVED lock. The change | ||||
| 40756 | ** from SHARED to RESERVED marks the beginning of a normal | ||||
| 40757 | ** write operation (not a hot journal rollback). | ||||
| 40758 | */ | ||||
| 40759 | if( rc==SQLITE_OK0 | ||||
| 40760 | && pFile->eFileLock<=SHARED_LOCK1 | ||||
| 40761 | && eFileLock==RESERVED_LOCK2 | ||||
| 40762 | ){ | ||||
| 40763 | pFile->transCntrChng = 0; | ||||
| 40764 | pFile->dbUpdate = 0; | ||||
| 40765 | pFile->inNormalWrite = 1; | ||||
| 40766 | } | ||||
| 40767 | #endif | ||||
| 40768 | |||||
| 40769 | if( rc==SQLITE_OK0 ){ | ||||
| 40770 | pFile->eFileLock = eFileLock; | ||||
| 40771 | pInode->eFileLock = eFileLock; | ||||
| 40772 | } | ||||
| 40773 | |||||
| 40774 | end_lock: | ||||
| 40775 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 40776 | OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), | ||||
| 40777 | rc==SQLITE_OK ? "ok" : "failed")); | ||||
| 40778 | return rc; | ||||
| 40779 | } | ||||
| 40780 | |||||
| 40781 | /* | ||||
| 40782 | ** Add the file descriptor used by file handle pFile to the corresponding | ||||
| 40783 | ** pUnused list. | ||||
| 40784 | */ | ||||
| 40785 | static void setPendingFd(unixFile *pFile){ | ||||
| 40786 | unixInodeInfo *pInode = pFile->pInode; | ||||
| 40787 | UnixUnusedFd *p = pFile->pPreallocatedUnused; | ||||
| 40788 | assert( unixFileMutexHeld(pFile) )((void) (0)); | ||||
| 40789 | p->pNext = pInode->pUnused; | ||||
| 40790 | pInode->pUnused = p; | ||||
| 40791 | pFile->h = -1; | ||||
| 40792 | pFile->pPreallocatedUnused = 0; | ||||
| 40793 | } | ||||
| 40794 | |||||
| 40795 | /* | ||||
| 40796 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 40797 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 40798 | ** | ||||
| 40799 | ** If the locking level of the file descriptor is already at or below | ||||
| 40800 | ** the requested locking level, this routine is a no-op. | ||||
| 40801 | ** | ||||
| 40802 | ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED | ||||
| 40803 | ** the byte range is divided into 2 parts and the first part is unlocked then | ||||
| 40804 | ** set to a read lock, then the other part is simply unlocked. This works | ||||
| 40805 | ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to | ||||
| 40806 | ** remove the write lock on a region when a read lock is set. | ||||
| 40807 | */ | ||||
| 40808 | static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){ | ||||
| 40809 | unixFile *pFile = (unixFile*)id; | ||||
| 40810 | unixInodeInfo *pInode; | ||||
| 40811 | struct flock lock; | ||||
| 40812 | int rc = SQLITE_OK0; | ||||
| 40813 | |||||
| 40814 | assert( pFile )((void) (0)); | ||||
| 40815 | OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock, | ||||
| 40816 | pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, | ||||
| 40817 | osGetpid(0))); | ||||
| 40818 | |||||
| 40819 | assert( eFileLock<=SHARED_LOCK )((void) (0)); | ||||
| 40820 | if( pFile->eFileLock<=eFileLock ){ | ||||
| 40821 | return SQLITE_OK0; | ||||
| 40822 | } | ||||
| 40823 | pInode = pFile->pInode; | ||||
| 40824 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 40825 | assert( pInode->nShared!=0 )((void) (0)); | ||||
| 40826 | if( pFile->eFileLock>SHARED_LOCK1 ){ | ||||
| 40827 | assert( pInode->eFileLock==pFile->eFileLock )((void) (0)); | ||||
| 40828 | |||||
| 40829 | #ifdef SQLITE_DEBUG | ||||
| 40830 | /* When reducing a lock such that other processes can start | ||||
| 40831 | ** reading the database file again, make sure that the | ||||
| 40832 | ** transaction counter was updated if any part of the database | ||||
| 40833 | ** file changed. If the transaction counter is not updated, | ||||
| 40834 | ** other connections to the same file might not realize that | ||||
| 40835 | ** the file has changed and hence might not know to flush their | ||||
| 40836 | ** cache. The use of a stale cache can lead to database corruption. | ||||
| 40837 | */ | ||||
| 40838 | pFile->inNormalWrite = 0; | ||||
| 40839 | #endif | ||||
| 40840 | |||||
| 40841 | /* downgrading to a shared lock on NFS involves clearing the write lock | ||||
| 40842 | ** before establishing the readlock - to avoid a race condition we downgrade | ||||
| 40843 | ** the lock in 2 blocks, so that part of the range will be covered by a | ||||
| 40844 | ** write lock until the rest is covered by a read lock: | ||||
| 40845 | ** 1: [WWWWW] | ||||
| 40846 | ** 2: [....W] | ||||
| 40847 | ** 3: [RRRRW] | ||||
| 40848 | ** 4: [RRRR.] | ||||
| 40849 | */ | ||||
| 40850 | if( eFileLock==SHARED_LOCK1 ){ | ||||
| 40851 | #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 40852 | (void)handleNFSUnlock; | ||||
| 40853 | assert( handleNFSUnlock==0 )((void) (0)); | ||||
| 40854 | #endif | ||||
| 40855 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 40856 | if( handleNFSUnlock ){ | ||||
| 40857 | int tErrno; /* Error code from system call errors */ | ||||
| 40858 | off_t divSize = SHARED_SIZE510 - 1; | ||||
| 40859 | |||||
| 40860 | lock.l_type = F_UNLCK2; | ||||
| 40861 | lock.l_whence = SEEK_SET0; | ||||
| 40862 | lock.l_start = SHARED_FIRST(sqlite3PendingByte+2); | ||||
| 40863 | lock.l_len = divSize; | ||||
| 40864 | if( unixFileLock(pFile, &lock)==(-1) ){ | ||||
| 40865 | tErrno = errno(*__errno_location ()); | ||||
| 40866 | rc = SQLITE_IOERR_UNLOCK(10 | (8<<8)); | ||||
| 40867 | storeLastErrno(pFile, tErrno); | ||||
| 40868 | goto end_unlock; | ||||
| 40869 | } | ||||
| 40870 | lock.l_type = F_RDLCK0; | ||||
| 40871 | lock.l_whence = SEEK_SET0; | ||||
| 40872 | lock.l_start = SHARED_FIRST(sqlite3PendingByte+2); | ||||
| 40873 | lock.l_len = divSize; | ||||
| 40874 | if( unixFileLock(pFile, &lock)==(-1) ){ | ||||
| 40875 | tErrno = errno(*__errno_location ()); | ||||
| 40876 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK(10 | (9<<8))); | ||||
| 40877 | if( IS_LOCK_ERROR(rc)((rc != 0) && (rc != 5)) ){ | ||||
| 40878 | storeLastErrno(pFile, tErrno); | ||||
| 40879 | } | ||||
| 40880 | goto end_unlock; | ||||
| 40881 | } | ||||
| 40882 | lock.l_type = F_UNLCK2; | ||||
| 40883 | lock.l_whence = SEEK_SET0; | ||||
| 40884 | lock.l_start = SHARED_FIRST(sqlite3PendingByte+2)+divSize; | ||||
| 40885 | lock.l_len = SHARED_SIZE510-divSize; | ||||
| 40886 | if( unixFileLock(pFile, &lock)==(-1) ){ | ||||
| 40887 | tErrno = errno(*__errno_location ()); | ||||
| 40888 | rc = SQLITE_IOERR_UNLOCK(10 | (8<<8)); | ||||
| 40889 | storeLastErrno(pFile, tErrno); | ||||
| 40890 | goto end_unlock; | ||||
| 40891 | } | ||||
| 40892 | }else | ||||
| 40893 | #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ | ||||
| 40894 | { | ||||
| 40895 | lock.l_type = F_RDLCK0; | ||||
| 40896 | lock.l_whence = SEEK_SET0; | ||||
| 40897 | lock.l_start = SHARED_FIRST(sqlite3PendingByte+2); | ||||
| 40898 | lock.l_len = SHARED_SIZE510; | ||||
| 40899 | if( unixFileLock(pFile, &lock) ){ | ||||
| 40900 | /* In theory, the call to unixFileLock() cannot fail because another | ||||
| 40901 | ** process is holding an incompatible lock. If it does, this | ||||
| 40902 | ** indicates that the other process is not following the locking | ||||
| 40903 | ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning | ||||
| 40904 | ** SQLITE_BUSY would confuse the upper layer (in practice it causes | ||||
| 40905 | ** an assert to fail). */ | ||||
| 40906 | rc = SQLITE_IOERR_RDLOCK(10 | (9<<8)); | ||||
| 40907 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 40908 | goto end_unlock; | ||||
| 40909 | } | ||||
| 40910 | } | ||||
| 40911 | } | ||||
| 40912 | lock.l_type = F_UNLCK2; | ||||
| 40913 | lock.l_whence = SEEK_SET0; | ||||
| 40914 | lock.l_start = PENDING_BYTEsqlite3PendingByte; | ||||
| 40915 | lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE )((void) (0)); | ||||
| 40916 | if( unixFileLock(pFile, &lock)==0 ){ | ||||
| 40917 | pInode->eFileLock = SHARED_LOCK1; | ||||
| 40918 | }else{ | ||||
| 40919 | rc = SQLITE_IOERR_UNLOCK(10 | (8<<8)); | ||||
| 40920 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 40921 | goto end_unlock; | ||||
| 40922 | } | ||||
| 40923 | } | ||||
| 40924 | if( eFileLock==NO_LOCK0 ){ | ||||
| 40925 | /* Decrement the shared lock counter. Release the lock using an | ||||
| 40926 | ** OS call only when all threads in this same process have released | ||||
| 40927 | ** the lock. | ||||
| 40928 | */ | ||||
| 40929 | pInode->nShared--; | ||||
| 40930 | if( pInode->nShared==0 ){ | ||||
| 40931 | lock.l_type = F_UNLCK2; | ||||
| 40932 | lock.l_whence = SEEK_SET0; | ||||
| 40933 | lock.l_start = lock.l_len = 0L; | ||||
| 40934 | if( unixFileLock(pFile, &lock)==0 ){ | ||||
| 40935 | pInode->eFileLock = NO_LOCK0; | ||||
| 40936 | }else{ | ||||
| 40937 | rc = SQLITE_IOERR_UNLOCK(10 | (8<<8)); | ||||
| 40938 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 40939 | pInode->eFileLock = NO_LOCK0; | ||||
| 40940 | pFile->eFileLock = NO_LOCK0; | ||||
| 40941 | } | ||||
| 40942 | } | ||||
| 40943 | |||||
| 40944 | /* Decrement the count of locks against this same file. When the | ||||
| 40945 | ** count reaches zero, close any other file descriptors whose close | ||||
| 40946 | ** was deferred because of outstanding locks. | ||||
| 40947 | */ | ||||
| 40948 | pInode->nLock--; | ||||
| 40949 | assert( pInode->nLock>=0 )((void) (0)); | ||||
| 40950 | if( pInode->nLock==0 ) closePendingFds(pFile); | ||||
| 40951 | } | ||||
| 40952 | |||||
| 40953 | end_unlock: | ||||
| 40954 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 40955 | if( rc==SQLITE_OK0 ){ | ||||
| 40956 | pFile->eFileLock = eFileLock; | ||||
| 40957 | } | ||||
| 40958 | return rc; | ||||
| 40959 | } | ||||
| 40960 | |||||
| 40961 | /* | ||||
| 40962 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 40963 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 40964 | ** | ||||
| 40965 | ** If the locking level of the file descriptor is already at or below | ||||
| 40966 | ** the requested locking level, this routine is a no-op. | ||||
| 40967 | */ | ||||
| 40968 | static int unixUnlock(sqlite3_file *id, int eFileLock){ | ||||
| 40969 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 40970 | assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 )((void) (0)); | ||||
| 40971 | #endif | ||||
| 40972 | return posixUnlock(id, eFileLock, 0); | ||||
| 40973 | } | ||||
| 40974 | |||||
| 40975 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 40976 | static int unixMapfile(unixFile *pFd, i64 nByte); | ||||
| 40977 | static void unixUnmapfile(unixFile *pFd); | ||||
| 40978 | #endif | ||||
| 40979 | |||||
| 40980 | /* | ||||
| 40981 | ** This function performs the parts of the "close file" operation | ||||
| 40982 | ** common to all locking schemes. It closes the directory and file | ||||
| 40983 | ** handles, if they are valid, and sets all fields of the unixFile | ||||
| 40984 | ** structure to 0. | ||||
| 40985 | ** | ||||
| 40986 | ** It is *not* necessary to hold the mutex when this routine is called, | ||||
| 40987 | ** even on VxWorks. A mutex will be acquired on VxWorks by the | ||||
| 40988 | ** vxworksReleaseFileId() routine. | ||||
| 40989 | */ | ||||
| 40990 | static int closeUnixFile(sqlite3_file *id){ | ||||
| 40991 | unixFile *pFile = (unixFile*)id; | ||||
| 40992 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 40993 | unixUnmapfile(pFile); | ||||
| 40994 | #endif | ||||
| 40995 | if( pFile->h>=0 ){ | ||||
| 40996 | robust_close(pFile, pFile->h, __LINE__40996); | ||||
| 40997 | pFile->h = -1; | ||||
| 40998 | } | ||||
| 40999 | #if OS_VXWORKS0 | ||||
| 41000 | if( pFile->pId ){ | ||||
| 41001 | if( pFile->ctrlFlags & UNIXFILE_DELETE0x20 ){ | ||||
| 41002 | osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(pFile->pId->zCanonicalName); | ||||
| 41003 | } | ||||
| 41004 | vxworksReleaseFileId(pFile->pId); | ||||
| 41005 | pFile->pId = 0; | ||||
| 41006 | } | ||||
| 41007 | #endif | ||||
| 41008 | #ifdef SQLITE_UNLINK_AFTER_CLOSE | ||||
| 41009 | if( pFile->ctrlFlags & UNIXFILE_DELETE0x20 ){ | ||||
| 41010 | osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(pFile->zPath); | ||||
| 41011 | sqlite3_free(*(char**)&pFile->zPath); | ||||
| 41012 | pFile->zPath = 0; | ||||
| 41013 | } | ||||
| 41014 | #endif | ||||
| 41015 | OSTRACE(("CLOSE %-3d\n", pFile->h)); | ||||
| 41016 | OpenCounter(-1); | ||||
| 41017 | sqlite3_free(pFile->pPreallocatedUnused); | ||||
| 41018 | memset(pFile, 0, sizeof(unixFile)); | ||||
| 41019 | return SQLITE_OK0; | ||||
| 41020 | } | ||||
| 41021 | |||||
| 41022 | /* | ||||
| 41023 | ** Close a file. | ||||
| 41024 | */ | ||||
| 41025 | static int unixClose(sqlite3_file *id){ | ||||
| 41026 | int rc = SQLITE_OK0; | ||||
| 41027 | unixFile *pFile = (unixFile *)id; | ||||
| 41028 | unixInodeInfo *pInode = pFile->pInode; | ||||
| 41029 | |||||
| 41030 | assert( pInode!=0 )((void) (0)); | ||||
| 41031 | verifyDbFile(pFile); | ||||
| 41032 | unixUnlock(id, NO_LOCK0); | ||||
| 41033 | assert( unixFileMutexNotheld(pFile) )((void) (0)); | ||||
| 41034 | unixEnterMutex(); | ||||
| 41035 | |||||
| 41036 | /* unixFile.pInode is always valid here. Otherwise, a different close | ||||
| 41037 | ** routine (e.g. nolockClose()) would be called instead. | ||||
| 41038 | */ | ||||
| 41039 | assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 )((void) (0)); | ||||
| 41040 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 41041 | if( pInode->nLock ){ | ||||
| 41042 | /* If there are outstanding locks, do not actually close the file just | ||||
| 41043 | ** yet because that would clear those locks. Instead, add the file | ||||
| 41044 | ** descriptor to pInode->pUnused list. It will be automatically closed | ||||
| 41045 | ** when the last lock is cleared. | ||||
| 41046 | */ | ||||
| 41047 | setPendingFd(pFile); | ||||
| 41048 | } | ||||
| 41049 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 41050 | releaseInodeInfo(pFile); | ||||
| 41051 | assert( pFile->pShm==0 )((void) (0)); | ||||
| 41052 | rc = closeUnixFile(id); | ||||
| 41053 | unixLeaveMutex(); | ||||
| 41054 | return rc; | ||||
| 41055 | } | ||||
| 41056 | |||||
| 41057 | /************** End of the posix advisory lock implementation ***************** | ||||
| 41058 | ******************************************************************************/ | ||||
| 41059 | |||||
| 41060 | /****************************************************************************** | ||||
| 41061 | ****************************** No-op Locking ********************************** | ||||
| 41062 | ** | ||||
| 41063 | ** Of the various locking implementations available, this is by far the | ||||
| 41064 | ** simplest: locking is ignored. No attempt is made to lock the database | ||||
| 41065 | ** file for reading or writing. | ||||
| 41066 | ** | ||||
| 41067 | ** This locking mode is appropriate for use on read-only databases | ||||
| 41068 | ** (ex: databases that are burned into CD-ROM, for example.) It can | ||||
| 41069 | ** also be used if the application employs some external mechanism to | ||||
| 41070 | ** prevent simultaneous access of the same database by two or more | ||||
| 41071 | ** database connections. But there is a serious risk of database | ||||
| 41072 | ** corruption if this locking mode is used in situations where multiple | ||||
| 41073 | ** database connections are accessing the same database file at the same | ||||
| 41074 | ** time and one or more of those connections are writing. | ||||
| 41075 | */ | ||||
| 41076 | |||||
| 41077 | static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){ | ||||
| 41078 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 41079 | *pResOut = 0; | ||||
| 41080 | return SQLITE_OK0; | ||||
| 41081 | } | ||||
| 41082 | static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){ | ||||
| 41083 | UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2); | ||||
| 41084 | return SQLITE_OK0; | ||||
| 41085 | } | ||||
| 41086 | static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){ | ||||
| 41087 | UNUSED_PARAMETER2(NotUsed, NotUsed2)(void)(NotUsed),(void)(NotUsed2); | ||||
| 41088 | return SQLITE_OK0; | ||||
| 41089 | } | ||||
| 41090 | |||||
| 41091 | /* | ||||
| 41092 | ** Close the file. | ||||
| 41093 | */ | ||||
| 41094 | static int nolockClose(sqlite3_file *id) { | ||||
| 41095 | return closeUnixFile(id); | ||||
| 41096 | } | ||||
| 41097 | |||||
| 41098 | /******************* End of the no-op lock implementation ********************* | ||||
| 41099 | ******************************************************************************/ | ||||
| 41100 | |||||
| 41101 | /****************************************************************************** | ||||
| 41102 | ************************* Begin dot-file Locking ****************************** | ||||
| 41103 | ** | ||||
| 41104 | ** The dotfile locking implementation uses the existence of separate lock | ||||
| 41105 | ** files (really a directory) to control access to the database. This works | ||||
| 41106 | ** on just about every filesystem imaginable. But there are serious downsides: | ||||
| 41107 | ** | ||||
| 41108 | ** (1) There is zero concurrency. A single reader blocks all other | ||||
| 41109 | ** connections from reading or writing the database. | ||||
| 41110 | ** | ||||
| 41111 | ** (2) An application crash or power loss can leave stale lock files | ||||
| 41112 | ** sitting around that need to be cleared manually. | ||||
| 41113 | ** | ||||
| 41114 | ** Nevertheless, a dotlock is an appropriate locking mode for use if no | ||||
| 41115 | ** other locking strategy is available. | ||||
| 41116 | ** | ||||
| 41117 | ** Dotfile locking works by creating a subdirectory in the same directory as | ||||
| 41118 | ** the database and with the same name but with a ".lock" extension added. | ||||
| 41119 | ** The existence of a lock directory implies an EXCLUSIVE lock. All other | ||||
| 41120 | ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE. | ||||
| 41121 | */ | ||||
| 41122 | |||||
| 41123 | /* | ||||
| 41124 | ** The file suffix added to the data base filename in order to create the | ||||
| 41125 | ** lock directory. | ||||
| 41126 | */ | ||||
| 41127 | #define DOTLOCK_SUFFIX".lock" ".lock" | ||||
| 41128 | |||||
| 41129 | /* | ||||
| 41130 | ** This routine checks if there is a RESERVED lock held on the specified | ||||
| 41131 | ** file by this or any other process. If the caller holds a SHARED | ||||
| 41132 | ** or greater lock when it is called, then it is assumed that no other | ||||
| 41133 | ** client may hold RESERVED. Or, if the caller holds no lock, then it | ||||
| 41134 | ** is assumed another client holds RESERVED if the lock-file exists. | ||||
| 41135 | */ | ||||
| 41136 | static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { | ||||
| 41137 | unixFile *pFile = (unixFile*)id; | ||||
| 41138 | SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); | ||||
| 41139 | |||||
| 41140 | if( pFile->eFileLock>=SHARED_LOCK1 ){ | ||||
| 41141 | *pResOut = 0; | ||||
| 41142 | }else{ | ||||
| 41143 | *pResOut = osAccess((int(*)(const char*,int))aSyscall[2].pCurrent)((const char*)pFile->lockingContext, 0)==0; | ||||
| 41144 | } | ||||
| 41145 | OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, 0, *pResOut)); | ||||
| 41146 | return SQLITE_OK0; | ||||
| 41147 | } | ||||
| 41148 | |||||
| 41149 | /* | ||||
| 41150 | ** Lock the file with the lock specified by parameter eFileLock - one | ||||
| 41151 | ** of the following: | ||||
| 41152 | ** | ||||
| 41153 | ** (1) SHARED_LOCK | ||||
| 41154 | ** (2) RESERVED_LOCK | ||||
| 41155 | ** (3) PENDING_LOCK | ||||
| 41156 | ** (4) EXCLUSIVE_LOCK | ||||
| 41157 | ** | ||||
| 41158 | ** Sometimes when requesting one lock state, additional lock states | ||||
| 41159 | ** are inserted in between. The locking might fail on one of the later | ||||
| 41160 | ** transitions leaving the lock state different from what it started but | ||||
| 41161 | ** still short of its goal. The following chart shows the allowed | ||||
| 41162 | ** transitions and the inserted intermediate states: | ||||
| 41163 | ** | ||||
| 41164 | ** UNLOCKED -> SHARED | ||||
| 41165 | ** SHARED -> RESERVED | ||||
| 41166 | ** SHARED -> (PENDING) -> EXCLUSIVE | ||||
| 41167 | ** RESERVED -> (PENDING) -> EXCLUSIVE | ||||
| 41168 | ** PENDING -> EXCLUSIVE | ||||
| 41169 | ** | ||||
| 41170 | ** This routine will only increase a lock. Use the sqlite3OsUnlock() | ||||
| 41171 | ** routine to lower a locking level. | ||||
| 41172 | ** | ||||
| 41173 | ** With dotfile locking, we really only support state (4): EXCLUSIVE. | ||||
| 41174 | ** But we track the other locking levels internally. | ||||
| 41175 | */ | ||||
| 41176 | static int dotlockLock(sqlite3_file *id, int eFileLock) { | ||||
| 41177 | unixFile *pFile = (unixFile*)id; | ||||
| 41178 | char *zLockFile = (char *)pFile->lockingContext; | ||||
| 41179 | int rc = SQLITE_OK0; | ||||
| 41180 | |||||
| 41181 | |||||
| 41182 | /* If we have any lock, then the lock file already exists. All we have | ||||
| 41183 | ** to do is adjust our internal record of the lock level. | ||||
| 41184 | */ | ||||
| 41185 | if( pFile->eFileLock > NO_LOCK0 ){ | ||||
| 41186 | pFile->eFileLock = eFileLock; | ||||
| 41187 | /* Always update the timestamp on the old file */ | ||||
| 41188 | #ifdef HAVE_UTIME | ||||
| 41189 | utime(zLockFile, NULL((void*)0)); | ||||
| 41190 | #else | ||||
| 41191 | utimes(zLockFile, NULL((void*)0)); | ||||
| 41192 | #endif | ||||
| 41193 | return SQLITE_OK0; | ||||
| 41194 | } | ||||
| 41195 | |||||
| 41196 | /* grab an exclusive lock */ | ||||
| 41197 | rc = osMkdir((int(*)(const char*,mode_t))aSyscall[18].pCurrent)(zLockFile, 0777); | ||||
| 41198 | if( rc<0 ){ | ||||
| 41199 | /* failed to open/create the lock directory */ | ||||
| 41200 | int tErrno = errno(*__errno_location ()); | ||||
| 41201 | if( EEXIST17 == tErrno ){ | ||||
| 41202 | rc = SQLITE_BUSY5; | ||||
| 41203 | } else { | ||||
| 41204 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK(10 | (15<<8))); | ||||
| 41205 | if( rc!=SQLITE_BUSY5 ){ | ||||
| 41206 | storeLastErrno(pFile, tErrno); | ||||
| 41207 | } | ||||
| 41208 | } | ||||
| 41209 | return rc; | ||||
| 41210 | } | ||||
| 41211 | |||||
| 41212 | /* got it, set the type and return ok */ | ||||
| 41213 | pFile->eFileLock = eFileLock; | ||||
| 41214 | return rc; | ||||
| 41215 | } | ||||
| 41216 | |||||
| 41217 | /* | ||||
| 41218 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 41219 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 41220 | ** | ||||
| 41221 | ** If the locking level of the file descriptor is already at or below | ||||
| 41222 | ** the requested locking level, this routine is a no-op. | ||||
| 41223 | ** | ||||
| 41224 | ** When the locking level reaches NO_LOCK, delete the lock file. | ||||
| 41225 | */ | ||||
| 41226 | static int dotlockUnlock(sqlite3_file *id, int eFileLock) { | ||||
| 41227 | unixFile *pFile = (unixFile*)id; | ||||
| 41228 | char *zLockFile = (char *)pFile->lockingContext; | ||||
| 41229 | int rc; | ||||
| 41230 | |||||
| 41231 | assert( pFile )((void) (0)); | ||||
| 41232 | OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock, | ||||
| 41233 | pFile->eFileLock, osGetpid(0))); | ||||
| 41234 | assert( eFileLock<=SHARED_LOCK )((void) (0)); | ||||
| 41235 | |||||
| 41236 | /* no-op if possible */ | ||||
| 41237 | if( pFile->eFileLock==eFileLock ){ | ||||
| 41238 | return SQLITE_OK0; | ||||
| 41239 | } | ||||
| 41240 | |||||
| 41241 | /* To downgrade to shared, simply update our internal notion of the | ||||
| 41242 | ** lock state. No need to mess with the file on disk. | ||||
| 41243 | */ | ||||
| 41244 | if( eFileLock==SHARED_LOCK1 ){ | ||||
| 41245 | pFile->eFileLock = SHARED_LOCK1; | ||||
| 41246 | return SQLITE_OK0; | ||||
| 41247 | } | ||||
| 41248 | |||||
| 41249 | /* To fully unlock the database, delete the lock file */ | ||||
| 41250 | assert( eFileLock==NO_LOCK )((void) (0)); | ||||
| 41251 | rc = osRmdir((int(*)(const char*))aSyscall[19].pCurrent)(zLockFile); | ||||
| 41252 | if( rc<0 ){ | ||||
| 41253 | int tErrno = errno(*__errno_location ()); | ||||
| 41254 | if( tErrno==ENOENT2 ){ | ||||
| 41255 | rc = SQLITE_OK0; | ||||
| 41256 | }else{ | ||||
| 41257 | rc = SQLITE_IOERR_UNLOCK(10 | (8<<8)); | ||||
| 41258 | storeLastErrno(pFile, tErrno); | ||||
| 41259 | } | ||||
| 41260 | return rc; | ||||
| 41261 | } | ||||
| 41262 | pFile->eFileLock = NO_LOCK0; | ||||
| 41263 | return SQLITE_OK0; | ||||
| 41264 | } | ||||
| 41265 | |||||
| 41266 | /* | ||||
| 41267 | ** Close a file. Make sure the lock has been released before closing. | ||||
| 41268 | */ | ||||
| 41269 | static int dotlockClose(sqlite3_file *id) { | ||||
| 41270 | unixFile *pFile = (unixFile*)id; | ||||
| 41271 | assert( id!=0 )((void) (0)); | ||||
| 41272 | dotlockUnlock(id, NO_LOCK0); | ||||
| 41273 | sqlite3_free(pFile->lockingContext); | ||||
| 41274 | return closeUnixFile(id); | ||||
| 41275 | } | ||||
| 41276 | /****************** End of the dot-file lock implementation ******************* | ||||
| 41277 | ******************************************************************************/ | ||||
| 41278 | |||||
| 41279 | /****************************************************************************** | ||||
| 41280 | ************************** Begin flock Locking ******************************** | ||||
| 41281 | ** | ||||
| 41282 | ** Use the flock() system call to do file locking. | ||||
| 41283 | ** | ||||
| 41284 | ** flock() locking is like dot-file locking in that the various | ||||
| 41285 | ** fine-grain locking levels supported by SQLite are collapsed into | ||||
| 41286 | ** a single exclusive lock. In other words, SHARED, RESERVED, and | ||||
| 41287 | ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite | ||||
| 41288 | ** still works when you do this, but concurrency is reduced since | ||||
| 41289 | ** only a single process can be reading the database at a time. | ||||
| 41290 | ** | ||||
| 41291 | ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off | ||||
| 41292 | */ | ||||
| 41293 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 41294 | |||||
| 41295 | /* | ||||
| 41296 | ** Retry flock() calls that fail with EINTR | ||||
| 41297 | */ | ||||
| 41298 | #ifdef EINTR4 | ||||
| 41299 | static int robust_flock(int fd, int op){ | ||||
| 41300 | int rc; | ||||
| 41301 | do{ rc = flock(fd,op); }while( rc<0 && errno(*__errno_location ())==EINTR4 ); | ||||
| 41302 | return rc; | ||||
| 41303 | } | ||||
| 41304 | #else | ||||
| 41305 | # define robust_flock(a,b) flock(a,b) | ||||
| 41306 | #endif | ||||
| 41307 | |||||
| 41308 | |||||
| 41309 | /* | ||||
| 41310 | ** This routine checks if there is a RESERVED lock held on the specified | ||||
| 41311 | ** file by this or any other process. If such a lock is held, set *pResOut | ||||
| 41312 | ** to a non-zero value otherwise *pResOut is set to zero. The return value | ||||
| 41313 | ** is set to SQLITE_OK unless an I/O error occurs during lock checking. | ||||
| 41314 | */ | ||||
| 41315 | static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ | ||||
| 41316 | #ifdef SQLITE_DEBUG | ||||
| 41317 | unixFile *pFile = (unixFile*)id; | ||||
| 41318 | #else | ||||
| 41319 | UNUSED_PARAMETER(id)(void)(id); | ||||
| 41320 | #endif | ||||
| 41321 | |||||
| 41322 | SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); | ||||
| 41323 | |||||
| 41324 | assert( pFile )((void) (0)); | ||||
| 41325 | assert( pFile->eFileLock<=SHARED_LOCK )((void) (0)); | ||||
| 41326 | |||||
| 41327 | /* The flock VFS only ever takes exclusive locks (see function flockLock). | ||||
| 41328 | ** Therefore, if this connection is holding any lock at all, no other | ||||
| 41329 | ** connection may be holding a RESERVED lock. So set *pResOut to 0 | ||||
| 41330 | ** in this case. | ||||
| 41331 | ** | ||||
| 41332 | ** Or, this connection may be holding no lock. In that case, set *pResOut to | ||||
| 41333 | ** 0 as well. The caller will then attempt to take an EXCLUSIVE lock on the | ||||
| 41334 | ** db in order to roll the hot journal back. If there is another connection | ||||
| 41335 | ** holding a lock, that attempt will fail and an SQLITE_BUSY returned to | ||||
| 41336 | ** the user. With other VFS, we try to avoid this, in order to allow a reader | ||||
| 41337 | ** to proceed while a writer is preparing its transaction. But that won't | ||||
| 41338 | ** work with the flock VFS - as it always takes EXCLUSIVE locks - so it is | ||||
| 41339 | ** not a problem in this case. */ | ||||
| 41340 | *pResOut = 0; | ||||
| 41341 | |||||
| 41342 | return SQLITE_OK0; | ||||
| 41343 | } | ||||
| 41344 | |||||
| 41345 | /* | ||||
| 41346 | ** Lock the file with the lock specified by parameter eFileLock - one | ||||
| 41347 | ** of the following: | ||||
| 41348 | ** | ||||
| 41349 | ** (1) SHARED_LOCK | ||||
| 41350 | ** (2) RESERVED_LOCK | ||||
| 41351 | ** (3) PENDING_LOCK | ||||
| 41352 | ** (4) EXCLUSIVE_LOCK | ||||
| 41353 | ** | ||||
| 41354 | ** Sometimes when requesting one lock state, additional lock states | ||||
| 41355 | ** are inserted in between. The locking might fail on one of the later | ||||
| 41356 | ** transitions leaving the lock state different from what it started but | ||||
| 41357 | ** still short of its goal. The following chart shows the allowed | ||||
| 41358 | ** transitions and the inserted intermediate states: | ||||
| 41359 | ** | ||||
| 41360 | ** UNLOCKED -> SHARED | ||||
| 41361 | ** SHARED -> RESERVED | ||||
| 41362 | ** SHARED -> (PENDING) -> EXCLUSIVE | ||||
| 41363 | ** RESERVED -> (PENDING) -> EXCLUSIVE | ||||
| 41364 | ** PENDING -> EXCLUSIVE | ||||
| 41365 | ** | ||||
| 41366 | ** flock() only really support EXCLUSIVE locks. We track intermediate | ||||
| 41367 | ** lock states in the sqlite3_file structure, but all locks SHARED or | ||||
| 41368 | ** above are really EXCLUSIVE locks and exclude all other processes from | ||||
| 41369 | ** access the file. | ||||
| 41370 | ** | ||||
| 41371 | ** This routine will only increase a lock. Use the sqlite3OsUnlock() | ||||
| 41372 | ** routine to lower a locking level. | ||||
| 41373 | */ | ||||
| 41374 | static int flockLock(sqlite3_file *id, int eFileLock) { | ||||
| 41375 | int rc = SQLITE_OK0; | ||||
| 41376 | unixFile *pFile = (unixFile*)id; | ||||
| 41377 | |||||
| 41378 | assert( pFile )((void) (0)); | ||||
| 41379 | |||||
| 41380 | /* if we already have a lock, it is exclusive. | ||||
| 41381 | ** Just adjust level and punt on outta here. */ | ||||
| 41382 | if (pFile->eFileLock > NO_LOCK0) { | ||||
| 41383 | pFile->eFileLock = eFileLock; | ||||
| 41384 | return SQLITE_OK0; | ||||
| 41385 | } | ||||
| 41386 | |||||
| 41387 | /* grab an exclusive lock */ | ||||
| 41388 | |||||
| 41389 | if (robust_flock(pFile->h, LOCK_EX2 | LOCK_NB4)) { | ||||
| 41390 | int tErrno = errno(*__errno_location ()); | ||||
| 41391 | /* didn't get, must be busy */ | ||||
| 41392 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK(10 | (15<<8))); | ||||
| 41393 | if( IS_LOCK_ERROR(rc)((rc != 0) && (rc != 5)) ){ | ||||
| 41394 | storeLastErrno(pFile, tErrno); | ||||
| 41395 | } | ||||
| 41396 | } else { | ||||
| 41397 | /* got it, set the type and return ok */ | ||||
| 41398 | pFile->eFileLock = eFileLock; | ||||
| 41399 | } | ||||
| 41400 | OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), | ||||
| 41401 | rc==SQLITE_OK ? "ok" : "failed")); | ||||
| 41402 | #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS | ||||
| 41403 | if( (rc & 0xff) == SQLITE_IOERR10 ){ | ||||
| 41404 | rc = SQLITE_BUSY5; | ||||
| 41405 | } | ||||
| 41406 | #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ | ||||
| 41407 | return rc; | ||||
| 41408 | } | ||||
| 41409 | |||||
| 41410 | |||||
| 41411 | /* | ||||
| 41412 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 41413 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 41414 | ** | ||||
| 41415 | ** If the locking level of the file descriptor is already at or below | ||||
| 41416 | ** the requested locking level, this routine is a no-op. | ||||
| 41417 | */ | ||||
| 41418 | static int flockUnlock(sqlite3_file *id, int eFileLock) { | ||||
| 41419 | unixFile *pFile = (unixFile*)id; | ||||
| 41420 | |||||
| 41421 | assert( pFile )((void) (0)); | ||||
| 41422 | OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock, | ||||
| 41423 | pFile->eFileLock, osGetpid(0))); | ||||
| 41424 | assert( eFileLock<=SHARED_LOCK )((void) (0)); | ||||
| 41425 | |||||
| 41426 | /* no-op if possible */ | ||||
| 41427 | if( pFile->eFileLock==eFileLock ){ | ||||
| 41428 | return SQLITE_OK0; | ||||
| 41429 | } | ||||
| 41430 | |||||
| 41431 | /* shared can just be set because we always have an exclusive */ | ||||
| 41432 | if (eFileLock==SHARED_LOCK1) { | ||||
| 41433 | pFile->eFileLock = eFileLock; | ||||
| 41434 | return SQLITE_OK0; | ||||
| 41435 | } | ||||
| 41436 | |||||
| 41437 | /* no, really, unlock. */ | ||||
| 41438 | if( robust_flock(pFile->h, LOCK_UN8) ){ | ||||
| 41439 | #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS | ||||
| 41440 | return SQLITE_OK0; | ||||
| 41441 | #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ | ||||
| 41442 | return SQLITE_IOERR_UNLOCK(10 | (8<<8)); | ||||
| 41443 | }else{ | ||||
| 41444 | pFile->eFileLock = NO_LOCK0; | ||||
| 41445 | return SQLITE_OK0; | ||||
| 41446 | } | ||||
| 41447 | } | ||||
| 41448 | |||||
| 41449 | /* | ||||
| 41450 | ** Close a file. | ||||
| 41451 | */ | ||||
| 41452 | static int flockClose(sqlite3_file *id) { | ||||
| 41453 | assert( id!=0 )((void) (0)); | ||||
| 41454 | flockUnlock(id, NO_LOCK0); | ||||
| 41455 | return closeUnixFile(id); | ||||
| 41456 | } | ||||
| 41457 | |||||
| 41458 | #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */ | ||||
| 41459 | |||||
| 41460 | /******************* End of the flock lock implementation ********************* | ||||
| 41461 | ******************************************************************************/ | ||||
| 41462 | |||||
| 41463 | /****************************************************************************** | ||||
| 41464 | ************************ Begin Named Semaphore Locking ************************ | ||||
| 41465 | ** | ||||
| 41466 | ** Named semaphore locking is only supported on VxWorks. | ||||
| 41467 | ** | ||||
| 41468 | ** Semaphore locking is like dot-lock and flock in that it really only | ||||
| 41469 | ** supports EXCLUSIVE locking. Only a single process can read or write | ||||
| 41470 | ** the database file at a time. This reduces potential concurrency, but | ||||
| 41471 | ** makes the lock implementation much easier. | ||||
| 41472 | */ | ||||
| 41473 | #if OS_VXWORKS0 | ||||
| 41474 | |||||
| 41475 | /* | ||||
| 41476 | ** This routine checks if there is a RESERVED lock held on the specified | ||||
| 41477 | ** file by this or any other process. If such a lock is held, set *pResOut | ||||
| 41478 | ** to a non-zero value otherwise *pResOut is set to zero. The return value | ||||
| 41479 | ** is set to SQLITE_OK unless an I/O error occurs during lock checking. | ||||
| 41480 | */ | ||||
| 41481 | static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) { | ||||
| 41482 | int rc = SQLITE_OK0; | ||||
| 41483 | int reserved = 0; | ||||
| 41484 | unixFile *pFile = (unixFile*)id; | ||||
| 41485 | |||||
| 41486 | SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); | ||||
| 41487 | |||||
| 41488 | assert( pFile )((void) (0)); | ||||
| 41489 | |||||
| 41490 | /* Check if a thread in this process holds such a lock */ | ||||
| 41491 | if( pFile->eFileLock>SHARED_LOCK1 ){ | ||||
| 41492 | reserved = 1; | ||||
| 41493 | } | ||||
| 41494 | |||||
| 41495 | /* Otherwise see if some other process holds it. */ | ||||
| 41496 | if( !reserved ){ | ||||
| 41497 | sem_t *pSem = pFile->pInode->pSem; | ||||
| 41498 | |||||
| 41499 | if( sem_trywait(pSem)==-1 ){ | ||||
| 41500 | int tErrno = errno(*__errno_location ()); | ||||
| 41501 | if( EAGAIN11 != tErrno ){ | ||||
| 41502 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK(10 | (14<<8))); | ||||
| 41503 | storeLastErrno(pFile, tErrno); | ||||
| 41504 | } else { | ||||
| 41505 | /* someone else has the lock when we are in NO_LOCK */ | ||||
| 41506 | reserved = (pFile->eFileLock < SHARED_LOCK1); | ||||
| 41507 | } | ||||
| 41508 | }else{ | ||||
| 41509 | /* we could have it if we want it */ | ||||
| 41510 | sem_post(pSem); | ||||
| 41511 | } | ||||
| 41512 | } | ||||
| 41513 | OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved)); | ||||
| 41514 | |||||
| 41515 | *pResOut = reserved; | ||||
| 41516 | return rc; | ||||
| 41517 | } | ||||
| 41518 | |||||
| 41519 | /* | ||||
| 41520 | ** Lock the file with the lock specified by parameter eFileLock - one | ||||
| 41521 | ** of the following: | ||||
| 41522 | ** | ||||
| 41523 | ** (1) SHARED_LOCK | ||||
| 41524 | ** (2) RESERVED_LOCK | ||||
| 41525 | ** (3) PENDING_LOCK | ||||
| 41526 | ** (4) EXCLUSIVE_LOCK | ||||
| 41527 | ** | ||||
| 41528 | ** Sometimes when requesting one lock state, additional lock states | ||||
| 41529 | ** are inserted in between. The locking might fail on one of the later | ||||
| 41530 | ** transitions leaving the lock state different from what it started but | ||||
| 41531 | ** still short of its goal. The following chart shows the allowed | ||||
| 41532 | ** transitions and the inserted intermediate states: | ||||
| 41533 | ** | ||||
| 41534 | ** UNLOCKED -> SHARED | ||||
| 41535 | ** SHARED -> RESERVED | ||||
| 41536 | ** SHARED -> (PENDING) -> EXCLUSIVE | ||||
| 41537 | ** RESERVED -> (PENDING) -> EXCLUSIVE | ||||
| 41538 | ** PENDING -> EXCLUSIVE | ||||
| 41539 | ** | ||||
| 41540 | ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate | ||||
| 41541 | ** lock states in the sqlite3_file structure, but all locks SHARED or | ||||
| 41542 | ** above are really EXCLUSIVE locks and exclude all other processes from | ||||
| 41543 | ** access the file. | ||||
| 41544 | ** | ||||
| 41545 | ** This routine will only increase a lock. Use the sqlite3OsUnlock() | ||||
| 41546 | ** routine to lower a locking level. | ||||
| 41547 | */ | ||||
| 41548 | static int semXLock(sqlite3_file *id, int eFileLock) { | ||||
| 41549 | unixFile *pFile = (unixFile*)id; | ||||
| 41550 | sem_t *pSem = pFile->pInode->pSem; | ||||
| 41551 | int rc = SQLITE_OK0; | ||||
| 41552 | |||||
| 41553 | /* if we already have a lock, it is exclusive. | ||||
| 41554 | ** Just adjust level and punt on outta here. */ | ||||
| 41555 | if (pFile->eFileLock > NO_LOCK0) { | ||||
| 41556 | pFile->eFileLock = eFileLock; | ||||
| 41557 | rc = SQLITE_OK0; | ||||
| 41558 | goto sem_end_lock; | ||||
| 41559 | } | ||||
| 41560 | |||||
| 41561 | /* lock semaphore now but bail out when already locked. */ | ||||
| 41562 | if( sem_trywait(pSem)==-1 ){ | ||||
| 41563 | rc = SQLITE_BUSY5; | ||||
| 41564 | goto sem_end_lock; | ||||
| 41565 | } | ||||
| 41566 | |||||
| 41567 | /* got it, set the type and return ok */ | ||||
| 41568 | pFile->eFileLock = eFileLock; | ||||
| 41569 | |||||
| 41570 | sem_end_lock: | ||||
| 41571 | return rc; | ||||
| 41572 | } | ||||
| 41573 | |||||
| 41574 | /* | ||||
| 41575 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 41576 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 41577 | ** | ||||
| 41578 | ** If the locking level of the file descriptor is already at or below | ||||
| 41579 | ** the requested locking level, this routine is a no-op. | ||||
| 41580 | */ | ||||
| 41581 | static int semXUnlock(sqlite3_file *id, int eFileLock) { | ||||
| 41582 | unixFile *pFile = (unixFile*)id; | ||||
| 41583 | sem_t *pSem = pFile->pInode->pSem; | ||||
| 41584 | |||||
| 41585 | assert( pFile )((void) (0)); | ||||
| 41586 | assert( pSem )((void) (0)); | ||||
| 41587 | OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock, | ||||
| 41588 | pFile->eFileLock, osGetpid(0))); | ||||
| 41589 | assert( eFileLock<=SHARED_LOCK )((void) (0)); | ||||
| 41590 | |||||
| 41591 | /* no-op if possible */ | ||||
| 41592 | if( pFile->eFileLock==eFileLock ){ | ||||
| 41593 | return SQLITE_OK0; | ||||
| 41594 | } | ||||
| 41595 | |||||
| 41596 | /* shared can just be set because we always have an exclusive */ | ||||
| 41597 | if (eFileLock==SHARED_LOCK1) { | ||||
| 41598 | pFile->eFileLock = eFileLock; | ||||
| 41599 | return SQLITE_OK0; | ||||
| 41600 | } | ||||
| 41601 | |||||
| 41602 | /* no, really unlock. */ | ||||
| 41603 | if ( sem_post(pSem)==-1 ) { | ||||
| 41604 | int rc, tErrno = errno(*__errno_location ()); | ||||
| 41605 | rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK(10 | (8<<8))); | ||||
| 41606 | if( IS_LOCK_ERROR(rc)((rc != 0) && (rc != 5)) ){ | ||||
| 41607 | storeLastErrno(pFile, tErrno); | ||||
| 41608 | } | ||||
| 41609 | return rc; | ||||
| 41610 | } | ||||
| 41611 | pFile->eFileLock = NO_LOCK0; | ||||
| 41612 | return SQLITE_OK0; | ||||
| 41613 | } | ||||
| 41614 | |||||
| 41615 | /* | ||||
| 41616 | ** Close a file. | ||||
| 41617 | */ | ||||
| 41618 | static int semXClose(sqlite3_file *id) { | ||||
| 41619 | if( id ){ | ||||
| 41620 | unixFile *pFile = (unixFile*)id; | ||||
| 41621 | semXUnlock(id, NO_LOCK0); | ||||
| 41622 | assert( pFile )((void) (0)); | ||||
| 41623 | assert( unixFileMutexNotheld(pFile) )((void) (0)); | ||||
| 41624 | unixEnterMutex(); | ||||
| 41625 | releaseInodeInfo(pFile); | ||||
| 41626 | unixLeaveMutex(); | ||||
| 41627 | closeUnixFile(id); | ||||
| 41628 | } | ||||
| 41629 | return SQLITE_OK0; | ||||
| 41630 | } | ||||
| 41631 | |||||
| 41632 | #endif /* OS_VXWORKS */ | ||||
| 41633 | /* | ||||
| 41634 | ** Named semaphore locking is only available on VxWorks. | ||||
| 41635 | ** | ||||
| 41636 | *************** End of the named semaphore lock implementation **************** | ||||
| 41637 | ******************************************************************************/ | ||||
| 41638 | |||||
| 41639 | |||||
| 41640 | /****************************************************************************** | ||||
| 41641 | *************************** Begin AFP Locking ********************************* | ||||
| 41642 | ** | ||||
| 41643 | ** AFP is the Apple Filing Protocol. AFP is a network filesystem found | ||||
| 41644 | ** on Apple Macintosh computers - both OS9 and OSX. | ||||
| 41645 | ** | ||||
| 41646 | ** Third-party implementations of AFP are available. But this code here | ||||
| 41647 | ** only works on OSX. | ||||
| 41648 | */ | ||||
| 41649 | |||||
| 41650 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 41651 | /* | ||||
| 41652 | ** The afpLockingContext structure contains all afp lock specific state | ||||
| 41653 | */ | ||||
| 41654 | typedef struct afpLockingContext afpLockingContext; | ||||
| 41655 | struct afpLockingContext { | ||||
| 41656 | int reserved; | ||||
| 41657 | const char *dbPath; /* Name of the open file */ | ||||
| 41658 | }; | ||||
| 41659 | |||||
| 41660 | struct ByteRangeLockPB2 | ||||
| 41661 | { | ||||
| 41662 | unsigned long long offset; /* offset to first byte to lock */ | ||||
| 41663 | unsigned long long length; /* nbr of bytes to lock */ | ||||
| 41664 | unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */ | ||||
| 41665 | unsigned char unLockFlag; /* 1 = unlock, 0 = lock */ | ||||
| 41666 | unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */ | ||||
| 41667 | int fd; /* file desc to assoc this lock with */ | ||||
| 41668 | }; | ||||
| 41669 | |||||
| 41670 | #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)(((2U|1U) << (((0 +8)+8)+14)) | ((('z')) << (0 +8 )) | (((23)) << 0) | ((((sizeof(struct ByteRangeLockPB2 )))) << ((0 +8)+8))) | ||||
| 41671 | |||||
| 41672 | /* | ||||
| 41673 | ** This is a utility for setting or clearing a bit-range lock on an | ||||
| 41674 | ** AFP filesystem. | ||||
| 41675 | ** | ||||
| 41676 | ** Return SQLITE_OK on success, SQLITE_BUSY on failure. | ||||
| 41677 | */ | ||||
| 41678 | static int afpSetLock( | ||||
| 41679 | const char *path, /* Name of the file to be locked or unlocked */ | ||||
| 41680 | unixFile *pFile, /* Open file descriptor on path */ | ||||
| 41681 | unsigned long long offset, /* First byte to be locked */ | ||||
| 41682 | unsigned long long length, /* Number of bytes to lock */ | ||||
| 41683 | int setLockFlag /* True to set lock. False to clear lock */ | ||||
| 41684 | ){ | ||||
| 41685 | struct ByteRangeLockPB2 pb; | ||||
| 41686 | int err; | ||||
| 41687 | |||||
| 41688 | pb.unLockFlag = setLockFlag ? 0 : 1; | ||||
| 41689 | pb.startEndFlag = 0; | ||||
| 41690 | pb.offset = offset; | ||||
| 41691 | pb.length = length; | ||||
| 41692 | pb.fd = pFile->h; | ||||
| 41693 | |||||
| 41694 | OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", | ||||
| 41695 | (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""), | ||||
| 41696 | offset, length)); | ||||
| 41697 | err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0); | ||||
| 41698 | if ( err==-1 ) { | ||||
| 41699 | int rc; | ||||
| 41700 | int tErrno = errno(*__errno_location ()); | ||||
| 41701 | OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n", | ||||
| 41702 | path, tErrno, strerror(tErrno))); | ||||
| 41703 | #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS | ||||
| 41704 | rc = SQLITE_BUSY5; | ||||
| 41705 | #else | ||||
| 41706 | rc = sqliteErrorFromPosixError(tErrno, | ||||
| 41707 | setLockFlag ? SQLITE_IOERR_LOCK(10 | (15<<8)) : SQLITE_IOERR_UNLOCK(10 | (8<<8))); | ||||
| 41708 | #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */ | ||||
| 41709 | if( IS_LOCK_ERROR(rc)((rc != 0) && (rc != 5)) ){ | ||||
| 41710 | storeLastErrno(pFile, tErrno); | ||||
| 41711 | } | ||||
| 41712 | return rc; | ||||
| 41713 | } else { | ||||
| 41714 | return SQLITE_OK0; | ||||
| 41715 | } | ||||
| 41716 | } | ||||
| 41717 | |||||
| 41718 | /* | ||||
| 41719 | ** This routine checks if there is a RESERVED lock held on the specified | ||||
| 41720 | ** file by this or any other process. If such a lock is held, set *pResOut | ||||
| 41721 | ** to a non-zero value otherwise *pResOut is set to zero. The return value | ||||
| 41722 | ** is set to SQLITE_OK unless an I/O error occurs during lock checking. | ||||
| 41723 | */ | ||||
| 41724 | static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ | ||||
| 41725 | int rc = SQLITE_OK0; | ||||
| 41726 | int reserved = 0; | ||||
| 41727 | unixFile *pFile = (unixFile*)id; | ||||
| 41728 | afpLockingContext *context; | ||||
| 41729 | |||||
| 41730 | SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); | ||||
| 41731 | |||||
| 41732 | assert( pFile )((void) (0)); | ||||
| 41733 | context = (afpLockingContext *) pFile->lockingContext; | ||||
| 41734 | if( context->reserved ){ | ||||
| 41735 | *pResOut = 1; | ||||
| 41736 | return SQLITE_OK0; | ||||
| 41737 | } | ||||
| 41738 | sqlite3_mutex_enter(pFile->pInode->pLockMutex); | ||||
| 41739 | /* Check if a thread in this process holds such a lock */ | ||||
| 41740 | if( pFile->pInode->eFileLock>SHARED_LOCK1 ){ | ||||
| 41741 | reserved = 1; | ||||
| 41742 | } | ||||
| 41743 | |||||
| 41744 | /* Otherwise see if some other process holds it. | ||||
| 41745 | */ | ||||
| 41746 | if( !reserved ){ | ||||
| 41747 | /* lock the RESERVED byte */ | ||||
| 41748 | int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE(sqlite3PendingByte+1), 1,1); | ||||
| 41749 | if( SQLITE_OK0==lrc ){ | ||||
| 41750 | /* if we succeeded in taking the reserved lock, unlock it to restore | ||||
| 41751 | ** the original state */ | ||||
| 41752 | lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE(sqlite3PendingByte+1), 1, 0); | ||||
| 41753 | } else { | ||||
| 41754 | /* if we failed to get the lock then someone else must have it */ | ||||
| 41755 | reserved = 1; | ||||
| 41756 | } | ||||
| 41757 | if( IS_LOCK_ERROR(lrc)((lrc != 0) && (lrc != 5)) ){ | ||||
| 41758 | rc=lrc; | ||||
| 41759 | } | ||||
| 41760 | } | ||||
| 41761 | |||||
| 41762 | sqlite3_mutex_leave(pFile->pInode->pLockMutex); | ||||
| 41763 | OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved)); | ||||
| 41764 | |||||
| 41765 | *pResOut = reserved; | ||||
| 41766 | return rc; | ||||
| 41767 | } | ||||
| 41768 | |||||
| 41769 | /* | ||||
| 41770 | ** Lock the file with the lock specified by parameter eFileLock - one | ||||
| 41771 | ** of the following: | ||||
| 41772 | ** | ||||
| 41773 | ** (1) SHARED_LOCK | ||||
| 41774 | ** (2) RESERVED_LOCK | ||||
| 41775 | ** (3) PENDING_LOCK | ||||
| 41776 | ** (4) EXCLUSIVE_LOCK | ||||
| 41777 | ** | ||||
| 41778 | ** Sometimes when requesting one lock state, additional lock states | ||||
| 41779 | ** are inserted in between. The locking might fail on one of the later | ||||
| 41780 | ** transitions leaving the lock state different from what it started but | ||||
| 41781 | ** still short of its goal. The following chart shows the allowed | ||||
| 41782 | ** transitions and the inserted intermediate states: | ||||
| 41783 | ** | ||||
| 41784 | ** UNLOCKED -> SHARED | ||||
| 41785 | ** SHARED -> RESERVED | ||||
| 41786 | ** SHARED -> (PENDING) -> EXCLUSIVE | ||||
| 41787 | ** RESERVED -> (PENDING) -> EXCLUSIVE | ||||
| 41788 | ** PENDING -> EXCLUSIVE | ||||
| 41789 | ** | ||||
| 41790 | ** This routine will only increase a lock. Use the sqlite3OsUnlock() | ||||
| 41791 | ** routine to lower a locking level. | ||||
| 41792 | */ | ||||
| 41793 | static int afpLock(sqlite3_file *id, int eFileLock){ | ||||
| 41794 | int rc = SQLITE_OK0; | ||||
| 41795 | unixFile *pFile = (unixFile*)id; | ||||
| 41796 | unixInodeInfo *pInode = pFile->pInode; | ||||
| 41797 | afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; | ||||
| 41798 | |||||
| 41799 | assert( pFile )((void) (0)); | ||||
| 41800 | OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h, | ||||
| 41801 | azFileLock(eFileLock), azFileLock(pFile->eFileLock), | ||||
| 41802 | azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0))); | ||||
| 41803 | |||||
| 41804 | /* If there is already a lock of this type or more restrictive on the | ||||
| 41805 | ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as | ||||
| 41806 | ** unixEnterMutex() hasn't been called yet. | ||||
| 41807 | */ | ||||
| 41808 | if( pFile->eFileLock>=eFileLock ){ | ||||
| 41809 | OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h, | ||||
| 41810 | azFileLock(eFileLock))); | ||||
| 41811 | return SQLITE_OK0; | ||||
| 41812 | } | ||||
| 41813 | |||||
| 41814 | /* Make sure the locking sequence is correct | ||||
| 41815 | ** (1) We never move from unlocked to anything higher than shared lock. | ||||
| 41816 | ** (2) SQLite never explicitly requests a pending lock. | ||||
| 41817 | ** (3) A shared lock is always held when a reserve lock is requested. | ||||
| 41818 | */ | ||||
| 41819 | assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK )((void) (0)); | ||||
| 41820 | assert( eFileLock!=PENDING_LOCK )((void) (0)); | ||||
| 41821 | assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK )((void) (0)); | ||||
| 41822 | |||||
| 41823 | /* This mutex is needed because pFile->pInode is shared across threads | ||||
| 41824 | */ | ||||
| 41825 | pInode = pFile->pInode; | ||||
| 41826 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 41827 | |||||
| 41828 | /* If some thread using this PID has a lock via a different unixFile* | ||||
| 41829 | ** handle that precludes the requested lock, return BUSY. | ||||
| 41830 | */ | ||||
| 41831 | if( (pFile->eFileLock!=pInode->eFileLock && | ||||
| 41832 | (pInode->eFileLock>=PENDING_LOCK3 || eFileLock>SHARED_LOCK1)) | ||||
| 41833 | ){ | ||||
| 41834 | rc = SQLITE_BUSY5; | ||||
| 41835 | goto afp_end_lock; | ||||
| 41836 | } | ||||
| 41837 | |||||
| 41838 | /* If a SHARED lock is requested, and some thread using this PID already | ||||
| 41839 | ** has a SHARED or RESERVED lock, then increment reference counts and | ||||
| 41840 | ** return SQLITE_OK. | ||||
| 41841 | */ | ||||
| 41842 | if( eFileLock==SHARED_LOCK1 && | ||||
| 41843 | (pInode->eFileLock==SHARED_LOCK1 || pInode->eFileLock==RESERVED_LOCK2) ){ | ||||
| 41844 | assert( eFileLock==SHARED_LOCK )((void) (0)); | ||||
| 41845 | assert( pFile->eFileLock==0 )((void) (0)); | ||||
| 41846 | assert( pInode->nShared>0 )((void) (0)); | ||||
| 41847 | pFile->eFileLock = SHARED_LOCK1; | ||||
| 41848 | pInode->nShared++; | ||||
| 41849 | pInode->nLock++; | ||||
| 41850 | goto afp_end_lock; | ||||
| 41851 | } | ||||
| 41852 | |||||
| 41853 | /* A PENDING lock is needed before acquiring a SHARED lock and before | ||||
| 41854 | ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will | ||||
| 41855 | ** be released. | ||||
| 41856 | */ | ||||
| 41857 | if( eFileLock==SHARED_LOCK1 | ||||
| 41858 | || (eFileLock==EXCLUSIVE_LOCK4 && pFile->eFileLock<PENDING_LOCK3) | ||||
| 41859 | ){ | ||||
| 41860 | int failed; | ||||
| 41861 | failed = afpSetLock(context->dbPath, pFile, PENDING_BYTEsqlite3PendingByte, 1, 1); | ||||
| 41862 | if (failed) { | ||||
| 41863 | rc = failed; | ||||
| 41864 | goto afp_end_lock; | ||||
| 41865 | } | ||||
| 41866 | } | ||||
| 41867 | |||||
| 41868 | /* If control gets to this point, then actually go ahead and make | ||||
| 41869 | ** operating system calls for the specified lock. | ||||
| 41870 | */ | ||||
| 41871 | if( eFileLock==SHARED_LOCK1 ){ | ||||
| 41872 | int lrc1, lrc2, lrc1Errno = 0; | ||||
| 41873 | long lk, mask; | ||||
| 41874 | |||||
| 41875 | assert( pInode->nShared==0 )((void) (0)); | ||||
| 41876 | assert( pInode->eFileLock==0 )((void) (0)); | ||||
| 41877 | |||||
| 41878 | mask = (sizeof(long)==8) ? LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32)) : 0x7fffffff; | ||||
| 41879 | /* Now get the read-lock SHARED_LOCK */ | ||||
| 41880 | /* note that the quality of the randomness doesn't matter that much */ | ||||
| 41881 | lk = random(); | ||||
| 41882 | pInode->sharedByte = (lk & mask)%(SHARED_SIZE510 - 1); | ||||
| 41883 | lrc1 = afpSetLock(context->dbPath, pFile, | ||||
| 41884 | SHARED_FIRST(sqlite3PendingByte+2)+pInode->sharedByte, 1, 1); | ||||
| 41885 | if( IS_LOCK_ERROR(lrc1)((lrc1 != 0) && (lrc1 != 5)) ){ | ||||
| 41886 | lrc1Errno = pFile->lastErrno; | ||||
| 41887 | } | ||||
| 41888 | /* Drop the temporary PENDING lock */ | ||||
| 41889 | lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTEsqlite3PendingByte, 1, 0); | ||||
| 41890 | |||||
| 41891 | if( IS_LOCK_ERROR(lrc1)((lrc1 != 0) && (lrc1 != 5)) ) { | ||||
| 41892 | storeLastErrno(pFile, lrc1Errno); | ||||
| 41893 | rc = lrc1; | ||||
| 41894 | goto afp_end_lock; | ||||
| 41895 | } else if( IS_LOCK_ERROR(lrc2)((lrc2 != 0) && (lrc2 != 5)) ){ | ||||
| 41896 | rc = lrc2; | ||||
| 41897 | goto afp_end_lock; | ||||
| 41898 | } else if( lrc1 != SQLITE_OK0 ) { | ||||
| 41899 | rc = lrc1; | ||||
| 41900 | } else { | ||||
| 41901 | pFile->eFileLock = SHARED_LOCK1; | ||||
| 41902 | pInode->nLock++; | ||||
| 41903 | pInode->nShared = 1; | ||||
| 41904 | } | ||||
| 41905 | }else if( eFileLock==EXCLUSIVE_LOCK4 && pInode->nShared>1 ){ | ||||
| 41906 | /* We are trying for an exclusive lock but another thread in this | ||||
| 41907 | ** same process is still holding a shared lock. */ | ||||
| 41908 | rc = SQLITE_BUSY5; | ||||
| 41909 | }else{ | ||||
| 41910 | /* The request was for a RESERVED or EXCLUSIVE lock. It is | ||||
| 41911 | ** assumed that there is a SHARED or greater lock on the file | ||||
| 41912 | ** already. | ||||
| 41913 | */ | ||||
| 41914 | int failed = 0; | ||||
| 41915 | assert( 0!=pFile->eFileLock )((void) (0)); | ||||
| 41916 | if (eFileLock >= RESERVED_LOCK2 && pFile->eFileLock < RESERVED_LOCK2) { | ||||
| 41917 | /* Acquire a RESERVED lock */ | ||||
| 41918 | failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE(sqlite3PendingByte+1), 1,1); | ||||
| 41919 | if( !failed ){ | ||||
| 41920 | context->reserved = 1; | ||||
| 41921 | } | ||||
| 41922 | } | ||||
| 41923 | if (!failed && eFileLock == EXCLUSIVE_LOCK4) { | ||||
| 41924 | /* Acquire an EXCLUSIVE lock */ | ||||
| 41925 | |||||
| 41926 | /* Remove the shared lock before trying the range. we'll need to | ||||
| 41927 | ** reestablish the shared lock if we can't get the afpUnlock | ||||
| 41928 | */ | ||||
| 41929 | if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST(sqlite3PendingByte+2) + | ||||
| 41930 | pInode->sharedByte, 1, 0)) ){ | ||||
| 41931 | int failed2 = SQLITE_OK0; | ||||
| 41932 | /* now attempt to get the exclusive lock range */ | ||||
| 41933 | failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST(sqlite3PendingByte+2), | ||||
| 41934 | SHARED_SIZE510, 1); | ||||
| 41935 | if( failed && (failed2 = afpSetLock(context->dbPath, pFile, | ||||
| 41936 | SHARED_FIRST(sqlite3PendingByte+2) + pInode->sharedByte, 1, 1)) ){ | ||||
| 41937 | /* Can't reestablish the shared lock. Sqlite can't deal, this is | ||||
| 41938 | ** a critical I/O error | ||||
| 41939 | */ | ||||
| 41940 | rc = ((failed & 0xff) == SQLITE_IOERR10) ? failed2 : | ||||
| 41941 | SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 41942 | goto afp_end_lock; | ||||
| 41943 | } | ||||
| 41944 | }else{ | ||||
| 41945 | rc = failed; | ||||
| 41946 | } | ||||
| 41947 | } | ||||
| 41948 | if( failed ){ | ||||
| 41949 | rc = failed; | ||||
| 41950 | } | ||||
| 41951 | } | ||||
| 41952 | |||||
| 41953 | if( rc==SQLITE_OK0 ){ | ||||
| 41954 | pFile->eFileLock = eFileLock; | ||||
| 41955 | pInode->eFileLock = eFileLock; | ||||
| 41956 | }else if( eFileLock==EXCLUSIVE_LOCK4 ){ | ||||
| 41957 | pFile->eFileLock = PENDING_LOCK3; | ||||
| 41958 | pInode->eFileLock = PENDING_LOCK3; | ||||
| 41959 | } | ||||
| 41960 | |||||
| 41961 | afp_end_lock: | ||||
| 41962 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 41963 | OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), | ||||
| 41964 | rc==SQLITE_OK ? "ok" : "failed")); | ||||
| 41965 | return rc; | ||||
| 41966 | } | ||||
| 41967 | |||||
| 41968 | /* | ||||
| 41969 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 41970 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 41971 | ** | ||||
| 41972 | ** If the locking level of the file descriptor is already at or below | ||||
| 41973 | ** the requested locking level, this routine is a no-op. | ||||
| 41974 | */ | ||||
| 41975 | static int afpUnlock(sqlite3_file *id, int eFileLock) { | ||||
| 41976 | int rc = SQLITE_OK0; | ||||
| 41977 | unixFile *pFile = (unixFile*)id; | ||||
| 41978 | unixInodeInfo *pInode; | ||||
| 41979 | afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; | ||||
| 41980 | int skipShared = 0; | ||||
| 41981 | |||||
| 41982 | assert( pFile )((void) (0)); | ||||
| 41983 | OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock, | ||||
| 41984 | pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, | ||||
| 41985 | osGetpid(0))); | ||||
| 41986 | |||||
| 41987 | assert( eFileLock<=SHARED_LOCK )((void) (0)); | ||||
| 41988 | if( pFile->eFileLock<=eFileLock ){ | ||||
| 41989 | return SQLITE_OK0; | ||||
| 41990 | } | ||||
| 41991 | pInode = pFile->pInode; | ||||
| 41992 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 41993 | assert( pInode->nShared!=0 )((void) (0)); | ||||
| 41994 | if( pFile->eFileLock>SHARED_LOCK1 ){ | ||||
| 41995 | assert( pInode->eFileLock==pFile->eFileLock )((void) (0)); | ||||
| 41996 | |||||
| 41997 | #ifdef SQLITE_DEBUG | ||||
| 41998 | /* When reducing a lock such that other processes can start | ||||
| 41999 | ** reading the database file again, make sure that the | ||||
| 42000 | ** transaction counter was updated if any part of the database | ||||
| 42001 | ** file changed. If the transaction counter is not updated, | ||||
| 42002 | ** other connections to the same file might not realize that | ||||
| 42003 | ** the file has changed and hence might not know to flush their | ||||
| 42004 | ** cache. The use of a stale cache can lead to database corruption. | ||||
| 42005 | */ | ||||
| 42006 | assert( pFile->inNormalWrite==0((void) (0)) | ||||
| 42007 | || pFile->dbUpdate==0((void) (0)) | ||||
| 42008 | || pFile->transCntrChng==1 )((void) (0)); | ||||
| 42009 | pFile->inNormalWrite = 0; | ||||
| 42010 | #endif | ||||
| 42011 | |||||
| 42012 | if( pFile->eFileLock==EXCLUSIVE_LOCK4 ){ | ||||
| 42013 | rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST(sqlite3PendingByte+2), SHARED_SIZE510, 0); | ||||
| 42014 | if( rc==SQLITE_OK0 && (eFileLock==SHARED_LOCK1 || pInode->nShared>1) ){ | ||||
| 42015 | /* only re-establish the shared lock if necessary */ | ||||
| 42016 | int sharedLockByte = SHARED_FIRST(sqlite3PendingByte+2)+pInode->sharedByte; | ||||
| 42017 | rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1); | ||||
| 42018 | } else { | ||||
| 42019 | skipShared = 1; | ||||
| 42020 | } | ||||
| 42021 | } | ||||
| 42022 | if( rc==SQLITE_OK0 && pFile->eFileLock>=PENDING_LOCK3 ){ | ||||
| 42023 | rc = afpSetLock(context->dbPath, pFile, PENDING_BYTEsqlite3PendingByte, 1, 0); | ||||
| 42024 | } | ||||
| 42025 | if( rc==SQLITE_OK0 && pFile->eFileLock>=RESERVED_LOCK2 && context->reserved ){ | ||||
| 42026 | rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE(sqlite3PendingByte+1), 1, 0); | ||||
| 42027 | if( !rc ){ | ||||
| 42028 | context->reserved = 0; | ||||
| 42029 | } | ||||
| 42030 | } | ||||
| 42031 | if( rc==SQLITE_OK0 && (eFileLock==SHARED_LOCK1 || pInode->nShared>1)){ | ||||
| 42032 | pInode->eFileLock = SHARED_LOCK1; | ||||
| 42033 | } | ||||
| 42034 | } | ||||
| 42035 | if( rc==SQLITE_OK0 && eFileLock==NO_LOCK0 ){ | ||||
| 42036 | |||||
| 42037 | /* Decrement the shared lock counter. Release the lock using an | ||||
| 42038 | ** OS call only when all threads in this same process have released | ||||
| 42039 | ** the lock. | ||||
| 42040 | */ | ||||
| 42041 | unsigned long long sharedLockByte = SHARED_FIRST(sqlite3PendingByte+2)+pInode->sharedByte; | ||||
| 42042 | pInode->nShared--; | ||||
| 42043 | if( pInode->nShared==0 ){ | ||||
| 42044 | if( !skipShared ){ | ||||
| 42045 | rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0); | ||||
| 42046 | } | ||||
| 42047 | if( !rc ){ | ||||
| 42048 | pInode->eFileLock = NO_LOCK0; | ||||
| 42049 | pFile->eFileLock = NO_LOCK0; | ||||
| 42050 | } | ||||
| 42051 | } | ||||
| 42052 | if( rc==SQLITE_OK0 ){ | ||||
| 42053 | pInode->nLock--; | ||||
| 42054 | assert( pInode->nLock>=0 )((void) (0)); | ||||
| 42055 | if( pInode->nLock==0 ) closePendingFds(pFile); | ||||
| 42056 | } | ||||
| 42057 | } | ||||
| 42058 | |||||
| 42059 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 42060 | if( rc==SQLITE_OK0 ){ | ||||
| 42061 | pFile->eFileLock = eFileLock; | ||||
| 42062 | } | ||||
| 42063 | return rc; | ||||
| 42064 | } | ||||
| 42065 | |||||
| 42066 | /* | ||||
| 42067 | ** Close a file & cleanup AFP specific locking context | ||||
| 42068 | */ | ||||
| 42069 | static int afpClose(sqlite3_file *id) { | ||||
| 42070 | int rc = SQLITE_OK0; | ||||
| 42071 | unixFile *pFile = (unixFile*)id; | ||||
| 42072 | assert( id!=0 )((void) (0)); | ||||
| 42073 | afpUnlock(id, NO_LOCK0); | ||||
| 42074 | assert( unixFileMutexNotheld(pFile) )((void) (0)); | ||||
| 42075 | unixEnterMutex(); | ||||
| 42076 | if( pFile->pInode ){ | ||||
| 42077 | unixInodeInfo *pInode = pFile->pInode; | ||||
| 42078 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 42079 | if( pInode->nLock ){ | ||||
| 42080 | /* If there are outstanding locks, do not actually close the file just | ||||
| 42081 | ** yet because that would clear those locks. Instead, add the file | ||||
| 42082 | ** descriptor to pInode->aPending. It will be automatically closed when | ||||
| 42083 | ** the last lock is cleared. | ||||
| 42084 | */ | ||||
| 42085 | setPendingFd(pFile); | ||||
| 42086 | } | ||||
| 42087 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 42088 | } | ||||
| 42089 | releaseInodeInfo(pFile); | ||||
| 42090 | sqlite3_free(pFile->lockingContext); | ||||
| 42091 | rc = closeUnixFile(id); | ||||
| 42092 | unixLeaveMutex(); | ||||
| 42093 | return rc; | ||||
| 42094 | } | ||||
| 42095 | |||||
| 42096 | #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ | ||||
| 42097 | /* | ||||
| 42098 | ** The code above is the AFP lock implementation. The code is specific | ||||
| 42099 | ** to MacOSX and does not work on other unix platforms. No alternative | ||||
| 42100 | ** is available. If you don't compile for a mac, then the "unix-afp" | ||||
| 42101 | ** VFS is not available. | ||||
| 42102 | ** | ||||
| 42103 | ********************* End of the AFP lock implementation ********************** | ||||
| 42104 | ******************************************************************************/ | ||||
| 42105 | |||||
| 42106 | /****************************************************************************** | ||||
| 42107 | *************************** Begin NFS Locking ********************************/ | ||||
| 42108 | |||||
| 42109 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 42110 | /* | ||||
| 42111 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 42112 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 42113 | ** | ||||
| 42114 | ** If the locking level of the file descriptor is already at or below | ||||
| 42115 | ** the requested locking level, this routine is a no-op. | ||||
| 42116 | */ | ||||
| 42117 | static int nfsUnlock(sqlite3_file *id, int eFileLock){ | ||||
| 42118 | return posixUnlock(id, eFileLock, 1); | ||||
| 42119 | } | ||||
| 42120 | |||||
| 42121 | #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ | ||||
| 42122 | /* | ||||
| 42123 | ** The code above is the NFS lock implementation. The code is specific | ||||
| 42124 | ** to MacOSX and does not work on other unix platforms. No alternative | ||||
| 42125 | ** is available. | ||||
| 42126 | ** | ||||
| 42127 | ********************* End of the NFS lock implementation ********************** | ||||
| 42128 | ******************************************************************************/ | ||||
| 42129 | |||||
| 42130 | /****************************************************************************** | ||||
| 42131 | **************** Non-locking sqlite3_file methods ***************************** | ||||
| 42132 | ** | ||||
| 42133 | ** The next division contains implementations for all methods of the | ||||
| 42134 | ** sqlite3_file object other than the locking methods. The locking | ||||
| 42135 | ** methods were defined in divisions above (one locking method per | ||||
| 42136 | ** division). Those methods that are common to all locking modes | ||||
| 42137 | ** are gather together into this division. | ||||
| 42138 | */ | ||||
| 42139 | |||||
| 42140 | /* | ||||
| 42141 | ** Seek to the offset passed as the second argument, then read cnt | ||||
| 42142 | ** bytes into pBuf. Return the number of bytes actually read. | ||||
| 42143 | ** | ||||
| 42144 | ** To avoid stomping the errno value on a failed read the lastErrno value | ||||
| 42145 | ** is set before returning. | ||||
| 42146 | */ | ||||
| 42147 | static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ | ||||
| 42148 | int got; | ||||
| 42149 | int prior = 0; | ||||
| 42150 | #if (!defined(USE_PREAD1) && !defined(USE_PREAD64)) | ||||
| 42151 | i64 newOffset; | ||||
| 42152 | #endif | ||||
| 42153 | TIMER_START; | ||||
| 42154 | assert( cnt==(cnt&0x1ffff) )((void) (0)); | ||||
| 42155 | assert( id->h>2 )((void) (0)); | ||||
| 42156 | do{ | ||||
| 42157 | #if defined(USE_PREAD1) | ||||
| 42158 | got = osPread((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)(id->h, pBuf, cnt, offset); | ||||
| 42159 | SimulateIOError( got = -1 ); | ||||
| 42160 | #elif defined(USE_PREAD64) | ||||
| 42161 | got = osPread64((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)(id->h, pBuf, cnt, offset); | ||||
| 42162 | SimulateIOError( got = -1 ); | ||||
| 42163 | #else | ||||
| 42164 | newOffset = lseek(id->h, offset, SEEK_SET0); | ||||
| 42165 | SimulateIOError( newOffset = -1 ); | ||||
| 42166 | if( newOffset<0 ){ | ||||
| 42167 | storeLastErrno((unixFile*)id, errno(*__errno_location ())); | ||||
| 42168 | return -1; | ||||
| 42169 | } | ||||
| 42170 | got = osRead((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)(id->h, pBuf, cnt); | ||||
| 42171 | #endif | ||||
| 42172 | if( got==cnt ) break; | ||||
| 42173 | if( got<0 ){ | ||||
| 42174 | if( errno(*__errno_location ())==EINTR4 ){ got = 1; continue; } | ||||
| 42175 | prior = 0; | ||||
| 42176 | storeLastErrno((unixFile*)id, errno(*__errno_location ())); | ||||
| 42177 | break; | ||||
| 42178 | }else if( got>0 ){ | ||||
| 42179 | cnt -= got; | ||||
| 42180 | offset += got; | ||||
| 42181 | prior += got; | ||||
| 42182 | pBuf = (void*)(got + (char*)pBuf); | ||||
| 42183 | } | ||||
| 42184 | }while( got>0 ); | ||||
| 42185 | TIMER_END; | ||||
| 42186 | OSTRACE(("READ %-3d %5d %7lld %llu\n", | ||||
| 42187 | id->h, got+prior, offset-prior, TIMER_ELAPSED)); | ||||
| 42188 | return got+prior; | ||||
| 42189 | } | ||||
| 42190 | |||||
| 42191 | /* | ||||
| 42192 | ** Read data from a file into a buffer. Return SQLITE_OK if all | ||||
| 42193 | ** bytes were read successfully and SQLITE_IOERR if anything goes | ||||
| 42194 | ** wrong. | ||||
| 42195 | */ | ||||
| 42196 | static int unixRead( | ||||
| 42197 | sqlite3_file *id, | ||||
| 42198 | void *pBuf, | ||||
| 42199 | int amt, | ||||
| 42200 | sqlite3_int64 offset | ||||
| 42201 | ){ | ||||
| 42202 | unixFile *pFile = (unixFile *)id; | ||||
| 42203 | int got; | ||||
| 42204 | assert( id )((void) (0)); | ||||
| 42205 | assert( offset>=0 )((void) (0)); | ||||
| 42206 | assert( amt>0 )((void) (0)); | ||||
| 42207 | |||||
| 42208 | /* If this is a database file (not a journal, super-journal or temp | ||||
| 42209 | ** file), the bytes in the locking range should never be read or written. */ | ||||
| 42210 | #if 0 | ||||
| 42211 | assert( pFile->pPreallocatedUnused==0((void) (0)) | ||||
| 42212 | || offset>=PENDING_BYTE+512((void) (0)) | ||||
| 42213 | || offset+amt<=PENDING_BYTE((void) (0)) | ||||
| 42214 | )((void) (0)); | ||||
| 42215 | #endif | ||||
| 42216 | |||||
| 42217 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 42218 | /* Deal with as much of this read request as possible by transferring | ||||
| 42219 | ** data from the memory mapping using memcpy(). */ | ||||
| 42220 | if( offset<pFile->mmapSize ){ | ||||
| 42221 | if( offset+amt <= pFile->mmapSize ){ | ||||
| 42222 | memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); | ||||
| 42223 | return SQLITE_OK0; | ||||
| 42224 | }else{ | ||||
| 42225 | int nCopy = pFile->mmapSize - offset; | ||||
| 42226 | memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); | ||||
| 42227 | pBuf = &((u8 *)pBuf)[nCopy]; | ||||
| 42228 | amt -= nCopy; | ||||
| 42229 | offset += nCopy; | ||||
| 42230 | } | ||||
| 42231 | } | ||||
| 42232 | #endif | ||||
| 42233 | |||||
| 42234 | got = seekAndRead(pFile, offset, pBuf, amt); | ||||
| 42235 | if( got==amt ){ | ||||
| 42236 | return SQLITE_OK0; | ||||
| 42237 | }else if( got<0 ){ | ||||
| 42238 | /* pFile->lastErrno has been set by seekAndRead(). | ||||
| 42239 | ** Usually we return SQLITE_IOERR_READ here, though for some | ||||
| 42240 | ** kinds of errors we return SQLITE_IOERR_CORRUPTFS. The | ||||
| 42241 | ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT | ||||
| 42242 | ** prior to returning to the application by the sqlite3ApiExit() | ||||
| 42243 | ** routine. | ||||
| 42244 | */ | ||||
| 42245 | switch( pFile->lastErrno ){ | ||||
| 42246 | case ERANGE34: | ||||
| 42247 | case EIO5: | ||||
| 42248 | #ifdef ENXIO6 | ||||
| 42249 | case ENXIO6: | ||||
| 42250 | #endif | ||||
| 42251 | #ifdef EDEVERR | ||||
| 42252 | case EDEVERR: | ||||
| 42253 | #endif | ||||
| 42254 | return SQLITE_IOERR_CORRUPTFS(10 | (33<<8)); | ||||
| 42255 | } | ||||
| 42256 | return SQLITE_IOERR_READ(10 | (1<<8)); | ||||
| 42257 | }else{ | ||||
| 42258 | storeLastErrno(pFile, 0); /* not a system error */ | ||||
| 42259 | /* Unread parts of the buffer must be zero-filled */ | ||||
| 42260 | memset(&((char*)pBuf)[got], 0, amt-got); | ||||
| 42261 | return SQLITE_IOERR_SHORT_READ(10 | (2<<8)); | ||||
| 42262 | } | ||||
| 42263 | } | ||||
| 42264 | |||||
| 42265 | /* | ||||
| 42266 | ** Attempt to seek the file-descriptor passed as the first argument to | ||||
| 42267 | ** absolute offset iOff, then attempt to write nBuf bytes of data from | ||||
| 42268 | ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, | ||||
| 42269 | ** return the actual number of bytes written (which may be less than | ||||
| 42270 | ** nBuf). | ||||
| 42271 | */ | ||||
| 42272 | static int seekAndWriteFd( | ||||
| 42273 | int fd, /* File descriptor to write to */ | ||||
| 42274 | i64 iOff, /* File offset to begin writing at */ | ||||
| 42275 | const void *pBuf, /* Copy data from this buffer to the file */ | ||||
| 42276 | int nBuf, /* Size of buffer pBuf in bytes */ | ||||
| 42277 | int *piErrno /* OUT: Error number if error occurs */ | ||||
| 42278 | ){ | ||||
| 42279 | int rc = 0; /* Value returned by system call */ | ||||
| 42280 | |||||
| 42281 | assert( nBuf==(nBuf&0x1ffff) )((void) (0)); | ||||
| 42282 | assert( fd>2 )((void) (0)); | ||||
| 42283 | assert( piErrno!=0 )((void) (0)); | ||||
| 42284 | nBuf &= 0x1ffff; | ||||
| 42285 | TIMER_START; | ||||
| 42286 | |||||
| 42287 | #if defined(USE_PREAD1) | ||||
| 42288 | do{ rc = (int)osPwrite((ssize_t(*)(int,const void*,size_t,off_t)) aSyscall[12].pCurrent )(fd, pBuf, nBuf, iOff); }while( rc<0 && errno(*__errno_location ())==EINTR4 ); | ||||
| 42289 | #elif defined(USE_PREAD64) | ||||
| 42290 | do{ rc = (int)osPwrite64((ssize_t(*)(int,const void*,size_t,off64_t)) aSyscall[13].pCurrent )(fd, pBuf, nBuf, iOff);}while( rc<0 && errno(*__errno_location ())==EINTR4); | ||||
| 42291 | #else | ||||
| 42292 | do{ | ||||
| 42293 | i64 iSeek = lseek(fd, iOff, SEEK_SET0); | ||||
| 42294 | SimulateIOError( iSeek = -1 ); | ||||
| 42295 | if( iSeek<0 ){ | ||||
| 42296 | rc = -1; | ||||
| 42297 | break; | ||||
| 42298 | } | ||||
| 42299 | rc = osWrite((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)(fd, pBuf, nBuf); | ||||
| 42300 | }while( rc<0 && errno(*__errno_location ())==EINTR4 ); | ||||
| 42301 | #endif | ||||
| 42302 | |||||
| 42303 | TIMER_END; | ||||
| 42304 | OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); | ||||
| 42305 | |||||
| 42306 | if( rc<0 ) *piErrno = errno(*__errno_location ()); | ||||
| 42307 | return rc; | ||||
| 42308 | } | ||||
| 42309 | |||||
| 42310 | |||||
| 42311 | /* | ||||
| 42312 | ** Seek to the offset in id->offset then read cnt bytes into pBuf. | ||||
| 42313 | ** Return the number of bytes actually read. Update the offset. | ||||
| 42314 | ** | ||||
| 42315 | ** To avoid stomping the errno value on a failed write the lastErrno value | ||||
| 42316 | ** is set before returning. | ||||
| 42317 | */ | ||||
| 42318 | static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ | ||||
| 42319 | return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); | ||||
| 42320 | } | ||||
| 42321 | |||||
| 42322 | |||||
| 42323 | /* | ||||
| 42324 | ** Write data from a buffer into a file. Return SQLITE_OK on success | ||||
| 42325 | ** or some other error code on failure. | ||||
| 42326 | */ | ||||
| 42327 | static int unixWrite( | ||||
| 42328 | sqlite3_file *id, | ||||
| 42329 | const void *pBuf, | ||||
| 42330 | int amt, | ||||
| 42331 | sqlite3_int64 offset | ||||
| 42332 | ){ | ||||
| 42333 | unixFile *pFile = (unixFile*)id; | ||||
| 42334 | int wrote = 0; | ||||
| 42335 | assert( id )((void) (0)); | ||||
| 42336 | assert( amt>0 )((void) (0)); | ||||
| 42337 | |||||
| 42338 | /* If this is a database file (not a journal, super-journal or temp | ||||
| 42339 | ** file), the bytes in the locking range should never be read or written. */ | ||||
| 42340 | #if 0 | ||||
| 42341 | assert( pFile->pPreallocatedUnused==0((void) (0)) | ||||
| 42342 | || offset>=PENDING_BYTE+512((void) (0)) | ||||
| 42343 | || offset+amt<=PENDING_BYTE((void) (0)) | ||||
| 42344 | )((void) (0)); | ||||
| 42345 | #endif | ||||
| 42346 | |||||
| 42347 | #ifdef SQLITE_DEBUG | ||||
| 42348 | /* If we are doing a normal write to a database file (as opposed to | ||||
| 42349 | ** doing a hot-journal rollback or a write to some file other than a | ||||
| 42350 | ** normal database file) then record the fact that the database | ||||
| 42351 | ** has changed. If the transaction counter is modified, record that | ||||
| 42352 | ** fact too. | ||||
| 42353 | */ | ||||
| 42354 | if( pFile->inNormalWrite ){ | ||||
| 42355 | pFile->dbUpdate = 1; /* The database has been modified */ | ||||
| 42356 | if( offset<=24 && offset+amt>=27 ){ | ||||
| 42357 | int rc; | ||||
| 42358 | char oldCntr[4]; | ||||
| 42359 | SimulateIOErrorBenign(1); | ||||
| 42360 | rc = seekAndRead(pFile, 24, oldCntr, 4); | ||||
| 42361 | SimulateIOErrorBenign(0); | ||||
| 42362 | if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ | ||||
| 42363 | pFile->transCntrChng = 1; /* The transaction counter has changed */ | ||||
| 42364 | } | ||||
| 42365 | } | ||||
| 42366 | } | ||||
| 42367 | #endif | ||||
| 42368 | |||||
| 42369 | #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 42370 | /* Deal with as much of this write request as possible by transferring | ||||
| 42371 | ** data from the memory mapping using memcpy(). */ | ||||
| 42372 | if( offset<pFile->mmapSize ){ | ||||
| 42373 | if( offset+amt <= pFile->mmapSize ){ | ||||
| 42374 | memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); | ||||
| 42375 | return SQLITE_OK0; | ||||
| 42376 | }else{ | ||||
| 42377 | int nCopy = pFile->mmapSize - offset; | ||||
| 42378 | memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); | ||||
| 42379 | pBuf = &((u8 *)pBuf)[nCopy]; | ||||
| 42380 | amt -= nCopy; | ||||
| 42381 | offset += nCopy; | ||||
| 42382 | } | ||||
| 42383 | } | ||||
| 42384 | #endif | ||||
| 42385 | |||||
| 42386 | while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){ | ||||
| 42387 | amt -= wrote; | ||||
| 42388 | offset += wrote; | ||||
| 42389 | pBuf = &((char*)pBuf)[wrote]; | ||||
| 42390 | } | ||||
| 42391 | SimulateIOError(( wrote=(-1), amt=1 )); | ||||
| 42392 | SimulateDiskfullError(( wrote=0, amt=1 )); | ||||
| 42393 | |||||
| 42394 | if( amt>wrote ){ | ||||
| 42395 | if( wrote<0 && pFile->lastErrno!=ENOSPC28 ){ | ||||
| 42396 | /* lastErrno set by seekAndWrite */ | ||||
| 42397 | return SQLITE_IOERR_WRITE(10 | (3<<8)); | ||||
| 42398 | }else{ | ||||
| 42399 | storeLastErrno(pFile, 0); /* not a system error */ | ||||
| 42400 | return SQLITE_FULL13; | ||||
| 42401 | } | ||||
| 42402 | } | ||||
| 42403 | |||||
| 42404 | return SQLITE_OK0; | ||||
| 42405 | } | ||||
| 42406 | |||||
| 42407 | #ifdef SQLITE_TEST | ||||
| 42408 | /* | ||||
| 42409 | ** Count the number of fullsyncs and normal syncs. This is used to test | ||||
| 42410 | ** that syncs and fullsyncs are occurring at the right times. | ||||
| 42411 | */ | ||||
| 42412 | SQLITE_API int sqlite3_sync_count = 0; | ||||
| 42413 | SQLITE_API int sqlite3_fullsync_count = 0; | ||||
| 42414 | #endif | ||||
| 42415 | |||||
| 42416 | /* | ||||
| 42417 | ** We do not trust systems to provide a working fdatasync(). Some do. | ||||
| 42418 | ** Others do no. To be safe, we will stick with the (slightly slower) | ||||
| 42419 | ** fsync(). If you know that your system does support fdatasync() correctly, | ||||
| 42420 | ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC | ||||
| 42421 | */ | ||||
| 42422 | #if !defined(fdatasyncfsync) && !HAVE_FDATASYNC | ||||
| 42423 | # define fdatasyncfsync fsync | ||||
| 42424 | #endif | ||||
| 42425 | |||||
| 42426 | /* | ||||
| 42427 | ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not | ||||
| 42428 | ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently | ||||
| 42429 | ** only available on Mac OS X. But that could change. | ||||
| 42430 | */ | ||||
| 42431 | #ifdef F_FULLFSYNC | ||||
| 42432 | # define HAVE_FULLFSYNC0 1 | ||||
| 42433 | #else | ||||
| 42434 | # define HAVE_FULLFSYNC0 0 | ||||
| 42435 | #endif | ||||
| 42436 | |||||
| 42437 | |||||
| 42438 | /* | ||||
| 42439 | ** The fsync() system call does not work as advertised on many | ||||
| 42440 | ** unix systems. The following procedure is an attempt to make | ||||
| 42441 | ** it work better. | ||||
| 42442 | ** | ||||
| 42443 | ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful | ||||
| 42444 | ** for testing when we want to run through the test suite quickly. | ||||
| 42445 | ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC | ||||
| 42446 | ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash | ||||
| 42447 | ** or power failure will likely corrupt the database file. | ||||
| 42448 | ** | ||||
| 42449 | ** SQLite sets the dataOnly flag if the size of the file is unchanged. | ||||
| 42450 | ** The idea behind dataOnly is that it should only write the file content | ||||
| 42451 | ** to disk, not the inode. We only set dataOnly if the file size is | ||||
| 42452 | ** unchanged since the file size is part of the inode. However, | ||||
| 42453 | ** Ted Ts'o tells us that fdatasync() will also write the inode if the | ||||
| 42454 | ** file size has changed. The only real difference between fdatasync() | ||||
| 42455 | ** and fsync(), Ted tells us, is that fdatasync() will not flush the | ||||
| 42456 | ** inode if the mtime or owner or other inode attributes have changed. | ||||
| 42457 | ** We only care about the file size, not the other file attributes, so | ||||
| 42458 | ** as far as SQLite is concerned, an fdatasync() is always adequate. | ||||
| 42459 | ** So, we always use fdatasync() if it is available, regardless of | ||||
| 42460 | ** the value of the dataOnly flag. | ||||
| 42461 | */ | ||||
| 42462 | static int full_fsync(int fd, int fullSync, int dataOnly){ | ||||
| 42463 | int rc; | ||||
| 42464 | |||||
| 42465 | /* The following "ifdef/elif/else/" block has the same structure as | ||||
| 42466 | ** the one below. It is replicated here solely to avoid cluttering | ||||
| 42467 | ** up the real code with the UNUSED_PARAMETER() macros. | ||||
| 42468 | */ | ||||
| 42469 | #ifdef SQLITE_NO_SYNC | ||||
| 42470 | UNUSED_PARAMETER(fd)(void)(fd); | ||||
| 42471 | UNUSED_PARAMETER(fullSync)(void)(fullSync); | ||||
| 42472 | UNUSED_PARAMETER(dataOnly)(void)(dataOnly); | ||||
| 42473 | #elif HAVE_FULLFSYNC0 | ||||
| 42474 | UNUSED_PARAMETER(dataOnly)(void)(dataOnly); | ||||
| 42475 | #else | ||||
| 42476 | UNUSED_PARAMETER(fullSync)(void)(fullSync); | ||||
| 42477 | UNUSED_PARAMETER(dataOnly)(void)(dataOnly); | ||||
| 42478 | #endif | ||||
| 42479 | |||||
| 42480 | /* Record the number of times that we do a normal fsync() and | ||||
| 42481 | ** FULLSYNC. This is used during testing to verify that this procedure | ||||
| 42482 | ** gets called with the correct arguments. | ||||
| 42483 | */ | ||||
| 42484 | #ifdef SQLITE_TEST | ||||
| 42485 | if( fullSync ) sqlite3_fullsync_count++; | ||||
| 42486 | sqlite3_sync_count++; | ||||
| 42487 | #endif | ||||
| 42488 | |||||
| 42489 | /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a | ||||
| 42490 | ** no-op. But go ahead and call fstat() to validate the file | ||||
| 42491 | ** descriptor as we need a method to provoke a failure during | ||||
| 42492 | ** coverage testing. | ||||
| 42493 | */ | ||||
| 42494 | #ifdef SQLITE_NO_SYNC | ||||
| 42495 | { | ||||
| 42496 | struct stat buf; | ||||
| 42497 | rc = osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(fd, &buf); | ||||
| 42498 | } | ||||
| 42499 | #elif HAVE_FULLFSYNC0 | ||||
| 42500 | if( fullSync ){ | ||||
| 42501 | rc = osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(fd, F_FULLFSYNC, 0); | ||||
| 42502 | }else{ | ||||
| 42503 | rc = 1; | ||||
| 42504 | } | ||||
| 42505 | /* If the FULLFSYNC failed, fall back to attempting an fsync(). | ||||
| 42506 | ** It shouldn't be possible for fullfsync to fail on the local | ||||
| 42507 | ** file system (on OSX), so failure indicates that FULLFSYNC | ||||
| 42508 | ** isn't supported for this file system. So, attempt an fsync | ||||
| 42509 | ** and (for now) ignore the overhead of a superfluous fcntl call. | ||||
| 42510 | ** It'd be better to detect fullfsync support once and avoid | ||||
| 42511 | ** the fcntl call every time sync is called. | ||||
| 42512 | */ | ||||
| 42513 | if( rc ) rc = fsync(fd); | ||||
| 42514 | |||||
| 42515 | #elif defined(__APPLE__) | ||||
| 42516 | /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly | ||||
| 42517 | ** so currently we default to the macro that redefines fdatasync to fsync | ||||
| 42518 | */ | ||||
| 42519 | rc = fsync(fd); | ||||
| 42520 | #else | ||||
| 42521 | rc = fdatasyncfsync(fd); | ||||
| 42522 | #if OS_VXWORKS0 | ||||
| 42523 | if( rc==-1 && errno(*__errno_location ())==ENOTSUP95 ){ | ||||
| 42524 | rc = fsync(fd); | ||||
| 42525 | } | ||||
| 42526 | #endif /* OS_VXWORKS */ | ||||
| 42527 | #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ | ||||
| 42528 | |||||
| 42529 | if( OS_VXWORKS0 && rc!= -1 ){ | ||||
| 42530 | rc = 0; | ||||
| 42531 | } | ||||
| 42532 | return rc; | ||||
| 42533 | } | ||||
| 42534 | |||||
| 42535 | /* | ||||
| 42536 | ** Open a file descriptor to the directory containing file zFilename. | ||||
| 42537 | ** If successful, *pFd is set to the opened file descriptor and | ||||
| 42538 | ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM | ||||
| 42539 | ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined | ||||
| 42540 | ** value. | ||||
| 42541 | ** | ||||
| 42542 | ** The directory file descriptor is used for only one thing - to | ||||
| 42543 | ** fsync() a directory to make sure file creation and deletion events | ||||
| 42544 | ** are flushed to disk. Such fsyncs are not needed on newer | ||||
| 42545 | ** journaling filesystems, but are required on older filesystems. | ||||
| 42546 | ** | ||||
| 42547 | ** This routine can be overridden using the xSetSysCall interface. | ||||
| 42548 | ** The ability to override this routine was added in support of the | ||||
| 42549 | ** chromium sandbox. Opening a directory is a security risk (we are | ||||
| 42550 | ** told) so making it overrideable allows the chromium sandbox to | ||||
| 42551 | ** replace this routine with a harmless no-op. To make this routine | ||||
| 42552 | ** a no-op, replace it with a stub that returns SQLITE_OK but leaves | ||||
| 42553 | ** *pFd set to a negative number. | ||||
| 42554 | ** | ||||
| 42555 | ** If SQLITE_OK is returned, the caller is responsible for closing | ||||
| 42556 | ** the file descriptor *pFd using close(). | ||||
| 42557 | */ | ||||
| 42558 | static int openDirectory(const char *zFilename, int *pFd){ | ||||
| 42559 | int ii; | ||||
| 42560 | int fd = -1; | ||||
| 42561 | char zDirname[MAX_PATHNAME512+1]; | ||||
| 42562 | |||||
| 42563 | sqlite3_snprintf(MAX_PATHNAME512, zDirname, "%s", zFilename); | ||||
| 42564 | for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--); | ||||
| 42565 | if( ii>0 ){ | ||||
| 42566 | zDirname[ii] = '\0'; | ||||
| 42567 | }else{ | ||||
| 42568 | if( zDirname[0]!='/' ) zDirname[0] = '.'; | ||||
| 42569 | zDirname[1] = 0; | ||||
| 42570 | } | ||||
| 42571 | fd = robust_open(zDirname, O_RDONLY00|O_BINARY0, 0); | ||||
| 42572 | if( fd>=0 ){ | ||||
| 42573 | OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); | ||||
| 42574 | } | ||||
| 42575 | *pFd = fd; | ||||
| 42576 | if( fd>=0 ) return SQLITE_OK0; | ||||
| 42577 | return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname)unixLogErrorAtLine(sqlite3CantopenError(42577),"openDirectory" ,zDirname,42577); | ||||
| 42578 | } | ||||
| 42579 | |||||
| 42580 | /* | ||||
| 42581 | ** Make sure all writes to a particular file are committed to disk. | ||||
| 42582 | ** | ||||
| 42583 | ** If dataOnly==0 then both the file itself and its metadata (file | ||||
| 42584 | ** size, access time, etc) are synced. If dataOnly!=0 then only the | ||||
| 42585 | ** file data is synced. | ||||
| 42586 | ** | ||||
| 42587 | ** Under Unix, also make sure that the directory entry for the file | ||||
| 42588 | ** has been created by fsync-ing the directory that contains the file. | ||||
| 42589 | ** If we do not do this and we encounter a power failure, the directory | ||||
| 42590 | ** entry for the journal might not exist after we reboot. The next | ||||
| 42591 | ** SQLite to access the file will not know that the journal exists (because | ||||
| 42592 | ** the directory entry for the journal was never created) and the transaction | ||||
| 42593 | ** will not roll back - possibly leading to database corruption. | ||||
| 42594 | */ | ||||
| 42595 | static int unixSync(sqlite3_file *id, int flags){ | ||||
| 42596 | int rc; | ||||
| 42597 | unixFile *pFile = (unixFile*)id; | ||||
| 42598 | |||||
| 42599 | int isDataOnly = (flags&SQLITE_SYNC_DATAONLY0x00010); | ||||
| 42600 | int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL0x00003; | ||||
| 42601 | |||||
| 42602 | /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ | ||||
| 42603 | assert((flags&0x0F)==SQLITE_SYNC_NORMAL((void) (0)) | ||||
| 42604 | || (flags&0x0F)==SQLITE_SYNC_FULL((void) (0)) | ||||
| 42605 | )((void) (0)); | ||||
| 42606 | |||||
| 42607 | /* Unix cannot, but some systems may return SQLITE_FULL from here. This | ||||
| 42608 | ** line is to test that doing so does not cause any problems. | ||||
| 42609 | */ | ||||
| 42610 | SimulateDiskfullError( return SQLITE_FULL ); | ||||
| 42611 | |||||
| 42612 | assert( pFile )((void) (0)); | ||||
| 42613 | OSTRACE(("SYNC %-3d\n", pFile->h)); | ||||
| 42614 | rc = full_fsync(pFile->h, isFullsync, isDataOnly); | ||||
| 42615 | SimulateIOError( rc=1 ); | ||||
| 42616 | if( rc ){ | ||||
| 42617 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 42618 | return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath)unixLogErrorAtLine((10 | (4<<8)),"full_fsync",pFile-> zPath,42618); | ||||
| 42619 | } | ||||
| 42620 | |||||
| 42621 | /* Also fsync the directory containing the file if the DIRSYNC flag | ||||
| 42622 | ** is set. This is a one-time occurrence. Many systems (examples: AIX) | ||||
| 42623 | ** are unable to fsync a directory, so ignore errors on the fsync. | ||||
| 42624 | */ | ||||
| 42625 | if( pFile->ctrlFlags & UNIXFILE_DIRSYNC0x08 ){ | ||||
| 42626 | int dirfd; | ||||
| 42627 | OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, | ||||
| 42628 | HAVE_FULLFSYNC, isFullsync)); | ||||
| 42629 | rc = osOpenDirectory((int(*)(const char*,int*))aSyscall[17].pCurrent)(pFile->zPath, &dirfd); | ||||
| 42630 | if( rc==SQLITE_OK0 ){ | ||||
| 42631 | full_fsync(dirfd, 0, 0); | ||||
| 42632 | robust_close(pFile, dirfd, __LINE__42632); | ||||
| 42633 | }else{ | ||||
| 42634 | assert( rc==SQLITE_CANTOPEN )((void) (0)); | ||||
| 42635 | rc = SQLITE_OK0; | ||||
| 42636 | } | ||||
| 42637 | pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC0x08; | ||||
| 42638 | } | ||||
| 42639 | return rc; | ||||
| 42640 | } | ||||
| 42641 | |||||
| 42642 | /* | ||||
| 42643 | ** Truncate an open file to a specified size | ||||
| 42644 | */ | ||||
| 42645 | static int unixTruncate(sqlite3_file *id, i64 nByte){ | ||||
| 42646 | unixFile *pFile = (unixFile *)id; | ||||
| 42647 | int rc; | ||||
| 42648 | assert( pFile )((void) (0)); | ||||
| 42649 | SimulateIOError( return SQLITE_IOERR_TRUNCATE ); | ||||
| 42650 | |||||
| 42651 | /* If the user has configured a chunk-size for this file, truncate the | ||||
| 42652 | ** file so that it consists of an integer number of chunks (i.e. the | ||||
| 42653 | ** actual file size after the operation may be larger than the requested | ||||
| 42654 | ** size). | ||||
| 42655 | */ | ||||
| 42656 | if( pFile->szChunk>0 ){ | ||||
| 42657 | nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; | ||||
| 42658 | } | ||||
| 42659 | |||||
| 42660 | rc = robust_ftruncate(pFile->h, nByte); | ||||
| 42661 | if( rc ){ | ||||
| 42662 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 42663 | return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath)unixLogErrorAtLine((10 | (6<<8)),"ftruncate",pFile-> zPath,42663); | ||||
| 42664 | }else{ | ||||
| 42665 | #ifdef SQLITE_DEBUG | ||||
| 42666 | /* If we are doing a normal write to a database file (as opposed to | ||||
| 42667 | ** doing a hot-journal rollback or a write to some file other than a | ||||
| 42668 | ** normal database file) and we truncate the file to zero length, | ||||
| 42669 | ** that effectively updates the change counter. This might happen | ||||
| 42670 | ** when restoring a database using the backup API from a zero-length | ||||
| 42671 | ** source. | ||||
| 42672 | */ | ||||
| 42673 | if( pFile->inNormalWrite && nByte==0 ){ | ||||
| 42674 | pFile->transCntrChng = 1; | ||||
| 42675 | } | ||||
| 42676 | #endif | ||||
| 42677 | |||||
| 42678 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 42679 | /* If the file was just truncated to a size smaller than the currently | ||||
| 42680 | ** mapped region, reduce the effective mapping size as well. SQLite will | ||||
| 42681 | ** use read() and write() to access data beyond this point from now on. | ||||
| 42682 | */ | ||||
| 42683 | if( nByte<pFile->mmapSize ){ | ||||
| 42684 | pFile->mmapSize = nByte; | ||||
| 42685 | } | ||||
| 42686 | #endif | ||||
| 42687 | |||||
| 42688 | return SQLITE_OK0; | ||||
| 42689 | } | ||||
| 42690 | } | ||||
| 42691 | |||||
| 42692 | /* | ||||
| 42693 | ** Determine the current size of a file in bytes | ||||
| 42694 | */ | ||||
| 42695 | static int unixFileSize(sqlite3_file *id, i64 *pSize){ | ||||
| 42696 | int rc; | ||||
| 42697 | struct stat buf; | ||||
| 42698 | assert( id )((void) (0)); | ||||
| 42699 | rc = osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(((unixFile*)id)->h, &buf); | ||||
| 42700 | SimulateIOError( rc=1 ); | ||||
| 42701 | if( rc!=0 ){ | ||||
| 42702 | storeLastErrno((unixFile*)id, errno(*__errno_location ())); | ||||
| 42703 | return SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 42704 | } | ||||
| 42705 | *pSize = buf.st_size; | ||||
| 42706 | |||||
| 42707 | /* When opening a zero-size database, the findInodeInfo() procedure | ||||
| 42708 | ** writes a single byte into that file in order to work around a bug | ||||
| 42709 | ** in the OS-X msdos filesystem. In order to avoid problems with upper | ||||
| 42710 | ** layers, we need to report this file size as zero even though it is | ||||
| 42711 | ** really 1. Ticket #3260. | ||||
| 42712 | */ | ||||
| 42713 | if( *pSize==1 ) *pSize = 0; | ||||
| 42714 | |||||
| 42715 | |||||
| 42716 | return SQLITE_OK0; | ||||
| 42717 | } | ||||
| 42718 | |||||
| 42719 | #if SQLITE_ENABLE_LOCKING_STYLE0 && defined(__APPLE__) | ||||
| 42720 | /* | ||||
| 42721 | ** Handler for proxy-locking file-control verbs. Defined below in the | ||||
| 42722 | ** proxying locking division. | ||||
| 42723 | */ | ||||
| 42724 | static int proxyFileControl(sqlite3_file*,int,void*); | ||||
| 42725 | #endif | ||||
| 42726 | |||||
| 42727 | /* | ||||
| 42728 | ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT | ||||
| 42729 | ** file-control operation. Enlarge the database to nBytes in size | ||||
| 42730 | ** (rounded up to the next chunk-size). If the database is already | ||||
| 42731 | ** nBytes or larger, this routine is a no-op. | ||||
| 42732 | */ | ||||
| 42733 | static int fcntlSizeHint(unixFile *pFile, i64 nByte){ | ||||
| 42734 | if( pFile->szChunk>0 ){ | ||||
| 42735 | i64 nSize; /* Required file size */ | ||||
| 42736 | struct stat buf; /* Used to hold return values of fstat() */ | ||||
| 42737 | |||||
| 42738 | if( osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(pFile->h, &buf) ){ | ||||
| 42739 | return SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 42740 | } | ||||
| 42741 | |||||
| 42742 | nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; | ||||
| 42743 | if( nSize>(i64)buf.st_size ){ | ||||
| 42744 | |||||
| 42745 | #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE | ||||
| 42746 | /* The code below is handling the return value of osFallocate() | ||||
| 42747 | ** correctly. posix_fallocate() is defined to "returns zero on success, | ||||
| 42748 | ** or an error number on failure". See the manpage for details. */ | ||||
| 42749 | int err; | ||||
| 42750 | do{ | ||||
| 42751 | err = osFallocate((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)(pFile->h, buf.st_size, nSize-buf.st_size); | ||||
| 42752 | }while( err==EINTR4 ); | ||||
| 42753 | if( err && err!=EINVAL22 ) return SQLITE_IOERR_WRITE(10 | (3<<8)); | ||||
| 42754 | #else | ||||
| 42755 | /* If the OS does not have posix_fallocate(), fake it. Write a | ||||
| 42756 | ** single byte to the last byte in each block that falls entirely | ||||
| 42757 | ** within the extended region. Then, if required, a single byte | ||||
| 42758 | ** at offset (nSize-1), to set the size of the file correctly. | ||||
| 42759 | ** This is a similar technique to that used by glibc on systems | ||||
| 42760 | ** that do not have a real fallocate() call. | ||||
| 42761 | */ | ||||
| 42762 | int nBlk = buf.st_blksize; /* File-system block size */ | ||||
| 42763 | int nWrite = 0; /* Number of bytes written by seekAndWrite */ | ||||
| 42764 | i64 iWrite; /* Next offset to write to */ | ||||
| 42765 | |||||
| 42766 | iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1; | ||||
| 42767 | assert( iWrite>=buf.st_size )((void) (0)); | ||||
| 42768 | assert( ((iWrite+1)%nBlk)==0 )((void) (0)); | ||||
| 42769 | for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){ | ||||
| 42770 | if( iWrite>=nSize ) iWrite = nSize - 1; | ||||
| 42771 | nWrite = seekAndWrite(pFile, iWrite, "", 1); | ||||
| 42772 | if( nWrite!=1 ) return SQLITE_IOERR_WRITE(10 | (3<<8)); | ||||
| 42773 | } | ||||
| 42774 | #endif | ||||
| 42775 | } | ||||
| 42776 | } | ||||
| 42777 | |||||
| 42778 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 42779 | if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){ | ||||
| 42780 | int rc; | ||||
| 42781 | if( pFile->szChunk<=0 ){ | ||||
| 42782 | if( robust_ftruncate(pFile->h, nByte) ){ | ||||
| 42783 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 42784 | return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath)unixLogErrorAtLine((10 | (6<<8)),"ftruncate",pFile-> zPath,42784); | ||||
| 42785 | } | ||||
| 42786 | } | ||||
| 42787 | |||||
| 42788 | rc = unixMapfile(pFile, nByte); | ||||
| 42789 | return rc; | ||||
| 42790 | } | ||||
| 42791 | #endif | ||||
| 42792 | |||||
| 42793 | return SQLITE_OK0; | ||||
| 42794 | } | ||||
| 42795 | |||||
| 42796 | /* | ||||
| 42797 | ** If *pArg is initially negative then this is a query. Set *pArg to | ||||
| 42798 | ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. | ||||
| 42799 | ** | ||||
| 42800 | ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. | ||||
| 42801 | */ | ||||
| 42802 | static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){ | ||||
| 42803 | if( *pArg<0 ){ | ||||
| 42804 | *pArg = (pFile->ctrlFlags & mask)!=0; | ||||
| 42805 | }else if( (*pArg)==0 ){ | ||||
| 42806 | pFile->ctrlFlags &= ~mask; | ||||
| 42807 | }else{ | ||||
| 42808 | pFile->ctrlFlags |= mask; | ||||
| 42809 | } | ||||
| 42810 | } | ||||
| 42811 | |||||
| 42812 | /* Forward declaration */ | ||||
| 42813 | static int unixGetTempname(int nBuf, char *zBuf); | ||||
| 42814 | #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) | ||||
| 42815 | static int unixFcntlExternalReader(unixFile*, int*); | ||||
| 42816 | #endif | ||||
| 42817 | |||||
| 42818 | /* | ||||
| 42819 | ** Information and control of an open file handle. | ||||
| 42820 | */ | ||||
| 42821 | static int unixFileControl(sqlite3_file *id, int op, void *pArg){ | ||||
| 42822 | unixFile *pFile = (unixFile*)id; | ||||
| 42823 | switch( op ){ | ||||
| 42824 | #if defined(__linux__1) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) | ||||
| 42825 | case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE31: { | ||||
| 42826 | int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((1)) << 0) | ((0) << ((0 +8)+8)))); | ||||
| 42827 | return rc ? SQLITE_IOERR_BEGIN_ATOMIC(10 | (29<<8)) : SQLITE_OK0; | ||||
| 42828 | } | ||||
| 42829 | case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE32: { | ||||
| 42830 | int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((2)) << 0) | ((0) << ((0 +8)+8)))); | ||||
| 42831 | return rc ? SQLITE_IOERR_COMMIT_ATOMIC(10 | (30<<8)) : SQLITE_OK0; | ||||
| 42832 | } | ||||
| 42833 | case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE33: { | ||||
| 42834 | int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE(((0U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((5)) << 0) | ((0) << ((0 +8)+8)))); | ||||
| 42835 | return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC(10 | (31<<8)) : SQLITE_OK0; | ||||
| 42836 | } | ||||
| 42837 | #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ | ||||
| 42838 | |||||
| 42839 | case SQLITE_FCNTL_NULL_IO43: { | ||||
| 42840 | osClose((int(*)(int))aSyscall[1].pCurrent)(pFile->h); | ||||
| 42841 | pFile->h = -1; | ||||
| 42842 | return SQLITE_OK0; | ||||
| 42843 | } | ||||
| 42844 | case SQLITE_FCNTL_LOCKSTATE1: { | ||||
| 42845 | *(int*)pArg = pFile->eFileLock; | ||||
| 42846 | return SQLITE_OK0; | ||||
| 42847 | } | ||||
| 42848 | case SQLITE_FCNTL_LAST_ERRNO4: { | ||||
| 42849 | *(int*)pArg = pFile->lastErrno; | ||||
| 42850 | return SQLITE_OK0; | ||||
| 42851 | } | ||||
| 42852 | case SQLITE_FCNTL_CHUNK_SIZE6: { | ||||
| 42853 | pFile->szChunk = *(int *)pArg; | ||||
| 42854 | return SQLITE_OK0; | ||||
| 42855 | } | ||||
| 42856 | case SQLITE_FCNTL_SIZE_HINT5: { | ||||
| 42857 | int rc; | ||||
| 42858 | SimulateIOErrorBenign(1); | ||||
| 42859 | rc = fcntlSizeHint(pFile, *(i64 *)pArg); | ||||
| 42860 | SimulateIOErrorBenign(0); | ||||
| 42861 | return rc; | ||||
| 42862 | } | ||||
| 42863 | case SQLITE_FCNTL_PERSIST_WAL10: { | ||||
| 42864 | unixModeBit(pFile, UNIXFILE_PERSIST_WAL0x04, (int*)pArg); | ||||
| 42865 | return SQLITE_OK0; | ||||
| 42866 | } | ||||
| 42867 | case SQLITE_FCNTL_POWERSAFE_OVERWRITE13: { | ||||
| 42868 | unixModeBit(pFile, UNIXFILE_PSOW0x10, (int*)pArg); | ||||
| 42869 | return SQLITE_OK0; | ||||
| 42870 | } | ||||
| 42871 | case SQLITE_FCNTL_VFSNAME12: { | ||||
| 42872 | *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); | ||||
| 42873 | return SQLITE_OK0; | ||||
| 42874 | } | ||||
| 42875 | case SQLITE_FCNTL_TEMPFILENAME16: { | ||||
| 42876 | char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname ); | ||||
| 42877 | if( zTFile ){ | ||||
| 42878 | unixGetTempname(pFile->pVfs->mxPathname, zTFile); | ||||
| 42879 | *(char**)pArg = zTFile; | ||||
| 42880 | } | ||||
| 42881 | return SQLITE_OK0; | ||||
| 42882 | } | ||||
| 42883 | case SQLITE_FCNTL_HAS_MOVED20: { | ||||
| 42884 | *(int*)pArg = fileHasMoved(pFile); | ||||
| 42885 | return SQLITE_OK0; | ||||
| 42886 | } | ||||
| 42887 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 42888 | case SQLITE_FCNTL_LOCK_TIMEOUT34: { | ||||
| 42889 | int iOld = pFile->iBusyTimeout; | ||||
| 42890 | int iNew = *(int*)pArg; | ||||
| 42891 | #if SQLITE_ENABLE_SETLK_TIMEOUT==1 | ||||
| 42892 | pFile->iBusyTimeout = iNew<0 ? 0x7FFFFFFF : (unsigned)iNew; | ||||
| 42893 | #elif SQLITE_ENABLE_SETLK_TIMEOUT==2 | ||||
| 42894 | pFile->iBusyTimeout = !!(*(int*)pArg); | ||||
| 42895 | #else | ||||
| 42896 | # error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2" | ||||
| 42897 | #endif | ||||
| 42898 | *(int*)pArg = iOld; | ||||
| 42899 | return SQLITE_OK0; | ||||
| 42900 | } | ||||
| 42901 | case SQLITE_FCNTL_BLOCK_ON_CONNECT44: { | ||||
| 42902 | int iNew = *(int*)pArg; | ||||
| 42903 | pFile->bBlockOnConnect = iNew; | ||||
| 42904 | return SQLITE_OK0; | ||||
| 42905 | } | ||||
| 42906 | #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ | ||||
| 42907 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 42908 | case SQLITE_FCNTL_MMAP_SIZE18: { | ||||
| 42909 | i64 newLimit = *(i64*)pArg; | ||||
| 42910 | int rc = SQLITE_OK0; | ||||
| 42911 | if( newLimit>sqlite3GlobalConfigsqlite3Config.mxMmap ){ | ||||
| 42912 | newLimit = sqlite3GlobalConfigsqlite3Config.mxMmap; | ||||
| 42913 | } | ||||
| 42914 | |||||
| 42915 | /* The value of newLimit may be eventually cast to (size_t) and passed | ||||
| 42916 | ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a | ||||
| 42917 | ** 64-bit type. */ | ||||
| 42918 | if( newLimit>0 && sizeof(size_t)<8 ){ | ||||
| 42919 | newLimit = (newLimit & 0x7FFFFFFF); | ||||
| 42920 | } | ||||
| 42921 | |||||
| 42922 | *(i64*)pArg = pFile->mmapSizeMax; | ||||
| 42923 | if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ | ||||
| 42924 | pFile->mmapSizeMax = newLimit; | ||||
| 42925 | if( pFile->mmapSize>0 ){ | ||||
| 42926 | unixUnmapfile(pFile); | ||||
| 42927 | rc = unixMapfile(pFile, -1); | ||||
| 42928 | } | ||||
| 42929 | } | ||||
| 42930 | return rc; | ||||
| 42931 | } | ||||
| 42932 | #endif | ||||
| 42933 | #ifdef SQLITE_DEBUG | ||||
| 42934 | /* The pager calls this method to signal that it has done | ||||
| 42935 | ** a rollback and that the database is therefore unchanged and | ||||
| 42936 | ** it hence it is OK for the transaction change counter to be | ||||
| 42937 | ** unchanged. | ||||
| 42938 | */ | ||||
| 42939 | case SQLITE_FCNTL_DB_UNCHANGED0xca093fa0: { | ||||
| 42940 | ((unixFile*)id)->dbUpdate = 0; | ||||
| 42941 | return SQLITE_OK0; | ||||
| 42942 | } | ||||
| 42943 | #endif | ||||
| 42944 | #if SQLITE_ENABLE_LOCKING_STYLE0 && defined(__APPLE__) | ||||
| 42945 | case SQLITE_FCNTL_SET_LOCKPROXYFILE3: | ||||
| 42946 | case SQLITE_FCNTL_GET_LOCKPROXYFILE2: { | ||||
| 42947 | return proxyFileControl(id,op,pArg); | ||||
| 42948 | } | ||||
| 42949 | #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */ | ||||
| 42950 | |||||
| 42951 | case SQLITE_FCNTL_EXTERNAL_READER40: { | ||||
| 42952 | #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) | ||||
| 42953 | return unixFcntlExternalReader((unixFile*)id, (int*)pArg); | ||||
| 42954 | #else | ||||
| 42955 | *(int*)pArg = 0; | ||||
| 42956 | return SQLITE_OK0; | ||||
| 42957 | #endif | ||||
| 42958 | } | ||||
| 42959 | } | ||||
| 42960 | return SQLITE_NOTFOUND12; | ||||
| 42961 | } | ||||
| 42962 | |||||
| 42963 | /* | ||||
| 42964 | ** If pFd->sectorSize is non-zero when this function is called, it is a | ||||
| 42965 | ** no-op. Otherwise, the values of pFd->sectorSize and | ||||
| 42966 | ** pFd->deviceCharacteristics are set according to the file-system | ||||
| 42967 | ** characteristics. | ||||
| 42968 | ** | ||||
| 42969 | ** There are two versions of this function. One for QNX and one for all | ||||
| 42970 | ** other systems. | ||||
| 42971 | */ | ||||
| 42972 | #ifndef __QNXNTO__ | ||||
| 42973 | static void setDeviceCharacteristics(unixFile *pFd){ | ||||
| 42974 | assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 )((void) (0)); | ||||
| 42975 | if( pFd->sectorSize==0 ){ | ||||
| 42976 | #if defined(__linux__1) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) | ||||
| 42977 | int res; | ||||
| 42978 | u32 f = 0; | ||||
| 42979 | |||||
| 42980 | /* Check for support for F2FS atomic batch writes. */ | ||||
| 42981 | res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES(((2U) << (((0 +8)+8)+14)) | (((0xf5)) << (0 +8)) | (((12)) << 0) | ((((sizeof(u32)))) << ((0 +8)+ 8))), &f); | ||||
| 42982 | if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE0x0004) ){ | ||||
| 42983 | pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC0x00004000; | ||||
| 42984 | } | ||||
| 42985 | #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ | ||||
| 42986 | |||||
| 42987 | /* Set the POWERSAFE_OVERWRITE flag if requested. */ | ||||
| 42988 | if( pFd->ctrlFlags & UNIXFILE_PSOW0x10 ){ | ||||
| 42989 | pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE0x00001000; | ||||
| 42990 | } | ||||
| 42991 | pFd->deviceCharacteristics |= SQLITE_IOCAP_SUBPAGE_READ0x00008000; | ||||
| 42992 | |||||
| 42993 | pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE4096; | ||||
| 42994 | } | ||||
| 42995 | } | ||||
| 42996 | #else | ||||
| 42997 | #include <sys/dcmd_blk.h> | ||||
| 42998 | #include <sys/statvfs.h> | ||||
| 42999 | static void setDeviceCharacteristics(unixFile *pFile){ | ||||
| 43000 | if( pFile->sectorSize == 0 ){ | ||||
| 43001 | struct statvfs fsInfo; | ||||
| 43002 | |||||
| 43003 | /* Set defaults for non-supported filesystems */ | ||||
| 43004 | pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE4096; | ||||
| 43005 | pFile->deviceCharacteristics = 0; | ||||
| 43006 | if( fstatvfs(pFile->h, &fsInfo) == -1 ) { | ||||
| 43007 | return; | ||||
| 43008 | } | ||||
| 43009 | |||||
| 43010 | if( !strcmp(fsInfo.f_basetype, "tmp") ) { | ||||
| 43011 | pFile->sectorSize = fsInfo.f_bsize; | ||||
| 43012 | pFile->deviceCharacteristics = | ||||
| 43013 | SQLITE_IOCAP_ATOMIC4K0x00000010 | /* All ram filesystem writes are atomic */ | ||||
| 43014 | SQLITE_IOCAP_SAFE_APPEND0x00000200 | /* growing the file does not occur until | ||||
| 43015 | ** the write succeeds */ | ||||
| 43016 | SQLITE_IOCAP_SEQUENTIAL0x00000400 | /* The ram filesystem has no write behind | ||||
| 43017 | ** so it is ordered */ | ||||
| 43018 | 0; | ||||
| 43019 | }else if( strstr(fsInfo.f_basetype, "etfs") ){ | ||||
| 43020 | pFile->sectorSize = fsInfo.f_bsize; | ||||
| 43021 | pFile->deviceCharacteristics = | ||||
| 43022 | /* etfs cluster size writes are atomic */ | ||||
| 43023 | (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC5120x00000002) | | ||||
| 43024 | SQLITE_IOCAP_SAFE_APPEND0x00000200 | /* growing the file does not occur until | ||||
| 43025 | ** the write succeeds */ | ||||
| 43026 | SQLITE_IOCAP_SEQUENTIAL0x00000400 | /* The ram filesystem has no write behind | ||||
| 43027 | ** so it is ordered */ | ||||
| 43028 | 0; | ||||
| 43029 | }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){ | ||||
| 43030 | pFile->sectorSize = fsInfo.f_bsize; | ||||
| 43031 | pFile->deviceCharacteristics = | ||||
| 43032 | SQLITE_IOCAP_ATOMIC0x00000001 | /* All filesystem writes are atomic */ | ||||
| 43033 | SQLITE_IOCAP_SAFE_APPEND0x00000200 | /* growing the file does not occur until | ||||
| 43034 | ** the write succeeds */ | ||||
| 43035 | SQLITE_IOCAP_SEQUENTIAL0x00000400 | /* The ram filesystem has no write behind | ||||
| 43036 | ** so it is ordered */ | ||||
| 43037 | 0; | ||||
| 43038 | }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){ | ||||
| 43039 | pFile->sectorSize = fsInfo.f_bsize; | ||||
| 43040 | pFile->deviceCharacteristics = | ||||
| 43041 | /* full bitset of atomics from max sector size and smaller */ | ||||
| 43042 | (((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC5120x00000002) << 1) - 2) | | ||||
| 43043 | SQLITE_IOCAP_SEQUENTIAL0x00000400 | /* The ram filesystem has no write behind | ||||
| 43044 | ** so it is ordered */ | ||||
| 43045 | 0; | ||||
| 43046 | }else if( strstr(fsInfo.f_basetype, "dos") ){ | ||||
| 43047 | pFile->sectorSize = fsInfo.f_bsize; | ||||
| 43048 | pFile->deviceCharacteristics = | ||||
| 43049 | /* full bitset of atomics from max sector size and smaller */ | ||||
| 43050 | (((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC5120x00000002) << 1) - 2) | | ||||
| 43051 | SQLITE_IOCAP_SEQUENTIAL0x00000400 | /* The ram filesystem has no write behind | ||||
| 43052 | ** so it is ordered */ | ||||
| 43053 | 0; | ||||
| 43054 | }else{ | ||||
| 43055 | pFile->deviceCharacteristics = | ||||
| 43056 | SQLITE_IOCAP_ATOMIC5120x00000002 | /* blocks are atomic */ | ||||
| 43057 | SQLITE_IOCAP_SAFE_APPEND0x00000200 | /* growing the file does not occur until | ||||
| 43058 | ** the write succeeds */ | ||||
| 43059 | 0; | ||||
| 43060 | } | ||||
| 43061 | } | ||||
| 43062 | /* Last chance verification. If the sector size isn't a multiple of 512 | ||||
| 43063 | ** then it isn't valid.*/ | ||||
| 43064 | if( pFile->sectorSize % 512 != 0 ){ | ||||
| 43065 | pFile->deviceCharacteristics = 0; | ||||
| 43066 | pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE4096; | ||||
| 43067 | } | ||||
| 43068 | } | ||||
| 43069 | #endif | ||||
| 43070 | |||||
| 43071 | /* | ||||
| 43072 | ** Return the sector size in bytes of the underlying block device for | ||||
| 43073 | ** the specified file. This is almost always 512 bytes, but may be | ||||
| 43074 | ** larger for some devices. | ||||
| 43075 | ** | ||||
| 43076 | ** SQLite code assumes this function cannot fail. It also assumes that | ||||
| 43077 | ** if two files are created in the same file-system directory (i.e. | ||||
| 43078 | ** a database and its journal file) that the sector size will be the | ||||
| 43079 | ** same for both. | ||||
| 43080 | */ | ||||
| 43081 | static int unixSectorSize(sqlite3_file *id){ | ||||
| 43082 | unixFile *pFd = (unixFile*)id; | ||||
| 43083 | setDeviceCharacteristics(pFd); | ||||
| 43084 | return pFd->sectorSize; | ||||
| 43085 | } | ||||
| 43086 | |||||
| 43087 | /* | ||||
| 43088 | ** Return the device characteristics for the file. | ||||
| 43089 | ** | ||||
| 43090 | ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default. | ||||
| 43091 | ** However, that choice is controversial since technically the underlying | ||||
| 43092 | ** file system does not always provide powersafe overwrites. (In other | ||||
| 43093 | ** words, after a power-loss event, parts of the file that were never | ||||
| 43094 | ** written might end up being altered.) However, non-PSOW behavior is very, | ||||
| 43095 | ** very rare. And asserting PSOW makes a large reduction in the amount | ||||
| 43096 | ** of required I/O for journaling, since a lot of padding is eliminated. | ||||
| 43097 | ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control | ||||
| 43098 | ** available to turn it off and URI query parameter available to turn it off. | ||||
| 43099 | */ | ||||
| 43100 | static int unixDeviceCharacteristics(sqlite3_file *id){ | ||||
| 43101 | unixFile *pFd = (unixFile*)id; | ||||
| 43102 | setDeviceCharacteristics(pFd); | ||||
| 43103 | return pFd->deviceCharacteristics; | ||||
| 43104 | } | ||||
| 43105 | |||||
| 43106 | #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 43107 | |||||
| 43108 | /* | ||||
| 43109 | ** Return the system page size. | ||||
| 43110 | ** | ||||
| 43111 | ** This function should not be called directly by other code in this file. | ||||
| 43112 | ** Instead, it should be called via macro osGetpagesize(). | ||||
| 43113 | */ | ||||
| 43114 | static int unixGetpagesize(void){ | ||||
| 43115 | #if OS_VXWORKS0 | ||||
| 43116 | return 1024; | ||||
| 43117 | #elif defined(_BSD_SOURCE) | ||||
| 43118 | return getpagesize(); | ||||
| 43119 | #else | ||||
| 43120 | return (int)sysconf(_SC_PAGESIZE_SC_PAGESIZE); | ||||
| 43121 | #endif | ||||
| 43122 | } | ||||
| 43123 | |||||
| 43124 | #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */ | ||||
| 43125 | |||||
| 43126 | #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) | ||||
| 43127 | |||||
| 43128 | /* | ||||
| 43129 | ** Object used to represent an shared memory buffer. | ||||
| 43130 | ** | ||||
| 43131 | ** When multiple threads all reference the same wal-index, each thread | ||||
| 43132 | ** has its own unixShm object, but they all point to a single instance | ||||
| 43133 | ** of this unixShmNode object. In other words, each wal-index is opened | ||||
| 43134 | ** only once per process. | ||||
| 43135 | ** | ||||
| 43136 | ** Each unixShmNode object is connected to a single unixInodeInfo object. | ||||
| 43137 | ** We could coalesce this object into unixInodeInfo, but that would mean | ||||
| 43138 | ** every open file that does not use shared memory (in other words, most | ||||
| 43139 | ** open files) would have to carry around this extra information. So | ||||
| 43140 | ** the unixInodeInfo object contains a pointer to this unixShmNode object | ||||
| 43141 | ** and the unixShmNode object is created only when needed. | ||||
| 43142 | ** | ||||
| 43143 | ** unixMutexHeld() must be true when creating or destroying | ||||
| 43144 | ** this object or while reading or writing the following fields: | ||||
| 43145 | ** | ||||
| 43146 | ** nRef | ||||
| 43147 | ** | ||||
| 43148 | ** The following fields are read-only after the object is created: | ||||
| 43149 | ** | ||||
| 43150 | ** hShm | ||||
| 43151 | ** zFilename | ||||
| 43152 | ** | ||||
| 43153 | ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and | ||||
| 43154 | ** unixMutexHeld() is true when reading or writing any other field | ||||
| 43155 | ** in this structure. | ||||
| 43156 | ** | ||||
| 43157 | ** aLock[SQLITE_SHM_NLOCK]: | ||||
| 43158 | ** This array records the various locks held by clients on each of the | ||||
| 43159 | ** SQLITE_SHM_NLOCK slots. If the aLock[] entry is set to 0, then no | ||||
| 43160 | ** locks are held by the process on this slot. If it is set to -1, then | ||||
| 43161 | ** some client holds an EXCLUSIVE lock on the locking slot. If the aLock[] | ||||
| 43162 | ** value is set to a positive value, then it is the number of shared | ||||
| 43163 | ** locks currently held on the slot. | ||||
| 43164 | ** | ||||
| 43165 | ** aMutex[SQLITE_SHM_NLOCK]: | ||||
| 43166 | ** Normally, when SQLITE_ENABLE_SETLK_TIMEOUT is not defined, mutex | ||||
| 43167 | ** pShmMutex is used to protect the aLock[] array and the right to | ||||
| 43168 | ** call fcntl() on unixShmNode.hShm to obtain or release locks. | ||||
| 43169 | ** | ||||
| 43170 | ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined though, we use an array | ||||
| 43171 | ** of mutexes - one for each locking slot. To read or write locking | ||||
| 43172 | ** slot aLock[iSlot], the caller must hold the corresponding mutex | ||||
| 43173 | ** aMutex[iSlot]. Similarly, to call fcntl() to obtain or release a | ||||
| 43174 | ** lock corresponding to slot iSlot, mutex aMutex[iSlot] must be held. | ||||
| 43175 | */ | ||||
| 43176 | struct unixShmNode { | ||||
| 43177 | unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */ | ||||
| 43178 | sqlite3_mutex *pShmMutex; /* Mutex to access this object */ | ||||
| 43179 | char *zFilename; /* Name of the mmapped file */ | ||||
| 43180 | int hShm; /* Open file descriptor */ | ||||
| 43181 | int szRegion; /* Size of shared-memory regions */ | ||||
| 43182 | u16 nRegion; /* Size of array apRegion */ | ||||
| 43183 | u8 isReadonly; /* True if read-only */ | ||||
| 43184 | u8 isUnlocked; /* True if no DMS lock held */ | ||||
| 43185 | char **apRegion; /* Array of mapped shared-memory regions */ | ||||
| 43186 | int nRef; /* Number of unixShm objects pointing to this */ | ||||
| 43187 | unixShm *pFirst; /* All unixShm objects pointing to this */ | ||||
| 43188 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43189 | sqlite3_mutex *aMutex[SQLITE_SHM_NLOCK8]; | ||||
| 43190 | #endif | ||||
| 43191 | int aLock[SQLITE_SHM_NLOCK8]; /* # shared locks on slot, -1==excl lock */ | ||||
| 43192 | #ifdef SQLITE_DEBUG | ||||
| 43193 | u8 nextShmId; /* Next available unixShm.id value */ | ||||
| 43194 | #endif | ||||
| 43195 | }; | ||||
| 43196 | |||||
| 43197 | /* | ||||
| 43198 | ** Structure used internally by this VFS to record the state of an | ||||
| 43199 | ** open shared memory connection. | ||||
| 43200 | ** | ||||
| 43201 | ** The following fields are initialized when this object is created and | ||||
| 43202 | ** are read-only thereafter: | ||||
| 43203 | ** | ||||
| 43204 | ** unixShm.pShmNode | ||||
| 43205 | ** unixShm.id | ||||
| 43206 | ** | ||||
| 43207 | ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must | ||||
| 43208 | ** be held while accessing any read/write fields. | ||||
| 43209 | */ | ||||
| 43210 | struct unixShm { | ||||
| 43211 | unixShmNode *pShmNode; /* The underlying unixShmNode object */ | ||||
| 43212 | unixShm *pNext; /* Next unixShm with the same unixShmNode */ | ||||
| 43213 | u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */ | ||||
| 43214 | u8 id; /* Id of this connection within its unixShmNode */ | ||||
| 43215 | u16 sharedMask; /* Mask of shared locks held */ | ||||
| 43216 | u16 exclMask; /* Mask of exclusive locks held */ | ||||
| 43217 | }; | ||||
| 43218 | |||||
| 43219 | /* | ||||
| 43220 | ** Constants used for locking | ||||
| 43221 | */ | ||||
| 43222 | #define UNIX_SHM_BASE((22+8)*4) ((22+SQLITE_SHM_NLOCK8)*4) /* first lock byte */ | ||||
| 43223 | #define UNIX_SHM_DMS(((22+8)*4)+8) (UNIX_SHM_BASE((22+8)*4)+SQLITE_SHM_NLOCK8) /* deadman switch */ | ||||
| 43224 | |||||
| 43225 | /* | ||||
| 43226 | ** Use F_GETLK to check whether or not there are any readers with open | ||||
| 43227 | ** wal-mode transactions in other processes on database file pFile. If | ||||
| 43228 | ** no error occurs, return SQLITE_OK and set (*piOut) to 1 if there are | ||||
| 43229 | ** such transactions, or 0 otherwise. If an error occurs, return an | ||||
| 43230 | ** SQLite error code. The final value of *piOut is undefined in this | ||||
| 43231 | ** case. | ||||
| 43232 | */ | ||||
| 43233 | static int unixFcntlExternalReader(unixFile *pFile, int *piOut){ | ||||
| 43234 | int rc = SQLITE_OK0; | ||||
| 43235 | *piOut = 0; | ||||
| 43236 | if( pFile->pShm){ | ||||
| 43237 | unixShmNode *pShmNode = pFile->pShm->pShmNode; | ||||
| 43238 | struct flock f; | ||||
| 43239 | |||||
| 43240 | memset(&f, 0, sizeof(f)); | ||||
| 43241 | f.l_type = F_WRLCK1; | ||||
| 43242 | f.l_whence = SEEK_SET0; | ||||
| 43243 | f.l_start = UNIX_SHM_BASE((22+8)*4) + 3; | ||||
| 43244 | f.l_len = SQLITE_SHM_NLOCK8 - 3; | ||||
| 43245 | |||||
| 43246 | sqlite3_mutex_enter(pShmNode->pShmMutex); | ||||
| 43247 | if( osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(pShmNode->hShm, F_GETLK5, &f)<0 ){ | ||||
| 43248 | rc = SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 43249 | }else{ | ||||
| 43250 | *piOut = (f.l_type!=F_UNLCK2); | ||||
| 43251 | } | ||||
| 43252 | sqlite3_mutex_leave(pShmNode->pShmMutex); | ||||
| 43253 | } | ||||
| 43254 | |||||
| 43255 | return rc; | ||||
| 43256 | } | ||||
| 43257 | |||||
| 43258 | |||||
| 43259 | /* | ||||
| 43260 | ** Apply posix advisory locks for all bytes from ofst through ofst+n-1. | ||||
| 43261 | ** | ||||
| 43262 | ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking | ||||
| 43263 | ** otherwise. | ||||
| 43264 | */ | ||||
| 43265 | static int unixShmSystemLock( | ||||
| 43266 | unixFile *pFile, /* Open connection to the WAL file */ | ||||
| 43267 | int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */ | ||||
| 43268 | int ofst, /* First byte of the locking range */ | ||||
| 43269 | int n /* Number of bytes to lock */ | ||||
| 43270 | ){ | ||||
| 43271 | unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */ | ||||
| 43272 | struct flock f; /* The posix advisory locking structure */ | ||||
| 43273 | int rc = SQLITE_OK0; /* Result code form fcntl() */ | ||||
| 43274 | |||||
| 43275 | pShmNode = pFile->pInode->pShmNode; | ||||
| 43276 | |||||
| 43277 | /* Assert that the parameters are within expected range and that the | ||||
| 43278 | ** correct mutex or mutexes are held. */ | ||||
| 43279 | assert( pShmNode->nRef>=0 )((void) (0)); | ||||
| 43280 | assert( (ofst==UNIX_SHM_DMS && n==1)((void) (0)) | ||||
| 43281 | || (ofst>=UNIX_SHM_BASE && ofst+n<=(UNIX_SHM_BASE+SQLITE_SHM_NLOCK))((void) (0)) | ||||
| 43282 | )((void) (0)); | ||||
| 43283 | if( ofst==UNIX_SHM_DMS(((22+8)*4)+8) ){ | ||||
| 43284 | assert( pShmNode->nRef>0 || unixMutexHeld() )((void) (0)); | ||||
| 43285 | assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) )((void) (0)); | ||||
| 43286 | }else{ | ||||
| 43287 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43288 | int ii; | ||||
| 43289 | for(ii=ofst-UNIX_SHM_BASE((22+8)*4); ii<ofst-UNIX_SHM_BASE((22+8)*4)+n; ii++){ | ||||
| 43290 | assert( sqlite3_mutex_held(pShmNode->aMutex[ii]) )((void) (0)); | ||||
| 43291 | } | ||||
| 43292 | #else | ||||
| 43293 | assert( sqlite3_mutex_held(pShmNode->pShmMutex) )((void) (0)); | ||||
| 43294 | assert( pShmNode->nRef>0 )((void) (0)); | ||||
| 43295 | #endif | ||||
| 43296 | } | ||||
| 43297 | |||||
| 43298 | /* Shared locks never span more than one byte */ | ||||
| 43299 | assert( n==1 || lockType!=F_RDLCK )((void) (0)); | ||||
| 43300 | |||||
| 43301 | /* Locks are within range */ | ||||
| 43302 | assert( n>=1 && n<=SQLITE_SHM_NLOCK )((void) (0)); | ||||
| 43303 | assert( ofst>=UNIX_SHM_BASE && ofst<=(UNIX_SHM_DMS+SQLITE_SHM_NLOCK) )((void) (0)); | ||||
| 43304 | |||||
| 43305 | if( pShmNode->hShm>=0 ){ | ||||
| 43306 | int res; | ||||
| 43307 | /* Initialize the locking parameters */ | ||||
| 43308 | f.l_type = lockType; | ||||
| 43309 | f.l_whence = SEEK_SET0; | ||||
| 43310 | f.l_start = ofst; | ||||
| 43311 | f.l_len = n; | ||||
| 43312 | res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile)((int(*)(int,int,...))aSyscall[7].pCurrent)(pShmNode->hShm ,6,&f); | ||||
| 43313 | if( res==-1 ){ | ||||
| 43314 | #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && SQLITE_ENABLE_SETLK_TIMEOUT==1 | ||||
| 43315 | rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT(5 | (3<<8)) : SQLITE_BUSY5); | ||||
| 43316 | #else | ||||
| 43317 | rc = SQLITE_BUSY5; | ||||
| 43318 | #endif | ||||
| 43319 | } | ||||
| 43320 | } | ||||
| 43321 | |||||
| 43322 | /* Do debug tracing */ | ||||
| 43323 | #ifdef SQLITE_DEBUG | ||||
| 43324 | OSTRACE(("SHM-LOCK ")); | ||||
| 43325 | if( rc==SQLITE_OK0 ){ | ||||
| 43326 | if( lockType==F_UNLCK2 ){ | ||||
| 43327 | OSTRACE(("unlock %d..%d ok\n", ofst, ofst+n-1)); | ||||
| 43328 | }else if( lockType==F_RDLCK0 ){ | ||||
| 43329 | OSTRACE(("read-lock %d..%d ok\n", ofst, ofst+n-1)); | ||||
| 43330 | }else{ | ||||
| 43331 | assert( lockType==F_WRLCK )((void) (0)); | ||||
| 43332 | OSTRACE(("write-lock %d..%d ok\n", ofst, ofst+n-1)); | ||||
| 43333 | } | ||||
| 43334 | }else{ | ||||
| 43335 | if( lockType==F_UNLCK2 ){ | ||||
| 43336 | OSTRACE(("unlock %d..%d failed\n", ofst, ofst+n-1)); | ||||
| 43337 | }else if( lockType==F_RDLCK0 ){ | ||||
| 43338 | OSTRACE(("read-lock %d..%d failed\n", ofst, ofst+n-1)); | ||||
| 43339 | }else{ | ||||
| 43340 | assert( lockType==F_WRLCK )((void) (0)); | ||||
| 43341 | OSTRACE(("write-lock %d..%d failed\n", ofst, ofst+n-1)); | ||||
| 43342 | } | ||||
| 43343 | } | ||||
| 43344 | #endif | ||||
| 43345 | |||||
| 43346 | return rc; | ||||
| 43347 | } | ||||
| 43348 | |||||
| 43349 | /* | ||||
| 43350 | ** Return the minimum number of 32KB shm regions that should be mapped at | ||||
| 43351 | ** a time, assuming that each mapping must be an integer multiple of the | ||||
| 43352 | ** current system page-size. | ||||
| 43353 | ** | ||||
| 43354 | ** Usually, this is 1. The exception seems to be systems that are configured | ||||
| 43355 | ** to use 64KB pages - in this case each mapping must cover at least two | ||||
| 43356 | ** shm regions. | ||||
| 43357 | */ | ||||
| 43358 | static int unixShmRegionPerMap(void){ | ||||
| 43359 | int shmsz = 32*1024; /* SHM region size */ | ||||
| 43360 | int pgsz = osGetpagesize((int(*)(void))aSyscall[25].pCurrent)(); /* System page size */ | ||||
| 43361 | assert( ((pgsz-1)&pgsz)==0 )((void) (0)); /* Page size must be a power of 2 */ | ||||
| 43362 | if( pgsz<shmsz ) return 1; | ||||
| 43363 | return pgsz/shmsz; | ||||
| 43364 | } | ||||
| 43365 | |||||
| 43366 | /* | ||||
| 43367 | ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0. | ||||
| 43368 | ** | ||||
| 43369 | ** This is not a VFS shared-memory method; it is a utility function called | ||||
| 43370 | ** by VFS shared-memory methods. | ||||
| 43371 | */ | ||||
| 43372 | static void unixShmPurge(unixFile *pFd){ | ||||
| 43373 | unixShmNode *p = pFd->pInode->pShmNode; | ||||
| 43374 | assert( unixMutexHeld() )((void) (0)); | ||||
| 43375 | if( p && ALWAYS(p->nRef==0)(p->nRef==0) ){ | ||||
| 43376 | int nShmPerMap = unixShmRegionPerMap(); | ||||
| 43377 | int i; | ||||
| 43378 | assert( p->pInode==pFd->pInode )((void) (0)); | ||||
| 43379 | sqlite3_mutex_free(p->pShmMutex); | ||||
| 43380 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43381 | for(i=0; i<SQLITE_SHM_NLOCK8; i++){ | ||||
| 43382 | sqlite3_mutex_free(p->aMutex[i]); | ||||
| 43383 | } | ||||
| 43384 | #endif | ||||
| 43385 | for(i=0; i<p->nRegion; i+=nShmPerMap){ | ||||
| 43386 | if( p->hShm>=0 ){ | ||||
| 43387 | osMunmap((int(*)(void*,size_t))aSyscall[23].pCurrent)(p->apRegion[i], p->szRegion); | ||||
| 43388 | }else{ | ||||
| 43389 | sqlite3_free(p->apRegion[i]); | ||||
| 43390 | } | ||||
| 43391 | } | ||||
| 43392 | sqlite3_free(p->apRegion); | ||||
| 43393 | if( p->hShm>=0 ){ | ||||
| 43394 | robust_close(pFd, p->hShm, __LINE__43394); | ||||
| 43395 | p->hShm = -1; | ||||
| 43396 | } | ||||
| 43397 | p->pInode->pShmNode = 0; | ||||
| 43398 | sqlite3_free(p); | ||||
| 43399 | } | ||||
| 43400 | } | ||||
| 43401 | |||||
| 43402 | /* | ||||
| 43403 | ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to | ||||
| 43404 | ** take it now. Return SQLITE_OK if successful, or an SQLite error | ||||
| 43405 | ** code otherwise. | ||||
| 43406 | ** | ||||
| 43407 | ** If the DMS cannot be locked because this is a readonly_shm=1 | ||||
| 43408 | ** connection and no other process already holds a lock, return | ||||
| 43409 | ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1. | ||||
| 43410 | */ | ||||
| 43411 | static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){ | ||||
| 43412 | struct flock lock; | ||||
| 43413 | int rc = SQLITE_OK0; | ||||
| 43414 | |||||
| 43415 | /* Use F_GETLK to determine the locks other processes are holding | ||||
| 43416 | ** on the DMS byte. If it indicates that another process is holding | ||||
| 43417 | ** a SHARED lock, then this process may also take a SHARED lock | ||||
| 43418 | ** and proceed with opening the *-shm file. | ||||
| 43419 | ** | ||||
| 43420 | ** Or, if no other process is holding any lock, then this process | ||||
| 43421 | ** is the first to open it. In this case take an EXCLUSIVE lock on the | ||||
| 43422 | ** DMS byte and truncate the *-shm file to zero bytes in size. Then | ||||
| 43423 | ** downgrade to a SHARED lock on the DMS byte. | ||||
| 43424 | ** | ||||
| 43425 | ** If another process is holding an EXCLUSIVE lock on the DMS byte, | ||||
| 43426 | ** return SQLITE_BUSY to the caller (it will try again). An earlier | ||||
| 43427 | ** version of this code attempted the SHARED lock at this point. But | ||||
| 43428 | ** this introduced a subtle race condition: if the process holding | ||||
| 43429 | ** EXCLUSIVE failed just before truncating the *-shm file, then this | ||||
| 43430 | ** process might open and use the *-shm file without truncating it. | ||||
| 43431 | ** And if the *-shm file has been corrupted by a power failure or | ||||
| 43432 | ** system crash, the database itself may also become corrupt. */ | ||||
| 43433 | lock.l_whence = SEEK_SET0; | ||||
| 43434 | lock.l_start = UNIX_SHM_DMS(((22+8)*4)+8); | ||||
| 43435 | lock.l_len = 1; | ||||
| 43436 | lock.l_type = F_WRLCK1; | ||||
| 43437 | if( osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(pShmNode->hShm, F_GETLK5, &lock)!=0 ) { | ||||
| 43438 | rc = SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 43439 | }else if( lock.l_type==F_UNLCK2 ){ | ||||
| 43440 | if( pShmNode->isReadonly ){ | ||||
| 43441 | pShmNode->isUnlocked = 1; | ||||
| 43442 | rc = SQLITE_READONLY_CANTINIT(8 | (5<<8)); | ||||
| 43443 | }else{ | ||||
| 43444 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43445 | /* Do not use a blocking lock here. If the lock cannot be obtained | ||||
| 43446 | ** immediately, it means some other connection is truncating the | ||||
| 43447 | ** *-shm file. And after it has done so, it will not release its | ||||
| 43448 | ** lock, but only downgrade it to a shared lock. So no point in | ||||
| 43449 | ** blocking here. The call below to obtain the shared DMS lock may | ||||
| 43450 | ** use a blocking lock. */ | ||||
| 43451 | int iSaveTimeout = pDbFd->iBusyTimeout; | ||||
| 43452 | pDbFd->iBusyTimeout = 0; | ||||
| 43453 | #endif | ||||
| 43454 | rc = unixShmSystemLock(pDbFd, F_WRLCK1, UNIX_SHM_DMS(((22+8)*4)+8), 1); | ||||
| 43455 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43456 | pDbFd->iBusyTimeout = iSaveTimeout; | ||||
| 43457 | #endif | ||||
| 43458 | /* The first connection to attach must truncate the -shm file. We | ||||
| 43459 | ** truncate to 3 bytes (an arbitrary small number, less than the | ||||
| 43460 | ** -shm header size) rather than 0 as a system debugging aid, to | ||||
| 43461 | ** help detect if a -shm file truncation is legitimate or is the work | ||||
| 43462 | ** or a rogue process. */ | ||||
| 43463 | if( rc==SQLITE_OK0 && robust_ftruncate(pShmNode->hShm, 3) ){ | ||||
| 43464 | rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename)unixLogErrorAtLine((10 | (18<<8)),"ftruncate",pShmNode-> zFilename,43464); | ||||
| 43465 | } | ||||
| 43466 | } | ||||
| 43467 | }else if( lock.l_type==F_WRLCK1 ){ | ||||
| 43468 | rc = SQLITE_BUSY5; | ||||
| 43469 | } | ||||
| 43470 | |||||
| 43471 | if( rc==SQLITE_OK0 ){ | ||||
| 43472 | assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK )((void) (0)); | ||||
| 43473 | rc = unixShmSystemLock(pDbFd, F_RDLCK0, UNIX_SHM_DMS(((22+8)*4)+8), 1); | ||||
| 43474 | } | ||||
| 43475 | return rc; | ||||
| 43476 | } | ||||
| 43477 | |||||
| 43478 | /* | ||||
| 43479 | ** Open a shared-memory area associated with open database file pDbFd. | ||||
| 43480 | ** This particular implementation uses mmapped files. | ||||
| 43481 | ** | ||||
| 43482 | ** The file used to implement shared-memory is in the same directory | ||||
| 43483 | ** as the open database file and has the same name as the open database | ||||
| 43484 | ** file with the "-shm" suffix added. For example, if the database file | ||||
| 43485 | ** is "/home/user1/config.db" then the file that is created and mmapped | ||||
| 43486 | ** for shared memory will be called "/home/user1/config.db-shm". | ||||
| 43487 | ** | ||||
| 43488 | ** Another approach to is to use files in /dev/shm or /dev/tmp or an | ||||
| 43489 | ** some other tmpfs mount. But if a file in a different directory | ||||
| 43490 | ** from the database file is used, then differing access permissions | ||||
| 43491 | ** or a chroot() might cause two different processes on the same | ||||
| 43492 | ** database to end up using different files for shared memory - | ||||
| 43493 | ** meaning that their memory would not really be shared - resulting | ||||
| 43494 | ** in database corruption. Nevertheless, this tmpfs file usage | ||||
| 43495 | ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm" | ||||
| 43496 | ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time | ||||
| 43497 | ** option results in an incompatible build of SQLite; builds of SQLite | ||||
| 43498 | ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the | ||||
| 43499 | ** same database file at the same time, database corruption will likely | ||||
| 43500 | ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered | ||||
| 43501 | ** "unsupported" and may go away in a future SQLite release. | ||||
| 43502 | ** | ||||
| 43503 | ** When opening a new shared-memory file, if no other instances of that | ||||
| 43504 | ** file are currently open, in this process or in other processes, then | ||||
| 43505 | ** the file must be truncated to zero length or have its header cleared. | ||||
| 43506 | ** | ||||
| 43507 | ** If the original database file (pDbFd) is using the "unix-excl" VFS | ||||
| 43508 | ** that means that an exclusive lock is held on the database file and | ||||
| 43509 | ** that no other processes are able to read or write the database. In | ||||
| 43510 | ** that case, we do not really need shared memory. No shared memory | ||||
| 43511 | ** file is created. The shared memory will be simulated with heap memory. | ||||
| 43512 | */ | ||||
| 43513 | static int unixOpenSharedMemory(unixFile *pDbFd){ | ||||
| 43514 | struct unixShm *p = 0; /* The connection to be opened */ | ||||
| 43515 | struct unixShmNode *pShmNode; /* The underlying mmapped file */ | ||||
| 43516 | int rc = SQLITE_OK0; /* Result code */ | ||||
| 43517 | unixInodeInfo *pInode; /* The inode of fd */ | ||||
| 43518 | char *zShm; /* Name of the file used for SHM */ | ||||
| 43519 | int nShmFilename; /* Size of the SHM filename in bytes */ | ||||
| 43520 | |||||
| 43521 | /* Allocate space for the new unixShm object. */ | ||||
| 43522 | p = sqlite3_malloc64( sizeof(*p) ); | ||||
| 43523 | if( p==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 43524 | memset(p, 0, sizeof(*p)); | ||||
| 43525 | assert( pDbFd->pShm==0 )((void) (0)); | ||||
| 43526 | |||||
| 43527 | /* Check to see if a unixShmNode object already exists. Reuse an existing | ||||
| 43528 | ** one if present. Create a new one if necessary. | ||||
| 43529 | */ | ||||
| 43530 | assert( unixFileMutexNotheld(pDbFd) )((void) (0)); | ||||
| 43531 | unixEnterMutex(); | ||||
| 43532 | pInode = pDbFd->pInode; | ||||
| 43533 | pShmNode = pInode->pShmNode; | ||||
| 43534 | if( pShmNode==0 ){ | ||||
| 43535 | struct stat sStat; /* fstat() info for database file */ | ||||
| 43536 | #ifndef SQLITE_SHM_DIRECTORY | ||||
| 43537 | const char *zBasePath = pDbFd->zPath; | ||||
| 43538 | #endif | ||||
| 43539 | |||||
| 43540 | /* Call fstat() to figure out the permissions on the database file. If | ||||
| 43541 | ** a new *-shm file is created, an attempt will be made to create it | ||||
| 43542 | ** with the same permissions. | ||||
| 43543 | */ | ||||
| 43544 | if( osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(pDbFd->h, &sStat) ){ | ||||
| 43545 | rc = SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 43546 | goto shm_open_err; | ||||
| 43547 | } | ||||
| 43548 | |||||
| 43549 | #ifdef SQLITE_SHM_DIRECTORY | ||||
| 43550 | nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31; | ||||
| 43551 | #else | ||||
| 43552 | nShmFilename = 6 + (int)strlen(zBasePath); | ||||
| 43553 | #endif | ||||
| 43554 | pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename ); | ||||
| 43555 | if( pShmNode==0 ){ | ||||
| 43556 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 43557 | goto shm_open_err; | ||||
| 43558 | } | ||||
| 43559 | memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename); | ||||
| 43560 | zShm = pShmNode->zFilename = (char*)&pShmNode[1]; | ||||
| 43561 | #ifdef SQLITE_SHM_DIRECTORY | ||||
| 43562 | sqlite3_snprintf(nShmFilename, zShm, | ||||
| 43563 | SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", | ||||
| 43564 | (u32)sStat.st_ino, (u32)sStat.st_dev); | ||||
| 43565 | #else | ||||
| 43566 | sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath); | ||||
| 43567 | sqlite3FileSuffix3(pDbFd->zPath, zShm); | ||||
| 43568 | #endif | ||||
| 43569 | pShmNode->hShm = -1; | ||||
| 43570 | pDbFd->pInode->pShmNode = pShmNode; | ||||
| 43571 | pShmNode->pInode = pDbFd->pInode; | ||||
| 43572 | if( sqlite3GlobalConfigsqlite3Config.bCoreMutex ){ | ||||
| 43573 | pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST0); | ||||
| 43574 | if( pShmNode->pShmMutex==0 ){ | ||||
| 43575 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 43576 | goto shm_open_err; | ||||
| 43577 | } | ||||
| 43578 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43579 | { | ||||
| 43580 | int ii; | ||||
| 43581 | for(ii=0; ii<SQLITE_SHM_NLOCK8; ii++){ | ||||
| 43582 | pShmNode->aMutex[ii] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST0); | ||||
| 43583 | if( pShmNode->aMutex[ii]==0 ){ | ||||
| 43584 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 43585 | goto shm_open_err; | ||||
| 43586 | } | ||||
| 43587 | } | ||||
| 43588 | } | ||||
| 43589 | #endif | ||||
| 43590 | } | ||||
| 43591 | |||||
| 43592 | if( pInode->bProcessLock==0 ){ | ||||
| 43593 | if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ | ||||
| 43594 | pShmNode->hShm = robust_open(zShm, O_RDWR02|O_CREAT0100|O_NOFOLLOW0400000, | ||||
| 43595 | (sStat.st_mode&0777)); | ||||
| 43596 | } | ||||
| 43597 | if( pShmNode->hShm<0 ){ | ||||
| 43598 | pShmNode->hShm = robust_open(zShm, O_RDONLY00|O_NOFOLLOW0400000, | ||||
| 43599 | (sStat.st_mode&0777)); | ||||
| 43600 | if( pShmNode->hShm<0 ){ | ||||
| 43601 | rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm)unixLogErrorAtLine(sqlite3CantopenError(43601),"open",zShm,43601 ); | ||||
| 43602 | goto shm_open_err; | ||||
| 43603 | } | ||||
| 43604 | pShmNode->isReadonly = 1; | ||||
| 43605 | } | ||||
| 43606 | |||||
| 43607 | /* If this process is running as root, make sure that the SHM file | ||||
| 43608 | ** is owned by the same user that owns the original database. Otherwise, | ||||
| 43609 | ** the original owner will not be able to connect. | ||||
| 43610 | */ | ||||
| 43611 | robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid); | ||||
| 43612 | |||||
| 43613 | rc = unixLockSharedMemory(pDbFd, pShmNode); | ||||
| 43614 | if( rc!=SQLITE_OK0 && rc!=SQLITE_READONLY_CANTINIT(8 | (5<<8)) ) goto shm_open_err; | ||||
| 43615 | } | ||||
| 43616 | } | ||||
| 43617 | |||||
| 43618 | /* Make the new connection a child of the unixShmNode */ | ||||
| 43619 | p->pShmNode = pShmNode; | ||||
| 43620 | #ifdef SQLITE_DEBUG | ||||
| 43621 | p->id = pShmNode->nextShmId++; | ||||
| 43622 | #endif | ||||
| 43623 | pShmNode->nRef++; | ||||
| 43624 | pDbFd->pShm = p; | ||||
| 43625 | unixLeaveMutex(); | ||||
| 43626 | |||||
| 43627 | /* The reference count on pShmNode has already been incremented under | ||||
| 43628 | ** the cover of the unixEnterMutex() mutex and the pointer from the | ||||
| 43629 | ** new (struct unixShm) object to the pShmNode has been set. All that is | ||||
| 43630 | ** left to do is to link the new object into the linked list starting | ||||
| 43631 | ** at pShmNode->pFirst. This must be done while holding the | ||||
| 43632 | ** pShmNode->pShmMutex. | ||||
| 43633 | */ | ||||
| 43634 | sqlite3_mutex_enter(pShmNode->pShmMutex); | ||||
| 43635 | p->pNext = pShmNode->pFirst; | ||||
| 43636 | pShmNode->pFirst = p; | ||||
| 43637 | sqlite3_mutex_leave(pShmNode->pShmMutex); | ||||
| 43638 | return rc; | ||||
| 43639 | |||||
| 43640 | /* Jump here on any error */ | ||||
| 43641 | shm_open_err: | ||||
| 43642 | unixShmPurge(pDbFd); /* This call frees pShmNode if required */ | ||||
| 43643 | sqlite3_free(p); | ||||
| 43644 | unixLeaveMutex(); | ||||
| 43645 | return rc; | ||||
| 43646 | } | ||||
| 43647 | |||||
| 43648 | /* | ||||
| 43649 | ** This function is called to obtain a pointer to region iRegion of the | ||||
| 43650 | ** shared-memory associated with the database file fd. Shared-memory regions | ||||
| 43651 | ** are numbered starting from zero. Each shared-memory region is szRegion | ||||
| 43652 | ** bytes in size. | ||||
| 43653 | ** | ||||
| 43654 | ** If an error occurs, an error code is returned and *pp is set to NULL. | ||||
| 43655 | ** | ||||
| 43656 | ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory | ||||
| 43657 | ** region has not been allocated (by any client, including one running in a | ||||
| 43658 | ** separate process), then *pp is set to NULL and SQLITE_OK returned. If | ||||
| 43659 | ** bExtend is non-zero and the requested shared-memory region has not yet | ||||
| 43660 | ** been allocated, it is allocated by this function. | ||||
| 43661 | ** | ||||
| 43662 | ** If the shared-memory region has already been allocated or is allocated by | ||||
| 43663 | ** this call as described above, then it is mapped into this processes | ||||
| 43664 | ** address space (if it is not already), *pp is set to point to the mapped | ||||
| 43665 | ** memory and SQLITE_OK returned. | ||||
| 43666 | */ | ||||
| 43667 | static int unixShmMap( | ||||
| 43668 | sqlite3_file *fd, /* Handle open on database file */ | ||||
| 43669 | int iRegion, /* Region to retrieve */ | ||||
| 43670 | int szRegion, /* Size of regions */ | ||||
| 43671 | int bExtend, /* True to extend file if necessary */ | ||||
| 43672 | void volatile **pp /* OUT: Mapped memory */ | ||||
| 43673 | ){ | ||||
| 43674 | unixFile *pDbFd = (unixFile*)fd; | ||||
| 43675 | unixShm *p; | ||||
| 43676 | unixShmNode *pShmNode; | ||||
| 43677 | int rc = SQLITE_OK0; | ||||
| 43678 | int nShmPerMap = unixShmRegionPerMap(); | ||||
| 43679 | int nReqRegion; | ||||
| 43680 | |||||
| 43681 | /* If the shared-memory file has not yet been opened, open it now. */ | ||||
| 43682 | if( pDbFd->pShm==0 ){ | ||||
| 43683 | rc = unixOpenSharedMemory(pDbFd); | ||||
| 43684 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 43685 | } | ||||
| 43686 | |||||
| 43687 | p = pDbFd->pShm; | ||||
| 43688 | pShmNode = p->pShmNode; | ||||
| 43689 | sqlite3_mutex_enter(pShmNode->pShmMutex); | ||||
| 43690 | if( pShmNode->isUnlocked ){ | ||||
| 43691 | rc = unixLockSharedMemory(pDbFd, pShmNode); | ||||
| 43692 | if( rc!=SQLITE_OK0 ) goto shmpage_out; | ||||
| 43693 | pShmNode->isUnlocked = 0; | ||||
| 43694 | } | ||||
| 43695 | assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 )((void) (0)); | ||||
| 43696 | assert( pShmNode->pInode==pDbFd->pInode )((void) (0)); | ||||
| 43697 | assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 )((void) (0)); | ||||
| 43698 | assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 )((void) (0)); | ||||
| 43699 | |||||
| 43700 | /* Minimum number of regions required to be mapped. */ | ||||
| 43701 | nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; | ||||
| 43702 | |||||
| 43703 | if( pShmNode->nRegion<nReqRegion ){ | ||||
| 43704 | char **apNew; /* New apRegion[] array */ | ||||
| 43705 | int nByte = nReqRegion*szRegion; /* Minimum required file size */ | ||||
| 43706 | struct stat sStat; /* Used by fstat() */ | ||||
| 43707 | |||||
| 43708 | pShmNode->szRegion = szRegion; | ||||
| 43709 | |||||
| 43710 | if( pShmNode->hShm>=0 ){ | ||||
| 43711 | /* The requested region is not mapped into this processes address space. | ||||
| 43712 | ** Check to see if it has been allocated (i.e. if the wal-index file is | ||||
| 43713 | ** large enough to contain the requested region). | ||||
| 43714 | */ | ||||
| 43715 | if( osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(pShmNode->hShm, &sStat) ){ | ||||
| 43716 | rc = SQLITE_IOERR_SHMSIZE(10 | (19<<8)); | ||||
| 43717 | goto shmpage_out; | ||||
| 43718 | } | ||||
| 43719 | |||||
| 43720 | if( sStat.st_size<nByte ){ | ||||
| 43721 | /* The requested memory region does not exist. If bExtend is set to | ||||
| 43722 | ** false, exit early. *pp will be set to NULL and SQLITE_OK returned. | ||||
| 43723 | */ | ||||
| 43724 | if( !bExtend ){ | ||||
| 43725 | goto shmpage_out; | ||||
| 43726 | } | ||||
| 43727 | |||||
| 43728 | /* Alternatively, if bExtend is true, extend the file. Do this by | ||||
| 43729 | ** writing a single byte to the end of each (OS) page being | ||||
| 43730 | ** allocated or extended. Technically, we need only write to the | ||||
| 43731 | ** last page in order to extend the file. But writing to all new | ||||
| 43732 | ** pages forces the OS to allocate them immediately, which reduces | ||||
| 43733 | ** the chances of SIGBUS while accessing the mapped region later on. | ||||
| 43734 | */ | ||||
| 43735 | else{ | ||||
| 43736 | static const int pgsz = 4096; | ||||
| 43737 | int iPg; | ||||
| 43738 | |||||
| 43739 | /* Write to the last byte of each newly allocated or extended page */ | ||||
| 43740 | assert( (nByte % pgsz)==0 )((void) (0)); | ||||
| 43741 | for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){ | ||||
| 43742 | int x = 0; | ||||
| 43743 | if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){ | ||||
| 43744 | const char *zFile = pShmNode->zFilename; | ||||
| 43745 | rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile)unixLogErrorAtLine((10 | (19<<8)),"write",zFile,43745); | ||||
| 43746 | goto shmpage_out; | ||||
| 43747 | } | ||||
| 43748 | } | ||||
| 43749 | } | ||||
| 43750 | } | ||||
| 43751 | } | ||||
| 43752 | |||||
| 43753 | /* Map the requested memory region into this processes address space. */ | ||||
| 43754 | apNew = (char **)sqlite3_realloc( | ||||
| 43755 | pShmNode->apRegion, nReqRegion*sizeof(char *) | ||||
| 43756 | ); | ||||
| 43757 | if( !apNew ){ | ||||
| 43758 | rc = SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 43759 | goto shmpage_out; | ||||
| 43760 | } | ||||
| 43761 | pShmNode->apRegion = apNew; | ||||
| 43762 | while( pShmNode->nRegion<nReqRegion ){ | ||||
| 43763 | int nMap = szRegion*nShmPerMap; | ||||
| 43764 | int i; | ||||
| 43765 | void *pMem; | ||||
| 43766 | if( pShmNode->hShm>=0 ){ | ||||
| 43767 | pMem = osMmap((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent )(0, nMap, | ||||
| 43768 | pShmNode->isReadonly ? PROT_READ0x1 : PROT_READ0x1|PROT_WRITE0x2, | ||||
| 43769 | MAP_SHARED0x01, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion | ||||
| 43770 | ); | ||||
| 43771 | if( pMem==MAP_FAILED((void *) -1) ){ | ||||
| 43772 | rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename)unixLogErrorAtLine((10 | (21<<8)),"mmap",pShmNode->zFilename ,43772); | ||||
| 43773 | goto shmpage_out; | ||||
| 43774 | } | ||||
| 43775 | }else{ | ||||
| 43776 | pMem = sqlite3_malloc64(nMap); | ||||
| 43777 | if( pMem==0 ){ | ||||
| 43778 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 43779 | goto shmpage_out; | ||||
| 43780 | } | ||||
| 43781 | memset(pMem, 0, nMap); | ||||
| 43782 | } | ||||
| 43783 | |||||
| 43784 | for(i=0; i<nShmPerMap; i++){ | ||||
| 43785 | pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i]; | ||||
| 43786 | } | ||||
| 43787 | pShmNode->nRegion += nShmPerMap; | ||||
| 43788 | } | ||||
| 43789 | } | ||||
| 43790 | |||||
| 43791 | shmpage_out: | ||||
| 43792 | if( pShmNode->nRegion>iRegion ){ | ||||
| 43793 | *pp = pShmNode->apRegion[iRegion]; | ||||
| 43794 | }else{ | ||||
| 43795 | *pp = 0; | ||||
| 43796 | } | ||||
| 43797 | if( pShmNode->isReadonly && rc==SQLITE_OK0 ) rc = SQLITE_READONLY8; | ||||
| 43798 | sqlite3_mutex_leave(pShmNode->pShmMutex); | ||||
| 43799 | return rc; | ||||
| 43800 | } | ||||
| 43801 | |||||
| 43802 | /* | ||||
| 43803 | ** Check that the pShmNode->aLock[] array comports with the locking bitmasks | ||||
| 43804 | ** held by each client. Return true if it does, or false otherwise. This | ||||
| 43805 | ** is to be used in an assert(). e.g. | ||||
| 43806 | ** | ||||
| 43807 | ** assert( assertLockingArrayOk(pShmNode) ); | ||||
| 43808 | */ | ||||
| 43809 | #ifdef SQLITE_DEBUG | ||||
| 43810 | static int assertLockingArrayOk(unixShmNode *pShmNode){ | ||||
| 43811 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43812 | return 1; | ||||
| 43813 | #else | ||||
| 43814 | unixShm *pX; | ||||
| 43815 | int aLock[SQLITE_SHM_NLOCK8]; | ||||
| 43816 | |||||
| 43817 | memset(aLock, 0, sizeof(aLock)); | ||||
| 43818 | for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ | ||||
| 43819 | int i; | ||||
| 43820 | for(i=0; i<SQLITE_SHM_NLOCK8; i++){ | ||||
| 43821 | if( pX->exclMask & (1<<i) ){ | ||||
| 43822 | assert( aLock[i]==0 )((void) (0)); | ||||
| 43823 | aLock[i] = -1; | ||||
| 43824 | }else if( pX->sharedMask & (1<<i) ){ | ||||
| 43825 | assert( aLock[i]>=0 )((void) (0)); | ||||
| 43826 | aLock[i]++; | ||||
| 43827 | } | ||||
| 43828 | } | ||||
| 43829 | } | ||||
| 43830 | |||||
| 43831 | assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) )((void) (0)); | ||||
| 43832 | return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0); | ||||
| 43833 | #endif | ||||
| 43834 | } | ||||
| 43835 | #endif | ||||
| 43836 | |||||
| 43837 | /* | ||||
| 43838 | ** Change the lock state for a shared-memory segment. | ||||
| 43839 | ** | ||||
| 43840 | ** Note that the relationship between SHARED and EXCLUSIVE locks is a little | ||||
| 43841 | ** different here than in posix. In xShmLock(), one can go from unlocked | ||||
| 43842 | ** to shared and back or from unlocked to exclusive and back. But one may | ||||
| 43843 | ** not go from shared to exclusive or from exclusive to shared. | ||||
| 43844 | */ | ||||
| 43845 | static int unixShmLock( | ||||
| 43846 | sqlite3_file *fd, /* Database file holding the shared memory */ | ||||
| 43847 | int ofst, /* First lock to acquire or release */ | ||||
| 43848 | int n, /* Number of locks to acquire or release */ | ||||
| 43849 | int flags /* What to do with the lock */ | ||||
| 43850 | ){ | ||||
| 43851 | unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */ | ||||
| 43852 | unixShm *p; /* The shared memory being locked */ | ||||
| 43853 | unixShmNode *pShmNode; /* The underlying file iNode */ | ||||
| 43854 | int rc = SQLITE_OK0; /* Result code */ | ||||
| 43855 | u16 mask = (1<<(ofst+n)) - (1<<ofst); /* Mask of locks to take or release */ | ||||
| 43856 | int *aLock; | ||||
| 43857 | |||||
| 43858 | p = pDbFd->pShm; | ||||
| 43859 | if( p==0 ) return SQLITE_IOERR_SHMLOCK(10 | (20<<8)); | ||||
| 43860 | pShmNode = p->pShmNode; | ||||
| 43861 | if( NEVER(pShmNode==0)(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK(10 | (20<<8)); | ||||
| 43862 | aLock = pShmNode->aLock; | ||||
| 43863 | |||||
| 43864 | assert( pShmNode==pDbFd->pInode->pShmNode )((void) (0)); | ||||
| 43865 | assert( pShmNode->pInode==pDbFd->pInode )((void) (0)); | ||||
| 43866 | assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK )((void) (0)); | ||||
| 43867 | assert( n>=1 )((void) (0)); | ||||
| 43868 | assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)((void) (0)) | ||||
| 43869 | || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)((void) (0)) | ||||
| 43870 | || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)((void) (0)) | ||||
| 43871 | || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) )((void) (0)); | ||||
| 43872 | assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 )((void) (0)); | ||||
| 43873 | assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 )((void) (0)); | ||||
| 43874 | assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 )((void) (0)); | ||||
| 43875 | |||||
| 43876 | /* Check that, if this to be a blocking lock, no locks that occur later | ||||
| 43877 | ** in the following list than the lock being obtained are already held: | ||||
| 43878 | ** | ||||
| 43879 | ** 1. Recovery lock (ofst==2). | ||||
| 43880 | ** 2. Checkpointer lock (ofst==1). | ||||
| 43881 | ** 3. Write lock (ofst==0). | ||||
| 43882 | ** 4. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK). | ||||
| 43883 | ** | ||||
| 43884 | ** In other words, if this is a blocking lock, none of the locks that | ||||
| 43885 | ** occur later in the above list than the lock being obtained may be | ||||
| 43886 | ** held. | ||||
| 43887 | */ | ||||
| 43888 | #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG) | ||||
| 43889 | { | ||||
| 43890 | u16 lockMask = (p->exclMask|p->sharedMask); | ||||
| 43891 | assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (((void) (0)) | ||||
| 43892 | (ofst!=2 || lockMask==0)((void) (0)) | ||||
| 43893 | && (ofst!=1 || lockMask==0 || lockMask==2)((void) (0)) | ||||
| 43894 | && (ofst!=0 || lockMask<3)((void) (0)) | ||||
| 43895 | && (ofst<3 || lockMask<(1<<ofst))((void) (0)) | ||||
| 43896 | ))((void) (0)); | ||||
| 43897 | } | ||||
| 43898 | #endif | ||||
| 43899 | |||||
| 43900 | /* Check if there is any work to do. There are three cases: | ||||
| 43901 | ** | ||||
| 43902 | ** a) An unlock operation where there are locks to unlock, | ||||
| 43903 | ** b) An shared lock where the requested lock is not already held | ||||
| 43904 | ** c) An exclusive lock where the requested lock is not already held | ||||
| 43905 | ** | ||||
| 43906 | ** The SQLite core never requests an exclusive lock that it already holds. | ||||
| 43907 | ** This is assert()ed below. | ||||
| 43908 | */ | ||||
| 43909 | assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)((void) (0)) | ||||
| 43910 | || 0==(p->exclMask & mask)((void) (0)) | ||||
| 43911 | )((void) (0)); | ||||
| 43912 | if( ((flags & SQLITE_SHM_UNLOCK1) && ((p->exclMask|p->sharedMask) & mask)) | ||||
| 43913 | || (flags==(SQLITE_SHM_SHARED4|SQLITE_SHM_LOCK2) && 0==(p->sharedMask & mask)) | ||||
| 43914 | || (flags==(SQLITE_SHM_EXCLUSIVE8|SQLITE_SHM_LOCK2)) | ||||
| 43915 | ){ | ||||
| 43916 | |||||
| 43917 | /* Take the required mutexes. In SETLK_TIMEOUT mode (blocking locks), if | ||||
| 43918 | ** this is an attempt on an exclusive lock use sqlite3_mutex_try(). If any | ||||
| 43919 | ** other thread is holding this mutex, then it is either holding or about | ||||
| 43920 | ** to hold a lock exclusive to the one being requested, and we may | ||||
| 43921 | ** therefore return SQLITE_BUSY to the caller. | ||||
| 43922 | ** | ||||
| 43923 | ** Doing this prevents some deadlock scenarios. For example, thread 1 may | ||||
| 43924 | ** be a checkpointer blocked waiting on the WRITER lock. And thread 2 | ||||
| 43925 | ** may be a normal SQL client upgrading to a write transaction. In this | ||||
| 43926 | ** case thread 2 does a non-blocking request for the WRITER lock. But - | ||||
| 43927 | ** if it were to use sqlite3_mutex_enter() then it would effectively | ||||
| 43928 | ** become a (doomed) blocking request, as thread 2 would block until thread | ||||
| 43929 | ** 1 obtained WRITER and released the mutex. Since thread 2 already holds | ||||
| 43930 | ** a lock on a read-locking slot at this point, this breaks the | ||||
| 43931 | ** anti-deadlock rules (see above). */ | ||||
| 43932 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 43933 | int iMutex; | ||||
| 43934 | for(iMutex=ofst; iMutex<ofst+n; iMutex++){ | ||||
| 43935 | if( flags==(SQLITE_SHM_LOCK2|SQLITE_SHM_EXCLUSIVE8) ){ | ||||
| 43936 | rc = sqlite3_mutex_try(pShmNode->aMutex[iMutex]); | ||||
| 43937 | if( rc!=SQLITE_OK0 ) goto leave_shmnode_mutexes; | ||||
| 43938 | }else{ | ||||
| 43939 | sqlite3_mutex_enter(pShmNode->aMutex[iMutex]); | ||||
| 43940 | } | ||||
| 43941 | } | ||||
| 43942 | #else | ||||
| 43943 | sqlite3_mutex_enter(pShmNode->pShmMutex); | ||||
| 43944 | #endif | ||||
| 43945 | |||||
| 43946 | if( ALWAYS(rc==SQLITE_OK)(rc==0) ){ | ||||
| 43947 | if( flags & SQLITE_SHM_UNLOCK1 ){ | ||||
| 43948 | /* Case (a) - unlock. */ | ||||
| 43949 | int bUnlock = 1; | ||||
| 43950 | assert( (p->exclMask & p->sharedMask)==0 )((void) (0)); | ||||
| 43951 | assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask )((void) (0)); | ||||
| 43952 | assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask )((void) (0)); | ||||
| 43953 | |||||
| 43954 | /* If this is a SHARED lock being unlocked, it is possible that other | ||||
| 43955 | ** clients within this process are holding the same SHARED lock. In | ||||
| 43956 | ** this case, set bUnlock to 0 so that the posix lock is not removed | ||||
| 43957 | ** from the file-descriptor below. */ | ||||
| 43958 | if( flags & SQLITE_SHM_SHARED4 ){ | ||||
| 43959 | assert( n==1 )((void) (0)); | ||||
| 43960 | assert( aLock[ofst]>=1 )((void) (0)); | ||||
| 43961 | if( aLock[ofst]>1 ){ | ||||
| 43962 | bUnlock = 0; | ||||
| 43963 | aLock[ofst]--; | ||||
| 43964 | p->sharedMask &= ~mask; | ||||
| 43965 | } | ||||
| 43966 | } | ||||
| 43967 | |||||
| 43968 | if( bUnlock ){ | ||||
| 43969 | rc = unixShmSystemLock(pDbFd, F_UNLCK2, ofst+UNIX_SHM_BASE((22+8)*4), n); | ||||
| 43970 | if( rc==SQLITE_OK0 ){ | ||||
| 43971 | memset(&aLock[ofst], 0, sizeof(int)*n); | ||||
| 43972 | p->sharedMask &= ~mask; | ||||
| 43973 | p->exclMask &= ~mask; | ||||
| 43974 | } | ||||
| 43975 | } | ||||
| 43976 | }else if( flags & SQLITE_SHM_SHARED4 ){ | ||||
| 43977 | /* Case (b) - a shared lock. */ | ||||
| 43978 | |||||
| 43979 | if( aLock[ofst]<0 ){ | ||||
| 43980 | /* An exclusive lock is held by some other connection. BUSY. */ | ||||
| 43981 | rc = SQLITE_BUSY5; | ||||
| 43982 | }else if( aLock[ofst]==0 ){ | ||||
| 43983 | rc = unixShmSystemLock(pDbFd, F_RDLCK0, ofst+UNIX_SHM_BASE((22+8)*4), n); | ||||
| 43984 | } | ||||
| 43985 | |||||
| 43986 | /* Get the local shared locks */ | ||||
| 43987 | if( rc==SQLITE_OK0 ){ | ||||
| 43988 | p->sharedMask |= mask; | ||||
| 43989 | aLock[ofst]++; | ||||
| 43990 | } | ||||
| 43991 | }else{ | ||||
| 43992 | /* Case (c) - an exclusive lock. */ | ||||
| 43993 | int ii; | ||||
| 43994 | |||||
| 43995 | assert( flags==(SQLITE_SHM_LOCK|SQLITE_SHM_EXCLUSIVE) )((void) (0)); | ||||
| 43996 | assert( (p->sharedMask & mask)==0 )((void) (0)); | ||||
| 43997 | assert( (p->exclMask & mask)==0 )((void) (0)); | ||||
| 43998 | |||||
| 43999 | /* Make sure no sibling connections hold locks that will block this | ||||
| 44000 | ** lock. If any do, return SQLITE_BUSY right away. */ | ||||
| 44001 | for(ii=ofst; ii<ofst+n; ii++){ | ||||
| 44002 | if( aLock[ii] ){ | ||||
| 44003 | rc = SQLITE_BUSY5; | ||||
| 44004 | break; | ||||
| 44005 | } | ||||
| 44006 | } | ||||
| 44007 | |||||
| 44008 | /* Get the exclusive locks at the system level. Then if successful | ||||
| 44009 | ** also update the in-memory values. */ | ||||
| 44010 | if( rc==SQLITE_OK0 ){ | ||||
| 44011 | rc = unixShmSystemLock(pDbFd, F_WRLCK1, ofst+UNIX_SHM_BASE((22+8)*4), n); | ||||
| 44012 | if( rc==SQLITE_OK0 ){ | ||||
| 44013 | p->exclMask |= mask; | ||||
| 44014 | for(ii=ofst; ii<ofst+n; ii++){ | ||||
| 44015 | aLock[ii] = -1; | ||||
| 44016 | } | ||||
| 44017 | } | ||||
| 44018 | } | ||||
| 44019 | } | ||||
| 44020 | assert( assertLockingArrayOk(pShmNode) )((void) (0)); | ||||
| 44021 | } | ||||
| 44022 | |||||
| 44023 | /* Drop the mutexes acquired above. */ | ||||
| 44024 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 44025 | leave_shmnode_mutexes: | ||||
| 44026 | for(iMutex--; iMutex>=ofst; iMutex--){ | ||||
| 44027 | sqlite3_mutex_leave(pShmNode->aMutex[iMutex]); | ||||
| 44028 | } | ||||
| 44029 | #else | ||||
| 44030 | sqlite3_mutex_leave(pShmNode->pShmMutex); | ||||
| 44031 | #endif | ||||
| 44032 | } | ||||
| 44033 | |||||
| 44034 | OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n", | ||||
| 44035 | p->id, osGetpid(0), p->sharedMask, p->exclMask)); | ||||
| 44036 | return rc; | ||||
| 44037 | } | ||||
| 44038 | |||||
| 44039 | /* | ||||
| 44040 | ** Implement a memory barrier or memory fence on shared memory. | ||||
| 44041 | ** | ||||
| 44042 | ** All loads and stores begun before the barrier must complete before | ||||
| 44043 | ** any load or store begun after the barrier. | ||||
| 44044 | */ | ||||
| 44045 | static void unixShmBarrier( | ||||
| 44046 | sqlite3_file *fd /* Database file holding the shared memory */ | ||||
| 44047 | ){ | ||||
| 44048 | UNUSED_PARAMETER(fd)(void)(fd); | ||||
| 44049 | sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ | ||||
| 44050 | assert( fd->pMethods->xLock==nolockLock((void) (0)) | ||||
| 44051 | || unixFileMutexNotheld((unixFile*)fd)((void) (0)) | ||||
| 44052 | )((void) (0)); | ||||
| 44053 | unixEnterMutex(); /* Also mutex, for redundancy */ | ||||
| 44054 | unixLeaveMutex(); | ||||
| 44055 | } | ||||
| 44056 | |||||
| 44057 | /* | ||||
| 44058 | ** Close a connection to shared-memory. Delete the underlying | ||||
| 44059 | ** storage if deleteFlag is true. | ||||
| 44060 | ** | ||||
| 44061 | ** If there is no shared memory associated with the connection then this | ||||
| 44062 | ** routine is a harmless no-op. | ||||
| 44063 | */ | ||||
| 44064 | static int unixShmUnmap( | ||||
| 44065 | sqlite3_file *fd, /* The underlying database file */ | ||||
| 44066 | int deleteFlag /* Delete shared-memory if true */ | ||||
| 44067 | ){ | ||||
| 44068 | unixShm *p; /* The connection to be closed */ | ||||
| 44069 | unixShmNode *pShmNode; /* The underlying shared-memory file */ | ||||
| 44070 | unixShm **pp; /* For looping over sibling connections */ | ||||
| 44071 | unixFile *pDbFd; /* The underlying database file */ | ||||
| 44072 | |||||
| 44073 | pDbFd = (unixFile*)fd; | ||||
| 44074 | p = pDbFd->pShm; | ||||
| 44075 | if( p==0 ) return SQLITE_OK0; | ||||
| 44076 | pShmNode = p->pShmNode; | ||||
| 44077 | |||||
| 44078 | assert( pShmNode==pDbFd->pInode->pShmNode )((void) (0)); | ||||
| 44079 | assert( pShmNode->pInode==pDbFd->pInode )((void) (0)); | ||||
| 44080 | |||||
| 44081 | /* Remove connection p from the set of connections associated | ||||
| 44082 | ** with pShmNode */ | ||||
| 44083 | sqlite3_mutex_enter(pShmNode->pShmMutex); | ||||
| 44084 | for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} | ||||
| 44085 | *pp = p->pNext; | ||||
| 44086 | |||||
| 44087 | /* Free the connection p */ | ||||
| 44088 | sqlite3_free(p); | ||||
| 44089 | pDbFd->pShm = 0; | ||||
| 44090 | sqlite3_mutex_leave(pShmNode->pShmMutex); | ||||
| 44091 | |||||
| 44092 | /* If pShmNode->nRef has reached 0, then close the underlying | ||||
| 44093 | ** shared-memory file, too */ | ||||
| 44094 | assert( unixFileMutexNotheld(pDbFd) )((void) (0)); | ||||
| 44095 | unixEnterMutex(); | ||||
| 44096 | assert( pShmNode->nRef>0 )((void) (0)); | ||||
| 44097 | pShmNode->nRef--; | ||||
| 44098 | if( pShmNode->nRef==0 ){ | ||||
| 44099 | if( deleteFlag && pShmNode->hShm>=0 ){ | ||||
| 44100 | osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(pShmNode->zFilename); | ||||
| 44101 | } | ||||
| 44102 | unixShmPurge(pDbFd); | ||||
| 44103 | } | ||||
| 44104 | unixLeaveMutex(); | ||||
| 44105 | |||||
| 44106 | return SQLITE_OK0; | ||||
| 44107 | } | ||||
| 44108 | |||||
| 44109 | |||||
| 44110 | #else | ||||
| 44111 | # define unixShmMap 0 | ||||
| 44112 | # define unixShmLock 0 | ||||
| 44113 | # define unixShmBarrier 0 | ||||
| 44114 | # define unixShmUnmap 0 | ||||
| 44115 | #endif /* #ifndef SQLITE_OMIT_WAL */ | ||||
| 44116 | |||||
| 44117 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 44118 | /* | ||||
| 44119 | ** If it is currently memory mapped, unmap file pFd. | ||||
| 44120 | */ | ||||
| 44121 | static void unixUnmapfile(unixFile *pFd){ | ||||
| 44122 | assert( pFd->nFetchOut==0 )((void) (0)); | ||||
| 44123 | if( pFd->pMapRegion ){ | ||||
| 44124 | osMunmap((int(*)(void*,size_t))aSyscall[23].pCurrent)(pFd->pMapRegion, pFd->mmapSizeActual); | ||||
| 44125 | pFd->pMapRegion = 0; | ||||
| 44126 | pFd->mmapSize = 0; | ||||
| 44127 | pFd->mmapSizeActual = 0; | ||||
| 44128 | } | ||||
| 44129 | } | ||||
| 44130 | |||||
| 44131 | /* | ||||
| 44132 | ** Attempt to set the size of the memory mapping maintained by file | ||||
| 44133 | ** descriptor pFd to nNew bytes. Any existing mapping is discarded. | ||||
| 44134 | ** | ||||
| 44135 | ** If successful, this function sets the following variables: | ||||
| 44136 | ** | ||||
| 44137 | ** unixFile.pMapRegion | ||||
| 44138 | ** unixFile.mmapSize | ||||
| 44139 | ** unixFile.mmapSizeActual | ||||
| 44140 | ** | ||||
| 44141 | ** If unsuccessful, an error message is logged via sqlite3_log() and | ||||
| 44142 | ** the three variables above are zeroed. In this case SQLite should | ||||
| 44143 | ** continue accessing the database using the xRead() and xWrite() | ||||
| 44144 | ** methods. | ||||
| 44145 | */ | ||||
| 44146 | static void unixRemapfile( | ||||
| 44147 | unixFile *pFd, /* File descriptor object */ | ||||
| 44148 | i64 nNew /* Required mapping size */ | ||||
| 44149 | ){ | ||||
| 44150 | const char *zErr = "mmap"; | ||||
| 44151 | int h = pFd->h; /* File descriptor open on db file */ | ||||
| 44152 | u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */ | ||||
| 44153 | i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */ | ||||
| 44154 | u8 *pNew = 0; /* Location of new mapping */ | ||||
| 44155 | int flags = PROT_READ0x1; /* Flags to pass to mmap() */ | ||||
| 44156 | |||||
| 44157 | assert( pFd->nFetchOut==0 )((void) (0)); | ||||
| 44158 | assert( nNew>pFd->mmapSize )((void) (0)); | ||||
| 44159 | assert( nNew<=pFd->mmapSizeMax )((void) (0)); | ||||
| 44160 | assert( nNew>0 )((void) (0)); | ||||
| 44161 | assert( pFd->mmapSizeActual>=pFd->mmapSize )((void) (0)); | ||||
| 44162 | assert( MAP_FAILED!=0 )((void) (0)); | ||||
| 44163 | |||||
| 44164 | #ifdef SQLITE_MMAP_READWRITE | ||||
| 44165 | if( (pFd->ctrlFlags & UNIXFILE_RDONLY0x02)==0 ) flags |= PROT_WRITE0x2; | ||||
| 44166 | #endif | ||||
| 44167 | |||||
| 44168 | if( pOrig ){ | ||||
| 44169 | #if HAVE_MREMAP1 | ||||
| 44170 | i64 nReuse = pFd->mmapSize; | ||||
| 44171 | #else | ||||
| 44172 | const int szSyspage = osGetpagesize((int(*)(void))aSyscall[25].pCurrent)(); | ||||
| 44173 | i64 nReuse = (pFd->mmapSize & ~(szSyspage-1)); | ||||
| 44174 | #endif | ||||
| 44175 | u8 *pReq = &pOrig[nReuse]; | ||||
| 44176 | |||||
| 44177 | /* Unmap any pages of the existing mapping that cannot be reused. */ | ||||
| 44178 | if( nReuse!=nOrig ){ | ||||
| 44179 | osMunmap((int(*)(void*,size_t))aSyscall[23].pCurrent)(pReq, nOrig-nReuse); | ||||
| 44180 | } | ||||
| 44181 | |||||
| 44182 | #if HAVE_MREMAP1 | ||||
| 44183 | pNew = osMremap((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent )(pOrig, nReuse, nNew, MREMAP_MAYMOVE1); | ||||
| 44184 | zErr = "mremap"; | ||||
| 44185 | #else | ||||
| 44186 | pNew = osMmap((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent )(pReq, nNew-nReuse, flags, MAP_SHARED0x01, h, nReuse); | ||||
| 44187 | if( pNew!=MAP_FAILED((void *) -1) ){ | ||||
| 44188 | if( pNew!=pReq ){ | ||||
| 44189 | osMunmap((int(*)(void*,size_t))aSyscall[23].pCurrent)(pNew, nNew - nReuse); | ||||
| 44190 | pNew = 0; | ||||
| 44191 | }else{ | ||||
| 44192 | pNew = pOrig; | ||||
| 44193 | } | ||||
| 44194 | } | ||||
| 44195 | #endif | ||||
| 44196 | |||||
| 44197 | /* The attempt to extend the existing mapping failed. Free it. */ | ||||
| 44198 | if( pNew==MAP_FAILED((void *) -1) || pNew==0 ){ | ||||
| 44199 | osMunmap((int(*)(void*,size_t))aSyscall[23].pCurrent)(pOrig, nReuse); | ||||
| 44200 | } | ||||
| 44201 | } | ||||
| 44202 | |||||
| 44203 | /* If pNew is still NULL, try to create an entirely new mapping. */ | ||||
| 44204 | if( pNew==0 ){ | ||||
| 44205 | pNew = osMmap((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent )(0, nNew, flags, MAP_SHARED0x01, h, 0); | ||||
| 44206 | } | ||||
| 44207 | |||||
| 44208 | if( pNew==MAP_FAILED((void *) -1) ){ | ||||
| 44209 | pNew = 0; | ||||
| 44210 | nNew = 0; | ||||
| 44211 | unixLogError(SQLITE_OK, zErr, pFd->zPath)unixLogErrorAtLine(0,zErr,pFd->zPath,44211); | ||||
| 44212 | |||||
| 44213 | /* If the mmap() above failed, assume that all subsequent mmap() calls | ||||
| 44214 | ** will probably fail too. Fall back to using xRead/xWrite exclusively | ||||
| 44215 | ** in this case. */ | ||||
| 44216 | pFd->mmapSizeMax = 0; | ||||
| 44217 | } | ||||
| 44218 | pFd->pMapRegion = (void *)pNew; | ||||
| 44219 | pFd->mmapSize = pFd->mmapSizeActual = nNew; | ||||
| 44220 | } | ||||
| 44221 | |||||
| 44222 | /* | ||||
| 44223 | ** Memory map or remap the file opened by file-descriptor pFd (if the file | ||||
| 44224 | ** is already mapped, the existing mapping is replaced by the new). Or, if | ||||
| 44225 | ** there already exists a mapping for this file, and there are still | ||||
| 44226 | ** outstanding xFetch() references to it, this function is a no-op. | ||||
| 44227 | ** | ||||
| 44228 | ** If parameter nByte is non-negative, then it is the requested size of | ||||
| 44229 | ** the mapping to create. Otherwise, if nByte is less than zero, then the | ||||
| 44230 | ** requested size is the size of the file on disk. The actual size of the | ||||
| 44231 | ** created mapping is either the requested size or the value configured | ||||
| 44232 | ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller. | ||||
| 44233 | ** | ||||
| 44234 | ** SQLITE_OK is returned if no error occurs (even if the mapping is not | ||||
| 44235 | ** recreated as a result of outstanding references) or an SQLite error | ||||
| 44236 | ** code otherwise. | ||||
| 44237 | */ | ||||
| 44238 | static int unixMapfile(unixFile *pFd, i64 nMap){ | ||||
| 44239 | assert( nMap>=0 || pFd->nFetchOut==0 )((void) (0)); | ||||
| 44240 | assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) )((void) (0)); | ||||
| 44241 | if( pFd->nFetchOut>0 ) return SQLITE_OK0; | ||||
| 44242 | |||||
| 44243 | if( nMap<0 ){ | ||||
| 44244 | struct stat statbuf; /* Low-level file information */ | ||||
| 44245 | if( osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(pFd->h, &statbuf) ){ | ||||
| 44246 | return SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 44247 | } | ||||
| 44248 | nMap = statbuf.st_size; | ||||
| 44249 | } | ||||
| 44250 | if( nMap>pFd->mmapSizeMax ){ | ||||
| 44251 | nMap = pFd->mmapSizeMax; | ||||
| 44252 | } | ||||
| 44253 | |||||
| 44254 | assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) )((void) (0)); | ||||
| 44255 | if( nMap!=pFd->mmapSize ){ | ||||
| 44256 | unixRemapfile(pFd, nMap); | ||||
| 44257 | } | ||||
| 44258 | |||||
| 44259 | return SQLITE_OK0; | ||||
| 44260 | } | ||||
| 44261 | #endif /* SQLITE_MAX_MMAP_SIZE>0 */ | ||||
| 44262 | |||||
| 44263 | /* | ||||
| 44264 | ** If possible, return a pointer to a mapping of file fd starting at offset | ||||
| 44265 | ** iOff. The mapping must be valid for at least nAmt bytes. | ||||
| 44266 | ** | ||||
| 44267 | ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. | ||||
| 44268 | ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. | ||||
| 44269 | ** Finally, if an error does occur, return an SQLite error code. The final | ||||
| 44270 | ** value of *pp is undefined in this case. | ||||
| 44271 | ** | ||||
| 44272 | ** If this function does return a pointer, the caller must eventually | ||||
| 44273 | ** release the reference by calling unixUnfetch(). | ||||
| 44274 | */ | ||||
| 44275 | static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ | ||||
| 44276 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 44277 | unixFile *pFd = (unixFile *)fd; /* The underlying database file */ | ||||
| 44278 | #endif | ||||
| 44279 | *pp = 0; | ||||
| 44280 | |||||
| 44281 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 44282 | if( pFd->mmapSizeMax>0 ){ | ||||
| 44283 | /* Ensure that there is always at least a 256 byte buffer of addressable | ||||
| 44284 | ** memory following the returned page. If the database is corrupt, | ||||
| 44285 | ** SQLite may overread the page slightly (in practice only a few bytes, | ||||
| 44286 | ** but 256 is safe, round, number). */ | ||||
| 44287 | const int nEofBuffer = 256; | ||||
| 44288 | if( pFd->pMapRegion==0 ){ | ||||
| 44289 | int rc = unixMapfile(pFd, -1); | ||||
| 44290 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 44291 | } | ||||
| 44292 | if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){ | ||||
| 44293 | *pp = &((u8 *)pFd->pMapRegion)[iOff]; | ||||
| 44294 | pFd->nFetchOut++; | ||||
| 44295 | } | ||||
| 44296 | } | ||||
| 44297 | #endif | ||||
| 44298 | return SQLITE_OK0; | ||||
| 44299 | } | ||||
| 44300 | |||||
| 44301 | /* | ||||
| 44302 | ** If the third argument is non-NULL, then this function releases a | ||||
| 44303 | ** reference obtained by an earlier call to unixFetch(). The second | ||||
| 44304 | ** argument passed to this function must be the same as the corresponding | ||||
| 44305 | ** argument that was passed to the unixFetch() invocation. | ||||
| 44306 | ** | ||||
| 44307 | ** Or, if the third argument is NULL, then this function is being called | ||||
| 44308 | ** to inform the VFS layer that, according to POSIX, any existing mapping | ||||
| 44309 | ** may now be invalid and should be unmapped. | ||||
| 44310 | */ | ||||
| 44311 | static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){ | ||||
| 44312 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 44313 | unixFile *pFd = (unixFile *)fd; /* The underlying database file */ | ||||
| 44314 | UNUSED_PARAMETER(iOff)(void)(iOff); | ||||
| 44315 | |||||
| 44316 | /* If p==0 (unmap the entire file) then there must be no outstanding | ||||
| 44317 | ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), | ||||
| 44318 | ** then there must be at least one outstanding. */ | ||||
| 44319 | assert( (p==0)==(pFd->nFetchOut==0) )((void) (0)); | ||||
| 44320 | |||||
| 44321 | /* If p!=0, it must match the iOff value. */ | ||||
| 44322 | assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] )((void) (0)); | ||||
| 44323 | |||||
| 44324 | if( p ){ | ||||
| 44325 | pFd->nFetchOut--; | ||||
| 44326 | }else{ | ||||
| 44327 | unixUnmapfile(pFd); | ||||
| 44328 | } | ||||
| 44329 | |||||
| 44330 | assert( pFd->nFetchOut>=0 )((void) (0)); | ||||
| 44331 | #else | ||||
| 44332 | UNUSED_PARAMETER(fd)(void)(fd); | ||||
| 44333 | UNUSED_PARAMETER(p)(void)(p); | ||||
| 44334 | UNUSED_PARAMETER(iOff)(void)(iOff); | ||||
| 44335 | #endif | ||||
| 44336 | return SQLITE_OK0; | ||||
| 44337 | } | ||||
| 44338 | |||||
| 44339 | /* | ||||
| 44340 | ** Here ends the implementation of all sqlite3_file methods. | ||||
| 44341 | ** | ||||
| 44342 | ********************** End sqlite3_file Methods ******************************* | ||||
| 44343 | ******************************************************************************/ | ||||
| 44344 | |||||
| 44345 | /* | ||||
| 44346 | ** This division contains definitions of sqlite3_io_methods objects that | ||||
| 44347 | ** implement various file locking strategies. It also contains definitions | ||||
| 44348 | ** of "finder" functions. A finder-function is used to locate the appropriate | ||||
| 44349 | ** sqlite3_io_methods object for a particular database file. The pAppData | ||||
| 44350 | ** field of the sqlite3_vfs VFS objects are initialized to be pointers to | ||||
| 44351 | ** the correct finder-function for that VFS. | ||||
| 44352 | ** | ||||
| 44353 | ** Most finder functions return a pointer to a fixed sqlite3_io_methods | ||||
| 44354 | ** object. The only interesting finder-function is autolockIoFinder, which | ||||
| 44355 | ** looks at the filesystem type and tries to guess the best locking | ||||
| 44356 | ** strategy from that. | ||||
| 44357 | ** | ||||
| 44358 | ** For finder-function F, two objects are created: | ||||
| 44359 | ** | ||||
| 44360 | ** (1) The real finder-function named "FImpt()". | ||||
| 44361 | ** | ||||
| 44362 | ** (2) A constant pointer to this function named just "F". | ||||
| 44363 | ** | ||||
| 44364 | ** | ||||
| 44365 | ** A pointer to the F pointer is used as the pAppData value for VFS | ||||
| 44366 | ** objects. We have to do this instead of letting pAppData point | ||||
| 44367 | ** directly at the finder-function since C90 rules prevent a void* | ||||
| 44368 | ** from be cast into a function pointer. | ||||
| 44369 | ** | ||||
| 44370 | ** | ||||
| 44371 | ** Each instance of this macro generates two objects: | ||||
| 44372 | ** | ||||
| 44373 | ** * A constant sqlite3_io_methods object call METHOD that has locking | ||||
| 44374 | ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. | ||||
| 44375 | ** | ||||
| 44376 | ** * An I/O method finder function called FINDER that returns a pointer | ||||
| 44377 | ** to the METHOD object in the previous bullet. | ||||
| 44378 | */ | ||||
| 44379 | #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)static const sqlite3_io_methods METHOD = { VERSION, CLOSE, unixRead , unixWrite, unixTruncate, unixSync, unixFileSize, LOCK, UNLOCK , CKLOCK, unixFileControl, unixSectorSize, unixDeviceCharacteristics , SHMMAP, unixShmLock, unixShmBarrier, unixShmUnmap, unixFetch , unixUnfetch, }; static const sqlite3_io_methods *FINDERImpl (const char *z, unixFile *p){ (void)(z); (void)(p); return & METHOD; } static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) = FINDERImpl; \ | ||||
| 44380 | static const sqlite3_io_methods METHOD = { \ | ||||
| 44381 | VERSION, /* iVersion */ \ | ||||
| 44382 | CLOSE, /* xClose */ \ | ||||
| 44383 | unixRead, /* xRead */ \ | ||||
| 44384 | unixWrite, /* xWrite */ \ | ||||
| 44385 | unixTruncate, /* xTruncate */ \ | ||||
| 44386 | unixSync, /* xSync */ \ | ||||
| 44387 | unixFileSize, /* xFileSize */ \ | ||||
| 44388 | LOCK, /* xLock */ \ | ||||
| 44389 | UNLOCK, /* xUnlock */ \ | ||||
| 44390 | CKLOCK, /* xCheckReservedLock */ \ | ||||
| 44391 | unixFileControl, /* xFileControl */ \ | ||||
| 44392 | unixSectorSize, /* xSectorSize */ \ | ||||
| 44393 | unixDeviceCharacteristics, /* xDeviceCapabilities */ \ | ||||
| 44394 | SHMMAP, /* xShmMap */ \ | ||||
| 44395 | unixShmLock, /* xShmLock */ \ | ||||
| 44396 | unixShmBarrier, /* xShmBarrier */ \ | ||||
| 44397 | unixShmUnmap, /* xShmUnmap */ \ | ||||
| 44398 | unixFetch, /* xFetch */ \ | ||||
| 44399 | unixUnfetch, /* xUnfetch */ \ | ||||
| 44400 | }; \ | ||||
| 44401 | static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ | ||||
| 44402 | UNUSED_PARAMETER(z)(void)(z); UNUSED_PARAMETER(p)(void)(p); \ | ||||
| 44403 | return &METHOD; \ | ||||
| 44404 | } \ | ||||
| 44405 | static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ | ||||
| 44406 | = FINDER##Impl; | ||||
| 44407 | |||||
| 44408 | /* | ||||
| 44409 | ** Here are all of the sqlite3_io_methods objects for each of the | ||||
| 44410 | ** locking strategies. Functions that return pointers to these methods | ||||
| 44411 | ** are also created. | ||||
| 44412 | */ | ||||
| 44413 | IOMETHODS(static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44414 | posixIoFinder, /* Finder function name */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44415 | posixIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44416 | 3, /* shared memory and mmap are enabled */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44417 | unixClose, /* xClose method */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44418 | unixLock, /* xLock method */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44419 | unixUnlock, /* xUnlock method */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44420 | unixCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44421 | unixShmMap /* xShmMap method */static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44422 | )static const sqlite3_io_methods posixIoMethods = { 3, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , unixUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, unixShmMap, unixShmLock, unixShmBarrier , unixShmUnmap, unixFetch, unixUnfetch, }; static const sqlite3_io_methods *posixIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &posixIoMethods; } static const sqlite3_io_methods *(*const posixIoFinder)(const char*,unixFile *p) = posixIoFinderImpl ; | ||||
| 44423 | IOMETHODS(static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44424 | nolockIoFinder, /* Finder function name */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44425 | nolockIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44426 | 3, /* shared memory and mmap are enabled */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44427 | nolockClose, /* xClose method */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44428 | nolockLock, /* xLock method */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44429 | nolockUnlock, /* xUnlock method */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44430 | nolockCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44431 | 0 /* xShmMap method */static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44432 | )static const sqlite3_io_methods nolockIoMethods = { 3, nolockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, nolockLock , nolockUnlock, nolockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nolockIoMethods; } static const sqlite3_io_methods *(*const nolockIoFinder)(const char*,unixFile *p) = nolockIoFinderImpl ; | ||||
| 44433 | IOMETHODS(static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44434 | dotlockIoFinder, /* Finder function name */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44435 | dotlockIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44436 | 1, /* shared memory is disabled */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44437 | dotlockClose, /* xClose method */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44438 | dotlockLock, /* xLock method */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44439 | dotlockUnlock, /* xUnlock method */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44440 | dotlockCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44441 | 0 /* xShmMap method */static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44442 | )static const sqlite3_io_methods dotlockIoMethods = { 1, dotlockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, dotlockLock , dotlockUnlock, dotlockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * dotlockIoFinderImpl(const char *z, unixFile *p){ (void)(z); ( void)(p); return &dotlockIoMethods; } static const sqlite3_io_methods *(*const dotlockIoFinder)(const char*,unixFile *p) = dotlockIoFinderImpl ; | ||||
| 44443 | |||||
| 44444 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 44445 | IOMETHODS(static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44446 | flockIoFinder, /* Finder function name */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44447 | flockIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44448 | 1, /* shared memory is disabled */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44449 | flockClose, /* xClose method */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44450 | flockLock, /* xLock method */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44451 | flockUnlock, /* xUnlock method */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44452 | flockCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44453 | 0 /* xShmMap method */static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44454 | )static const sqlite3_io_methods flockIoMethods = { 1, flockClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, flockLock , flockUnlock, flockCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * flockIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &flockIoMethods; } static const sqlite3_io_methods *(*const flockIoFinder)(const char*,unixFile *p) = flockIoFinderImpl ; | ||||
| 44455 | #endif | ||||
| 44456 | |||||
| 44457 | #if OS_VXWORKS0 | ||||
| 44458 | IOMETHODS(static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44459 | semIoFinder, /* Finder function name */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44460 | semIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44461 | 1, /* shared memory is disabled */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44462 | semXClose, /* xClose method */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44463 | semXLock, /* xLock method */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44464 | semXUnlock, /* xUnlock method */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44465 | semXCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44466 | 0 /* xShmMap method */static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44467 | )static const sqlite3_io_methods semIoMethods = { 1, semXClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, semXLock , semXUnlock, semXCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * semIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &semIoMethods; } static const sqlite3_io_methods *(*const semIoFinder)(const char*,unixFile *p) = semIoFinderImpl ; | ||||
| 44468 | #endif | ||||
| 44469 | |||||
| 44470 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 44471 | IOMETHODS(static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44472 | afpIoFinder, /* Finder function name */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44473 | afpIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44474 | 1, /* shared memory is disabled */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44475 | afpClose, /* xClose method */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44476 | afpLock, /* xLock method */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44477 | afpUnlock, /* xUnlock method */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44478 | afpCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44479 | 0 /* xShmMap method */static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44480 | )static const sqlite3_io_methods afpIoMethods = { 1, afpClose, unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, afpLock , afpUnlock, afpCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * afpIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &afpIoMethods; } static const sqlite3_io_methods *(*const afpIoFinder)(const char*,unixFile *p) = afpIoFinderImpl ; | ||||
| 44481 | #endif | ||||
| 44482 | |||||
| 44483 | /* | ||||
| 44484 | ** The proxy locking method is a "super-method" in the sense that it | ||||
| 44485 | ** opens secondary file descriptors for the conch and lock files and | ||||
| 44486 | ** it uses proxy, dot-file, AFP, and flock() locking methods on those | ||||
| 44487 | ** secondary files. For this reason, the division that implements | ||||
| 44488 | ** proxy locking is located much further down in the file. But we need | ||||
| 44489 | ** to go ahead and define the sqlite3_io_methods and finder function | ||||
| 44490 | ** for proxy locking here. So we forward declare the I/O methods. | ||||
| 44491 | */ | ||||
| 44492 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 44493 | static int proxyClose(sqlite3_file*); | ||||
| 44494 | static int proxyLock(sqlite3_file*, int); | ||||
| 44495 | static int proxyUnlock(sqlite3_file*, int); | ||||
| 44496 | static int proxyCheckReservedLock(sqlite3_file*, int*); | ||||
| 44497 | IOMETHODS(static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44498 | proxyIoFinder, /* Finder function name */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44499 | proxyIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44500 | 1, /* shared memory is disabled */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44501 | proxyClose, /* xClose method */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44502 | proxyLock, /* xLock method */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44503 | proxyUnlock, /* xUnlock method */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44504 | proxyCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44505 | 0 /* xShmMap method */static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44506 | )static const sqlite3_io_methods proxyIoMethods = { 1, proxyClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, proxyLock , proxyUnlock, proxyCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * proxyIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &proxyIoMethods; } static const sqlite3_io_methods *(*const proxyIoFinder)(const char*,unixFile *p) = proxyIoFinderImpl ; | ||||
| 44507 | #endif | ||||
| 44508 | |||||
| 44509 | /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */ | ||||
| 44510 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 44511 | IOMETHODS(static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44512 | nfsIoFinder, /* Finder function name */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44513 | nfsIoMethods, /* sqlite3_io_methods object name */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44514 | 1, /* shared memory is disabled */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44515 | unixClose, /* xClose method */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44516 | unixLock, /* xLock method */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44517 | nfsUnlock, /* xUnlock method */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44518 | unixCheckReservedLock, /* xCheckReservedLock method */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44519 | 0 /* xShmMap method */static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44520 | )static const sqlite3_io_methods nfsIoMethods = { 1, unixClose , unixRead, unixWrite, unixTruncate, unixSync, unixFileSize, unixLock , nfsUnlock, unixCheckReservedLock, unixFileControl, unixSectorSize , unixDeviceCharacteristics, 0, unixShmLock, unixShmBarrier, unixShmUnmap , unixFetch, unixUnfetch, }; static const sqlite3_io_methods * nfsIoFinderImpl(const char *z, unixFile *p){ (void)(z); (void )(p); return &nfsIoMethods; } static const sqlite3_io_methods *(*const nfsIoFinder)(const char*,unixFile *p) = nfsIoFinderImpl ; | ||||
| 44521 | #endif | ||||
| 44522 | |||||
| 44523 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 44524 | /* | ||||
| 44525 | ** This "finder" function attempts to determine the best locking strategy | ||||
| 44526 | ** for the database file "filePath". It then returns the sqlite3_io_methods | ||||
| 44527 | ** object that implements that strategy. | ||||
| 44528 | ** | ||||
| 44529 | ** This is for MacOSX only. | ||||
| 44530 | */ | ||||
| 44531 | static const sqlite3_io_methods *autolockIoFinderImpl( | ||||
| 44532 | const char *filePath, /* name of the database file */ | ||||
| 44533 | unixFile *pNew /* open file object for the database file */ | ||||
| 44534 | ){ | ||||
| 44535 | static const struct Mapping { | ||||
| 44536 | const char *zFilesystem; /* Filesystem type name */ | ||||
| 44537 | const sqlite3_io_methods *pMethods; /* Appropriate locking method */ | ||||
| 44538 | } aMap[] = { | ||||
| 44539 | { "hfs", &posixIoMethods }, | ||||
| 44540 | { "ufs", &posixIoMethods }, | ||||
| 44541 | { "afpfs", &afpIoMethods }, | ||||
| 44542 | { "smbfs", &afpIoMethods }, | ||||
| 44543 | { "webdav", &nolockIoMethods }, | ||||
| 44544 | { 0, 0 } | ||||
| 44545 | }; | ||||
| 44546 | int i; | ||||
| 44547 | struct statfs fsInfo; | ||||
| 44548 | struct flock lockInfo; | ||||
| 44549 | |||||
| 44550 | if( !filePath ){ | ||||
| 44551 | /* If filePath==NULL that means we are dealing with a transient file | ||||
| 44552 | ** that does not need to be locked. */ | ||||
| 44553 | return &nolockIoMethods; | ||||
| 44554 | } | ||||
| 44555 | if( statfs(filePath, &fsInfo) != -1 ){ | ||||
| 44556 | if( fsInfo.f_flags & MNT_RDONLY ){ | ||||
| 44557 | return &nolockIoMethods; | ||||
| 44558 | } | ||||
| 44559 | for(i=0; aMap[i].zFilesystem; i++){ | ||||
| 44560 | if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){ | ||||
| 44561 | return aMap[i].pMethods; | ||||
| 44562 | } | ||||
| 44563 | } | ||||
| 44564 | } | ||||
| 44565 | |||||
| 44566 | /* Default case. Handles, amongst others, "nfs". | ||||
| 44567 | ** Test byte-range lock using fcntl(). If the call succeeds, | ||||
| 44568 | ** assume that the file-system supports POSIX style locks. | ||||
| 44569 | */ | ||||
| 44570 | lockInfo.l_len = 1; | ||||
| 44571 | lockInfo.l_start = 0; | ||||
| 44572 | lockInfo.l_whence = SEEK_SET0; | ||||
| 44573 | lockInfo.l_type = F_RDLCK0; | ||||
| 44574 | if( osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(pNew->h, F_GETLK5, &lockInfo)!=-1 ) { | ||||
| 44575 | if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){ | ||||
| 44576 | return &nfsIoMethods; | ||||
| 44577 | } else { | ||||
| 44578 | return &posixIoMethods; | ||||
| 44579 | } | ||||
| 44580 | }else{ | ||||
| 44581 | return &dotlockIoMethods; | ||||
| 44582 | } | ||||
| 44583 | } | ||||
| 44584 | static const sqlite3_io_methods | ||||
| 44585 | *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; | ||||
| 44586 | |||||
| 44587 | #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ | ||||
| 44588 | |||||
| 44589 | #if OS_VXWORKS0 | ||||
| 44590 | /* | ||||
| 44591 | ** This "finder" function for VxWorks checks to see if posix advisory | ||||
| 44592 | ** locking works. If it does, then that is what is used. If it does not | ||||
| 44593 | ** work, then fallback to named semaphore locking. | ||||
| 44594 | */ | ||||
| 44595 | static const sqlite3_io_methods *vxworksIoFinderImpl( | ||||
| 44596 | const char *filePath, /* name of the database file */ | ||||
| 44597 | unixFile *pNew /* the open file object */ | ||||
| 44598 | ){ | ||||
| 44599 | struct flock lockInfo; | ||||
| 44600 | |||||
| 44601 | if( !filePath ){ | ||||
| 44602 | /* If filePath==NULL that means we are dealing with a transient file | ||||
| 44603 | ** that does not need to be locked. */ | ||||
| 44604 | return &nolockIoMethods; | ||||
| 44605 | } | ||||
| 44606 | |||||
| 44607 | /* Test if fcntl() is supported and use POSIX style locks. | ||||
| 44608 | ** Otherwise fall back to the named semaphore method. | ||||
| 44609 | */ | ||||
| 44610 | lockInfo.l_len = 1; | ||||
| 44611 | lockInfo.l_start = 0; | ||||
| 44612 | lockInfo.l_whence = SEEK_SET0; | ||||
| 44613 | lockInfo.l_type = F_RDLCK0; | ||||
| 44614 | if( osFcntl((int(*)(int,int,...))aSyscall[7].pCurrent)(pNew->h, F_GETLK5, &lockInfo)!=-1 ) { | ||||
| 44615 | return &posixIoMethods; | ||||
| 44616 | }else{ | ||||
| 44617 | return &semIoMethods; | ||||
| 44618 | } | ||||
| 44619 | } | ||||
| 44620 | static const sqlite3_io_methods | ||||
| 44621 | *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl; | ||||
| 44622 | |||||
| 44623 | #endif /* OS_VXWORKS */ | ||||
| 44624 | |||||
| 44625 | /* | ||||
| 44626 | ** An abstract type for a pointer to an IO method finder function: | ||||
| 44627 | */ | ||||
| 44628 | typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*); | ||||
| 44629 | |||||
| 44630 | |||||
| 44631 | /**************************************************************************** | ||||
| 44632 | **************************** sqlite3_vfs methods **************************** | ||||
| 44633 | ** | ||||
| 44634 | ** This division contains the implementation of methods on the | ||||
| 44635 | ** sqlite3_vfs object. | ||||
| 44636 | */ | ||||
| 44637 | |||||
| 44638 | /* | ||||
| 44639 | ** Initialize the contents of the unixFile structure pointed to by pId. | ||||
| 44640 | */ | ||||
| 44641 | static int fillInUnixFile( | ||||
| 44642 | sqlite3_vfs *pVfs, /* Pointer to vfs object */ | ||||
| 44643 | int h, /* Open file descriptor of file being opened */ | ||||
| 44644 | sqlite3_file *pId, /* Write to the unixFile structure here */ | ||||
| 44645 | const char *zFilename, /* Name of the file being opened */ | ||||
| 44646 | int ctrlFlags /* Zero or more UNIXFILE_* values */ | ||||
| 44647 | ){ | ||||
| 44648 | const sqlite3_io_methods *pLockingStyle; | ||||
| 44649 | unixFile *pNew = (unixFile *)pId; | ||||
| 44650 | int rc = SQLITE_OK0; | ||||
| 44651 | |||||
| 44652 | assert( pNew->pInode==NULL )((void) (0)); | ||||
| 44653 | |||||
| 44654 | /* No locking occurs in temporary files */ | ||||
| 44655 | assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 )((void) (0)); | ||||
| 44656 | |||||
| 44657 | OSTRACE(("OPEN %-3d %s\n", h, zFilename)); | ||||
| 44658 | pNew->h = h; | ||||
| 44659 | pNew->pVfs = pVfs; | ||||
| 44660 | pNew->zPath = zFilename; | ||||
| 44661 | pNew->ctrlFlags = (u8)ctrlFlags; | ||||
| 44662 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 44663 | pNew->mmapSizeMax = sqlite3GlobalConfigsqlite3Config.szMmap; | ||||
| 44664 | #endif | ||||
| 44665 | if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI0x40) ? zFilename : 0), | ||||
| 44666 | "psow", SQLITE_POWERSAFE_OVERWRITE1) ){ | ||||
| 44667 | pNew->ctrlFlags |= UNIXFILE_PSOW0x10; | ||||
| 44668 | } | ||||
| 44669 | if( strcmp(pVfs->zName,"unix-excl")==0 ){ | ||||
| 44670 | pNew->ctrlFlags |= UNIXFILE_EXCL0x01; | ||||
| 44671 | } | ||||
| 44672 | |||||
| 44673 | #if OS_VXWORKS0 | ||||
| 44674 | pNew->pId = vxworksFindFileId(zFilename); | ||||
| 44675 | if( pNew->pId==0 ){ | ||||
| 44676 | ctrlFlags |= UNIXFILE_NOLOCK0x80; | ||||
| 44677 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 44678 | } | ||||
| 44679 | #endif | ||||
| 44680 | |||||
| 44681 | if( ctrlFlags & UNIXFILE_NOLOCK0x80 ){ | ||||
| 44682 | pLockingStyle = &nolockIoMethods; | ||||
| 44683 | }else{ | ||||
| 44684 | pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); | ||||
| 44685 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 44686 | /* Cache zFilename in the locking context (AFP and dotlock override) for | ||||
| 44687 | ** proxyLock activation is possible (remote proxy is based on db name) | ||||
| 44688 | ** zFilename remains valid until file is closed, to support */ | ||||
| 44689 | pNew->lockingContext = (void*)zFilename; | ||||
| 44690 | #endif | ||||
| 44691 | } | ||||
| 44692 | |||||
| 44693 | if( pLockingStyle == &posixIoMethods | ||||
| 44694 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 44695 | || pLockingStyle == &nfsIoMethods | ||||
| 44696 | #endif | ||||
| 44697 | ){ | ||||
| 44698 | unixEnterMutex(); | ||||
| 44699 | rc = findInodeInfo(pNew, &pNew->pInode); | ||||
| 44700 | if( rc!=SQLITE_OK0 ){ | ||||
| 44701 | /* If an error occurred in findInodeInfo(), close the file descriptor | ||||
| 44702 | ** immediately, before releasing the mutex. findInodeInfo() may fail | ||||
| 44703 | ** in two scenarios: | ||||
| 44704 | ** | ||||
| 44705 | ** (a) A call to fstat() failed. | ||||
| 44706 | ** (b) A malloc failed. | ||||
| 44707 | ** | ||||
| 44708 | ** Scenario (b) may only occur if the process is holding no other | ||||
| 44709 | ** file descriptors open on the same file. If there were other file | ||||
| 44710 | ** descriptors on this file, then no malloc would be required by | ||||
| 44711 | ** findInodeInfo(). If this is the case, it is quite safe to close | ||||
| 44712 | ** handle h - as it is guaranteed that no posix locks will be released | ||||
| 44713 | ** by doing so. | ||||
| 44714 | ** | ||||
| 44715 | ** If scenario (a) caused the error then things are not so safe. The | ||||
| 44716 | ** implicit assumption here is that if fstat() fails, things are in | ||||
| 44717 | ** such bad shape that dropping a lock or two doesn't matter much. | ||||
| 44718 | */ | ||||
| 44719 | robust_close(pNew, h, __LINE__44719); | ||||
| 44720 | h = -1; | ||||
| 44721 | } | ||||
| 44722 | unixLeaveMutex(); | ||||
| 44723 | } | ||||
| 44724 | |||||
| 44725 | #if SQLITE_ENABLE_LOCKING_STYLE0 && defined(__APPLE__) | ||||
| 44726 | else if( pLockingStyle == &afpIoMethods ){ | ||||
| 44727 | /* AFP locking uses the file path so it needs to be included in | ||||
| 44728 | ** the afpLockingContext. | ||||
| 44729 | */ | ||||
| 44730 | afpLockingContext *pCtx; | ||||
| 44731 | pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) ); | ||||
| 44732 | if( pCtx==0 ){ | ||||
| 44733 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 44734 | }else{ | ||||
| 44735 | /* NB: zFilename exists and remains valid until the file is closed | ||||
| 44736 | ** according to requirement F11141. So we do not need to make a | ||||
| 44737 | ** copy of the filename. */ | ||||
| 44738 | pCtx->dbPath = zFilename; | ||||
| 44739 | pCtx->reserved = 0; | ||||
| 44740 | srandomdev(); | ||||
| 44741 | unixEnterMutex(); | ||||
| 44742 | rc = findInodeInfo(pNew, &pNew->pInode); | ||||
| 44743 | if( rc!=SQLITE_OK0 ){ | ||||
| 44744 | sqlite3_free(pNew->lockingContext); | ||||
| 44745 | robust_close(pNew, h, __LINE__44745); | ||||
| 44746 | h = -1; | ||||
| 44747 | } | ||||
| 44748 | unixLeaveMutex(); | ||||
| 44749 | } | ||||
| 44750 | } | ||||
| 44751 | #endif | ||||
| 44752 | |||||
| 44753 | else if( pLockingStyle == &dotlockIoMethods ){ | ||||
| 44754 | /* Dotfile locking uses the file path so it needs to be included in | ||||
| 44755 | ** the dotlockLockingContext | ||||
| 44756 | */ | ||||
| 44757 | char *zLockFile; | ||||
| 44758 | int nFilename; | ||||
| 44759 | assert( zFilename!=0 )((void) (0)); | ||||
| 44760 | nFilename = (int)strlen(zFilename) + 6; | ||||
| 44761 | zLockFile = (char *)sqlite3_malloc64(nFilename); | ||||
| 44762 | if( zLockFile==0 ){ | ||||
| 44763 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 44764 | }else{ | ||||
| 44765 | sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX".lock", zFilename); | ||||
| 44766 | } | ||||
| 44767 | pNew->lockingContext = zLockFile; | ||||
| 44768 | } | ||||
| 44769 | |||||
| 44770 | #if OS_VXWORKS0 | ||||
| 44771 | else if( pLockingStyle == &semIoMethods ){ | ||||
| 44772 | /* Named semaphore locking uses the file path so it needs to be | ||||
| 44773 | ** included in the semLockingContext | ||||
| 44774 | */ | ||||
| 44775 | unixEnterMutex(); | ||||
| 44776 | rc = findInodeInfo(pNew, &pNew->pInode); | ||||
| 44777 | if( (rc==SQLITE_OK0) && (pNew->pInode->pSem==NULL((void*)0)) ){ | ||||
| 44778 | char *zSemName = pNew->pInode->aSemName; | ||||
| 44779 | int n; | ||||
| 44780 | sqlite3_snprintf(MAX_PATHNAME512, zSemName, "/%s.sem", | ||||
| 44781 | pNew->pId->zCanonicalName); | ||||
| 44782 | for( n=1; zSemName[n]; n++ ) | ||||
| 44783 | if( zSemName[n]=='/' ) zSemName[n] = '_'; | ||||
| 44784 | pNew->pInode->pSem = sem_open(zSemName, O_CREAT0100, 0666, 1); | ||||
| 44785 | if( pNew->pInode->pSem == SEM_FAILED ){ | ||||
| 44786 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 44787 | pNew->pInode->aSemName[0] = '\0'; | ||||
| 44788 | } | ||||
| 44789 | } | ||||
| 44790 | unixLeaveMutex(); | ||||
| 44791 | } | ||||
| 44792 | #endif | ||||
| 44793 | |||||
| 44794 | storeLastErrno(pNew, 0); | ||||
| 44795 | #if OS_VXWORKS0 | ||||
| 44796 | if( rc!=SQLITE_OK0 ){ | ||||
| 44797 | if( h>=0 ) robust_close(pNew, h, __LINE__44797); | ||||
| 44798 | h = -1; | ||||
| 44799 | osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(zFilename); | ||||
| 44800 | pNew->ctrlFlags |= UNIXFILE_DELETE0x20; | ||||
| 44801 | } | ||||
| 44802 | #endif | ||||
| 44803 | if( rc!=SQLITE_OK0 ){ | ||||
| 44804 | if( h>=0 ) robust_close(pNew, h, __LINE__44804); | ||||
| 44805 | }else{ | ||||
| 44806 | pId->pMethods = pLockingStyle; | ||||
| 44807 | OpenCounter(+1); | ||||
| 44808 | verifyDbFile(pNew); | ||||
| 44809 | } | ||||
| 44810 | return rc; | ||||
| 44811 | } | ||||
| 44812 | |||||
| 44813 | /* | ||||
| 44814 | ** Directories to consider for temp files. | ||||
| 44815 | */ | ||||
| 44816 | static const char *azTempDirs[] = { | ||||
| 44817 | 0, | ||||
| 44818 | 0, | ||||
| 44819 | "/var/tmp", | ||||
| 44820 | "/usr/tmp", | ||||
| 44821 | "/tmp", | ||||
| 44822 | "." | ||||
| 44823 | }; | ||||
| 44824 | |||||
| 44825 | /* | ||||
| 44826 | ** Initialize first two members of azTempDirs[] array. | ||||
| 44827 | */ | ||||
| 44828 | static void unixTempFileInit(void){ | ||||
| 44829 | azTempDirs[0] = getenv("SQLITE_TMPDIR"); | ||||
| 44830 | azTempDirs[1] = getenv("TMPDIR"); | ||||
| 44831 | } | ||||
| 44832 | |||||
| 44833 | /* | ||||
| 44834 | ** Return the name of a directory in which to put temporary files. | ||||
| 44835 | ** If no suitable temporary file directory can be found, return NULL. | ||||
| 44836 | */ | ||||
| 44837 | static const char *unixTempFileDir(void){ | ||||
| 44838 | unsigned int i = 0; | ||||
| 44839 | struct stat buf; | ||||
| 44840 | const char *zDir = sqlite3_temp_directory; | ||||
| 44841 | |||||
| 44842 | while(1){ | ||||
| 44843 | if( zDir!=0 | ||||
| 44844 | && osStat((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)(zDir, &buf)==0 | ||||
| 44845 | && S_ISDIR(buf.st_mode)((((buf.st_mode)) & 0170000) == (0040000)) | ||||
| 44846 | && osAccess((int(*)(const char*,int))aSyscall[2].pCurrent)(zDir, 03)==0 | ||||
| 44847 | ){ | ||||
| 44848 | return zDir; | ||||
| 44849 | } | ||||
| 44850 | if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break; | ||||
| 44851 | zDir = azTempDirs[i++]; | ||||
| 44852 | } | ||||
| 44853 | return 0; | ||||
| 44854 | } | ||||
| 44855 | |||||
| 44856 | /* | ||||
| 44857 | ** Create a temporary file name in zBuf. zBuf must be allocated | ||||
| 44858 | ** by the calling process and must be big enough to hold at least | ||||
| 44859 | ** pVfs->mxPathname bytes. | ||||
| 44860 | */ | ||||
| 44861 | static int unixGetTempname(int nBuf, char *zBuf){ | ||||
| 44862 | const char *zDir; | ||||
| 44863 | int iLimit = 0; | ||||
| 44864 | int rc = SQLITE_OK0; | ||||
| 44865 | |||||
| 44866 | /* It's odd to simulate an io-error here, but really this is just | ||||
| 44867 | ** using the io-error infrastructure to test that SQLite handles this | ||||
| 44868 | ** function failing. | ||||
| 44869 | */ | ||||
| 44870 | zBuf[0] = 0; | ||||
| 44871 | SimulateIOError( return SQLITE_IOERR ); | ||||
| 44872 | |||||
| 44873 | sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 44874 | zDir = unixTempFileDir(); | ||||
| 44875 | if( zDir==0 ){ | ||||
| 44876 | rc = SQLITE_IOERR_GETTEMPPATH(10 | (25<<8)); | ||||
| 44877 | }else{ | ||||
| 44878 | do{ | ||||
| 44879 | u64 r; | ||||
| 44880 | sqlite3_randomness(sizeof(r), &r); | ||||
| 44881 | assert( nBuf>2 )((void) (0)); | ||||
| 44882 | zBuf[nBuf-2] = 0; | ||||
| 44883 | sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"etilqs_""%llx%c", | ||||
| 44884 | zDir, r, 0); | ||||
| 44885 | if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){ | ||||
| 44886 | rc = SQLITE_ERROR1; | ||||
| 44887 | break; | ||||
| 44888 | } | ||||
| 44889 | }while( osAccess((int(*)(const char*,int))aSyscall[2].pCurrent)(zBuf,0)==0 ); | ||||
| 44890 | } | ||||
| 44891 | sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 44892 | return rc; | ||||
| 44893 | } | ||||
| 44894 | |||||
| 44895 | #if SQLITE_ENABLE_LOCKING_STYLE0 && defined(__APPLE__) | ||||
| 44896 | /* | ||||
| 44897 | ** Routine to transform a unixFile into a proxy-locking unixFile. | ||||
| 44898 | ** Implementation in the proxy-lock division, but used by unixOpen() | ||||
| 44899 | ** if SQLITE_PREFER_PROXY_LOCKING is defined. | ||||
| 44900 | */ | ||||
| 44901 | static int proxyTransformUnixFile(unixFile*, const char*); | ||||
| 44902 | #endif | ||||
| 44903 | |||||
| 44904 | /* | ||||
| 44905 | ** Search for an unused file descriptor that was opened on the database | ||||
| 44906 | ** file (not a journal or super-journal file) identified by pathname | ||||
| 44907 | ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second | ||||
| 44908 | ** argument to this function. | ||||
| 44909 | ** | ||||
| 44910 | ** Such a file descriptor may exist if a database connection was closed | ||||
| 44911 | ** but the associated file descriptor could not be closed because some | ||||
| 44912 | ** other file descriptor open on the same file is holding a file-lock. | ||||
| 44913 | ** Refer to comments in the unixClose() function and the lengthy comment | ||||
| 44914 | ** describing "Posix Advisory Locking" at the start of this file for | ||||
| 44915 | ** further details. Also, ticket #4018. | ||||
| 44916 | ** | ||||
| 44917 | ** If a suitable file descriptor is found, then it is returned. If no | ||||
| 44918 | ** such file descriptor is located, -1 is returned. | ||||
| 44919 | */ | ||||
| 44920 | static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ | ||||
| 44921 | UnixUnusedFd *pUnused = 0; | ||||
| 44922 | |||||
| 44923 | /* Do not search for an unused file descriptor on vxworks. Not because | ||||
| 44924 | ** vxworks would not benefit from the change (it might, we're not sure), | ||||
| 44925 | ** but because no way to test it is currently available. It is better | ||||
| 44926 | ** not to risk breaking vxworks support for the sake of such an obscure | ||||
| 44927 | ** feature. */ | ||||
| 44928 | #if !OS_VXWORKS0 | ||||
| 44929 | struct stat sStat; /* Results of stat() call */ | ||||
| 44930 | |||||
| 44931 | unixEnterMutex(); | ||||
| 44932 | |||||
| 44933 | /* A stat() call may fail for various reasons. If this happens, it is | ||||
| 44934 | ** almost certain that an open() call on the same path will also fail. | ||||
| 44935 | ** For this reason, if an error occurs in the stat() call here, it is | ||||
| 44936 | ** ignored and -1 is returned. The caller will try to open a new file | ||||
| 44937 | ** descriptor on the same path, fail, and return an error to SQLite. | ||||
| 44938 | ** | ||||
| 44939 | ** Even if a subsequent open() call does succeed, the consequences of | ||||
| 44940 | ** not searching for a reusable file descriptor are not dire. */ | ||||
| 44941 | if( inodeList!=0 && 0==osStat((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)(zPath, &sStat) ){ | ||||
| 44942 | unixInodeInfo *pInode; | ||||
| 44943 | |||||
| 44944 | pInode = inodeList; | ||||
| 44945 | while( pInode && (pInode->fileId.dev!=sStat.st_dev | ||||
| 44946 | || pInode->fileId.ino!=(u64)sStat.st_ino) ){ | ||||
| 44947 | pInode = pInode->pNext; | ||||
| 44948 | } | ||||
| 44949 | if( pInode ){ | ||||
| 44950 | UnixUnusedFd **pp; | ||||
| 44951 | assert( sqlite3_mutex_notheld(pInode->pLockMutex) )((void) (0)); | ||||
| 44952 | sqlite3_mutex_enter(pInode->pLockMutex); | ||||
| 44953 | flags &= (SQLITE_OPEN_READONLY0x00000001|SQLITE_OPEN_READWRITE0x00000002); | ||||
| 44954 | for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); | ||||
| 44955 | pUnused = *pp; | ||||
| 44956 | if( pUnused ){ | ||||
| 44957 | *pp = pUnused->pNext; | ||||
| 44958 | } | ||||
| 44959 | sqlite3_mutex_leave(pInode->pLockMutex); | ||||
| 44960 | } | ||||
| 44961 | } | ||||
| 44962 | unixLeaveMutex(); | ||||
| 44963 | #endif /* if !OS_VXWORKS */ | ||||
| 44964 | return pUnused; | ||||
| 44965 | } | ||||
| 44966 | |||||
| 44967 | /* | ||||
| 44968 | ** Find the mode, uid and gid of file zFile. | ||||
| 44969 | */ | ||||
| 44970 | static int getFileMode( | ||||
| 44971 | const char *zFile, /* File name */ | ||||
| 44972 | mode_t *pMode, /* OUT: Permissions of zFile */ | ||||
| 44973 | uid_t *pUid, /* OUT: uid of zFile. */ | ||||
| 44974 | gid_t *pGid /* OUT: gid of zFile. */ | ||||
| 44975 | ){ | ||||
| 44976 | struct stat sStat; /* Output of stat() on database file */ | ||||
| 44977 | int rc = SQLITE_OK0; | ||||
| 44978 | if( 0==osStat((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)(zFile, &sStat) ){ | ||||
| 44979 | *pMode = sStat.st_mode & 0777; | ||||
| 44980 | *pUid = sStat.st_uid; | ||||
| 44981 | *pGid = sStat.st_gid; | ||||
| 44982 | }else{ | ||||
| 44983 | rc = SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 44984 | } | ||||
| 44985 | return rc; | ||||
| 44986 | } | ||||
| 44987 | |||||
| 44988 | /* | ||||
| 44989 | ** This function is called by unixOpen() to determine the unix permissions | ||||
| 44990 | ** to create new files with. If no error occurs, then SQLITE_OK is returned | ||||
| 44991 | ** and a value suitable for passing as the third argument to open(2) is | ||||
| 44992 | ** written to *pMode. If an IO error occurs, an SQLite error code is | ||||
| 44993 | ** returned and the value of *pMode is not modified. | ||||
| 44994 | ** | ||||
| 44995 | ** In most cases, this routine sets *pMode to 0, which will become | ||||
| 44996 | ** an indication to robust_open() to create the file using | ||||
| 44997 | ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask. | ||||
| 44998 | ** But if the file being opened is a WAL or regular journal file, then | ||||
| 44999 | ** this function queries the file-system for the permissions on the | ||||
| 45000 | ** corresponding database file and sets *pMode to this value. Whenever | ||||
| 45001 | ** possible, WAL and journal files are created using the same permissions | ||||
| 45002 | ** as the associated database file. | ||||
| 45003 | ** | ||||
| 45004 | ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the | ||||
| 45005 | ** original filename is unavailable. But 8_3_NAMES is only used for | ||||
| 45006 | ** FAT filesystems and permissions do not matter there, so just use | ||||
| 45007 | ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero. | ||||
| 45008 | */ | ||||
| 45009 | static int findCreateFileMode( | ||||
| 45010 | const char *zPath, /* Path of file (possibly) being created */ | ||||
| 45011 | int flags, /* Flags passed as 4th argument to xOpen() */ | ||||
| 45012 | mode_t *pMode, /* OUT: Permissions to open file with */ | ||||
| 45013 | uid_t *pUid, /* OUT: uid to set on the file */ | ||||
| 45014 | gid_t *pGid /* OUT: gid to set on the file */ | ||||
| 45015 | ){ | ||||
| 45016 | int rc = SQLITE_OK0; /* Return Code */ | ||||
| 45017 | *pMode = 0; | ||||
| 45018 | *pUid = 0; | ||||
| 45019 | *pGid = 0; | ||||
| 45020 | if( flags & (SQLITE_OPEN_WAL0x00080000|SQLITE_OPEN_MAIN_JOURNAL0x00000800) ){ | ||||
| 45021 | char zDb[MAX_PATHNAME512+1]; /* Database file path */ | ||||
| 45022 | int nDb; /* Number of valid bytes in zDb */ | ||||
| 45023 | |||||
| 45024 | /* zPath is a path to a WAL or journal file. The following block derives | ||||
| 45025 | ** the path to the associated database file from zPath. This block handles | ||||
| 45026 | ** the following naming conventions: | ||||
| 45027 | ** | ||||
| 45028 | ** "<path to db>-journal" | ||||
| 45029 | ** "<path to db>-wal" | ||||
| 45030 | ** "<path to db>-journalNN" | ||||
| 45031 | ** "<path to db>-walNN" | ||||
| 45032 | ** | ||||
| 45033 | ** where NN is a decimal number. The NN naming schemes are | ||||
| 45034 | ** used by the test_multiplex.c module. | ||||
| 45035 | ** | ||||
| 45036 | ** In normal operation, the journal file name will always contain | ||||
| 45037 | ** a '-' character. However in 8+3 filename mode, or if a corrupt | ||||
| 45038 | ** rollback journal specifies a super-journal with a goofy name, then | ||||
| 45039 | ** the '-' might be missing or the '-' might be the first character in | ||||
| 45040 | ** the filename. In that case, just return SQLITE_OK with *pMode==0. | ||||
| 45041 | */ | ||||
| 45042 | nDb = sqlite3Strlen30(zPath) - 1; | ||||
| 45043 | while( nDb>0 && zPath[nDb]!='.' ){ | ||||
| 45044 | if( zPath[nDb]=='-' ){ | ||||
| 45045 | memcpy(zDb, zPath, nDb); | ||||
| 45046 | zDb[nDb] = '\0'; | ||||
| 45047 | rc = getFileMode(zDb, pMode, pUid, pGid); | ||||
| 45048 | break; | ||||
| 45049 | } | ||||
| 45050 | nDb--; | ||||
| 45051 | } | ||||
| 45052 | }else if( flags & SQLITE_OPEN_DELETEONCLOSE0x00000008 ){ | ||||
| 45053 | *pMode = 0600; | ||||
| 45054 | }else if( flags & SQLITE_OPEN_URI0x00000040 ){ | ||||
| 45055 | /* If this is a main database file and the file was opened using a URI | ||||
| 45056 | ** filename, check for the "modeof" parameter. If present, interpret | ||||
| 45057 | ** its value as a filename and try to copy the mode, uid and gid from | ||||
| 45058 | ** that file. */ | ||||
| 45059 | const char *z = sqlite3_uri_parameter(zPath, "modeof"); | ||||
| 45060 | if( z ){ | ||||
| 45061 | rc = getFileMode(z, pMode, pUid, pGid); | ||||
| 45062 | } | ||||
| 45063 | } | ||||
| 45064 | return rc; | ||||
| 45065 | } | ||||
| 45066 | |||||
| 45067 | /* | ||||
| 45068 | ** Open the file zPath. | ||||
| 45069 | ** | ||||
| 45070 | ** Previously, the SQLite OS layer used three functions in place of this | ||||
| 45071 | ** one: | ||||
| 45072 | ** | ||||
| 45073 | ** sqlite3OsOpenReadWrite(); | ||||
| 45074 | ** sqlite3OsOpenReadOnly(); | ||||
| 45075 | ** sqlite3OsOpenExclusive(); | ||||
| 45076 | ** | ||||
| 45077 | ** These calls correspond to the following combinations of flags: | ||||
| 45078 | ** | ||||
| 45079 | ** ReadWrite() -> (READWRITE | CREATE) | ||||
| 45080 | ** ReadOnly() -> (READONLY) | ||||
| 45081 | ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) | ||||
| 45082 | ** | ||||
| 45083 | ** The old OpenExclusive() accepted a boolean argument - "delFlag". If | ||||
| 45084 | ** true, the file was configured to be automatically deleted when the | ||||
| 45085 | ** file handle closed. To achieve the same effect using this new | ||||
| 45086 | ** interface, add the DELETEONCLOSE flag to those specified above for | ||||
| 45087 | ** OpenExclusive(). | ||||
| 45088 | */ | ||||
| 45089 | static int unixOpen( | ||||
| 45090 | sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ | ||||
| 45091 | const char *zPath, /* Pathname of file to be opened */ | ||||
| 45092 | sqlite3_file *pFile, /* The file descriptor to be filled in */ | ||||
| 45093 | int flags, /* Input flags to control the opening */ | ||||
| 45094 | int *pOutFlags /* Output flags returned to SQLite core */ | ||||
| 45095 | ){ | ||||
| 45096 | unixFile *p = (unixFile *)pFile; | ||||
| 45097 | int fd = -1; /* File descriptor returned by open() */ | ||||
| 45098 | int openFlags = 0; /* Flags to pass to open() */ | ||||
| 45099 | int eType = flags&0x0FFF00; /* Type of file to open */ | ||||
| 45100 | int noLock; /* True to omit locking primitives */ | ||||
| 45101 | int rc = SQLITE_OK0; /* Function Return Code */ | ||||
| 45102 | int ctrlFlags = 0; /* UNIXFILE_* flags */ | ||||
| 45103 | |||||
| 45104 | int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE0x00000010); | ||||
| 45105 | int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE0x00000008); | ||||
| 45106 | int isCreate = (flags & SQLITE_OPEN_CREATE0x00000004); | ||||
| 45107 | int isReadonly = (flags & SQLITE_OPEN_READONLY0x00000001); | ||||
| 45108 | int isReadWrite = (flags & SQLITE_OPEN_READWRITE0x00000002); | ||||
| 45109 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 45110 | int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY0x00000020); | ||||
| 45111 | #endif | ||||
| 45112 | #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 45113 | struct statfs fsInfo; | ||||
| 45114 | #endif | ||||
| 45115 | |||||
| 45116 | /* If creating a super- or main-file journal, this function will open | ||||
| 45117 | ** a file-descriptor on the directory too. The first time unixSync() | ||||
| 45118 | ** is called the directory file descriptor will be fsync()ed and close()d. | ||||
| 45119 | */ | ||||
| 45120 | int isNewJrnl = (isCreate && ( | ||||
| 45121 | eType==SQLITE_OPEN_SUPER_JOURNAL0x00004000 | ||||
| 45122 | || eType==SQLITE_OPEN_MAIN_JOURNAL0x00000800 | ||||
| 45123 | || eType==SQLITE_OPEN_WAL0x00080000 | ||||
| 45124 | )); | ||||
| 45125 | |||||
| 45126 | /* If argument zPath is a NULL pointer, this function is required to open | ||||
| 45127 | ** a temporary file. Use this buffer to store the file name in. | ||||
| 45128 | */ | ||||
| 45129 | char zTmpname[MAX_PATHNAME512+2]; | ||||
| 45130 | const char *zName = zPath; | ||||
| 45131 | |||||
| 45132 | /* Check the following statements are true: | ||||
| 45133 | ** | ||||
| 45134 | ** (a) Exactly one of the READWRITE and READONLY flags must be set, and | ||||
| 45135 | ** (b) if CREATE is set, then READWRITE must also be set, and | ||||
| 45136 | ** (c) if EXCLUSIVE is set, then CREATE must also be set. | ||||
| 45137 | ** (d) if DELETEONCLOSE is set, then CREATE must also be set. | ||||
| 45138 | */ | ||||
| 45139 | assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly))((void) (0)); | ||||
| 45140 | assert(isCreate==0 || isReadWrite)((void) (0)); | ||||
| 45141 | assert(isExclusive==0 || isCreate)((void) (0)); | ||||
| 45142 | assert(isDelete==0 || isCreate)((void) (0)); | ||||
| 45143 | |||||
| 45144 | /* The main DB, main journal, WAL file and super-journal are never | ||||
| 45145 | ** automatically deleted. Nor are they ever temporary files. */ | ||||
| 45146 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB )((void) (0)); | ||||
| 45147 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL )((void) (0)); | ||||
| 45148 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL )((void) (0)); | ||||
| 45149 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL )((void) (0)); | ||||
| 45150 | |||||
| 45151 | /* Assert that the upper layer has set one of the "file-type" flags. */ | ||||
| 45152 | assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB((void) (0)) | ||||
| 45153 | || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL((void) (0)) | ||||
| 45154 | || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL((void) (0)) | ||||
| 45155 | || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL((void) (0)) | ||||
| 45156 | )((void) (0)); | ||||
| 45157 | |||||
| 45158 | /* Detect a pid change and reset the PRNG. There is a race condition | ||||
| 45159 | ** here such that two or more threads all trying to open databases at | ||||
| 45160 | ** the same instant might all reset the PRNG. But multiple resets | ||||
| 45161 | ** are harmless. | ||||
| 45162 | */ | ||||
| 45163 | if( randomnessPid!=osGetpid(0)(pid_t)getpid() ){ | ||||
| 45164 | randomnessPid = osGetpid(0)(pid_t)getpid(); | ||||
| 45165 | sqlite3_randomness(0,0); | ||||
| 45166 | } | ||||
| 45167 | memset(p, 0, sizeof(unixFile)); | ||||
| 45168 | |||||
| 45169 | #ifdef SQLITE_ASSERT_NO_FILES | ||||
| 45170 | /* Applications that never read or write a persistent disk files */ | ||||
| 45171 | assert( zName==0 )((void) (0)); | ||||
| 45172 | #endif | ||||
| 45173 | |||||
| 45174 | if( eType==SQLITE_OPEN_MAIN_DB0x00000100 ){ | ||||
| 45175 | UnixUnusedFd *pUnused; | ||||
| 45176 | pUnused = findReusableFd(zName, flags); | ||||
| 45177 | if( pUnused ){ | ||||
| 45178 | fd = pUnused->fd; | ||||
| 45179 | }else{ | ||||
| 45180 | pUnused = sqlite3_malloc64(sizeof(*pUnused)); | ||||
| 45181 | if( !pUnused ){ | ||||
| 45182 | return SQLITE_NOMEM_BKPT7; | ||||
| 45183 | } | ||||
| 45184 | } | ||||
| 45185 | p->pPreallocatedUnused = pUnused; | ||||
| 45186 | |||||
| 45187 | /* Database filenames are double-zero terminated if they are not | ||||
| 45188 | ** URIs with parameters. Hence, they can always be passed into | ||||
| 45189 | ** sqlite3_uri_parameter(). */ | ||||
| 45190 | assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 )((void) (0)); | ||||
| 45191 | |||||
| 45192 | }else if( !zName ){ | ||||
| 45193 | /* If zName is NULL, the upper layer is requesting a temp file. */ | ||||
| 45194 | assert(isDelete && !isNewJrnl)((void) (0)); | ||||
| 45195 | rc = unixGetTempname(pVfs->mxPathname, zTmpname); | ||||
| 45196 | if( rc!=SQLITE_OK0 ){ | ||||
| 45197 | return rc; | ||||
| 45198 | } | ||||
| 45199 | zName = zTmpname; | ||||
| 45200 | |||||
| 45201 | /* Generated temporary filenames are always double-zero terminated | ||||
| 45202 | ** for use by sqlite3_uri_parameter(). */ | ||||
| 45203 | assert( zName[strlen(zName)+1]==0 )((void) (0)); | ||||
| 45204 | } | ||||
| 45205 | |||||
| 45206 | /* Determine the value of the flags parameter passed to POSIX function | ||||
| 45207 | ** open(). These must be calculated even if open() is not called, as | ||||
| 45208 | ** they may be stored as part of the file handle and used by the | ||||
| 45209 | ** 'conch file' locking functions later on. */ | ||||
| 45210 | if( isReadonly ) openFlags |= O_RDONLY00; | ||||
| 45211 | if( isReadWrite ) openFlags |= O_RDWR02; | ||||
| 45212 | if( isCreate ) openFlags |= O_CREAT0100; | ||||
| 45213 | if( isExclusive ) openFlags |= (O_EXCL0200|O_NOFOLLOW0400000); | ||||
| 45214 | openFlags |= (O_LARGEFILE0|O_BINARY0|O_NOFOLLOW0400000); | ||||
| 45215 | |||||
| 45216 | if( fd<0 ){ | ||||
| 45217 | mode_t openMode; /* Permissions to create file with */ | ||||
| 45218 | uid_t uid; /* Userid for the file */ | ||||
| 45219 | gid_t gid; /* Groupid for the file */ | ||||
| 45220 | rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid); | ||||
| 45221 | if( rc!=SQLITE_OK0 ){ | ||||
| 45222 | assert( !p->pPreallocatedUnused )((void) (0)); | ||||
| 45223 | assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL )((void) (0)); | ||||
| 45224 | return rc; | ||||
| 45225 | } | ||||
| 45226 | fd = robust_open(zName, openFlags, openMode); | ||||
| 45227 | OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); | ||||
| 45228 | assert( !isExclusive || (openFlags & O_CREAT)!=0 )((void) (0)); | ||||
| 45229 | if( fd<0 ){ | ||||
| 45230 | if( isNewJrnl && errno(*__errno_location ())==EACCES13 && osAccess((int(*)(const char*,int))aSyscall[2].pCurrent)(zName, F_OK0) ){ | ||||
| 45231 | /* If unable to create a journal because the directory is not | ||||
| 45232 | ** writable, change the error code to indicate that. */ | ||||
| 45233 | rc = SQLITE_READONLY_DIRECTORY(8 | (6<<8)); | ||||
| 45234 | }else if( errno(*__errno_location ())!=EISDIR21 && isReadWrite ){ | ||||
| 45235 | /* Failed to open the file for read/write access. Try read-only. */ | ||||
| 45236 | UnixUnusedFd *pReadonly = 0; | ||||
| 45237 | flags &= ~(SQLITE_OPEN_READWRITE0x00000002|SQLITE_OPEN_CREATE0x00000004); | ||||
| 45238 | openFlags &= ~(O_RDWR02|O_CREAT0100); | ||||
| 45239 | flags |= SQLITE_OPEN_READONLY0x00000001; | ||||
| 45240 | openFlags |= O_RDONLY00; | ||||
| 45241 | isReadonly = 1; | ||||
| 45242 | pReadonly = findReusableFd(zName, flags); | ||||
| 45243 | if( pReadonly ){ | ||||
| 45244 | fd = pReadonly->fd; | ||||
| 45245 | sqlite3_free(pReadonly); | ||||
| 45246 | }else{ | ||||
| 45247 | fd = robust_open(zName, openFlags, openMode); | ||||
| 45248 | } | ||||
| 45249 | } | ||||
| 45250 | } | ||||
| 45251 | if( fd<0 ){ | ||||
| 45252 | int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName)unixLogErrorAtLine(sqlite3CantopenError(45252),"open",zName,45252 ); | ||||
| 45253 | if( rc==SQLITE_OK0 ) rc = rc2; | ||||
| 45254 | goto open_finished; | ||||
| 45255 | } | ||||
| 45256 | |||||
| 45257 | /* The owner of the rollback journal or WAL file should always be the | ||||
| 45258 | ** same as the owner of the database file. Try to ensure that this is | ||||
| 45259 | ** the case. The chown() system call will be a no-op if the current | ||||
| 45260 | ** process lacks root privileges, be we should at least try. Without | ||||
| 45261 | ** this step, if a root process opens a database file, it can leave | ||||
| 45262 | ** behinds a journal/WAL that is owned by root and hence make the | ||||
| 45263 | ** database inaccessible to unprivileged processes. | ||||
| 45264 | ** | ||||
| 45265 | ** If openMode==0, then that means uid and gid are not set correctly | ||||
| 45266 | ** (probably because SQLite is configured to use 8+3 filename mode) and | ||||
| 45267 | ** in that case we do not want to attempt the chown(). | ||||
| 45268 | */ | ||||
| 45269 | if( openMode && (flags & (SQLITE_OPEN_WAL0x00080000|SQLITE_OPEN_MAIN_JOURNAL0x00000800))!=0 ){ | ||||
| 45270 | robustFchown(fd, uid, gid); | ||||
| 45271 | } | ||||
| 45272 | } | ||||
| 45273 | assert( fd>=0 )((void) (0)); | ||||
| 45274 | if( pOutFlags ){ | ||||
| 45275 | *pOutFlags = flags; | ||||
| 45276 | } | ||||
| 45277 | |||||
| 45278 | if( p->pPreallocatedUnused ){ | ||||
| 45279 | p->pPreallocatedUnused->fd = fd; | ||||
| 45280 | p->pPreallocatedUnused->flags = | ||||
| 45281 | flags & (SQLITE_OPEN_READONLY0x00000001|SQLITE_OPEN_READWRITE0x00000002); | ||||
| 45282 | } | ||||
| 45283 | |||||
| 45284 | if( isDelete ){ | ||||
| 45285 | #if OS_VXWORKS0 | ||||
| 45286 | zPath = zName; | ||||
| 45287 | #elif defined(SQLITE_UNLINK_AFTER_CLOSE) | ||||
| 45288 | zPath = sqlite3_mprintf("%s", zName); | ||||
| 45289 | if( zPath==0 ){ | ||||
| 45290 | robust_close(p, fd, __LINE__45290); | ||||
| 45291 | return SQLITE_NOMEM_BKPT7; | ||||
| 45292 | } | ||||
| 45293 | #else | ||||
| 45294 | osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(zName); | ||||
| 45295 | #endif | ||||
| 45296 | } | ||||
| 45297 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 45298 | else{ | ||||
| 45299 | p->openFlags = openFlags; | ||||
| 45300 | } | ||||
| 45301 | #endif | ||||
| 45302 | |||||
| 45303 | #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 45304 | if( fstatfs(fd, &fsInfo) == -1 ){ | ||||
| 45305 | storeLastErrno(p, errno(*__errno_location ())); | ||||
| 45306 | robust_close(p, fd, __LINE__45306); | ||||
| 45307 | return SQLITE_IOERR_ACCESS(10 | (13<<8)); | ||||
| 45308 | } | ||||
| 45309 | if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) { | ||||
| 45310 | ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS0x1; | ||||
| 45311 | } | ||||
| 45312 | if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) { | ||||
| 45313 | ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS0x1; | ||||
| 45314 | } | ||||
| 45315 | #endif | ||||
| 45316 | |||||
| 45317 | /* Set up appropriate ctrlFlags */ | ||||
| 45318 | if( isDelete ) ctrlFlags |= UNIXFILE_DELETE0x20; | ||||
| 45319 | if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY0x02; | ||||
| 45320 | noLock = eType!=SQLITE_OPEN_MAIN_DB0x00000100; | ||||
| 45321 | if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK0x80; | ||||
| 45322 | if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC0x08; | ||||
| 45323 | if( flags & SQLITE_OPEN_URI0x00000040 ) ctrlFlags |= UNIXFILE_URI0x40; | ||||
| 45324 | |||||
| 45325 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 45326 | #if SQLITE_PREFER_PROXY_LOCKING | ||||
| 45327 | isAutoProxy = 1; | ||||
| 45328 | #endif | ||||
| 45329 | if( isAutoProxy && (zPath!=NULL((void*)0)) && (!noLock) && pVfs->xOpen ){ | ||||
| 45330 | char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); | ||||
| 45331 | int useProxy = 0; | ||||
| 45332 | |||||
| 45333 | /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means | ||||
| 45334 | ** never use proxy, NULL means use proxy for non-local files only. */ | ||||
| 45335 | if( envforce!=NULL((void*)0) ){ | ||||
| 45336 | useProxy = atoi(envforce)>0; | ||||
| 45337 | }else{ | ||||
| 45338 | useProxy = !(fsInfo.f_flags&MNT_LOCAL); | ||||
| 45339 | } | ||||
| 45340 | if( useProxy ){ | ||||
| 45341 | rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); | ||||
| 45342 | if( rc==SQLITE_OK0 ){ | ||||
| 45343 | rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); | ||||
| 45344 | if( rc!=SQLITE_OK0 ){ | ||||
| 45345 | /* Use unixClose to clean up the resources added in fillInUnixFile | ||||
| 45346 | ** and clear all the structure's references. Specifically, | ||||
| 45347 | ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op | ||||
| 45348 | */ | ||||
| 45349 | unixClose(pFile); | ||||
| 45350 | return rc; | ||||
| 45351 | } | ||||
| 45352 | } | ||||
| 45353 | goto open_finished; | ||||
| 45354 | } | ||||
| 45355 | } | ||||
| 45356 | #endif | ||||
| 45357 | |||||
| 45358 | assert( zPath==0 || zPath[0]=='/'((void) (0)) | ||||
| 45359 | || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL((void) (0)) | ||||
| 45360 | )((void) (0)); | ||||
| 45361 | rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); | ||||
| 45362 | |||||
| 45363 | open_finished: | ||||
| 45364 | if( rc!=SQLITE_OK0 ){ | ||||
| 45365 | sqlite3_free(p->pPreallocatedUnused); | ||||
| 45366 | } | ||||
| 45367 | return rc; | ||||
| 45368 | } | ||||
| 45369 | |||||
| 45370 | |||||
| 45371 | /* | ||||
| 45372 | ** Delete the file at zPath. If the dirSync argument is true, fsync() | ||||
| 45373 | ** the directory after deleting the file. | ||||
| 45374 | */ | ||||
| 45375 | static int unixDelete( | ||||
| 45376 | sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ | ||||
| 45377 | const char *zPath, /* Name of file to be deleted */ | ||||
| 45378 | int dirSync /* If true, fsync() directory after deleting file */ | ||||
| 45379 | ){ | ||||
| 45380 | int rc = SQLITE_OK0; | ||||
| 45381 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45382 | SimulateIOError(return SQLITE_IOERR_DELETE); | ||||
| 45383 | if( osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(zPath)==(-1) ){ | ||||
| 45384 | if( errno(*__errno_location ())==ENOENT2 | ||||
| 45385 | #if OS_VXWORKS0 | ||||
| 45386 | || osAccess((int(*)(const char*,int))aSyscall[2].pCurrent)(zPath,0)!=0 | ||||
| 45387 | #endif | ||||
| 45388 | ){ | ||||
| 45389 | rc = SQLITE_IOERR_DELETE_NOENT(10 | (23<<8)); | ||||
| 45390 | }else{ | ||||
| 45391 | rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath)unixLogErrorAtLine((10 | (10<<8)),"unlink",zPath,45391); | ||||
| 45392 | } | ||||
| 45393 | return rc; | ||||
| 45394 | } | ||||
| 45395 | #ifndef SQLITE_DISABLE_DIRSYNC | ||||
| 45396 | if( (dirSync & 1)!=0 ){ | ||||
| 45397 | int fd; | ||||
| 45398 | rc = osOpenDirectory((int(*)(const char*,int*))aSyscall[17].pCurrent)(zPath, &fd); | ||||
| 45399 | if( rc==SQLITE_OK0 ){ | ||||
| 45400 | if( full_fsync(fd,0,0) ){ | ||||
| 45401 | rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath)unixLogErrorAtLine((10 | (5<<8)),"fsync",zPath,45401); | ||||
| 45402 | } | ||||
| 45403 | robust_close(0, fd, __LINE__45403); | ||||
| 45404 | }else{ | ||||
| 45405 | assert( rc==SQLITE_CANTOPEN )((void) (0)); | ||||
| 45406 | rc = SQLITE_OK0; | ||||
| 45407 | } | ||||
| 45408 | } | ||||
| 45409 | #endif | ||||
| 45410 | return rc; | ||||
| 45411 | } | ||||
| 45412 | |||||
| 45413 | /* | ||||
| 45414 | ** Test the existence of or access permissions of file zPath. The | ||||
| 45415 | ** test performed depends on the value of flags: | ||||
| 45416 | ** | ||||
| 45417 | ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists | ||||
| 45418 | ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. | ||||
| 45419 | ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. | ||||
| 45420 | ** | ||||
| 45421 | ** Otherwise return 0. | ||||
| 45422 | */ | ||||
| 45423 | static int unixAccess( | ||||
| 45424 | sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ | ||||
| 45425 | const char *zPath, /* Path of the file to examine */ | ||||
| 45426 | int flags, /* What do we want to learn about the zPath file? */ | ||||
| 45427 | int *pResOut /* Write result boolean here */ | ||||
| 45428 | ){ | ||||
| 45429 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45430 | SimulateIOError( return SQLITE_IOERR_ACCESS; ); | ||||
| 45431 | assert( pResOut!=0 )((void) (0)); | ||||
| 45432 | |||||
| 45433 | /* The spec says there are three possible values for flags. But only | ||||
| 45434 | ** two of them are actually used */ | ||||
| 45435 | assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE )((void) (0)); | ||||
| 45436 | |||||
| 45437 | if( flags==SQLITE_ACCESS_EXISTS0 ){ | ||||
| 45438 | struct stat buf; | ||||
| 45439 | *pResOut = 0==osStat((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)(zPath, &buf) && | ||||
| 45440 | (!S_ISREG(buf.st_mode)((((buf.st_mode)) & 0170000) == (0100000)) || buf.st_size>0); | ||||
| 45441 | }else{ | ||||
| 45442 | *pResOut = osAccess((int(*)(const char*,int))aSyscall[2].pCurrent)(zPath, W_OK2|R_OK4)==0; | ||||
| 45443 | } | ||||
| 45444 | return SQLITE_OK0; | ||||
| 45445 | } | ||||
| 45446 | |||||
| 45447 | /* | ||||
| 45448 | ** A pathname under construction | ||||
| 45449 | */ | ||||
| 45450 | typedef struct DbPath DbPath; | ||||
| 45451 | struct DbPath { | ||||
| 45452 | int rc; /* Non-zero following any error */ | ||||
| 45453 | int nSymlink; /* Number of symlinks resolved */ | ||||
| 45454 | char *zOut; /* Write the pathname here */ | ||||
| 45455 | int nOut; /* Bytes of space available to zOut[] */ | ||||
| 45456 | int nUsed; /* Bytes of zOut[] currently being used */ | ||||
| 45457 | }; | ||||
| 45458 | |||||
| 45459 | /* Forward reference */ | ||||
| 45460 | static void appendAllPathElements(DbPath*,const char*); | ||||
| 45461 | |||||
| 45462 | /* | ||||
| 45463 | ** Append a single path element to the DbPath under construction | ||||
| 45464 | */ | ||||
| 45465 | static void appendOnePathElement( | ||||
| 45466 | DbPath *pPath, /* Path under construction, to which to append zName */ | ||||
| 45467 | const char *zName, /* Name to append to pPath. Not zero-terminated */ | ||||
| 45468 | int nName /* Number of significant bytes in zName */ | ||||
| 45469 | ){ | ||||
| 45470 | assert( nName>0 )((void) (0)); | ||||
| 45471 | assert( zName!=0 )((void) (0)); | ||||
| 45472 | if( zName[0]=='.' ){ | ||||
| 45473 | if( nName==1 ) return; | ||||
| 45474 | if( zName[1]=='.' && nName==2 ){ | ||||
| 45475 | if( pPath->nUsed>1 ){ | ||||
| 45476 | assert( pPath->zOut[0]=='/' )((void) (0)); | ||||
| 45477 | while( pPath->zOut[--pPath->nUsed]!='/' ){} | ||||
| 45478 | } | ||||
| 45479 | return; | ||||
| 45480 | } | ||||
| 45481 | } | ||||
| 45482 | if( pPath->nUsed + nName + 2 >= pPath->nOut ){ | ||||
| 45483 | pPath->rc = SQLITE_ERROR1; | ||||
| 45484 | return; | ||||
| 45485 | } | ||||
| 45486 | pPath->zOut[pPath->nUsed++] = '/'; | ||||
| 45487 | memcpy(&pPath->zOut[pPath->nUsed], zName, nName); | ||||
| 45488 | pPath->nUsed += nName; | ||||
| 45489 | #if defined(HAVE_READLINK1) && defined(HAVE_LSTAT1) | ||||
| 45490 | if( pPath->rc==SQLITE_OK0 ){ | ||||
| 45491 | const char *zIn; | ||||
| 45492 | struct stat buf; | ||||
| 45493 | pPath->zOut[pPath->nUsed] = 0; | ||||
| 45494 | zIn = pPath->zOut; | ||||
| 45495 | if( osLstat((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)(zIn, &buf)!=0 ){ | ||||
| 45496 | if( errno(*__errno_location ())!=ENOENT2 ){ | ||||
| 45497 | pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn)unixLogErrorAtLine(sqlite3CantopenError(45497),"lstat",zIn,45497 ); | ||||
| 45498 | } | ||||
| 45499 | }else if( S_ISLNK(buf.st_mode)((((buf.st_mode)) & 0170000) == (0120000)) ){ | ||||
| 45500 | ssize_t got; | ||||
| 45501 | char zLnk[SQLITE_MAX_PATHLEN4096+2]; | ||||
| 45502 | if( pPath->nSymlink++ > SQLITE_MAX_SYMLINK200 ){ | ||||
| 45503 | pPath->rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(45503); | ||||
| 45504 | return; | ||||
| 45505 | } | ||||
| 45506 | got = osReadlink((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)(zIn, zLnk, sizeof(zLnk)-2); | ||||
| 45507 | if( got<=0 || got>=(ssize_t)sizeof(zLnk)-2 ){ | ||||
| 45508 | pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn)unixLogErrorAtLine(sqlite3CantopenError(45508),"readlink",zIn ,45508); | ||||
| 45509 | return; | ||||
| 45510 | } | ||||
| 45511 | zLnk[got] = 0; | ||||
| 45512 | if( zLnk[0]=='/' ){ | ||||
| 45513 | pPath->nUsed = 0; | ||||
| 45514 | }else{ | ||||
| 45515 | pPath->nUsed -= nName + 1; | ||||
| 45516 | } | ||||
| 45517 | appendAllPathElements(pPath, zLnk); | ||||
| 45518 | } | ||||
| 45519 | } | ||||
| 45520 | #endif | ||||
| 45521 | } | ||||
| 45522 | |||||
| 45523 | /* | ||||
| 45524 | ** Append all path elements in zPath to the DbPath under construction. | ||||
| 45525 | */ | ||||
| 45526 | static void appendAllPathElements( | ||||
| 45527 | DbPath *pPath, /* Path under construction, to which to append zName */ | ||||
| 45528 | const char *zPath /* Path to append to pPath. Is zero-terminated */ | ||||
| 45529 | ){ | ||||
| 45530 | int i = 0; | ||||
| 45531 | int j = 0; | ||||
| 45532 | do{ | ||||
| 45533 | while( zPath[i] && zPath[i]!='/' ){ i++; } | ||||
| 45534 | if( i>j ){ | ||||
| 45535 | appendOnePathElement(pPath, &zPath[j], i-j); | ||||
| 45536 | } | ||||
| 45537 | j = i+1; | ||||
| 45538 | }while( zPath[i++] ); | ||||
| 45539 | } | ||||
| 45540 | |||||
| 45541 | /* | ||||
| 45542 | ** Turn a relative pathname into a full pathname. The relative path | ||||
| 45543 | ** is stored as a nul-terminated string in the buffer pointed to by | ||||
| 45544 | ** zPath. | ||||
| 45545 | ** | ||||
| 45546 | ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes | ||||
| 45547 | ** (in this case, MAX_PATHNAME bytes). The full-path is written to | ||||
| 45548 | ** this buffer before returning. | ||||
| 45549 | */ | ||||
| 45550 | static int unixFullPathname( | ||||
| 45551 | sqlite3_vfs *pVfs, /* Pointer to vfs object */ | ||||
| 45552 | const char *zPath, /* Possibly relative input path */ | ||||
| 45553 | int nOut, /* Size of output buffer in bytes */ | ||||
| 45554 | char *zOut /* Output buffer */ | ||||
| 45555 | ){ | ||||
| 45556 | DbPath path; | ||||
| 45557 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 45558 | path.rc = 0; | ||||
| 45559 | path.nUsed = 0; | ||||
| 45560 | path.nSymlink = 0; | ||||
| 45561 | path.nOut = nOut; | ||||
| 45562 | path.zOut = zOut; | ||||
| 45563 | if( zPath[0]!='/' ){ | ||||
| 45564 | char zPwd[SQLITE_MAX_PATHLEN4096+2]; | ||||
| 45565 | if( osGetcwd((char*(*)(char*,size_t))aSyscall[3].pCurrent)(zPwd, sizeof(zPwd)-2)==0 ){ | ||||
| 45566 | return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath)unixLogErrorAtLine(sqlite3CantopenError(45566),"getcwd",zPath ,45566); | ||||
| 45567 | } | ||||
| 45568 | appendAllPathElements(&path, zPwd); | ||||
| 45569 | } | ||||
| 45570 | appendAllPathElements(&path, zPath); | ||||
| 45571 | zOut[path.nUsed] = 0; | ||||
| 45572 | if( path.rc || path.nUsed<2 ) return SQLITE_CANTOPEN_BKPTsqlite3CantopenError(45572); | ||||
| 45573 | if( path.nSymlink ) return SQLITE_OK_SYMLINK(0 | (2<<8)); | ||||
| 45574 | return SQLITE_OK0; | ||||
| 45575 | } | ||||
| 45576 | |||||
| 45577 | #ifndef SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 45578 | /* | ||||
| 45579 | ** Interfaces for opening a shared library, finding entry points | ||||
| 45580 | ** within the shared library, and closing the shared library. | ||||
| 45581 | */ | ||||
| 45582 | #include <dlfcn.h> | ||||
| 45583 | static void *unixDlOpen0(sqlite3_vfs *NotUsed, const char *zFilename){ | ||||
| 45584 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45585 | return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL); | ||||
| 45586 | } | ||||
| 45587 | |||||
| 45588 | /* | ||||
| 45589 | ** SQLite calls this function immediately after a call to unixDlSym() or | ||||
| 45590 | ** unixDlOpen() fails (returns a null pointer). If a more detailed error | ||||
| 45591 | ** message is available, it is written to zBufOut. If no error message | ||||
| 45592 | ** is available, zBufOut is left unmodified and SQLite uses a default | ||||
| 45593 | ** error message. | ||||
| 45594 | */ | ||||
| 45595 | static void unixDlError0(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ | ||||
| 45596 | const char *zErr; | ||||
| 45597 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45598 | unixEnterMutex(); | ||||
| 45599 | zErr = dlerror(); | ||||
| 45600 | if( zErr ){ | ||||
| 45601 | sqlite3_snprintf(nBuf, zBufOut, "%s", zErr); | ||||
| 45602 | } | ||||
| 45603 | unixLeaveMutex(); | ||||
| 45604 | } | ||||
| 45605 | static void (*unixDlSym0(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ | ||||
| 45606 | /* | ||||
| 45607 | ** GCC with -pedantic-errors says that C90 does not allow a void* to be | ||||
| 45608 | ** cast into a pointer to a function. And yet the library dlsym() routine | ||||
| 45609 | ** returns a void* which is really a pointer to a function. So how do we | ||||
| 45610 | ** use dlsym() with -pedantic-errors? | ||||
| 45611 | ** | ||||
| 45612 | ** Variable x below is defined to be a pointer to a function taking | ||||
| 45613 | ** parameters void* and const char* and returning a pointer to a function. | ||||
| 45614 | ** We initialize x by assigning it a pointer to the dlsym() function. | ||||
| 45615 | ** (That assignment requires a cast.) Then we call the function that | ||||
| 45616 | ** x points to. | ||||
| 45617 | ** | ||||
| 45618 | ** This work-around is unlikely to work correctly on any system where | ||||
| 45619 | ** you really cannot cast a function pointer into void*. But then, on the | ||||
| 45620 | ** other hand, dlsym() will not work on such a system either, so we have | ||||
| 45621 | ** not really lost anything. | ||||
| 45622 | */ | ||||
| 45623 | void (*(*x)(void*,const char*))(void); | ||||
| 45624 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45625 | x = (void(*(*)(void*,const char*))(void))dlsym; | ||||
| 45626 | return (*x)(p, zSym); | ||||
| 45627 | } | ||||
| 45628 | static void unixDlClose0(sqlite3_vfs *NotUsed, void *pHandle){ | ||||
| 45629 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45630 | dlclose(pHandle); | ||||
| 45631 | } | ||||
| 45632 | #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ | ||||
| 45633 | #define unixDlOpen0 0 | ||||
| 45634 | #define unixDlError0 0 | ||||
| 45635 | #define unixDlSym0 0 | ||||
| 45636 | #define unixDlClose0 0 | ||||
| 45637 | #endif | ||||
| 45638 | |||||
| 45639 | /* | ||||
| 45640 | ** Write nBuf bytes of random data to the supplied buffer zBuf. | ||||
| 45641 | */ | ||||
| 45642 | static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ | ||||
| 45643 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45644 | assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)))((void) (0)); | ||||
| 45645 | |||||
| 45646 | /* We have to initialize zBuf to prevent valgrind from reporting | ||||
| 45647 | ** errors. The reports issued by valgrind are incorrect - we would | ||||
| 45648 | ** prefer that the randomness be increased by making use of the | ||||
| 45649 | ** uninitialized space in zBuf - but valgrind errors tend to worry | ||||
| 45650 | ** some users. Rather than argue, it seems easier just to initialize | ||||
| 45651 | ** the whole array and silence valgrind, even if that means less randomness | ||||
| 45652 | ** in the random seed. | ||||
| 45653 | ** | ||||
| 45654 | ** When testing, initializing zBuf[] to zero is all we do. That means | ||||
| 45655 | ** that we always use the same random number sequence. This makes the | ||||
| 45656 | ** tests repeatable. | ||||
| 45657 | */ | ||||
| 45658 | memset(zBuf, 0, nBuf); | ||||
| 45659 | randomnessPid = osGetpid(0)(pid_t)getpid(); | ||||
| 45660 | #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) | ||||
| 45661 | { | ||||
| 45662 | int fd, got; | ||||
| 45663 | fd = robust_open("/dev/urandom", O_RDONLY00, 0); | ||||
| 45664 | if( fd<0 ){ | ||||
| 45665 | time_t t; | ||||
| 45666 | time(&t); | ||||
| 45667 | memcpy(zBuf, &t, sizeof(t)); | ||||
| 45668 | memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid)); | ||||
| 45669 | assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf )((void) (0)); | ||||
| 45670 | nBuf = sizeof(t) + sizeof(randomnessPid); | ||||
| 45671 | }else{ | ||||
| 45672 | do{ got = osRead((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)(fd, zBuf, nBuf); }while( got<0 && errno(*__errno_location ())==EINTR4 ); | ||||
| 45673 | robust_close(0, fd, __LINE__45673); | ||||
| 45674 | } | ||||
| 45675 | } | ||||
| 45676 | #endif | ||||
| 45677 | return nBuf; | ||||
| 45678 | } | ||||
| 45679 | |||||
| 45680 | |||||
| 45681 | /* | ||||
| 45682 | ** Sleep for a little while. Return the amount of time slept. | ||||
| 45683 | ** The argument is the number of microseconds we want to sleep. | ||||
| 45684 | ** The return value is the number of microseconds of sleep actually | ||||
| 45685 | ** requested from the underlying operating system, a number which | ||||
| 45686 | ** might be greater than or equal to the argument, but not less | ||||
| 45687 | ** than the argument. | ||||
| 45688 | */ | ||||
| 45689 | static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ | ||||
| 45690 | #if !defined(HAVE_NANOSLEEP) || HAVE_NANOSLEEP+0 | ||||
| 45691 | struct timespec sp; | ||||
| 45692 | sp.tv_sec = microseconds / 1000000; | ||||
| 45693 | sp.tv_nsec = (microseconds % 1000000) * 1000; | ||||
| 45694 | |||||
| 45695 | /* Almost all modern unix systems support nanosleep(). But if you are | ||||
| 45696 | ** compiling for one of the rare exceptions, you can use | ||||
| 45697 | ** -DHAVE_NANOSLEEP=0 (perhaps in conjunction with -DHAVE_USLEEP if | ||||
| 45698 | ** usleep() is available) in order to bypass the use of nanosleep() */ | ||||
| 45699 | nanosleep(&sp, NULL((void*)0)); | ||||
| 45700 | |||||
| 45701 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45702 | return microseconds; | ||||
| 45703 | #elif defined(HAVE_USLEEP1) && HAVE_USLEEP1 | ||||
| 45704 | if( microseconds>=1000000 ) sleep(microseconds/1000000); | ||||
| 45705 | if( microseconds%1000000 ) usleep(microseconds%1000000); | ||||
| 45706 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45707 | return microseconds; | ||||
| 45708 | #else | ||||
| 45709 | int seconds = (microseconds+999999)/1000000; | ||||
| 45710 | sleep(seconds); | ||||
| 45711 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45712 | return seconds*1000000; | ||||
| 45713 | #endif | ||||
| 45714 | } | ||||
| 45715 | |||||
| 45716 | /* | ||||
| 45717 | ** The following variable, if set to a non-zero value, is interpreted as | ||||
| 45718 | ** the number of seconds since 1970 and is used to set the result of | ||||
| 45719 | ** sqlite3OsCurrentTime() during testing. | ||||
| 45720 | */ | ||||
| 45721 | #ifdef SQLITE_TEST | ||||
| 45722 | SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ | ||||
| 45723 | #endif | ||||
| 45724 | |||||
| 45725 | /* | ||||
| 45726 | ** Find the current time (in Universal Coordinated Time). Write into *piNow | ||||
| 45727 | ** the current time and date as a Julian Day number times 86_400_000. In | ||||
| 45728 | ** other words, write into *piNow the number of milliseconds since the Julian | ||||
| 45729 | ** epoch of noon in Greenwich on November 24, 4714 B.C according to the | ||||
| 45730 | ** proleptic Gregorian calendar. | ||||
| 45731 | ** | ||||
| 45732 | ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date | ||||
| 45733 | ** cannot be found. | ||||
| 45734 | */ | ||||
| 45735 | static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ | ||||
| 45736 | static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; | ||||
| 45737 | int rc = SQLITE_OK0; | ||||
| 45738 | #if defined(NO_GETTOD) | ||||
| 45739 | time_t t; | ||||
| 45740 | time(&t); | ||||
| 45741 | *piNow = ((sqlite3_int64)t)*1000 + unixEpoch; | ||||
| 45742 | #elif OS_VXWORKS0 | ||||
| 45743 | struct timespec sNow; | ||||
| 45744 | clock_gettime(CLOCK_REALTIME0, &sNow); | ||||
| 45745 | *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000; | ||||
| 45746 | #else | ||||
| 45747 | struct timeval sNow; | ||||
| 45748 | (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */ | ||||
| 45749 | *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; | ||||
| 45750 | #endif | ||||
| 45751 | |||||
| 45752 | #ifdef SQLITE_TEST | ||||
| 45753 | if( sqlite3_current_time ){ | ||||
| 45754 | *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; | ||||
| 45755 | } | ||||
| 45756 | #endif | ||||
| 45757 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45758 | return rc; | ||||
| 45759 | } | ||||
| 45760 | |||||
| 45761 | #ifndef SQLITE_OMIT_DEPRECATED1 | ||||
| 45762 | /* | ||||
| 45763 | ** Find the current time (in Universal Coordinated Time). Write the | ||||
| 45764 | ** current time and date as a Julian Day number into *prNow and | ||||
| 45765 | ** return 0. Return 1 if the time and date cannot be found. | ||||
| 45766 | */ | ||||
| 45767 | static int unixCurrentTime0(sqlite3_vfs *NotUsed, double *prNow){ | ||||
| 45768 | sqlite3_int64 i = 0; | ||||
| 45769 | int rc; | ||||
| 45770 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45771 | rc = unixCurrentTimeInt64(0, &i); | ||||
| 45772 | *prNow = i/86400000.0; | ||||
| 45773 | return rc; | ||||
| 45774 | } | ||||
| 45775 | #else | ||||
| 45776 | # define unixCurrentTime0 0 | ||||
| 45777 | #endif | ||||
| 45778 | |||||
| 45779 | /* | ||||
| 45780 | ** The xGetLastError() method is designed to return a better | ||||
| 45781 | ** low-level error message when operating-system problems come up | ||||
| 45782 | ** during SQLite operation. Only the integer return code is currently | ||||
| 45783 | ** used. | ||||
| 45784 | */ | ||||
| 45785 | static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ | ||||
| 45786 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 45787 | UNUSED_PARAMETER(NotUsed2)(void)(NotUsed2); | ||||
| 45788 | UNUSED_PARAMETER(NotUsed3)(void)(NotUsed3); | ||||
| 45789 | return errno(*__errno_location ()); | ||||
| 45790 | } | ||||
| 45791 | |||||
| 45792 | |||||
| 45793 | /* | ||||
| 45794 | ************************ End of sqlite3_vfs methods *************************** | ||||
| 45795 | ******************************************************************************/ | ||||
| 45796 | |||||
| 45797 | /****************************************************************************** | ||||
| 45798 | ************************** Begin Proxy Locking ******************************** | ||||
| 45799 | ** | ||||
| 45800 | ** Proxy locking is a "uber-locking-method" in this sense: It uses the | ||||
| 45801 | ** other locking methods on secondary lock files. Proxy locking is a | ||||
| 45802 | ** meta-layer over top of the primitive locking implemented above. For | ||||
| 45803 | ** this reason, the division that implements of proxy locking is deferred | ||||
| 45804 | ** until late in the file (here) after all of the other I/O methods have | ||||
| 45805 | ** been defined - so that the primitive locking methods are available | ||||
| 45806 | ** as services to help with the implementation of proxy locking. | ||||
| 45807 | ** | ||||
| 45808 | **** | ||||
| 45809 | ** | ||||
| 45810 | ** The default locking schemes in SQLite use byte-range locks on the | ||||
| 45811 | ** database file to coordinate safe, concurrent access by multiple readers | ||||
| 45812 | ** and writers [http://sqlite.org/lockingv3.html]. The five file locking | ||||
| 45813 | ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented | ||||
| 45814 | ** as POSIX read & write locks over fixed set of locations (via fsctl), | ||||
| 45815 | ** on AFP and SMB only exclusive byte-range locks are available via fsctl | ||||
| 45816 | ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states. | ||||
| 45817 | ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected | ||||
| 45818 | ** address in the shared range is taken for a SHARED lock, the entire | ||||
| 45819 | ** shared range is taken for an EXCLUSIVE lock): | ||||
| 45820 | ** | ||||
| 45821 | ** PENDING_BYTE 0x40000000 | ||||
| 45822 | ** RESERVED_BYTE 0x40000001 | ||||
| 45823 | ** SHARED_RANGE 0x40000002 -> 0x40000200 | ||||
| 45824 | ** | ||||
| 45825 | ** This works well on the local file system, but shows a nearly 100x | ||||
| 45826 | ** slowdown in read performance on AFP because the AFP client disables | ||||
| 45827 | ** the read cache when byte-range locks are present. Enabling the read | ||||
| 45828 | ** cache exposes a cache coherency problem that is present on all OS X | ||||
| 45829 | ** supported network file systems. NFS and AFP both observe the | ||||
| 45830 | ** close-to-open semantics for ensuring cache coherency | ||||
| 45831 | ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively | ||||
| 45832 | ** address the requirements for concurrent database access by multiple | ||||
| 45833 | ** readers and writers | ||||
| 45834 | ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html]. | ||||
| 45835 | ** | ||||
| 45836 | ** To address the performance and cache coherency issues, proxy file locking | ||||
| 45837 | ** changes the way database access is controlled by limiting access to a | ||||
| 45838 | ** single host at a time and moving file locks off of the database file | ||||
| 45839 | ** and onto a proxy file on the local file system. | ||||
| 45840 | ** | ||||
| 45841 | ** | ||||
| 45842 | ** Using proxy locks | ||||
| 45843 | ** ----------------- | ||||
| 45844 | ** | ||||
| 45845 | ** C APIs | ||||
| 45846 | ** | ||||
| 45847 | ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE, | ||||
| 45848 | ** <proxy_path> | ":auto:"); | ||||
| 45849 | ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE, | ||||
| 45850 | ** &<proxy_path>); | ||||
| 45851 | ** | ||||
| 45852 | ** | ||||
| 45853 | ** SQL pragmas | ||||
| 45854 | ** | ||||
| 45855 | ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto: | ||||
| 45856 | ** PRAGMA [database.]lock_proxy_file | ||||
| 45857 | ** | ||||
| 45858 | ** Specifying ":auto:" means that if there is a conch file with a matching | ||||
| 45859 | ** host ID in it, the proxy path in the conch file will be used, otherwise | ||||
| 45860 | ** a proxy path based on the user's temp dir | ||||
| 45861 | ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the | ||||
| 45862 | ** actual proxy file name is generated from the name and path of the | ||||
| 45863 | ** database file. For example: | ||||
| 45864 | ** | ||||
| 45865 | ** For database path "/Users/me/foo.db" | ||||
| 45866 | ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:") | ||||
| 45867 | ** | ||||
| 45868 | ** Once a lock proxy is configured for a database connection, it can not | ||||
| 45869 | ** be removed, however it may be switched to a different proxy path via | ||||
| 45870 | ** the above APIs (assuming the conch file is not being held by another | ||||
| 45871 | ** connection or process). | ||||
| 45872 | ** | ||||
| 45873 | ** | ||||
| 45874 | ** How proxy locking works | ||||
| 45875 | ** ----------------------- | ||||
| 45876 | ** | ||||
| 45877 | ** Proxy file locking relies primarily on two new supporting files: | ||||
| 45878 | ** | ||||
| 45879 | ** * conch file to limit access to the database file to a single host | ||||
| 45880 | ** at a time | ||||
| 45881 | ** | ||||
| 45882 | ** * proxy file to act as a proxy for the advisory locks normally | ||||
| 45883 | ** taken on the database | ||||
| 45884 | ** | ||||
| 45885 | ** The conch file - to use a proxy file, sqlite must first "hold the conch" | ||||
| 45886 | ** by taking an sqlite-style shared lock on the conch file, reading the | ||||
| 45887 | ** contents and comparing the host's unique host ID (see below) and lock | ||||
| 45888 | ** proxy path against the values stored in the conch. The conch file is | ||||
| 45889 | ** stored in the same directory as the database file and the file name | ||||
| 45890 | ** is patterned after the database file name as ".<databasename>-conch". | ||||
| 45891 | ** If the conch file does not exist, or its contents do not match the | ||||
| 45892 | ** host ID and/or proxy path, then the lock is escalated to an exclusive | ||||
| 45893 | ** lock and the conch file contents is updated with the host ID and proxy | ||||
| 45894 | ** path and the lock is downgraded to a shared lock again. If the conch | ||||
| 45895 | ** is held by another process (with a shared lock), the exclusive lock | ||||
| 45896 | ** will fail and SQLITE_BUSY is returned. | ||||
| 45897 | ** | ||||
| 45898 | ** The proxy file - a single-byte file used for all advisory file locks | ||||
| 45899 | ** normally taken on the database file. This allows for safe sharing | ||||
| 45900 | ** of the database file for multiple readers and writers on the same | ||||
| 45901 | ** host (the conch ensures that they all use the same local lock file). | ||||
| 45902 | ** | ||||
| 45903 | ** Requesting the lock proxy does not immediately take the conch, it is | ||||
| 45904 | ** only taken when the first request to lock database file is made. | ||||
| 45905 | ** This matches the semantics of the traditional locking behavior, where | ||||
| 45906 | ** opening a connection to a database file does not take a lock on it. | ||||
| 45907 | ** The shared lock and an open file descriptor are maintained until | ||||
| 45908 | ** the connection to the database is closed. | ||||
| 45909 | ** | ||||
| 45910 | ** The proxy file and the lock file are never deleted so they only need | ||||
| 45911 | ** to be created the first time they are used. | ||||
| 45912 | ** | ||||
| 45913 | ** Configuration options | ||||
| 45914 | ** --------------------- | ||||
| 45915 | ** | ||||
| 45916 | ** SQLITE_PREFER_PROXY_LOCKING | ||||
| 45917 | ** | ||||
| 45918 | ** Database files accessed on non-local file systems are | ||||
| 45919 | ** automatically configured for proxy locking, lock files are | ||||
| 45920 | ** named automatically using the same logic as | ||||
| 45921 | ** PRAGMA lock_proxy_file=":auto:" | ||||
| 45922 | ** | ||||
| 45923 | ** SQLITE_PROXY_DEBUG | ||||
| 45924 | ** | ||||
| 45925 | ** Enables the logging of error messages during host id file | ||||
| 45926 | ** retrieval and creation | ||||
| 45927 | ** | ||||
| 45928 | ** LOCKPROXYDIR | ||||
| 45929 | ** | ||||
| 45930 | ** Overrides the default directory used for lock proxy files that | ||||
| 45931 | ** are named automatically via the ":auto:" setting | ||||
| 45932 | ** | ||||
| 45933 | ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS | ||||
| 45934 | ** | ||||
| 45935 | ** Permissions to use when creating a directory for storing the | ||||
| 45936 | ** lock proxy files, only used when LOCKPROXYDIR is not set. | ||||
| 45937 | ** | ||||
| 45938 | ** | ||||
| 45939 | ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING, | ||||
| 45940 | ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will | ||||
| 45941 | ** force proxy locking to be used for every database file opened, and 0 | ||||
| 45942 | ** will force automatic proxy locking to be disabled for all database | ||||
| 45943 | ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or | ||||
| 45944 | ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING). | ||||
| 45945 | */ | ||||
| 45946 | |||||
| 45947 | /* | ||||
| 45948 | ** Proxy locking is only available on MacOSX | ||||
| 45949 | */ | ||||
| 45950 | #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 45951 | |||||
| 45952 | /* | ||||
| 45953 | ** The proxyLockingContext has the path and file structures for the remote | ||||
| 45954 | ** and local proxy files in it | ||||
| 45955 | */ | ||||
| 45956 | typedef struct proxyLockingContext proxyLockingContext; | ||||
| 45957 | struct proxyLockingContext { | ||||
| 45958 | unixFile *conchFile; /* Open conch file */ | ||||
| 45959 | char *conchFilePath; /* Name of the conch file */ | ||||
| 45960 | unixFile *lockProxy; /* Open proxy lock file */ | ||||
| 45961 | char *lockProxyPath; /* Name of the proxy lock file */ | ||||
| 45962 | char *dbPath; /* Name of the open file */ | ||||
| 45963 | int conchHeld; /* 1 if the conch is held, -1 if lockless */ | ||||
| 45964 | int nFails; /* Number of conch taking failures */ | ||||
| 45965 | void *oldLockingContext; /* Original lockingcontext to restore on close */ | ||||
| 45966 | sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ | ||||
| 45967 | }; | ||||
| 45968 | |||||
| 45969 | /* | ||||
| 45970 | ** The proxy lock file path for the database at dbPath is written into lPath, | ||||
| 45971 | ** which must point to valid, writable memory large enough for a maxLen length | ||||
| 45972 | ** file path. | ||||
| 45973 | */ | ||||
| 45974 | static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ | ||||
| 45975 | int len; | ||||
| 45976 | int dbLen; | ||||
| 45977 | int i; | ||||
| 45978 | |||||
| 45979 | #ifdef LOCKPROXYDIR | ||||
| 45980 | len = strlcpy(lPath, LOCKPROXYDIR, maxLen); | ||||
| 45981 | #else | ||||
| 45982 | # ifdef _CS_DARWIN_USER_TEMP_DIR | ||||
| 45983 | { | ||||
| 45984 | if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){ | ||||
| 45985 | OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n", | ||||
| 45986 | lPath, errno, osGetpid(0))); | ||||
| 45987 | return SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 45988 | } | ||||
| 45989 | len = strlcat(lPath, "sqliteplocks", maxLen); | ||||
| 45990 | } | ||||
| 45991 | # else | ||||
| 45992 | len = strlcpy(lPath, "/tmp/", maxLen); | ||||
| 45993 | # endif | ||||
| 45994 | #endif | ||||
| 45995 | |||||
| 45996 | if( lPath[len-1]!='/' ){ | ||||
| 45997 | len = strlcat(lPath, "/", maxLen); | ||||
| 45998 | } | ||||
| 45999 | |||||
| 46000 | /* transform the db path to a unique cache name */ | ||||
| 46001 | dbLen = (int)strlen(dbPath); | ||||
| 46002 | for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){ | ||||
| 46003 | char c = dbPath[i]; | ||||
| 46004 | lPath[i+len] = (c=='/')?'_':c; | ||||
| 46005 | } | ||||
| 46006 | lPath[i+len]='\0'; | ||||
| 46007 | strlcat(lPath, ":auto:", maxLen); | ||||
| 46008 | OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0))); | ||||
| 46009 | return SQLITE_OK0; | ||||
| 46010 | } | ||||
| 46011 | |||||
| 46012 | /* | ||||
| 46013 | ** Creates the lock file and any missing directories in lockPath | ||||
| 46014 | */ | ||||
| 46015 | static int proxyCreateLockPath(const char *lockPath){ | ||||
| 46016 | int i, len; | ||||
| 46017 | char buf[MAXPATHLEN]; | ||||
| 46018 | int start = 0; | ||||
| 46019 | |||||
| 46020 | assert(lockPath!=NULL)((void) (0)); | ||||
| 46021 | /* try to create all the intermediate directories */ | ||||
| 46022 | len = (int)strlen(lockPath); | ||||
| 46023 | buf[0] = lockPath[0]; | ||||
| 46024 | for( i=1; i<len; i++ ){ | ||||
| 46025 | if( lockPath[i] == '/' && (i - start > 0) ){ | ||||
| 46026 | /* only mkdir if leaf dir != "." or "/" or ".." */ | ||||
| 46027 | if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') | ||||
| 46028 | || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ | ||||
| 46029 | buf[i]='\0'; | ||||
| 46030 | if( osMkdir((int(*)(const char*,mode_t))aSyscall[18].pCurrent)(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS0755) ){ | ||||
| 46031 | int err=errno(*__errno_location ()); | ||||
| 46032 | if( err!=EEXIST17 ) { | ||||
| 46033 | OSTRACE(("CREATELOCKPATH FAILED creating %s, " | ||||
| 46034 | "'%s' proxy lock path=%s pid=%d\n", | ||||
| 46035 | buf, strerror(err), lockPath, osGetpid(0))); | ||||
| 46036 | return err; | ||||
| 46037 | } | ||||
| 46038 | } | ||||
| 46039 | } | ||||
| 46040 | start=i+1; | ||||
| 46041 | } | ||||
| 46042 | buf[i] = lockPath[i]; | ||||
| 46043 | } | ||||
| 46044 | OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0))); | ||||
| 46045 | return 0; | ||||
| 46046 | } | ||||
| 46047 | |||||
| 46048 | /* | ||||
| 46049 | ** Create a new VFS file descriptor (stored in memory obtained from | ||||
| 46050 | ** sqlite3_malloc) and open the file named "path" in the file descriptor. | ||||
| 46051 | ** | ||||
| 46052 | ** The caller is responsible not only for closing the file descriptor | ||||
| 46053 | ** but also for freeing the memory associated with the file descriptor. | ||||
| 46054 | */ | ||||
| 46055 | static int proxyCreateUnixFile( | ||||
| 46056 | const char *path, /* path for the new unixFile */ | ||||
| 46057 | unixFile **ppFile, /* unixFile created and returned by ref */ | ||||
| 46058 | int islockfile /* if non zero missing dirs will be created */ | ||||
| 46059 | ) { | ||||
| 46060 | int fd = -1; | ||||
| 46061 | unixFile *pNew; | ||||
| 46062 | int rc = SQLITE_OK0; | ||||
| 46063 | int openFlags = O_RDWR02 | O_CREAT0100 | O_NOFOLLOW0400000; | ||||
| 46064 | sqlite3_vfs dummyVfs; | ||||
| 46065 | int terrno = 0; | ||||
| 46066 | UnixUnusedFd *pUnused = NULL((void*)0); | ||||
| 46067 | |||||
| 46068 | /* 1. first try to open/create the file | ||||
| 46069 | ** 2. if that fails, and this is a lock file (not-conch), try creating | ||||
| 46070 | ** the parent directories and then try again. | ||||
| 46071 | ** 3. if that fails, try to open the file read-only | ||||
| 46072 | ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file | ||||
| 46073 | */ | ||||
| 46074 | pUnused = findReusableFd(path, openFlags); | ||||
| 46075 | if( pUnused ){ | ||||
| 46076 | fd = pUnused->fd; | ||||
| 46077 | }else{ | ||||
| 46078 | pUnused = sqlite3_malloc64(sizeof(*pUnused)); | ||||
| 46079 | if( !pUnused ){ | ||||
| 46080 | return SQLITE_NOMEM_BKPT7; | ||||
| 46081 | } | ||||
| 46082 | } | ||||
| 46083 | if( fd<0 ){ | ||||
| 46084 | fd = robust_open(path, openFlags, 0); | ||||
| 46085 | terrno = errno(*__errno_location ()); | ||||
| 46086 | if( fd<0 && errno(*__errno_location ())==ENOENT2 && islockfile ){ | ||||
| 46087 | if( proxyCreateLockPath(path) == SQLITE_OK0 ){ | ||||
| 46088 | fd = robust_open(path, openFlags, 0); | ||||
| 46089 | } | ||||
| 46090 | } | ||||
| 46091 | } | ||||
| 46092 | if( fd<0 ){ | ||||
| 46093 | openFlags = O_RDONLY00 | O_NOFOLLOW0400000; | ||||
| 46094 | fd = robust_open(path, openFlags, 0); | ||||
| 46095 | terrno = errno(*__errno_location ()); | ||||
| 46096 | } | ||||
| 46097 | if( fd<0 ){ | ||||
| 46098 | if( islockfile ){ | ||||
| 46099 | return SQLITE_BUSY5; | ||||
| 46100 | } | ||||
| 46101 | switch (terrno) { | ||||
| 46102 | case EACCES13: | ||||
| 46103 | return SQLITE_PERM3; | ||||
| 46104 | case EIO5: | ||||
| 46105 | return SQLITE_IOERR_LOCK(10 | (15<<8)); /* even though it is the conch */ | ||||
| 46106 | default: | ||||
| 46107 | return SQLITE_CANTOPEN_BKPTsqlite3CantopenError(46107); | ||||
| 46108 | } | ||||
| 46109 | } | ||||
| 46110 | |||||
| 46111 | pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew)); | ||||
| 46112 | if( pNew==NULL((void*)0) ){ | ||||
| 46113 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 46114 | goto end_create_proxy; | ||||
| 46115 | } | ||||
| 46116 | memset(pNew, 0, sizeof(unixFile)); | ||||
| 46117 | pNew->openFlags = openFlags; | ||||
| 46118 | memset(&dummyVfs, 0, sizeof(dummyVfs)); | ||||
| 46119 | dummyVfs.pAppData = (void*)&autolockIoFinder; | ||||
| 46120 | dummyVfs.zName = "dummy"; | ||||
| 46121 | pUnused->fd = fd; | ||||
| 46122 | pUnused->flags = openFlags; | ||||
| 46123 | pNew->pPreallocatedUnused = pUnused; | ||||
| 46124 | |||||
| 46125 | rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0); | ||||
| 46126 | if( rc==SQLITE_OK0 ){ | ||||
| 46127 | *ppFile = pNew; | ||||
| 46128 | return SQLITE_OK0; | ||||
| 46129 | } | ||||
| 46130 | end_create_proxy: | ||||
| 46131 | robust_close(pNew, fd, __LINE__46131); | ||||
| 46132 | sqlite3_free(pNew); | ||||
| 46133 | sqlite3_free(pUnused); | ||||
| 46134 | return rc; | ||||
| 46135 | } | ||||
| 46136 | |||||
| 46137 | #ifdef SQLITE_TEST | ||||
| 46138 | /* simulate multiple hosts by creating unique hostid file paths */ | ||||
| 46139 | SQLITE_API int sqlite3_hostid_num = 0; | ||||
| 46140 | #endif | ||||
| 46141 | |||||
| 46142 | #define PROXY_HOSTIDLEN 16 /* conch file host id length */ | ||||
| 46143 | |||||
| 46144 | #if HAVE_GETHOSTUUID0 | ||||
| 46145 | /* Not always defined in the headers as it ought to be */ | ||||
| 46146 | extern int gethostuuid(uuid_t id, const struct timespec *wait); | ||||
| 46147 | #endif | ||||
| 46148 | |||||
| 46149 | /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN | ||||
| 46150 | ** bytes of writable memory. | ||||
| 46151 | */ | ||||
| 46152 | static int proxyGetHostID(unsigned char *pHostID, int *pError){ | ||||
| 46153 | assert(PROXY_HOSTIDLEN == sizeof(uuid_t))((void) (0)); | ||||
| 46154 | memset(pHostID, 0, PROXY_HOSTIDLEN); | ||||
| 46155 | #if HAVE_GETHOSTUUID0 | ||||
| 46156 | { | ||||
| 46157 | struct timespec timeout = {1, 0}; /* 1 sec timeout */ | ||||
| 46158 | if( gethostuuid(pHostID, &timeout) ){ | ||||
| 46159 | int err = errno(*__errno_location ()); | ||||
| 46160 | if( pError ){ | ||||
| 46161 | *pError = err; | ||||
| 46162 | } | ||||
| 46163 | return SQLITE_IOERR10; | ||||
| 46164 | } | ||||
| 46165 | } | ||||
| 46166 | #else | ||||
| 46167 | UNUSED_PARAMETER(pError)(void)(pError); | ||||
| 46168 | #endif | ||||
| 46169 | #ifdef SQLITE_TEST | ||||
| 46170 | /* simulate multiple hosts by creating unique hostid file paths */ | ||||
| 46171 | if( sqlite3_hostid_num != 0){ | ||||
| 46172 | pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); | ||||
| 46173 | } | ||||
| 46174 | #endif | ||||
| 46175 | |||||
| 46176 | return SQLITE_OK0; | ||||
| 46177 | } | ||||
| 46178 | |||||
| 46179 | /* The conch file contains the header, host id and lock file path | ||||
| 46180 | */ | ||||
| 46181 | #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */ | ||||
| 46182 | #define PROXY_HEADERLEN 1 /* conch file header length */ | ||||
| 46183 | #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN) | ||||
| 46184 | #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN) | ||||
| 46185 | |||||
| 46186 | /* | ||||
| 46187 | ** Takes an open conch file, copies the contents to a new path and then moves | ||||
| 46188 | ** it back. The newly created file's file descriptor is assigned to the | ||||
| 46189 | ** conch file structure and finally the original conch file descriptor is | ||||
| 46190 | ** closed. Returns zero if successful. | ||||
| 46191 | */ | ||||
| 46192 | static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ | ||||
| 46193 | proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46194 | unixFile *conchFile = pCtx->conchFile; | ||||
| 46195 | char tPath[MAXPATHLEN]; | ||||
| 46196 | char buf[PROXY_MAXCONCHLEN]; | ||||
| 46197 | char *cPath = pCtx->conchFilePath; | ||||
| 46198 | size_t readLen = 0; | ||||
| 46199 | size_t pathLen = 0; | ||||
| 46200 | char errmsg[64] = ""; | ||||
| 46201 | int fd = -1; | ||||
| 46202 | int rc = -1; | ||||
| 46203 | UNUSED_PARAMETER(myHostID)(void)(myHostID); | ||||
| 46204 | |||||
| 46205 | /* create a new path by replace the trailing '-conch' with '-break' */ | ||||
| 46206 | pathLen = strlcpy(tPath, cPath, MAXPATHLEN); | ||||
| 46207 | if( pathLen>MAXPATHLEN || pathLen<6 || | ||||
| 46208 | (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ | ||||
| 46209 | sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); | ||||
| 46210 | goto end_breaklock; | ||||
| 46211 | } | ||||
| 46212 | /* read the conch content */ | ||||
| 46213 | readLen = osPread((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); | ||||
| 46214 | if( readLen<PROXY_PATHINDEX ){ | ||||
| 46215 | sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen); | ||||
| 46216 | goto end_breaklock; | ||||
| 46217 | } | ||||
| 46218 | /* write it out to the temporary break file */ | ||||
| 46219 | fd = robust_open(tPath, (O_RDWR02|O_CREAT0100|O_EXCL0200|O_NOFOLLOW0400000), 0); | ||||
| 46220 | if( fd<0 ){ | ||||
| 46221 | sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno(*__errno_location ())); | ||||
| 46222 | goto end_breaklock; | ||||
| 46223 | } | ||||
| 46224 | if( osPwrite((ssize_t(*)(int,const void*,size_t,off_t)) aSyscall[12].pCurrent )(fd, buf, readLen, 0) != (ssize_t)readLen ){ | ||||
| 46225 | sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno(*__errno_location ())); | ||||
| 46226 | goto end_breaklock; | ||||
| 46227 | } | ||||
| 46228 | if( rename(tPath, cPath) ){ | ||||
| 46229 | sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno(*__errno_location ())); | ||||
| 46230 | goto end_breaklock; | ||||
| 46231 | } | ||||
| 46232 | rc = 0; | ||||
| 46233 | fprintf(stderrstderr, "broke stale lock on %s\n", cPath); | ||||
| 46234 | robust_close(pFile, conchFile->h, __LINE__46234); | ||||
| 46235 | conchFile->h = fd; | ||||
| 46236 | conchFile->openFlags = O_RDWR02 | O_CREAT0100; | ||||
| 46237 | |||||
| 46238 | end_breaklock: | ||||
| 46239 | if( rc ){ | ||||
| 46240 | if( fd>=0 ){ | ||||
| 46241 | osUnlink((int(*)(const char*))aSyscall[16].pCurrent)(tPath); | ||||
| 46242 | robust_close(pFile, fd, __LINE__46242); | ||||
| 46243 | } | ||||
| 46244 | fprintf(stderrstderr, "failed to break stale lock on %s, %s\n", cPath, errmsg); | ||||
| 46245 | } | ||||
| 46246 | return rc; | ||||
| 46247 | } | ||||
| 46248 | |||||
| 46249 | /* Take the requested lock on the conch file and break a stale lock if the | ||||
| 46250 | ** host id matches. | ||||
| 46251 | */ | ||||
| 46252 | static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ | ||||
| 46253 | proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46254 | unixFile *conchFile = pCtx->conchFile; | ||||
| 46255 | int rc = SQLITE_OK0; | ||||
| 46256 | int nTries = 0; | ||||
| 46257 | struct timespec conchModTime; | ||||
| 46258 | |||||
| 46259 | memset(&conchModTime, 0, sizeof(conchModTime)); | ||||
| 46260 | do { | ||||
| 46261 | rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); | ||||
| 46262 | nTries ++; | ||||
| 46263 | if( rc==SQLITE_BUSY5 ){ | ||||
| 46264 | /* If the lock failed (busy): | ||||
| 46265 | * 1st try: get the mod time of the conch, wait 0.5s and try again. | ||||
| 46266 | * 2nd try: fail if the mod time changed or host id is different, wait | ||||
| 46267 | * 10 sec and try again | ||||
| 46268 | * 3rd try: break the lock unless the mod time has changed. | ||||
| 46269 | */ | ||||
| 46270 | struct stat buf; | ||||
| 46271 | if( osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(conchFile->h, &buf) ){ | ||||
| 46272 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 46273 | return SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 46274 | } | ||||
| 46275 | |||||
| 46276 | if( nTries==1 ){ | ||||
| 46277 | conchModTime = buf.st_mtimespec; | ||||
| 46278 | unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/ | ||||
| 46279 | continue; | ||||
| 46280 | } | ||||
| 46281 | |||||
| 46282 | assert( nTries>1 )((void) (0)); | ||||
| 46283 | if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || | ||||
| 46284 | conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){ | ||||
| 46285 | return SQLITE_BUSY5; | ||||
| 46286 | } | ||||
| 46287 | |||||
| 46288 | if( nTries==2 ){ | ||||
| 46289 | char tBuf[PROXY_MAXCONCHLEN]; | ||||
| 46290 | int len = osPread((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); | ||||
| 46291 | if( len<0 ){ | ||||
| 46292 | storeLastErrno(pFile, errno(*__errno_location ())); | ||||
| 46293 | return SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 46294 | } | ||||
| 46295 | if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){ | ||||
| 46296 | /* don't break the lock if the host id doesn't match */ | ||||
| 46297 | if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){ | ||||
| 46298 | return SQLITE_BUSY5; | ||||
| 46299 | } | ||||
| 46300 | }else{ | ||||
| 46301 | /* don't break the lock on short read or a version mismatch */ | ||||
| 46302 | return SQLITE_BUSY5; | ||||
| 46303 | } | ||||
| 46304 | unixSleep(0,10000000); /* wait 10 sec and try the lock again */ | ||||
| 46305 | continue; | ||||
| 46306 | } | ||||
| 46307 | |||||
| 46308 | assert( nTries==3 )((void) (0)); | ||||
| 46309 | if( 0==proxyBreakConchLock(pFile, myHostID) ){ | ||||
| 46310 | rc = SQLITE_OK0; | ||||
| 46311 | if( lockType==EXCLUSIVE_LOCK4 ){ | ||||
| 46312 | rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK1); | ||||
| 46313 | } | ||||
| 46314 | if( !rc ){ | ||||
| 46315 | rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); | ||||
| 46316 | } | ||||
| 46317 | } | ||||
| 46318 | } | ||||
| 46319 | } while( rc==SQLITE_BUSY5 && nTries<3 ); | ||||
| 46320 | |||||
| 46321 | return rc; | ||||
| 46322 | } | ||||
| 46323 | |||||
| 46324 | /* Takes the conch by taking a shared lock and read the contents conch, if | ||||
| 46325 | ** lockPath is non-NULL, the host ID and lock file path must match. A NULL | ||||
| 46326 | ** lockPath means that the lockPath in the conch file will be used if the | ||||
| 46327 | ** host IDs match, or a new lock path will be generated automatically | ||||
| 46328 | ** and written to the conch file. | ||||
| 46329 | */ | ||||
| 46330 | static int proxyTakeConch(unixFile *pFile){ | ||||
| 46331 | proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46332 | |||||
| 46333 | if( pCtx->conchHeld!=0 ){ | ||||
| 46334 | return SQLITE_OK0; | ||||
| 46335 | }else{ | ||||
| 46336 | unixFile *conchFile = pCtx->conchFile; | ||||
| 46337 | uuid_t myHostID; | ||||
| 46338 | int pError = 0; | ||||
| 46339 | char readBuf[PROXY_MAXCONCHLEN]; | ||||
| 46340 | char lockPath[MAXPATHLEN]; | ||||
| 46341 | char *tempLockPath = NULL((void*)0); | ||||
| 46342 | int rc = SQLITE_OK0; | ||||
| 46343 | int createConch = 0; | ||||
| 46344 | int hostIdMatch = 0; | ||||
| 46345 | int readLen = 0; | ||||
| 46346 | int tryOldLockPath = 0; | ||||
| 46347 | int forceNewLockPath = 0; | ||||
| 46348 | |||||
| 46349 | OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h, | ||||
| 46350 | (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), | ||||
| 46351 | osGetpid(0))); | ||||
| 46352 | |||||
| 46353 | rc = proxyGetHostID(myHostID, &pError); | ||||
| 46354 | if( (rc&0xff)==SQLITE_IOERR10 ){ | ||||
| 46355 | storeLastErrno(pFile, pError); | ||||
| 46356 | goto end_takeconch; | ||||
| 46357 | } | ||||
| 46358 | rc = proxyConchLock(pFile, myHostID, SHARED_LOCK1); | ||||
| 46359 | if( rc!=SQLITE_OK0 ){ | ||||
| 46360 | goto end_takeconch; | ||||
| 46361 | } | ||||
| 46362 | /* read the existing conch file */ | ||||
| 46363 | readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN); | ||||
| 46364 | if( readLen<0 ){ | ||||
| 46365 | /* I/O error: lastErrno set by seekAndRead */ | ||||
| 46366 | storeLastErrno(pFile, conchFile->lastErrno); | ||||
| 46367 | rc = SQLITE_IOERR_READ(10 | (1<<8)); | ||||
| 46368 | goto end_takeconch; | ||||
| 46369 | }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || | ||||
| 46370 | readBuf[0]!=(char)PROXY_CONCHVERSION ){ | ||||
| 46371 | /* a short read or version format mismatch means we need to create a new | ||||
| 46372 | ** conch file. | ||||
| 46373 | */ | ||||
| 46374 | createConch = 1; | ||||
| 46375 | } | ||||
| 46376 | /* if the host id matches and the lock path already exists in the conch | ||||
| 46377 | ** we'll try to use the path there, if we can't open that path, we'll | ||||
| 46378 | ** retry with a new auto-generated path | ||||
| 46379 | */ | ||||
| 46380 | do { /* in case we need to try again for an :auto: named lock file */ | ||||
| 46381 | |||||
| 46382 | if( !createConch && !forceNewLockPath ){ | ||||
| 46383 | hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, | ||||
| 46384 | PROXY_HOSTIDLEN); | ||||
| 46385 | /* if the conch has data compare the contents */ | ||||
| 46386 | if( !pCtx->lockProxyPath ){ | ||||
| 46387 | /* for auto-named local lock file, just check the host ID and we'll | ||||
| 46388 | ** use the local lock file path that's already in there | ||||
| 46389 | */ | ||||
| 46390 | if( hostIdMatch ){ | ||||
| 46391 | size_t pathLen = (readLen - PROXY_PATHINDEX); | ||||
| 46392 | |||||
| 46393 | if( pathLen>=MAXPATHLEN ){ | ||||
| 46394 | pathLen=MAXPATHLEN-1; | ||||
| 46395 | } | ||||
| 46396 | memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); | ||||
| 46397 | lockPath[pathLen] = 0; | ||||
| 46398 | tempLockPath = lockPath; | ||||
| 46399 | tryOldLockPath = 1; | ||||
| 46400 | /* create a copy of the lock path if the conch is taken */ | ||||
| 46401 | goto end_takeconch; | ||||
| 46402 | } | ||||
| 46403 | }else if( hostIdMatch | ||||
| 46404 | && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], | ||||
| 46405 | readLen-PROXY_PATHINDEX) | ||||
| 46406 | ){ | ||||
| 46407 | /* conch host and lock path match */ | ||||
| 46408 | goto end_takeconch; | ||||
| 46409 | } | ||||
| 46410 | } | ||||
| 46411 | |||||
| 46412 | /* if the conch isn't writable and doesn't match, we can't take it */ | ||||
| 46413 | if( (conchFile->openFlags&O_RDWR02) == 0 ){ | ||||
| 46414 | rc = SQLITE_BUSY5; | ||||
| 46415 | goto end_takeconch; | ||||
| 46416 | } | ||||
| 46417 | |||||
| 46418 | /* either the conch didn't match or we need to create a new one */ | ||||
| 46419 | if( !pCtx->lockProxyPath ){ | ||||
| 46420 | proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); | ||||
| 46421 | tempLockPath = lockPath; | ||||
| 46422 | /* create a copy of the lock path _only_ if the conch is taken */ | ||||
| 46423 | } | ||||
| 46424 | |||||
| 46425 | /* update conch with host and path (this will fail if other process | ||||
| 46426 | ** has a shared lock already), if the host id matches, use the big | ||||
| 46427 | ** stick. | ||||
| 46428 | */ | ||||
| 46429 | futimes(conchFile->h, NULL((void*)0)); | ||||
| 46430 | if( hostIdMatch && !createConch ){ | ||||
| 46431 | if( conchFile->pInode && conchFile->pInode->nShared>1 ){ | ||||
| 46432 | /* We are trying for an exclusive lock but another thread in this | ||||
| 46433 | ** same process is still holding a shared lock. */ | ||||
| 46434 | rc = SQLITE_BUSY5; | ||||
| 46435 | } else { | ||||
| 46436 | rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK4); | ||||
| 46437 | } | ||||
| 46438 | }else{ | ||||
| 46439 | rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK4); | ||||
| 46440 | } | ||||
| 46441 | if( rc==SQLITE_OK0 ){ | ||||
| 46442 | char writeBuffer[PROXY_MAXCONCHLEN]; | ||||
| 46443 | int writeSize = 0; | ||||
| 46444 | |||||
| 46445 | writeBuffer[0] = (char)PROXY_CONCHVERSION; | ||||
| 46446 | memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); | ||||
| 46447 | if( pCtx->lockProxyPath!=NULL((void*)0) ){ | ||||
| 46448 | strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, | ||||
| 46449 | MAXPATHLEN); | ||||
| 46450 | }else{ | ||||
| 46451 | strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN); | ||||
| 46452 | } | ||||
| 46453 | writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); | ||||
| 46454 | robust_ftruncate(conchFile->h, writeSize); | ||||
| 46455 | rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); | ||||
| 46456 | full_fsync(conchFile->h,0,0); | ||||
| 46457 | /* If we created a new conch file (not just updated the contents of a | ||||
| 46458 | ** valid conch file), try to match the permissions of the database | ||||
| 46459 | */ | ||||
| 46460 | if( rc==SQLITE_OK0 && createConch ){ | ||||
| 46461 | struct stat buf; | ||||
| 46462 | int err = osFstat((int(*)(int,struct stat*))aSyscall[5].pCurrent)(pFile->h, &buf); | ||||
| 46463 | if( err==0 ){ | ||||
| 46464 | mode_t cmode = buf.st_mode&(S_IRUSR0400|S_IWUSR0200 | S_IRGRP(0400 >> 3)|S_IWGRP(0200 >> 3) | | ||||
| 46465 | S_IROTH((0400 >> 3) >> 3)|S_IWOTH((0200 >> 3) >> 3)); | ||||
| 46466 | /* try to match the database file R/W permissions, ignore failure */ | ||||
| 46467 | #ifndef SQLITE_PROXY_DEBUG | ||||
| 46468 | osFchmod((int(*)(int,mode_t))aSyscall[14].pCurrent)(conchFile->h, cmode); | ||||
| 46469 | #else | ||||
| 46470 | do{ | ||||
| 46471 | rc = osFchmod((int(*)(int,mode_t))aSyscall[14].pCurrent)(conchFile->h, cmode); | ||||
| 46472 | }while( rc==(-1) && errno(*__errno_location ())==EINTR4 ); | ||||
| 46473 | if( rc!=0 ){ | ||||
| 46474 | int code = errno(*__errno_location ()); | ||||
| 46475 | fprintf(stderrstderr, "fchmod %o FAILED with %d %s\n", | ||||
| 46476 | cmode, code, strerror(code)); | ||||
| 46477 | } else { | ||||
| 46478 | fprintf(stderrstderr, "fchmod %o SUCCEDED\n",cmode); | ||||
| 46479 | } | ||||
| 46480 | }else{ | ||||
| 46481 | int code = errno(*__errno_location ()); | ||||
| 46482 | fprintf(stderrstderr, "STAT FAILED[%d] with %d %s\n", | ||||
| 46483 | err, code, strerror(code)); | ||||
| 46484 | #endif | ||||
| 46485 | } | ||||
| 46486 | } | ||||
| 46487 | } | ||||
| 46488 | conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK1); | ||||
| 46489 | |||||
| 46490 | end_takeconch: | ||||
| 46491 | OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); | ||||
| 46492 | if( rc==SQLITE_OK0 && pFile->openFlags ){ | ||||
| 46493 | int fd; | ||||
| 46494 | if( pFile->h>=0 ){ | ||||
| 46495 | robust_close(pFile, pFile->h, __LINE__46495); | ||||
| 46496 | } | ||||
| 46497 | pFile->h = -1; | ||||
| 46498 | fd = robust_open(pCtx->dbPath, pFile->openFlags, 0); | ||||
| 46499 | OSTRACE(("TRANSPROXY: OPEN %d\n", fd)); | ||||
| 46500 | if( fd>=0 ){ | ||||
| 46501 | pFile->h = fd; | ||||
| 46502 | }else{ | ||||
| 46503 | rc=SQLITE_CANTOPEN_BKPTsqlite3CantopenError(46503); /* SQLITE_BUSY? proxyTakeConch called | ||||
| 46504 | during locking */ | ||||
| 46505 | } | ||||
| 46506 | } | ||||
| 46507 | if( rc==SQLITE_OK0 && !pCtx->lockProxy ){ | ||||
| 46508 | char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; | ||||
| 46509 | rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); | ||||
| 46510 | if( rc!=SQLITE_OK0 && rc!=SQLITE_NOMEM7 && tryOldLockPath ){ | ||||
| 46511 | /* we couldn't create the proxy lock file with the old lock file path | ||||
| 46512 | ** so try again via auto-naming | ||||
| 46513 | */ | ||||
| 46514 | forceNewLockPath = 1; | ||||
| 46515 | tryOldLockPath = 0; | ||||
| 46516 | continue; /* go back to the do {} while start point, try again */ | ||||
| 46517 | } | ||||
| 46518 | } | ||||
| 46519 | if( rc==SQLITE_OK0 ){ | ||||
| 46520 | /* Need to make a copy of path if we extracted the value | ||||
| 46521 | ** from the conch file or the path was allocated on the stack | ||||
| 46522 | */ | ||||
| 46523 | if( tempLockPath ){ | ||||
| 46524 | pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); | ||||
| 46525 | if( !pCtx->lockProxyPath ){ | ||||
| 46526 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 46527 | } | ||||
| 46528 | } | ||||
| 46529 | } | ||||
| 46530 | if( rc==SQLITE_OK0 ){ | ||||
| 46531 | pCtx->conchHeld = 1; | ||||
| 46532 | |||||
| 46533 | if( pCtx->lockProxy->pMethod == &afpIoMethods ){ | ||||
| 46534 | afpLockingContext *afpCtx; | ||||
| 46535 | afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; | ||||
| 46536 | afpCtx->dbPath = pCtx->lockProxyPath; | ||||
| 46537 | } | ||||
| 46538 | } else { | ||||
| 46539 | conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK0); | ||||
| 46540 | } | ||||
| 46541 | OSTRACE(("TAKECONCH %d %s\n", conchFile->h, | ||||
| 46542 | rc==SQLITE_OK?"ok":"failed")); | ||||
| 46543 | return rc; | ||||
| 46544 | } while (1); /* in case we need to retry the :auto: lock file - | ||||
| 46545 | ** we should never get here except via the 'continue' call. */ | ||||
| 46546 | } | ||||
| 46547 | } | ||||
| 46548 | |||||
| 46549 | /* | ||||
| 46550 | ** If pFile holds a lock on a conch file, then release that lock. | ||||
| 46551 | */ | ||||
| 46552 | static int proxyReleaseConch(unixFile *pFile){ | ||||
| 46553 | int rc = SQLITE_OK0; /* Subroutine return code */ | ||||
| 46554 | proxyLockingContext *pCtx; /* The locking context for the proxy lock */ | ||||
| 46555 | unixFile *conchFile; /* Name of the conch file */ | ||||
| 46556 | |||||
| 46557 | pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46558 | conchFile = pCtx->conchFile; | ||||
| 46559 | OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h, | ||||
| 46560 | (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), | ||||
| 46561 | osGetpid(0))); | ||||
| 46562 | if( pCtx->conchHeld>0 ){ | ||||
| 46563 | rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK0); | ||||
| 46564 | } | ||||
| 46565 | pCtx->conchHeld = 0; | ||||
| 46566 | OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, | ||||
| 46567 | (rc==SQLITE_OK ? "ok" : "failed"))); | ||||
| 46568 | return rc; | ||||
| 46569 | } | ||||
| 46570 | |||||
| 46571 | /* | ||||
| 46572 | ** Given the name of a database file, compute the name of its conch file. | ||||
| 46573 | ** Store the conch filename in memory obtained from sqlite3_malloc64(). | ||||
| 46574 | ** Make *pConchPath point to the new name. Return SQLITE_OK on success | ||||
| 46575 | ** or SQLITE_NOMEM if unable to obtain memory. | ||||
| 46576 | ** | ||||
| 46577 | ** The caller is responsible for ensuring that the allocated memory | ||||
| 46578 | ** space is eventually freed. | ||||
| 46579 | ** | ||||
| 46580 | ** *pConchPath is set to NULL if a memory allocation error occurs. | ||||
| 46581 | */ | ||||
| 46582 | static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ | ||||
| 46583 | int i; /* Loop counter */ | ||||
| 46584 | int len = (int)strlen(dbPath); /* Length of database filename - dbPath */ | ||||
| 46585 | char *conchPath; /* buffer in which to construct conch name */ | ||||
| 46586 | |||||
| 46587 | /* Allocate space for the conch filename and initialize the name to | ||||
| 46588 | ** the name of the original database file. */ | ||||
| 46589 | *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8); | ||||
| 46590 | if( conchPath==0 ){ | ||||
| 46591 | return SQLITE_NOMEM_BKPT7; | ||||
| 46592 | } | ||||
| 46593 | memcpy(conchPath, dbPath, len+1); | ||||
| 46594 | |||||
| 46595 | /* now insert a "." before the last / character */ | ||||
| 46596 | for( i=(len-1); i>=0; i-- ){ | ||||
| 46597 | if( conchPath[i]=='/' ){ | ||||
| 46598 | i++; | ||||
| 46599 | break; | ||||
| 46600 | } | ||||
| 46601 | } | ||||
| 46602 | conchPath[i]='.'; | ||||
| 46603 | while ( i<len ){ | ||||
| 46604 | conchPath[i+1]=dbPath[i]; | ||||
| 46605 | i++; | ||||
| 46606 | } | ||||
| 46607 | |||||
| 46608 | /* append the "-conch" suffix to the file */ | ||||
| 46609 | memcpy(&conchPath[i+1], "-conch", 7); | ||||
| 46610 | assert( (int)strlen(conchPath) == len+7 )((void) (0)); | ||||
| 46611 | |||||
| 46612 | return SQLITE_OK0; | ||||
| 46613 | } | ||||
| 46614 | |||||
| 46615 | |||||
| 46616 | /* Takes a fully configured proxy locking-style unix file and switches | ||||
| 46617 | ** the local lock file path | ||||
| 46618 | */ | ||||
| 46619 | static int switchLockProxyPath(unixFile *pFile, const char *path) { | ||||
| 46620 | proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; | ||||
| 46621 | char *oldPath = pCtx->lockProxyPath; | ||||
| 46622 | int rc = SQLITE_OK0; | ||||
| 46623 | |||||
| 46624 | if( pFile->eFileLock!=NO_LOCK0 ){ | ||||
| 46625 | return SQLITE_BUSY5; | ||||
| 46626 | } | ||||
| 46627 | |||||
| 46628 | /* nothing to do if the path is NULL, :auto: or matches the existing path */ | ||||
| 46629 | if( !path || path[0]=='\0' || !strcmp(path, ":auto:") || | ||||
| 46630 | (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){ | ||||
| 46631 | return SQLITE_OK0; | ||||
| 46632 | }else{ | ||||
| 46633 | unixFile *lockProxy = pCtx->lockProxy; | ||||
| 46634 | pCtx->lockProxy=NULL((void*)0); | ||||
| 46635 | pCtx->conchHeld = 0; | ||||
| 46636 | if( lockProxy!=NULL((void*)0) ){ | ||||
| 46637 | rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); | ||||
| 46638 | if( rc ) return rc; | ||||
| 46639 | sqlite3_free(lockProxy); | ||||
| 46640 | } | ||||
| 46641 | sqlite3_free(oldPath); | ||||
| 46642 | pCtx->lockProxyPath = sqlite3DbStrDup(0, path); | ||||
| 46643 | } | ||||
| 46644 | |||||
| 46645 | return rc; | ||||
| 46646 | } | ||||
| 46647 | |||||
| 46648 | /* | ||||
| 46649 | ** pFile is a file that has been opened by a prior xOpen call. dbPath | ||||
| 46650 | ** is a string buffer at least MAXPATHLEN+1 characters in size. | ||||
| 46651 | ** | ||||
| 46652 | ** This routine find the filename associated with pFile and writes it | ||||
| 46653 | ** int dbPath. | ||||
| 46654 | */ | ||||
| 46655 | static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ | ||||
| 46656 | #if defined(__APPLE__) | ||||
| 46657 | if( pFile->pMethod == &afpIoMethods ){ | ||||
| 46658 | /* afp style keeps a reference to the db path in the filePath field | ||||
| 46659 | ** of the struct */ | ||||
| 46660 | assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN )((void) (0)); | ||||
| 46661 | strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, | ||||
| 46662 | MAXPATHLEN); | ||||
| 46663 | } else | ||||
| 46664 | #endif | ||||
| 46665 | if( pFile->pMethod == &dotlockIoMethods ){ | ||||
| 46666 | /* dot lock style uses the locking context to store the dot lock | ||||
| 46667 | ** file path */ | ||||
| 46668 | int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX".lock"); | ||||
| 46669 | memcpy(dbPath, (char *)pFile->lockingContext, len + 1); | ||||
| 46670 | }else{ | ||||
| 46671 | /* all other styles use the locking context to store the db file path */ | ||||
| 46672 | assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN )((void) (0)); | ||||
| 46673 | strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); | ||||
| 46674 | } | ||||
| 46675 | return SQLITE_OK0; | ||||
| 46676 | } | ||||
| 46677 | |||||
| 46678 | /* | ||||
| 46679 | ** Takes an already filled in unix file and alters it so all file locking | ||||
| 46680 | ** will be performed on the local proxy lock file. The following fields | ||||
| 46681 | ** are preserved in the locking context so that they can be restored and | ||||
| 46682 | ** the unix structure properly cleaned up at close time: | ||||
| 46683 | ** ->lockingContext | ||||
| 46684 | ** ->pMethod | ||||
| 46685 | */ | ||||
| 46686 | static int proxyTransformUnixFile(unixFile *pFile, const char *path) { | ||||
| 46687 | proxyLockingContext *pCtx; | ||||
| 46688 | char dbPath[MAXPATHLEN+1]; /* Name of the database file */ | ||||
| 46689 | char *lockPath=NULL((void*)0); | ||||
| 46690 | int rc = SQLITE_OK0; | ||||
| 46691 | |||||
| 46692 | if( pFile->eFileLock!=NO_LOCK0 ){ | ||||
| 46693 | return SQLITE_BUSY5; | ||||
| 46694 | } | ||||
| 46695 | proxyGetDbPathForUnixFile(pFile, dbPath); | ||||
| 46696 | if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){ | ||||
| 46697 | lockPath=NULL((void*)0); | ||||
| 46698 | }else{ | ||||
| 46699 | lockPath=(char *)path; | ||||
| 46700 | } | ||||
| 46701 | |||||
| 46702 | OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, | ||||
| 46703 | (lockPath ? lockPath : ":auto:"), osGetpid(0))); | ||||
| 46704 | |||||
| 46705 | pCtx = sqlite3_malloc64( sizeof(*pCtx) ); | ||||
| 46706 | if( pCtx==0 ){ | ||||
| 46707 | return SQLITE_NOMEM_BKPT7; | ||||
| 46708 | } | ||||
| 46709 | memset(pCtx, 0, sizeof(*pCtx)); | ||||
| 46710 | |||||
| 46711 | rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); | ||||
| 46712 | if( rc==SQLITE_OK0 ){ | ||||
| 46713 | rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); | ||||
| 46714 | if( rc==SQLITE_CANTOPEN14 && ((pFile->openFlags&O_RDWR02) == 0) ){ | ||||
| 46715 | /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and | ||||
| 46716 | ** (c) the file system is read-only, then enable no-locking access. | ||||
| 46717 | ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts | ||||
| 46718 | ** that openFlags will have only one of O_RDONLY or O_RDWR. | ||||
| 46719 | */ | ||||
| 46720 | struct statfs fsInfo; | ||||
| 46721 | struct stat conchInfo; | ||||
| 46722 | int goLockless = 0; | ||||
| 46723 | |||||
| 46724 | if( osStat((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)(pCtx->conchFilePath, &conchInfo) == -1 ) { | ||||
| 46725 | int err = errno(*__errno_location ()); | ||||
| 46726 | if( (err==ENOENT2) && (statfs(dbPath, &fsInfo) != -1) ){ | ||||
| 46727 | goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY; | ||||
| 46728 | } | ||||
| 46729 | } | ||||
| 46730 | if( goLockless ){ | ||||
| 46731 | pCtx->conchHeld = -1; /* read only FS/ lockless */ | ||||
| 46732 | rc = SQLITE_OK0; | ||||
| 46733 | } | ||||
| 46734 | } | ||||
| 46735 | } | ||||
| 46736 | if( rc==SQLITE_OK0 && lockPath ){ | ||||
| 46737 | pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); | ||||
| 46738 | } | ||||
| 46739 | |||||
| 46740 | if( rc==SQLITE_OK0 ){ | ||||
| 46741 | pCtx->dbPath = sqlite3DbStrDup(0, dbPath); | ||||
| 46742 | if( pCtx->dbPath==NULL((void*)0) ){ | ||||
| 46743 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 46744 | } | ||||
| 46745 | } | ||||
| 46746 | if( rc==SQLITE_OK0 ){ | ||||
| 46747 | /* all memory is allocated, proxys are created and assigned, | ||||
| 46748 | ** switch the locking context and pMethod then return. | ||||
| 46749 | */ | ||||
| 46750 | pCtx->oldLockingContext = pFile->lockingContext; | ||||
| 46751 | pFile->lockingContext = pCtx; | ||||
| 46752 | pCtx->pOldMethod = pFile->pMethod; | ||||
| 46753 | pFile->pMethod = &proxyIoMethods; | ||||
| 46754 | }else{ | ||||
| 46755 | if( pCtx->conchFile ){ | ||||
| 46756 | pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); | ||||
| 46757 | sqlite3_free(pCtx->conchFile); | ||||
| 46758 | } | ||||
| 46759 | sqlite3DbFree(0, pCtx->lockProxyPath); | ||||
| 46760 | sqlite3_free(pCtx->conchFilePath); | ||||
| 46761 | sqlite3_free(pCtx); | ||||
| 46762 | } | ||||
| 46763 | OSTRACE(("TRANSPROXY %d %s\n", pFile->h, | ||||
| 46764 | (rc==SQLITE_OK ? "ok" : "failed"))); | ||||
| 46765 | return rc; | ||||
| 46766 | } | ||||
| 46767 | |||||
| 46768 | |||||
| 46769 | /* | ||||
| 46770 | ** This routine handles sqlite3_file_control() calls that are specific | ||||
| 46771 | ** to proxy locking. | ||||
| 46772 | */ | ||||
| 46773 | static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ | ||||
| 46774 | switch( op ){ | ||||
| 46775 | case SQLITE_FCNTL_GET_LOCKPROXYFILE2: { | ||||
| 46776 | unixFile *pFile = (unixFile*)id; | ||||
| 46777 | if( pFile->pMethod == &proxyIoMethods ){ | ||||
| 46778 | proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; | ||||
| 46779 | proxyTakeConch(pFile); | ||||
| 46780 | if( pCtx->lockProxyPath ){ | ||||
| 46781 | *(const char **)pArg = pCtx->lockProxyPath; | ||||
| 46782 | }else{ | ||||
| 46783 | *(const char **)pArg = ":auto: (not held)"; | ||||
| 46784 | } | ||||
| 46785 | } else { | ||||
| 46786 | *(const char **)pArg = NULL((void*)0); | ||||
| 46787 | } | ||||
| 46788 | return SQLITE_OK0; | ||||
| 46789 | } | ||||
| 46790 | case SQLITE_FCNTL_SET_LOCKPROXYFILE3: { | ||||
| 46791 | unixFile *pFile = (unixFile*)id; | ||||
| 46792 | int rc = SQLITE_OK0; | ||||
| 46793 | int isProxyStyle = (pFile->pMethod == &proxyIoMethods); | ||||
| 46794 | if( pArg==NULL((void*)0) || (const char *)pArg==0 ){ | ||||
| 46795 | if( isProxyStyle ){ | ||||
| 46796 | /* turn off proxy locking - not supported. If support is added for | ||||
| 46797 | ** switching proxy locking mode off then it will need to fail if | ||||
| 46798 | ** the journal mode is WAL mode. | ||||
| 46799 | */ | ||||
| 46800 | rc = SQLITE_ERROR1 /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/; | ||||
| 46801 | }else{ | ||||
| 46802 | /* turn off proxy locking - already off - NOOP */ | ||||
| 46803 | rc = SQLITE_OK0; | ||||
| 46804 | } | ||||
| 46805 | }else{ | ||||
| 46806 | const char *proxyPath = (const char *)pArg; | ||||
| 46807 | if( isProxyStyle ){ | ||||
| 46808 | proxyLockingContext *pCtx = | ||||
| 46809 | (proxyLockingContext*)pFile->lockingContext; | ||||
| 46810 | if( !strcmp(pArg, ":auto:") | ||||
| 46811 | || (pCtx->lockProxyPath && | ||||
| 46812 | !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN)) | ||||
| 46813 | ){ | ||||
| 46814 | rc = SQLITE_OK0; | ||||
| 46815 | }else{ | ||||
| 46816 | rc = switchLockProxyPath(pFile, proxyPath); | ||||
| 46817 | } | ||||
| 46818 | }else{ | ||||
| 46819 | /* turn on proxy file locking */ | ||||
| 46820 | rc = proxyTransformUnixFile(pFile, proxyPath); | ||||
| 46821 | } | ||||
| 46822 | } | ||||
| 46823 | return rc; | ||||
| 46824 | } | ||||
| 46825 | default: { | ||||
| 46826 | assert( 0 )((void) (0)); /* The call assures that only valid opcodes are sent */ | ||||
| 46827 | } | ||||
| 46828 | } | ||||
| 46829 | /*NOTREACHED*/ assert(0)((void) (0)); | ||||
| 46830 | return SQLITE_ERROR1; | ||||
| 46831 | } | ||||
| 46832 | |||||
| 46833 | /* | ||||
| 46834 | ** Within this division (the proxying locking implementation) the procedures | ||||
| 46835 | ** above this point are all utilities. The lock-related methods of the | ||||
| 46836 | ** proxy-locking sqlite3_io_method object follow. | ||||
| 46837 | */ | ||||
| 46838 | |||||
| 46839 | |||||
| 46840 | /* | ||||
| 46841 | ** This routine checks if there is a RESERVED lock held on the specified | ||||
| 46842 | ** file by this or any other process. If such a lock is held, set *pResOut | ||||
| 46843 | ** to a non-zero value otherwise *pResOut is set to zero. The return value | ||||
| 46844 | ** is set to SQLITE_OK unless an I/O error occurs during lock checking. | ||||
| 46845 | */ | ||||
| 46846 | static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { | ||||
| 46847 | unixFile *pFile = (unixFile*)id; | ||||
| 46848 | int rc = proxyTakeConch(pFile); | ||||
| 46849 | if( rc==SQLITE_OK0 ){ | ||||
| 46850 | proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46851 | if( pCtx->conchHeld>0 ){ | ||||
| 46852 | unixFile *proxy = pCtx->lockProxy; | ||||
| 46853 | return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); | ||||
| 46854 | }else{ /* conchHeld < 0 is lockless */ | ||||
| 46855 | pResOut=0; | ||||
| 46856 | } | ||||
| 46857 | } | ||||
| 46858 | return rc; | ||||
| 46859 | } | ||||
| 46860 | |||||
| 46861 | /* | ||||
| 46862 | ** Lock the file with the lock specified by parameter eFileLock - one | ||||
| 46863 | ** of the following: | ||||
| 46864 | ** | ||||
| 46865 | ** (1) SHARED_LOCK | ||||
| 46866 | ** (2) RESERVED_LOCK | ||||
| 46867 | ** (3) PENDING_LOCK | ||||
| 46868 | ** (4) EXCLUSIVE_LOCK | ||||
| 46869 | ** | ||||
| 46870 | ** Sometimes when requesting one lock state, additional lock states | ||||
| 46871 | ** are inserted in between. The locking might fail on one of the later | ||||
| 46872 | ** transitions leaving the lock state different from what it started but | ||||
| 46873 | ** still short of its goal. The following chart shows the allowed | ||||
| 46874 | ** transitions and the inserted intermediate states: | ||||
| 46875 | ** | ||||
| 46876 | ** UNLOCKED -> SHARED | ||||
| 46877 | ** SHARED -> RESERVED | ||||
| 46878 | ** SHARED -> (PENDING) -> EXCLUSIVE | ||||
| 46879 | ** RESERVED -> (PENDING) -> EXCLUSIVE | ||||
| 46880 | ** PENDING -> EXCLUSIVE | ||||
| 46881 | ** | ||||
| 46882 | ** This routine will only increase a lock. Use the sqlite3OsUnlock() | ||||
| 46883 | ** routine to lower a locking level. | ||||
| 46884 | */ | ||||
| 46885 | static int proxyLock(sqlite3_file *id, int eFileLock) { | ||||
| 46886 | unixFile *pFile = (unixFile*)id; | ||||
| 46887 | int rc = proxyTakeConch(pFile); | ||||
| 46888 | if( rc==SQLITE_OK0 ){ | ||||
| 46889 | proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46890 | if( pCtx->conchHeld>0 ){ | ||||
| 46891 | unixFile *proxy = pCtx->lockProxy; | ||||
| 46892 | rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); | ||||
| 46893 | pFile->eFileLock = proxy->eFileLock; | ||||
| 46894 | }else{ | ||||
| 46895 | /* conchHeld < 0 is lockless */ | ||||
| 46896 | } | ||||
| 46897 | } | ||||
| 46898 | return rc; | ||||
| 46899 | } | ||||
| 46900 | |||||
| 46901 | |||||
| 46902 | /* | ||||
| 46903 | ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock | ||||
| 46904 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 46905 | ** | ||||
| 46906 | ** If the locking level of the file descriptor is already at or below | ||||
| 46907 | ** the requested locking level, this routine is a no-op. | ||||
| 46908 | */ | ||||
| 46909 | static int proxyUnlock(sqlite3_file *id, int eFileLock) { | ||||
| 46910 | unixFile *pFile = (unixFile*)id; | ||||
| 46911 | int rc = proxyTakeConch(pFile); | ||||
| 46912 | if( rc==SQLITE_OK0 ){ | ||||
| 46913 | proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46914 | if( pCtx->conchHeld>0 ){ | ||||
| 46915 | unixFile *proxy = pCtx->lockProxy; | ||||
| 46916 | rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); | ||||
| 46917 | pFile->eFileLock = proxy->eFileLock; | ||||
| 46918 | }else{ | ||||
| 46919 | /* conchHeld < 0 is lockless */ | ||||
| 46920 | } | ||||
| 46921 | } | ||||
| 46922 | return rc; | ||||
| 46923 | } | ||||
| 46924 | |||||
| 46925 | /* | ||||
| 46926 | ** Close a file that uses proxy locks. | ||||
| 46927 | */ | ||||
| 46928 | static int proxyClose(sqlite3_file *id) { | ||||
| 46929 | if( ALWAYS(id)(id) ){ | ||||
| 46930 | unixFile *pFile = (unixFile*)id; | ||||
| 46931 | proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; | ||||
| 46932 | unixFile *lockProxy = pCtx->lockProxy; | ||||
| 46933 | unixFile *conchFile = pCtx->conchFile; | ||||
| 46934 | int rc = SQLITE_OK0; | ||||
| 46935 | |||||
| 46936 | if( lockProxy ){ | ||||
| 46937 | rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK0); | ||||
| 46938 | if( rc ) return rc; | ||||
| 46939 | rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); | ||||
| 46940 | if( rc ) return rc; | ||||
| 46941 | sqlite3_free(lockProxy); | ||||
| 46942 | pCtx->lockProxy = 0; | ||||
| 46943 | } | ||||
| 46944 | if( conchFile ){ | ||||
| 46945 | if( pCtx->conchHeld ){ | ||||
| 46946 | rc = proxyReleaseConch(pFile); | ||||
| 46947 | if( rc ) return rc; | ||||
| 46948 | } | ||||
| 46949 | rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); | ||||
| 46950 | if( rc ) return rc; | ||||
| 46951 | sqlite3_free(conchFile); | ||||
| 46952 | } | ||||
| 46953 | sqlite3DbFree(0, pCtx->lockProxyPath); | ||||
| 46954 | sqlite3_free(pCtx->conchFilePath); | ||||
| 46955 | sqlite3DbFree(0, pCtx->dbPath); | ||||
| 46956 | /* restore the original locking context and pMethod then close it */ | ||||
| 46957 | pFile->lockingContext = pCtx->oldLockingContext; | ||||
| 46958 | pFile->pMethod = pCtx->pOldMethod; | ||||
| 46959 | sqlite3_free(pCtx); | ||||
| 46960 | return pFile->pMethod->xClose(id); | ||||
| 46961 | } | ||||
| 46962 | return SQLITE_OK0; | ||||
| 46963 | } | ||||
| 46964 | |||||
| 46965 | |||||
| 46966 | |||||
| 46967 | #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ | ||||
| 46968 | /* | ||||
| 46969 | ** The proxy locking style is intended for use with AFP filesystems. | ||||
| 46970 | ** And since AFP is only supported on MacOSX, the proxy locking is also | ||||
| 46971 | ** restricted to MacOSX. | ||||
| 46972 | ** | ||||
| 46973 | ** | ||||
| 46974 | ******************* End of the proxy lock implementation ********************** | ||||
| 46975 | ******************************************************************************/ | ||||
| 46976 | |||||
| 46977 | /* | ||||
| 46978 | ** Initialize the operating system interface. | ||||
| 46979 | ** | ||||
| 46980 | ** This routine registers all VFS implementations for unix-like operating | ||||
| 46981 | ** systems. This routine, and the sqlite3_os_end() routine that follows, | ||||
| 46982 | ** should be the only routines in this file that are visible from other | ||||
| 46983 | ** files. | ||||
| 46984 | ** | ||||
| 46985 | ** This routine is called once during SQLite initialization and by a | ||||
| 46986 | ** single thread. The memory allocation and mutex subsystems have not | ||||
| 46987 | ** necessarily been initialized when this routine is called, and so they | ||||
| 46988 | ** should not be used. | ||||
| 46989 | */ | ||||
| 46990 | SQLITE_API int sqlite3_os_init(void){ | ||||
| 46991 | /* | ||||
| 46992 | ** The following macro defines an initializer for an sqlite3_vfs object. | ||||
| 46993 | ** The name of the VFS is NAME. The pAppData is a pointer to a pointer | ||||
| 46994 | ** to the "finder" function. (pAppData is a pointer to a pointer because | ||||
| 46995 | ** silly C90 rules prohibit a void* from being cast to a function pointer | ||||
| 46996 | ** and so we have to go through the intermediate pointer to avoid problems | ||||
| 46997 | ** when compiling with -pedantic-errors on GCC.) | ||||
| 46998 | ** | ||||
| 46999 | ** The FINDER parameter to this macro is the name of the pointer to the | ||||
| 47000 | ** finder-function. The finder-function returns a pointer to the | ||||
| 47001 | ** sqlite_io_methods object that implements the desired locking | ||||
| 47002 | ** behaviors. See the division above that contains the IOMETHODS | ||||
| 47003 | ** macro for addition information on finder-functions. | ||||
| 47004 | ** | ||||
| 47005 | ** Most finders simply return a pointer to a fixed sqlite3_io_methods | ||||
| 47006 | ** object. But the "autolockIoFinder" available on MacOSX does a little | ||||
| 47007 | ** more than that; it looks at the filesystem type that hosts the | ||||
| 47008 | ** database file and tries to choose an locking method appropriate for | ||||
| 47009 | ** that filesystem time. | ||||
| 47010 | */ | ||||
| 47011 | #define UNIXVFS(VFSNAME, FINDER){ 3, sizeof(unixFile), 512, 0, VFSNAME, (void*)&FINDER, unixOpen , unixDelete, unixAccess, unixFullPathname, 0, 0, 0, 0, unixRandomness , unixSleep, 0, unixGetLastError, unixCurrentTimeInt64, unixSetSystemCall , unixGetSystemCall, unixNextSystemCall, } { \ | ||||
| 47012 | 3, /* iVersion */ \ | ||||
| 47013 | sizeof(unixFile), /* szOsFile */ \ | ||||
| 47014 | MAX_PATHNAME512, /* mxPathname */ \ | ||||
| 47015 | 0, /* pNext */ \ | ||||
| 47016 | VFSNAME, /* zName */ \ | ||||
| 47017 | (void*)&FINDER, /* pAppData */ \ | ||||
| 47018 | unixOpen, /* xOpen */ \ | ||||
| 47019 | unixDelete, /* xDelete */ \ | ||||
| 47020 | unixAccess, /* xAccess */ \ | ||||
| 47021 | unixFullPathname, /* xFullPathname */ \ | ||||
| 47022 | unixDlOpen0, /* xDlOpen */ \ | ||||
| 47023 | unixDlError0, /* xDlError */ \ | ||||
| 47024 | unixDlSym0, /* xDlSym */ \ | ||||
| 47025 | unixDlClose0, /* xDlClose */ \ | ||||
| 47026 | unixRandomness, /* xRandomness */ \ | ||||
| 47027 | unixSleep, /* xSleep */ \ | ||||
| 47028 | unixCurrentTime0, /* xCurrentTime */ \ | ||||
| 47029 | unixGetLastError, /* xGetLastError */ \ | ||||
| 47030 | unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \ | ||||
| 47031 | unixSetSystemCall, /* xSetSystemCall */ \ | ||||
| 47032 | unixGetSystemCall, /* xGetSystemCall */ \ | ||||
| 47033 | unixNextSystemCall, /* xNextSystemCall */ \ | ||||
| 47034 | } | ||||
| 47035 | |||||
| 47036 | /* | ||||
| 47037 | ** All default VFSes for unix are contained in the following array. | ||||
| 47038 | ** | ||||
| 47039 | ** Note that the sqlite3_vfs.pNext field of the VFS object is modified | ||||
| 47040 | ** by the SQLite core when the VFS is registered. So the following | ||||
| 47041 | ** array cannot be const. | ||||
| 47042 | */ | ||||
| 47043 | static sqlite3_vfs aVfs[] = { | ||||
| 47044 | #if SQLITE_ENABLE_LOCKING_STYLE0 && defined(__APPLE__) | ||||
| 47045 | UNIXVFS("unix", autolockIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix", (void*)&autolockIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47046 | #elif OS_VXWORKS0 | ||||
| 47047 | UNIXVFS("unix", vxworksIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix", (void*)&vxworksIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47048 | #else | ||||
| 47049 | UNIXVFS("unix", posixIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix", (void*)&posixIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47050 | #endif | ||||
| 47051 | UNIXVFS("unix-none", nolockIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-none", (void*)&nolockIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47052 | UNIXVFS("unix-dotfile", dotlockIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-dotfile", (void*)&dotlockIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47053 | UNIXVFS("unix-excl", posixIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-excl", (void*)&posixIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47054 | #if OS_VXWORKS0 | ||||
| 47055 | UNIXVFS("unix-namedsem", semIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-namedsem", (void*)&semIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47056 | #endif | ||||
| 47057 | #if SQLITE_ENABLE_LOCKING_STYLE0 || OS_VXWORKS0 | ||||
| 47058 | UNIXVFS("unix-posix", posixIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-posix", (void*)&posixIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47059 | #endif | ||||
| 47060 | #if SQLITE_ENABLE_LOCKING_STYLE0 | ||||
| 47061 | UNIXVFS("unix-flock", flockIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-flock", (void*)&flockIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47062 | #endif | ||||
| 47063 | #if SQLITE_ENABLE_LOCKING_STYLE0 && defined(__APPLE__) | ||||
| 47064 | UNIXVFS("unix-afp", afpIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-afp", (void*)&afpIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47065 | UNIXVFS("unix-nfs", nfsIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-nfs", (void*)&nfsIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47066 | UNIXVFS("unix-proxy", proxyIoFinder ){ 3, sizeof(unixFile), 512, 0, "unix-proxy", (void*)&proxyIoFinder , unixOpen, unixDelete, unixAccess, unixFullPathname, 0, 0, 0 , 0, unixRandomness, unixSleep, 0, unixGetLastError, unixCurrentTimeInt64 , unixSetSystemCall, unixGetSystemCall, unixNextSystemCall, }, | ||||
| 47067 | #endif | ||||
| 47068 | }; | ||||
| 47069 | unsigned int i; /* Loop counter */ | ||||
| 47070 | |||||
| 47071 | /* Double-check that the aSyscall[] array has been constructed | ||||
| 47072 | ** correctly. See ticket [bb3a86e890c8e96ab] */ | ||||
| 47073 | assert( ArraySize(aSyscall)==29 )((void) (0)); | ||||
| 47074 | |||||
| 47075 | /* Register all VFSes defined in the aVfs[] array */ | ||||
| 47076 | for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ | ||||
| 47077 | #ifdef SQLITE_DEFAULT_UNIX_VFS | ||||
| 47078 | sqlite3_vfs_register(&aVfs[i], | ||||
| 47079 | 0==strcmp(aVfs[i].zName,SQLITE_DEFAULT_UNIX_VFS)); | ||||
| 47080 | #else | ||||
| 47081 | sqlite3_vfs_register(&aVfs[i], i==0); | ||||
| 47082 | #endif | ||||
| 47083 | } | ||||
| 47084 | #ifdef SQLITE_OS_KV_OPTIONAL | ||||
| 47085 | sqlite3KvvfsInit(); | ||||
| 47086 | #endif | ||||
| 47087 | unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS111); | ||||
| 47088 | |||||
| 47089 | #ifndef SQLITE_OMIT_WAL | ||||
| 47090 | /* Validate lock assumptions */ | ||||
| 47091 | assert( SQLITE_SHM_NLOCK==8 )((void) (0)); /* Number of available locks */ | ||||
| 47092 | assert( UNIX_SHM_BASE==120 )((void) (0)); /* Start of locking area */ | ||||
| 47093 | /* Locks: | ||||
| 47094 | ** WRITE UNIX_SHM_BASE 120 | ||||
| 47095 | ** CKPT UNIX_SHM_BASE+1 121 | ||||
| 47096 | ** RECOVER UNIX_SHM_BASE+2 122 | ||||
| 47097 | ** READ-0 UNIX_SHM_BASE+3 123 | ||||
| 47098 | ** READ-1 UNIX_SHM_BASE+4 124 | ||||
| 47099 | ** READ-2 UNIX_SHM_BASE+5 125 | ||||
| 47100 | ** READ-3 UNIX_SHM_BASE+6 126 | ||||
| 47101 | ** READ-4 UNIX_SHM_BASE+7 127 | ||||
| 47102 | ** DMS UNIX_SHM_BASE+8 128 | ||||
| 47103 | */ | ||||
| 47104 | assert( UNIX_SHM_DMS==128 )((void) (0)); /* Byte offset of the deadman-switch */ | ||||
| 47105 | #endif | ||||
| 47106 | |||||
| 47107 | /* Initialize temp file dir array. */ | ||||
| 47108 | unixTempFileInit(); | ||||
| 47109 | |||||
| 47110 | return SQLITE_OK0; | ||||
| 47111 | } | ||||
| 47112 | |||||
| 47113 | /* | ||||
| 47114 | ** Shutdown the operating system interface. | ||||
| 47115 | ** | ||||
| 47116 | ** Some operating systems might need to do some cleanup in this routine, | ||||
| 47117 | ** to release dynamically allocated objects. But not on unix. | ||||
| 47118 | ** This routine is a no-op for unix. | ||||
| 47119 | */ | ||||
| 47120 | SQLITE_API int sqlite3_os_end(void){ | ||||
| 47121 | unixBigLock = 0; | ||||
| 47122 | return SQLITE_OK0; | ||||
| 47123 | } | ||||
| 47124 | |||||
| 47125 | #endif /* SQLITE_OS_UNIX */ | ||||
| 47126 | |||||
| 47127 | /************** End of os_unix.c *********************************************/ | ||||
| 47128 | /************** Begin file os_win.c ******************************************/ | ||||
| 47129 | /* | ||||
| 47130 | ** 2004 May 22 | ||||
| 47131 | ** | ||||
| 47132 | ** The author disclaims copyright to this source code. In place of | ||||
| 47133 | ** a legal notice, here is a blessing: | ||||
| 47134 | ** | ||||
| 47135 | ** May you do good and not evil. | ||||
| 47136 | ** May you find forgiveness for yourself and forgive others. | ||||
| 47137 | ** May you share freely, never taking more than you give. | ||||
| 47138 | ** | ||||
| 47139 | ****************************************************************************** | ||||
| 47140 | ** | ||||
| 47141 | ** This file contains code that is specific to Windows. | ||||
| 47142 | */ | ||||
| 47143 | /* #include "sqliteInt.h" */ | ||||
| 47144 | #if SQLITE_OS_WIN0 /* This file is used for Windows only */ | ||||
| 47145 | |||||
| 47146 | /* | ||||
| 47147 | ** Include code that is common to all os_*.c files | ||||
| 47148 | */ | ||||
| 47149 | /* #include "os_common.h" */ | ||||
| 47150 | |||||
| 47151 | /* | ||||
| 47152 | ** Include the header file for the Windows VFS. | ||||
| 47153 | */ | ||||
| 47154 | /* #include "os_win.h" */ | ||||
| 47155 | |||||
| 47156 | /* | ||||
| 47157 | ** Compiling and using WAL mode requires several APIs that are only | ||||
| 47158 | ** available in Windows platforms based on the NT kernel. | ||||
| 47159 | */ | ||||
| 47160 | #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL) | ||||
| 47161 | # error "WAL mode requires support from the Windows NT kernel, compile\ | ||||
| 47162 | with SQLITE_OMIT_WAL." | ||||
| 47163 | #endif | ||||
| 47164 | |||||
| 47165 | #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 47166 | # error "Memory mapped files require support from the Windows NT kernel,\ | ||||
| 47167 | compile with SQLITE_MAX_MMAP_SIZE=0." | ||||
| 47168 | #endif | ||||
| 47169 | |||||
| 47170 | /* | ||||
| 47171 | ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions | ||||
| 47172 | ** based on the sub-platform)? | ||||
| 47173 | */ | ||||
| 47174 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI) | ||||
| 47175 | # define SQLITE_WIN32_HAS_ANSI | ||||
| 47176 | #endif | ||||
| 47177 | |||||
| 47178 | /* | ||||
| 47179 | ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions | ||||
| 47180 | ** based on the sub-platform)? | ||||
| 47181 | */ | ||||
| 47182 | #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \ | ||||
| 47183 | !defined(SQLITE_WIN32_NO_WIDE) | ||||
| 47184 | # define SQLITE_WIN32_HAS_WIDE | ||||
| 47185 | #endif | ||||
| 47186 | |||||
| 47187 | /* | ||||
| 47188 | ** Make sure at least one set of Win32 APIs is available. | ||||
| 47189 | */ | ||||
| 47190 | #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47191 | # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\ | ||||
| 47192 | must be defined." | ||||
| 47193 | #endif | ||||
| 47194 | |||||
| 47195 | /* | ||||
| 47196 | ** Define the required Windows SDK version constants if they are not | ||||
| 47197 | ** already available. | ||||
| 47198 | */ | ||||
| 47199 | #ifndef NTDDI_WIN8 | ||||
| 47200 | # define NTDDI_WIN8 0x06020000 | ||||
| 47201 | #endif | ||||
| 47202 | |||||
| 47203 | #ifndef NTDDI_WINBLUE | ||||
| 47204 | # define NTDDI_WINBLUE 0x06030000 | ||||
| 47205 | #endif | ||||
| 47206 | |||||
| 47207 | #ifndef NTDDI_WINTHRESHOLD | ||||
| 47208 | # define NTDDI_WINTHRESHOLD 0x06040000 | ||||
| 47209 | #endif | ||||
| 47210 | |||||
| 47211 | /* | ||||
| 47212 | ** Check to see if the GetVersionEx[AW] functions are deprecated on the | ||||
| 47213 | ** target system. GetVersionEx was first deprecated in Win8.1. | ||||
| 47214 | */ | ||||
| 47215 | #ifndef SQLITE_WIN32_GETVERSIONEX | ||||
| 47216 | # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE | ||||
| 47217 | # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */ | ||||
| 47218 | # else | ||||
| 47219 | # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */ | ||||
| 47220 | # endif | ||||
| 47221 | #endif | ||||
| 47222 | |||||
| 47223 | /* | ||||
| 47224 | ** Check to see if the CreateFileMappingA function is supported on the | ||||
| 47225 | ** target system. It is unavailable when using "mincore.lib" on Win10. | ||||
| 47226 | ** When compiling for Windows 10, always assume "mincore.lib" is in use. | ||||
| 47227 | */ | ||||
| 47228 | #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA | ||||
| 47229 | # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD | ||||
| 47230 | # define SQLITE_WIN32_CREATEFILEMAPPINGA 0 | ||||
| 47231 | # else | ||||
| 47232 | # define SQLITE_WIN32_CREATEFILEMAPPINGA 1 | ||||
| 47233 | # endif | ||||
| 47234 | #endif | ||||
| 47235 | |||||
| 47236 | /* | ||||
| 47237 | ** This constant should already be defined (in the "WinDef.h" SDK file). | ||||
| 47238 | */ | ||||
| 47239 | #ifndef MAX_PATH | ||||
| 47240 | # define MAX_PATH (260) | ||||
| 47241 | #endif | ||||
| 47242 | |||||
| 47243 | /* | ||||
| 47244 | ** Maximum pathname length (in chars) for Win32. This should normally be | ||||
| 47245 | ** MAX_PATH. | ||||
| 47246 | */ | ||||
| 47247 | #ifndef SQLITE_WIN32_MAX_PATH_CHARS | ||||
| 47248 | # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH) | ||||
| 47249 | #endif | ||||
| 47250 | |||||
| 47251 | /* | ||||
| 47252 | ** This constant should already be defined (in the "WinNT.h" SDK file). | ||||
| 47253 | */ | ||||
| 47254 | #ifndef UNICODE_STRING_MAX_CHARS | ||||
| 47255 | # define UNICODE_STRING_MAX_CHARS (32767) | ||||
| 47256 | #endif | ||||
| 47257 | |||||
| 47258 | /* | ||||
| 47259 | ** Maximum pathname length (in chars) for WinNT. This should normally be | ||||
| 47260 | ** UNICODE_STRING_MAX_CHARS. | ||||
| 47261 | */ | ||||
| 47262 | #ifndef SQLITE_WINNT_MAX_PATH_CHARS | ||||
| 47263 | # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS) | ||||
| 47264 | #endif | ||||
| 47265 | |||||
| 47266 | /* | ||||
| 47267 | ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in | ||||
| 47268 | ** characters, so we allocate 4 bytes per character assuming worst-case of | ||||
| 47269 | ** 4-bytes-per-character for UTF8. | ||||
| 47270 | */ | ||||
| 47271 | #ifndef SQLITE_WIN32_MAX_PATH_BYTES | ||||
| 47272 | # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4) | ||||
| 47273 | #endif | ||||
| 47274 | |||||
| 47275 | /* | ||||
| 47276 | ** Maximum pathname length (in bytes) for WinNT. This should normally be | ||||
| 47277 | ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR). | ||||
| 47278 | */ | ||||
| 47279 | #ifndef SQLITE_WINNT_MAX_PATH_BYTES | ||||
| 47280 | # define SQLITE_WINNT_MAX_PATH_BYTES \ | ||||
| 47281 | (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS) | ||||
| 47282 | #endif | ||||
| 47283 | |||||
| 47284 | /* | ||||
| 47285 | ** Maximum error message length (in chars) for WinRT. | ||||
| 47286 | */ | ||||
| 47287 | #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS | ||||
| 47288 | # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024) | ||||
| 47289 | #endif | ||||
| 47290 | |||||
| 47291 | /* | ||||
| 47292 | ** Returns non-zero if the character should be treated as a directory | ||||
| 47293 | ** separator. | ||||
| 47294 | */ | ||||
| 47295 | #ifndef winIsDirSep | ||||
| 47296 | # define winIsDirSep(a) (((a) == '/') || ((a) == '\\')) | ||||
| 47297 | #endif | ||||
| 47298 | |||||
| 47299 | /* | ||||
| 47300 | ** This macro is used when a local variable is set to a value that is | ||||
| 47301 | ** [sometimes] not used by the code (e.g. via conditional compilation). | ||||
| 47302 | */ | ||||
| 47303 | #ifndef UNUSED_VARIABLE_VALUE | ||||
| 47304 | # define UNUSED_VARIABLE_VALUE(x) (void)(x) | ||||
| 47305 | #endif | ||||
| 47306 | |||||
| 47307 | /* | ||||
| 47308 | ** Returns the character that should be used as the directory separator. | ||||
| 47309 | */ | ||||
| 47310 | #ifndef winGetDirSep | ||||
| 47311 | # define winGetDirSep() '\\' | ||||
| 47312 | #endif | ||||
| 47313 | |||||
| 47314 | /* | ||||
| 47315 | ** Do we need to manually define the Win32 file mapping APIs for use with WAL | ||||
| 47316 | ** mode or memory mapped files (e.g. these APIs are available in the Windows | ||||
| 47317 | ** CE SDK; however, they are not present in the header file)? | ||||
| 47318 | */ | ||||
| 47319 | #if SQLITE_WIN32_FILEMAPPING_API && \ | ||||
| 47320 | (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) | ||||
| 47321 | /* | ||||
| 47322 | ** Two of the file mapping APIs are different under WinRT. Figure out which | ||||
| 47323 | ** set we need. | ||||
| 47324 | */ | ||||
| 47325 | #if SQLITE_OS_WINRT | ||||
| 47326 | WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \ | ||||
| 47327 | LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR); | ||||
| 47328 | |||||
| 47329 | WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T); | ||||
| 47330 | #else | ||||
| 47331 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47332 | WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \ | ||||
| 47333 | DWORD, DWORD, DWORD, LPCSTR); | ||||
| 47334 | #endif /* defined(SQLITE_WIN32_HAS_ANSI) */ | ||||
| 47335 | |||||
| 47336 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47337 | WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \ | ||||
| 47338 | DWORD, DWORD, DWORD, LPCWSTR); | ||||
| 47339 | #endif /* defined(SQLITE_WIN32_HAS_WIDE) */ | ||||
| 47340 | |||||
| 47341 | WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T); | ||||
| 47342 | #endif /* SQLITE_OS_WINRT */ | ||||
| 47343 | |||||
| 47344 | /* | ||||
| 47345 | ** These file mapping APIs are common to both Win32 and WinRT. | ||||
| 47346 | */ | ||||
| 47347 | |||||
| 47348 | WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T); | ||||
| 47349 | WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID); | ||||
| 47350 | #endif /* SQLITE_WIN32_FILEMAPPING_API */ | ||||
| 47351 | |||||
| 47352 | /* | ||||
| 47353 | ** Some Microsoft compilers lack this definition. | ||||
| 47354 | */ | ||||
| 47355 | #ifndef INVALID_FILE_ATTRIBUTES | ||||
| 47356 | # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) | ||||
| 47357 | #endif | ||||
| 47358 | |||||
| 47359 | #ifndef FILE_FLAG_MASK | ||||
| 47360 | # define FILE_FLAG_MASK (0xFF3C0000) | ||||
| 47361 | #endif | ||||
| 47362 | |||||
| 47363 | #ifndef FILE_ATTRIBUTE_MASK | ||||
| 47364 | # define FILE_ATTRIBUTE_MASK (0x0003FFF7) | ||||
| 47365 | #endif | ||||
| 47366 | |||||
| 47367 | #ifndef SQLITE_OMIT_WAL | ||||
| 47368 | /* Forward references to structures used for WAL */ | ||||
| 47369 | typedef struct winShm winShm; /* A connection to shared-memory */ | ||||
| 47370 | typedef struct winShmNode winShmNode; /* A region of shared-memory */ | ||||
| 47371 | #endif | ||||
| 47372 | |||||
| 47373 | /* | ||||
| 47374 | ** WinCE lacks native support for file locking so we have to fake it | ||||
| 47375 | ** with some code of our own. | ||||
| 47376 | */ | ||||
| 47377 | #if SQLITE_OS_WINCE | ||||
| 47378 | typedef struct winceLock { | ||||
| 47379 | int nReaders; /* Number of reader locks obtained */ | ||||
| 47380 | BOOL bPending; /* Indicates a pending lock has been obtained */ | ||||
| 47381 | BOOL bReserved; /* Indicates a reserved lock has been obtained */ | ||||
| 47382 | BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ | ||||
| 47383 | } winceLock; | ||||
| 47384 | #endif | ||||
| 47385 | |||||
| 47386 | /* | ||||
| 47387 | ** The winFile structure is a subclass of sqlite3_file* specific to the win32 | ||||
| 47388 | ** portability layer. | ||||
| 47389 | */ | ||||
| 47390 | typedef struct winFile winFile; | ||||
| 47391 | struct winFile { | ||||
| 47392 | const sqlite3_io_methods *pMethod; /*** Must be first ***/ | ||||
| 47393 | sqlite3_vfs *pVfs; /* The VFS used to open this file */ | ||||
| 47394 | HANDLE h; /* Handle for accessing the file */ | ||||
| 47395 | u8 locktype; /* Type of lock currently held on this file */ | ||||
| 47396 | short sharedLockByte; /* Randomly chosen byte used as a shared lock */ | ||||
| 47397 | u8 ctrlFlags; /* Flags. See WINFILE_* below */ | ||||
| 47398 | DWORD lastErrno; /* The Windows errno from the last I/O error */ | ||||
| 47399 | #ifndef SQLITE_OMIT_WAL | ||||
| 47400 | winShm *pShm; /* Instance of shared memory on this file */ | ||||
| 47401 | #endif | ||||
| 47402 | const char *zPath; /* Full pathname of this file */ | ||||
| 47403 | int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ | ||||
| 47404 | #if SQLITE_OS_WINCE | ||||
| 47405 | LPWSTR zDeleteOnClose; /* Name of file to delete when closing */ | ||||
| 47406 | HANDLE hMutex; /* Mutex used to control access to shared lock */ | ||||
| 47407 | HANDLE hShared; /* Shared memory segment used for locking */ | ||||
| 47408 | winceLock local; /* Locks obtained by this instance of winFile */ | ||||
| 47409 | winceLock *shared; /* Global shared lock memory for the file */ | ||||
| 47410 | #endif | ||||
| 47411 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 47412 | int nFetchOut; /* Number of outstanding xFetch references */ | ||||
| 47413 | HANDLE hMap; /* Handle for accessing memory mapping */ | ||||
| 47414 | void *pMapRegion; /* Area memory mapped */ | ||||
| 47415 | sqlite3_int64 mmapSize; /* Size of mapped region */ | ||||
| 47416 | sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ | ||||
| 47417 | #endif | ||||
| 47418 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 47419 | DWORD iBusyTimeout; /* Wait this many millisec on locks */ | ||||
| 47420 | int bBlockOnConnect; | ||||
| 47421 | #endif | ||||
| 47422 | }; | ||||
| 47423 | |||||
| 47424 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 47425 | # define winFileBusyTimeout(pDbFd) pDbFd->iBusyTimeout | ||||
| 47426 | #else | ||||
| 47427 | # define winFileBusyTimeout(pDbFd) 0 | ||||
| 47428 | #endif | ||||
| 47429 | |||||
| 47430 | /* | ||||
| 47431 | ** The winVfsAppData structure is used for the pAppData member for all of the | ||||
| 47432 | ** Win32 VFS variants. | ||||
| 47433 | */ | ||||
| 47434 | typedef struct winVfsAppData winVfsAppData; | ||||
| 47435 | struct winVfsAppData { | ||||
| 47436 | const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */ | ||||
| 47437 | void *pAppData; /* The extra pAppData, if any. */ | ||||
| 47438 | BOOL bNoLock; /* Non-zero if locking is disabled. */ | ||||
| 47439 | }; | ||||
| 47440 | |||||
| 47441 | /* | ||||
| 47442 | ** Allowed values for winFile.ctrlFlags | ||||
| 47443 | */ | ||||
| 47444 | #define WINFILE_RDONLY 0x02 /* Connection is read only */ | ||||
| 47445 | #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ | ||||
| 47446 | #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ | ||||
| 47447 | |||||
| 47448 | /* | ||||
| 47449 | * The size of the buffer used by sqlite3_win32_write_debug(). | ||||
| 47450 | */ | ||||
| 47451 | #ifndef SQLITE_WIN32_DBG_BUF_SIZE | ||||
| 47452 | # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD))) | ||||
| 47453 | #endif | ||||
| 47454 | |||||
| 47455 | /* | ||||
| 47456 | * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the | ||||
| 47457 | * various Win32 API heap functions instead of our own. | ||||
| 47458 | */ | ||||
| 47459 | #ifdef SQLITE_WIN32_MALLOC | ||||
| 47460 | |||||
| 47461 | /* | ||||
| 47462 | * If this is non-zero, an isolated heap will be created by the native Win32 | ||||
| 47463 | * allocator subsystem; otherwise, the default process heap will be used. This | ||||
| 47464 | * setting has no effect when compiling for WinRT. By default, this is enabled | ||||
| 47465 | * and an isolated heap will be created to store all allocated data. | ||||
| 47466 | * | ||||
| 47467 | ****************************************************************************** | ||||
| 47468 | * WARNING: It is important to note that when this setting is non-zero and the | ||||
| 47469 | * winMemShutdown function is called (e.g. by the sqlite3_shutdown | ||||
| 47470 | * function), all data that was allocated using the isolated heap will | ||||
| 47471 | * be freed immediately and any attempt to access any of that freed | ||||
| 47472 | * data will almost certainly result in an immediate access violation. | ||||
| 47473 | ****************************************************************************** | ||||
| 47474 | */ | ||||
| 47475 | #ifndef SQLITE_WIN32_HEAP_CREATE | ||||
| 47476 | # define SQLITE_WIN32_HEAP_CREATE (TRUE) | ||||
| 47477 | #endif | ||||
| 47478 | |||||
| 47479 | /* | ||||
| 47480 | * This is the maximum possible initial size of the Win32-specific heap, in | ||||
| 47481 | * bytes. | ||||
| 47482 | */ | ||||
| 47483 | #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE | ||||
| 47484 | # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U) | ||||
| 47485 | #endif | ||||
| 47486 | |||||
| 47487 | /* | ||||
| 47488 | * This is the extra space for the initial size of the Win32-specific heap, | ||||
| 47489 | * in bytes. This value may be zero. | ||||
| 47490 | */ | ||||
| 47491 | #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA | ||||
| 47492 | # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304) | ||||
| 47493 | #endif | ||||
| 47494 | |||||
| 47495 | /* | ||||
| 47496 | * Calculate the maximum legal cache size, in pages, based on the maximum | ||||
| 47497 | * possible initial heap size and the default page size, setting aside the | ||||
| 47498 | * needed extra space. | ||||
| 47499 | */ | ||||
| 47500 | #ifndef SQLITE_WIN32_MAX_CACHE_SIZE | ||||
| 47501 | # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \ | ||||
| 47502 | (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \ | ||||
| 47503 | (SQLITE_DEFAULT_PAGE_SIZE4096)) | ||||
| 47504 | #endif | ||||
| 47505 | |||||
| 47506 | /* | ||||
| 47507 | * This is cache size used in the calculation of the initial size of the | ||||
| 47508 | * Win32-specific heap. It cannot be negative. | ||||
| 47509 | */ | ||||
| 47510 | #ifndef SQLITE_WIN32_CACHE_SIZE | ||||
| 47511 | # if SQLITE_DEFAULT_CACHE_SIZE128>=0 | ||||
| 47512 | # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE128) | ||||
| 47513 | # else | ||||
| 47514 | # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE128)) | ||||
| 47515 | # endif | ||||
| 47516 | #endif | ||||
| 47517 | |||||
| 47518 | /* | ||||
| 47519 | * Make sure that the calculated cache size, in pages, cannot cause the | ||||
| 47520 | * initial size of the Win32-specific heap to exceed the maximum amount | ||||
| 47521 | * of memory that can be specified in the call to HeapCreate. | ||||
| 47522 | */ | ||||
| 47523 | #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE | ||||
| 47524 | # undef SQLITE_WIN32_CACHE_SIZE | ||||
| 47525 | # define SQLITE_WIN32_CACHE_SIZE (2000) | ||||
| 47526 | #endif | ||||
| 47527 | |||||
| 47528 | /* | ||||
| 47529 | * The initial size of the Win32-specific heap. This value may be zero. | ||||
| 47530 | */ | ||||
| 47531 | #ifndef SQLITE_WIN32_HEAP_INIT_SIZE | ||||
| 47532 | # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \ | ||||
| 47533 | (SQLITE_DEFAULT_PAGE_SIZE4096) + \ | ||||
| 47534 | (SQLITE_WIN32_HEAP_INIT_EXTRA)) | ||||
| 47535 | #endif | ||||
| 47536 | |||||
| 47537 | /* | ||||
| 47538 | * The maximum size of the Win32-specific heap. This value may be zero. | ||||
| 47539 | */ | ||||
| 47540 | #ifndef SQLITE_WIN32_HEAP_MAX_SIZE | ||||
| 47541 | # define SQLITE_WIN32_HEAP_MAX_SIZE (0) | ||||
| 47542 | #endif | ||||
| 47543 | |||||
| 47544 | /* | ||||
| 47545 | * The extra flags to use in calls to the Win32 heap APIs. This value may be | ||||
| 47546 | * zero for the default behavior. | ||||
| 47547 | */ | ||||
| 47548 | #ifndef SQLITE_WIN32_HEAP_FLAGS | ||||
| 47549 | # define SQLITE_WIN32_HEAP_FLAGS (0) | ||||
| 47550 | #endif | ||||
| 47551 | |||||
| 47552 | |||||
| 47553 | /* | ||||
| 47554 | ** The winMemData structure stores information required by the Win32-specific | ||||
| 47555 | ** sqlite3_mem_methods implementation. | ||||
| 47556 | */ | ||||
| 47557 | typedef struct winMemData winMemData; | ||||
| 47558 | struct winMemData { | ||||
| 47559 | #ifndef NDEBUG1 | ||||
| 47560 | u32 magic1; /* Magic number to detect structure corruption. */ | ||||
| 47561 | #endif | ||||
| 47562 | HANDLE hHeap; /* The handle to our heap. */ | ||||
| 47563 | BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */ | ||||
| 47564 | #ifndef NDEBUG1 | ||||
| 47565 | u32 magic2; /* Magic number to detect structure corruption. */ | ||||
| 47566 | #endif | ||||
| 47567 | }; | ||||
| 47568 | |||||
| 47569 | #ifndef NDEBUG1 | ||||
| 47570 | #define WINMEM_MAGIC1 0x42b2830b | ||||
| 47571 | #define WINMEM_MAGIC2 0xbd4d7cf4 | ||||
| 47572 | #endif | ||||
| 47573 | |||||
| 47574 | static struct winMemData win_mem_data = { | ||||
| 47575 | #ifndef NDEBUG1 | ||||
| 47576 | WINMEM_MAGIC1, | ||||
| 47577 | #endif | ||||
| 47578 | NULL((void*)0), FALSE | ||||
| 47579 | #ifndef NDEBUG1 | ||||
| 47580 | ,WINMEM_MAGIC2 | ||||
| 47581 | #endif | ||||
| 47582 | }; | ||||
| 47583 | |||||
| 47584 | #ifndef NDEBUG1 | ||||
| 47585 | #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )((void) (0)) | ||||
| 47586 | #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )((void) (0)) | ||||
| 47587 | #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2(); | ||||
| 47588 | #else | ||||
| 47589 | #define winMemAssertMagic() | ||||
| 47590 | #endif | ||||
| 47591 | |||||
| 47592 | #define winMemGetDataPtr() &win_mem_data | ||||
| 47593 | #define winMemGetHeap() win_mem_data.hHeap | ||||
| 47594 | #define winMemGetOwned() win_mem_data.bOwned | ||||
| 47595 | |||||
| 47596 | static void *winMemMalloc(int nBytes); | ||||
| 47597 | static void winMemFree(void *pPrior); | ||||
| 47598 | static void *winMemRealloc(void *pPrior, int nBytes); | ||||
| 47599 | static int winMemSize(void *p); | ||||
| 47600 | static int winMemRoundup(int n); | ||||
| 47601 | static int winMemInit(void *pAppData); | ||||
| 47602 | static void winMemShutdown(void *pAppData); | ||||
| 47603 | |||||
| 47604 | SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetWin32(void); | ||||
| 47605 | #endif /* SQLITE_WIN32_MALLOC */ | ||||
| 47606 | |||||
| 47607 | /* | ||||
| 47608 | ** The following variable is (normally) set once and never changes | ||||
| 47609 | ** thereafter. It records whether the operating system is Win9x | ||||
| 47610 | ** or WinNT. | ||||
| 47611 | ** | ||||
| 47612 | ** 0: Operating system unknown. | ||||
| 47613 | ** 1: Operating system is Win9x. | ||||
| 47614 | ** 2: Operating system is WinNT. | ||||
| 47615 | ** | ||||
| 47616 | ** In order to facilitate testing on a WinNT system, the test fixture | ||||
| 47617 | ** can manually set this value to 1 to emulate Win98 behavior. | ||||
| 47618 | */ | ||||
| 47619 | #ifdef SQLITE_TEST | ||||
| 47620 | SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; | ||||
| 47621 | #else | ||||
| 47622 | static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; | ||||
| 47623 | #endif | ||||
| 47624 | |||||
| 47625 | #ifndef SYSCALL | ||||
| 47626 | # define SYSCALL sqlite3_syscall_ptr | ||||
| 47627 | #endif | ||||
| 47628 | |||||
| 47629 | /* | ||||
| 47630 | ** This function is not available on Windows CE or WinRT. | ||||
| 47631 | */ | ||||
| 47632 | |||||
| 47633 | #if SQLITE_OS_WINCE || SQLITE_OS_WINRT | ||||
| 47634 | # define osAreFileApisANSI() 1 | ||||
| 47635 | #endif | ||||
| 47636 | |||||
| 47637 | /* | ||||
| 47638 | ** Many system calls are accessed through pointer-to-functions so that | ||||
| 47639 | ** they may be overridden at runtime to facilitate fault injection during | ||||
| 47640 | ** testing and sandboxing. The following array holds the names and pointers | ||||
| 47641 | ** to all overrideable system calls. | ||||
| 47642 | */ | ||||
| 47643 | static struct win_syscall { | ||||
| 47644 | const char *zName; /* Name of the system call */ | ||||
| 47645 | sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ | ||||
| 47646 | sqlite3_syscall_ptr pDefault; /* Default value */ | ||||
| 47647 | } aSyscall[] = { | ||||
| 47648 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT | ||||
| 47649 | { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 }, | ||||
| 47650 | #else | ||||
| 47651 | { "AreFileApisANSI", (SYSCALL)0, 0 }, | ||||
| 47652 | #endif | ||||
| 47653 | |||||
| 47654 | #ifndef osAreFileApisANSI | ||||
| 47655 | #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent) | ||||
| 47656 | #endif | ||||
| 47657 | |||||
| 47658 | #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47659 | { "CharLowerW", (SYSCALL)CharLowerW, 0 }, | ||||
| 47660 | #else | ||||
| 47661 | { "CharLowerW", (SYSCALL)0, 0 }, | ||||
| 47662 | #endif | ||||
| 47663 | |||||
| 47664 | #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent) | ||||
| 47665 | |||||
| 47666 | #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47667 | { "CharUpperW", (SYSCALL)CharUpperW, 0 }, | ||||
| 47668 | #else | ||||
| 47669 | { "CharUpperW", (SYSCALL)0, 0 }, | ||||
| 47670 | #endif | ||||
| 47671 | |||||
| 47672 | #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent) | ||||
| 47673 | |||||
| 47674 | { "CloseHandle", (SYSCALL)CloseHandle, 0 }, | ||||
| 47675 | |||||
| 47676 | #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent) | ||||
| 47677 | |||||
| 47678 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47679 | { "CreateFileA", (SYSCALL)CreateFileA, 0 }, | ||||
| 47680 | #else | ||||
| 47681 | { "CreateFileA", (SYSCALL)0, 0 }, | ||||
| 47682 | #endif | ||||
| 47683 | |||||
| 47684 | #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \ | ||||
| 47685 | LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent) | ||||
| 47686 | |||||
| 47687 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47688 | { "CreateFileW", (SYSCALL)CreateFileW, 0 }, | ||||
| 47689 | #else | ||||
| 47690 | { "CreateFileW", (SYSCALL)0, 0 }, | ||||
| 47691 | #endif | ||||
| 47692 | |||||
| 47693 | #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \ | ||||
| 47694 | LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent) | ||||
| 47695 | |||||
| 47696 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \ | ||||
| 47697 | (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) && \ | ||||
| 47698 | SQLITE_WIN32_CREATEFILEMAPPINGA | ||||
| 47699 | { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 }, | ||||
| 47700 | #else | ||||
| 47701 | { "CreateFileMappingA", (SYSCALL)0, 0 }, | ||||
| 47702 | #endif | ||||
| 47703 | |||||
| 47704 | #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ | ||||
| 47705 | DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent) | ||||
| 47706 | |||||
| 47707 | #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ | ||||
| 47708 | (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0)) | ||||
| 47709 | { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 }, | ||||
| 47710 | #else | ||||
| 47711 | { "CreateFileMappingW", (SYSCALL)0, 0 }, | ||||
| 47712 | #endif | ||||
| 47713 | |||||
| 47714 | #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ | ||||
| 47715 | DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent) | ||||
| 47716 | |||||
| 47717 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47718 | { "CreateMutexW", (SYSCALL)CreateMutexW, 0 }, | ||||
| 47719 | #else | ||||
| 47720 | { "CreateMutexW", (SYSCALL)0, 0 }, | ||||
| 47721 | #endif | ||||
| 47722 | |||||
| 47723 | #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \ | ||||
| 47724 | LPCWSTR))aSyscall[8].pCurrent) | ||||
| 47725 | |||||
| 47726 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47727 | { "DeleteFileA", (SYSCALL)DeleteFileA, 0 }, | ||||
| 47728 | #else | ||||
| 47729 | { "DeleteFileA", (SYSCALL)0, 0 }, | ||||
| 47730 | #endif | ||||
| 47731 | |||||
| 47732 | #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent) | ||||
| 47733 | |||||
| 47734 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47735 | { "DeleteFileW", (SYSCALL)DeleteFileW, 0 }, | ||||
| 47736 | #else | ||||
| 47737 | { "DeleteFileW", (SYSCALL)0, 0 }, | ||||
| 47738 | #endif | ||||
| 47739 | |||||
| 47740 | #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent) | ||||
| 47741 | |||||
| 47742 | #if SQLITE_OS_WINCE | ||||
| 47743 | { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 }, | ||||
| 47744 | #else | ||||
| 47745 | { "FileTimeToLocalFileTime", (SYSCALL)0, 0 }, | ||||
| 47746 | #endif | ||||
| 47747 | |||||
| 47748 | #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(const FILETIME*, \ | ||||
| 47749 | LPFILETIME))aSyscall[11].pCurrent) | ||||
| 47750 | |||||
| 47751 | #if SQLITE_OS_WINCE | ||||
| 47752 | { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 }, | ||||
| 47753 | #else | ||||
| 47754 | { "FileTimeToSystemTime", (SYSCALL)0, 0 }, | ||||
| 47755 | #endif | ||||
| 47756 | |||||
| 47757 | #define osFileTimeToSystemTime ((BOOL(WINAPI*)(const FILETIME*, \ | ||||
| 47758 | LPSYSTEMTIME))aSyscall[12].pCurrent) | ||||
| 47759 | |||||
| 47760 | { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 }, | ||||
| 47761 | |||||
| 47762 | #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent) | ||||
| 47763 | |||||
| 47764 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47765 | { "FormatMessageA", (SYSCALL)FormatMessageA, 0 }, | ||||
| 47766 | #else | ||||
| 47767 | { "FormatMessageA", (SYSCALL)0, 0 }, | ||||
| 47768 | #endif | ||||
| 47769 | |||||
| 47770 | #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \ | ||||
| 47771 | DWORD,va_list*))aSyscall[14].pCurrent) | ||||
| 47772 | |||||
| 47773 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47774 | { "FormatMessageW", (SYSCALL)FormatMessageW, 0 }, | ||||
| 47775 | #else | ||||
| 47776 | { "FormatMessageW", (SYSCALL)0, 0 }, | ||||
| 47777 | #endif | ||||
| 47778 | |||||
| 47779 | #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \ | ||||
| 47780 | DWORD,va_list*))aSyscall[15].pCurrent) | ||||
| 47781 | |||||
| 47782 | #if !defined(SQLITE_OMIT_LOAD_EXTENSION1) | ||||
| 47783 | { "FreeLibrary", (SYSCALL)FreeLibrary, 0 }, | ||||
| 47784 | #else | ||||
| 47785 | { "FreeLibrary", (SYSCALL)0, 0 }, | ||||
| 47786 | #endif | ||||
| 47787 | |||||
| 47788 | #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent) | ||||
| 47789 | |||||
| 47790 | { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 }, | ||||
| 47791 | |||||
| 47792 | #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent) | ||||
| 47793 | |||||
| 47794 | #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47795 | { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 }, | ||||
| 47796 | #else | ||||
| 47797 | { "GetDiskFreeSpaceA", (SYSCALL)0, 0 }, | ||||
| 47798 | #endif | ||||
| 47799 | |||||
| 47800 | #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \ | ||||
| 47801 | LPDWORD))aSyscall[18].pCurrent) | ||||
| 47802 | |||||
| 47803 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47804 | { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 }, | ||||
| 47805 | #else | ||||
| 47806 | { "GetDiskFreeSpaceW", (SYSCALL)0, 0 }, | ||||
| 47807 | #endif | ||||
| 47808 | |||||
| 47809 | #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \ | ||||
| 47810 | LPDWORD))aSyscall[19].pCurrent) | ||||
| 47811 | |||||
| 47812 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47813 | { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 }, | ||||
| 47814 | #else | ||||
| 47815 | { "GetFileAttributesA", (SYSCALL)0, 0 }, | ||||
| 47816 | #endif | ||||
| 47817 | |||||
| 47818 | #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent) | ||||
| 47819 | |||||
| 47820 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47821 | { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 }, | ||||
| 47822 | #else | ||||
| 47823 | { "GetFileAttributesW", (SYSCALL)0, 0 }, | ||||
| 47824 | #endif | ||||
| 47825 | |||||
| 47826 | #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent) | ||||
| 47827 | |||||
| 47828 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47829 | { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 }, | ||||
| 47830 | #else | ||||
| 47831 | { "GetFileAttributesExW", (SYSCALL)0, 0 }, | ||||
| 47832 | #endif | ||||
| 47833 | |||||
| 47834 | #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \ | ||||
| 47835 | LPVOID))aSyscall[22].pCurrent) | ||||
| 47836 | |||||
| 47837 | #if !SQLITE_OS_WINRT | ||||
| 47838 | { "GetFileSize", (SYSCALL)GetFileSize, 0 }, | ||||
| 47839 | #else | ||||
| 47840 | { "GetFileSize", (SYSCALL)0, 0 }, | ||||
| 47841 | #endif | ||||
| 47842 | |||||
| 47843 | #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent) | ||||
| 47844 | |||||
| 47845 | #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47846 | { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 }, | ||||
| 47847 | #else | ||||
| 47848 | { "GetFullPathNameA", (SYSCALL)0, 0 }, | ||||
| 47849 | #endif | ||||
| 47850 | |||||
| 47851 | #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \ | ||||
| 47852 | LPSTR*))aSyscall[24].pCurrent) | ||||
| 47853 | |||||
| 47854 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47855 | { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 }, | ||||
| 47856 | #else | ||||
| 47857 | { "GetFullPathNameW", (SYSCALL)0, 0 }, | ||||
| 47858 | #endif | ||||
| 47859 | |||||
| 47860 | #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \ | ||||
| 47861 | LPWSTR*))aSyscall[25].pCurrent) | ||||
| 47862 | |||||
| 47863 | /* | ||||
| 47864 | ** For GetLastError(), MSDN says: | ||||
| 47865 | ** | ||||
| 47866 | ** Minimum supported client: Windows XP [desktop apps | UWP apps] | ||||
| 47867 | ** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps] | ||||
| 47868 | */ | ||||
| 47869 | { "GetLastError", (SYSCALL)GetLastError, 0 }, | ||||
| 47870 | |||||
| 47871 | #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent) | ||||
| 47872 | |||||
| 47873 | #if !defined(SQLITE_OMIT_LOAD_EXTENSION1) | ||||
| 47874 | #if SQLITE_OS_WINCE | ||||
| 47875 | /* The GetProcAddressA() routine is only available on Windows CE. */ | ||||
| 47876 | { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 }, | ||||
| 47877 | #else | ||||
| 47878 | /* All other Windows platforms expect GetProcAddress() to take | ||||
| 47879 | ** an ANSI string regardless of the _UNICODE setting */ | ||||
| 47880 | { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 }, | ||||
| 47881 | #endif | ||||
| 47882 | #else | ||||
| 47883 | { "GetProcAddressA", (SYSCALL)0, 0 }, | ||||
| 47884 | #endif | ||||
| 47885 | |||||
| 47886 | #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \ | ||||
| 47887 | LPCSTR))aSyscall[27].pCurrent) | ||||
| 47888 | |||||
| 47889 | #if !SQLITE_OS_WINRT | ||||
| 47890 | { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 }, | ||||
| 47891 | #else | ||||
| 47892 | { "GetSystemInfo", (SYSCALL)0, 0 }, | ||||
| 47893 | #endif | ||||
| 47894 | |||||
| 47895 | #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent) | ||||
| 47896 | |||||
| 47897 | { "GetSystemTime", (SYSCALL)GetSystemTime, 0 }, | ||||
| 47898 | |||||
| 47899 | #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent) | ||||
| 47900 | |||||
| 47901 | #if !SQLITE_OS_WINCE | ||||
| 47902 | { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 }, | ||||
| 47903 | #else | ||||
| 47904 | { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 }, | ||||
| 47905 | #endif | ||||
| 47906 | |||||
| 47907 | #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \ | ||||
| 47908 | LPFILETIME))aSyscall[30].pCurrent) | ||||
| 47909 | |||||
| 47910 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 47911 | { "GetTempPathA", (SYSCALL)GetTempPathA, 0 }, | ||||
| 47912 | #else | ||||
| 47913 | { "GetTempPathA", (SYSCALL)0, 0 }, | ||||
| 47914 | #endif | ||||
| 47915 | |||||
| 47916 | #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent) | ||||
| 47917 | |||||
| 47918 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 47919 | { "GetTempPathW", (SYSCALL)GetTempPathW, 0 }, | ||||
| 47920 | #else | ||||
| 47921 | { "GetTempPathW", (SYSCALL)0, 0 }, | ||||
| 47922 | #endif | ||||
| 47923 | |||||
| 47924 | #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent) | ||||
| 47925 | |||||
| 47926 | #if !SQLITE_OS_WINRT | ||||
| 47927 | { "GetTickCount", (SYSCALL)GetTickCount, 0 }, | ||||
| 47928 | #else | ||||
| 47929 | { "GetTickCount", (SYSCALL)0, 0 }, | ||||
| 47930 | #endif | ||||
| 47931 | |||||
| 47932 | #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent) | ||||
| 47933 | |||||
| 47934 | #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX | ||||
| 47935 | { "GetVersionExA", (SYSCALL)GetVersionExA, 0 }, | ||||
| 47936 | #else | ||||
| 47937 | { "GetVersionExA", (SYSCALL)0, 0 }, | ||||
| 47938 | #endif | ||||
| 47939 | |||||
| 47940 | #define osGetVersionExA ((BOOL(WINAPI*)( \ | ||||
| 47941 | LPOSVERSIONINFOA))aSyscall[34].pCurrent) | ||||
| 47942 | |||||
| 47943 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ | ||||
| 47944 | SQLITE_WIN32_GETVERSIONEX | ||||
| 47945 | { "GetVersionExW", (SYSCALL)GetVersionExW, 0 }, | ||||
| 47946 | #else | ||||
| 47947 | { "GetVersionExW", (SYSCALL)0, 0 }, | ||||
| 47948 | #endif | ||||
| 47949 | |||||
| 47950 | #define osGetVersionExW ((BOOL(WINAPI*)( \ | ||||
| 47951 | LPOSVERSIONINFOW))aSyscall[35].pCurrent) | ||||
| 47952 | |||||
| 47953 | { "HeapAlloc", (SYSCALL)HeapAlloc, 0 }, | ||||
| 47954 | |||||
| 47955 | #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \ | ||||
| 47956 | SIZE_T))aSyscall[36].pCurrent) | ||||
| 47957 | |||||
| 47958 | #if !SQLITE_OS_WINRT | ||||
| 47959 | { "HeapCreate", (SYSCALL)HeapCreate, 0 }, | ||||
| 47960 | #else | ||||
| 47961 | { "HeapCreate", (SYSCALL)0, 0 }, | ||||
| 47962 | #endif | ||||
| 47963 | |||||
| 47964 | #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \ | ||||
| 47965 | SIZE_T))aSyscall[37].pCurrent) | ||||
| 47966 | |||||
| 47967 | #if !SQLITE_OS_WINRT | ||||
| 47968 | { "HeapDestroy", (SYSCALL)HeapDestroy, 0 }, | ||||
| 47969 | #else | ||||
| 47970 | { "HeapDestroy", (SYSCALL)0, 0 }, | ||||
| 47971 | #endif | ||||
| 47972 | |||||
| 47973 | #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent) | ||||
| 47974 | |||||
| 47975 | { "HeapFree", (SYSCALL)HeapFree, 0 }, | ||||
| 47976 | |||||
| 47977 | #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent) | ||||
| 47978 | |||||
| 47979 | { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 }, | ||||
| 47980 | |||||
| 47981 | #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \ | ||||
| 47982 | SIZE_T))aSyscall[40].pCurrent) | ||||
| 47983 | |||||
| 47984 | { "HeapSize", (SYSCALL)HeapSize, 0 }, | ||||
| 47985 | |||||
| 47986 | #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \ | ||||
| 47987 | LPCVOID))aSyscall[41].pCurrent) | ||||
| 47988 | |||||
| 47989 | #if !SQLITE_OS_WINRT | ||||
| 47990 | { "HeapValidate", (SYSCALL)HeapValidate, 0 }, | ||||
| 47991 | #else | ||||
| 47992 | { "HeapValidate", (SYSCALL)0, 0 }, | ||||
| 47993 | #endif | ||||
| 47994 | |||||
| 47995 | #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \ | ||||
| 47996 | LPCVOID))aSyscall[42].pCurrent) | ||||
| 47997 | |||||
| 47998 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT | ||||
| 47999 | { "HeapCompact", (SYSCALL)HeapCompact, 0 }, | ||||
| 48000 | #else | ||||
| 48001 | { "HeapCompact", (SYSCALL)0, 0 }, | ||||
| 48002 | #endif | ||||
| 48003 | |||||
| 48004 | #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent) | ||||
| 48005 | |||||
| 48006 | #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION1) | ||||
| 48007 | { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 }, | ||||
| 48008 | #else | ||||
| 48009 | { "LoadLibraryA", (SYSCALL)0, 0 }, | ||||
| 48010 | #endif | ||||
| 48011 | |||||
| 48012 | #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent) | ||||
| 48013 | |||||
| 48014 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ | ||||
| 48015 | !defined(SQLITE_OMIT_LOAD_EXTENSION1) | ||||
| 48016 | { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 }, | ||||
| 48017 | #else | ||||
| 48018 | { "LoadLibraryW", (SYSCALL)0, 0 }, | ||||
| 48019 | #endif | ||||
| 48020 | |||||
| 48021 | #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent) | ||||
| 48022 | |||||
| 48023 | #if !SQLITE_OS_WINRT | ||||
| 48024 | { "LocalFree", (SYSCALL)LocalFree, 0 }, | ||||
| 48025 | #else | ||||
| 48026 | { "LocalFree", (SYSCALL)0, 0 }, | ||||
| 48027 | #endif | ||||
| 48028 | |||||
| 48029 | #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent) | ||||
| 48030 | |||||
| 48031 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT | ||||
| 48032 | { "LockFile", (SYSCALL)LockFile, 0 }, | ||||
| 48033 | #else | ||||
| 48034 | { "LockFile", (SYSCALL)0, 0 }, | ||||
| 48035 | #endif | ||||
| 48036 | |||||
| 48037 | #if !defined(osLockFile) && defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 48038 | #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ | ||||
| 48039 | DWORD))aSyscall[47].pCurrent) | ||||
| 48040 | #endif | ||||
| 48041 | |||||
| 48042 | #if !SQLITE_OS_WINCE | ||||
| 48043 | { "LockFileEx", (SYSCALL)LockFileEx, 0 }, | ||||
| 48044 | #else | ||||
| 48045 | { "LockFileEx", (SYSCALL)0, 0 }, | ||||
| 48046 | #endif | ||||
| 48047 | |||||
| 48048 | #ifndef osLockFileEx | ||||
| 48049 | #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \ | ||||
| 48050 | LPOVERLAPPED))aSyscall[48].pCurrent) | ||||
| 48051 | #endif | ||||
| 48052 | |||||
| 48053 | #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \ | ||||
| 48054 | (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0)) | ||||
| 48055 | { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 }, | ||||
| 48056 | #else | ||||
| 48057 | { "MapViewOfFile", (SYSCALL)0, 0 }, | ||||
| 48058 | #endif | ||||
| 48059 | |||||
| 48060 | #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ | ||||
| 48061 | SIZE_T))aSyscall[49].pCurrent) | ||||
| 48062 | |||||
| 48063 | { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, | ||||
| 48064 | |||||
| 48065 | #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \ | ||||
| 48066 | int))aSyscall[50].pCurrent) | ||||
| 48067 | |||||
| 48068 | { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 }, | ||||
| 48069 | |||||
| 48070 | #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \ | ||||
| 48071 | LARGE_INTEGER*))aSyscall[51].pCurrent) | ||||
| 48072 | |||||
| 48073 | { "ReadFile", (SYSCALL)ReadFile, 0 }, | ||||
| 48074 | |||||
| 48075 | #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \ | ||||
| 48076 | LPOVERLAPPED))aSyscall[52].pCurrent) | ||||
| 48077 | |||||
| 48078 | { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 }, | ||||
| 48079 | |||||
| 48080 | #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent) | ||||
| 48081 | |||||
| 48082 | #if !SQLITE_OS_WINRT | ||||
| 48083 | { "SetFilePointer", (SYSCALL)SetFilePointer, 0 }, | ||||
| 48084 | #else | ||||
| 48085 | { "SetFilePointer", (SYSCALL)0, 0 }, | ||||
| 48086 | #endif | ||||
| 48087 | |||||
| 48088 | #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \ | ||||
| 48089 | DWORD))aSyscall[54].pCurrent) | ||||
| 48090 | |||||
| 48091 | #if !SQLITE_OS_WINRT | ||||
| 48092 | { "Sleep", (SYSCALL)Sleep, 0 }, | ||||
| 48093 | #else | ||||
| 48094 | { "Sleep", (SYSCALL)0, 0 }, | ||||
| 48095 | #endif | ||||
| 48096 | |||||
| 48097 | #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent) | ||||
| 48098 | |||||
| 48099 | { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 }, | ||||
| 48100 | |||||
| 48101 | #define osSystemTimeToFileTime ((BOOL(WINAPI*)(const SYSTEMTIME*, \ | ||||
| 48102 | LPFILETIME))aSyscall[56].pCurrent) | ||||
| 48103 | |||||
| 48104 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT | ||||
| 48105 | { "UnlockFile", (SYSCALL)UnlockFile, 0 }, | ||||
| 48106 | #else | ||||
| 48107 | { "UnlockFile", (SYSCALL)0, 0 }, | ||||
| 48108 | #endif | ||||
| 48109 | |||||
| 48110 | #if !defined(osUnlockFile) && defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 48111 | #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ | ||||
| 48112 | DWORD))aSyscall[57].pCurrent) | ||||
| 48113 | #endif | ||||
| 48114 | |||||
| 48115 | #if !SQLITE_OS_WINCE | ||||
| 48116 | { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 }, | ||||
| 48117 | #else | ||||
| 48118 | { "UnlockFileEx", (SYSCALL)0, 0 }, | ||||
| 48119 | #endif | ||||
| 48120 | |||||
| 48121 | #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ | ||||
| 48122 | LPOVERLAPPED))aSyscall[58].pCurrent) | ||||
| 48123 | |||||
| 48124 | #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 48125 | { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 }, | ||||
| 48126 | #else | ||||
| 48127 | { "UnmapViewOfFile", (SYSCALL)0, 0 }, | ||||
| 48128 | #endif | ||||
| 48129 | |||||
| 48130 | #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent) | ||||
| 48131 | |||||
| 48132 | { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 }, | ||||
| 48133 | |||||
| 48134 | #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \ | ||||
| 48135 | LPCSTR,LPBOOL))aSyscall[60].pCurrent) | ||||
| 48136 | |||||
| 48137 | { "WriteFile", (SYSCALL)WriteFile, 0 }, | ||||
| 48138 | |||||
| 48139 | #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \ | ||||
| 48140 | LPOVERLAPPED))aSyscall[61].pCurrent) | ||||
| 48141 | |||||
| 48142 | #if SQLITE_OS_WINRT | ||||
| 48143 | { "CreateEventExW", (SYSCALL)CreateEventExW, 0 }, | ||||
| 48144 | #else | ||||
| 48145 | { "CreateEventExW", (SYSCALL)0, 0 }, | ||||
| 48146 | #endif | ||||
| 48147 | |||||
| 48148 | #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \ | ||||
| 48149 | DWORD,DWORD))aSyscall[62].pCurrent) | ||||
| 48150 | |||||
| 48151 | /* | ||||
| 48152 | ** For WaitForSingleObject(), MSDN says: | ||||
| 48153 | ** | ||||
| 48154 | ** Minimum supported client: Windows XP [desktop apps | UWP apps] | ||||
| 48155 | ** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps] | ||||
| 48156 | */ | ||||
| 48157 | { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 }, | ||||
| 48158 | |||||
| 48159 | #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \ | ||||
| 48160 | DWORD))aSyscall[63].pCurrent) | ||||
| 48161 | |||||
| 48162 | #if !SQLITE_OS_WINCE | ||||
| 48163 | { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 }, | ||||
| 48164 | #else | ||||
| 48165 | { "WaitForSingleObjectEx", (SYSCALL)0, 0 }, | ||||
| 48166 | #endif | ||||
| 48167 | |||||
| 48168 | #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \ | ||||
| 48169 | BOOL))aSyscall[64].pCurrent) | ||||
| 48170 | |||||
| 48171 | #if SQLITE_OS_WINRT | ||||
| 48172 | { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, | ||||
| 48173 | #else | ||||
| 48174 | { "SetFilePointerEx", (SYSCALL)0, 0 }, | ||||
| 48175 | #endif | ||||
| 48176 | |||||
| 48177 | #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \ | ||||
| 48178 | PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent) | ||||
| 48179 | |||||
| 48180 | #if SQLITE_OS_WINRT | ||||
| 48181 | { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 }, | ||||
| 48182 | #else | ||||
| 48183 | { "GetFileInformationByHandleEx", (SYSCALL)0, 0 }, | ||||
| 48184 | #endif | ||||
| 48185 | |||||
| 48186 | #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \ | ||||
| 48187 | FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent) | ||||
| 48188 | |||||
| 48189 | #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) | ||||
| 48190 | { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, | ||||
| 48191 | #else | ||||
| 48192 | { "MapViewOfFileFromApp", (SYSCALL)0, 0 }, | ||||
| 48193 | #endif | ||||
| 48194 | |||||
| 48195 | #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ | ||||
| 48196 | SIZE_T))aSyscall[67].pCurrent) | ||||
| 48197 | |||||
| 48198 | #if SQLITE_OS_WINRT | ||||
| 48199 | { "CreateFile2", (SYSCALL)CreateFile2, 0 }, | ||||
| 48200 | #else | ||||
| 48201 | { "CreateFile2", (SYSCALL)0, 0 }, | ||||
| 48202 | #endif | ||||
| 48203 | |||||
| 48204 | #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \ | ||||
| 48205 | LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent) | ||||
| 48206 | |||||
| 48207 | #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION1) | ||||
| 48208 | { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 }, | ||||
| 48209 | #else | ||||
| 48210 | { "LoadPackagedLibrary", (SYSCALL)0, 0 }, | ||||
| 48211 | #endif | ||||
| 48212 | |||||
| 48213 | #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \ | ||||
| 48214 | DWORD))aSyscall[69].pCurrent) | ||||
| 48215 | |||||
| 48216 | #if SQLITE_OS_WINRT | ||||
| 48217 | { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, | ||||
| 48218 | #else | ||||
| 48219 | { "GetTickCount64", (SYSCALL)0, 0 }, | ||||
| 48220 | #endif | ||||
| 48221 | |||||
| 48222 | #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent) | ||||
| 48223 | |||||
| 48224 | #if SQLITE_OS_WINRT | ||||
| 48225 | { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 }, | ||||
| 48226 | #else | ||||
| 48227 | { "GetNativeSystemInfo", (SYSCALL)0, 0 }, | ||||
| 48228 | #endif | ||||
| 48229 | |||||
| 48230 | #define osGetNativeSystemInfo ((VOID(WINAPI*)( \ | ||||
| 48231 | LPSYSTEM_INFO))aSyscall[71].pCurrent) | ||||
| 48232 | |||||
| 48233 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 48234 | { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, | ||||
| 48235 | #else | ||||
| 48236 | { "OutputDebugStringA", (SYSCALL)0, 0 }, | ||||
| 48237 | #endif | ||||
| 48238 | |||||
| 48239 | #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent) | ||||
| 48240 | |||||
| 48241 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 48242 | { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 }, | ||||
| 48243 | #else | ||||
| 48244 | { "OutputDebugStringW", (SYSCALL)0, 0 }, | ||||
| 48245 | #endif | ||||
| 48246 | |||||
| 48247 | #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent) | ||||
| 48248 | |||||
| 48249 | { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, | ||||
| 48250 | |||||
| 48251 | #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent) | ||||
| 48252 | |||||
| 48253 | #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE20971520>0) | ||||
| 48254 | { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 }, | ||||
| 48255 | #else | ||||
| 48256 | { "CreateFileMappingFromApp", (SYSCALL)0, 0 }, | ||||
| 48257 | #endif | ||||
| 48258 | |||||
| 48259 | #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \ | ||||
| 48260 | LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent) | ||||
| 48261 | |||||
| 48262 | /* | ||||
| 48263 | ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function" | ||||
| 48264 | ** is really just a macro that uses a compiler intrinsic (e.g. x64). | ||||
| 48265 | ** So do not try to make this is into a redefinable interface. | ||||
| 48266 | */ | ||||
| 48267 | #if defined(InterlockedCompareExchange) | ||||
| 48268 | { "InterlockedCompareExchange", (SYSCALL)0, 0 }, | ||||
| 48269 | |||||
| 48270 | #define osInterlockedCompareExchange InterlockedCompareExchange | ||||
| 48271 | #else | ||||
| 48272 | { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 }, | ||||
| 48273 | |||||
| 48274 | #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \ | ||||
| 48275 | SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent) | ||||
| 48276 | #endif /* defined(InterlockedCompareExchange) */ | ||||
| 48277 | |||||
| 48278 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID | ||||
| 48279 | { "UuidCreate", (SYSCALL)UuidCreate, 0 }, | ||||
| 48280 | #else | ||||
| 48281 | { "UuidCreate", (SYSCALL)0, 0 }, | ||||
| 48282 | #endif | ||||
| 48283 | |||||
| 48284 | #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent) | ||||
| 48285 | |||||
| 48286 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID | ||||
| 48287 | { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 }, | ||||
| 48288 | #else | ||||
| 48289 | { "UuidCreateSequential", (SYSCALL)0, 0 }, | ||||
| 48290 | #endif | ||||
| 48291 | |||||
| 48292 | #define osUuidCreateSequential \ | ||||
| 48293 | ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent) | ||||
| 48294 | |||||
| 48295 | #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 48296 | { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 }, | ||||
| 48297 | #else | ||||
| 48298 | { "FlushViewOfFile", (SYSCALL)0, 0 }, | ||||
| 48299 | #endif | ||||
| 48300 | |||||
| 48301 | #define osFlushViewOfFile \ | ||||
| 48302 | ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent) | ||||
| 48303 | |||||
| 48304 | /* | ||||
| 48305 | ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CreateEvent() | ||||
| 48306 | ** to implement blocking locks with timeouts. MSDN says: | ||||
| 48307 | ** | ||||
| 48308 | ** Minimum supported client: Windows XP [desktop apps | UWP apps] | ||||
| 48309 | ** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps] | ||||
| 48310 | */ | ||||
| 48311 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 48312 | { "CreateEvent", (SYSCALL)CreateEvent, 0 }, | ||||
| 48313 | #else | ||||
| 48314 | { "CreateEvent", (SYSCALL)0, 0 }, | ||||
| 48315 | #endif | ||||
| 48316 | |||||
| 48317 | #define osCreateEvent ( \ | ||||
| 48318 | (HANDLE(WINAPI*) (LPSECURITY_ATTRIBUTES,BOOL,BOOL,LPCSTR)) \ | ||||
| 48319 | aSyscall[80].pCurrent \ | ||||
| 48320 | ) | ||||
| 48321 | |||||
| 48322 | /* | ||||
| 48323 | ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CancelIo() | ||||
| 48324 | ** for the case where a timeout expires and a lock request must be | ||||
| 48325 | ** cancelled. | ||||
| 48326 | ** | ||||
| 48327 | ** Minimum supported client: Windows XP [desktop apps | UWP apps] | ||||
| 48328 | ** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps] | ||||
| 48329 | */ | ||||
| 48330 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 48331 | { "CancelIo", (SYSCALL)CancelIo, 0 }, | ||||
| 48332 | #else | ||||
| 48333 | { "CancelIo", (SYSCALL)0, 0 }, | ||||
| 48334 | #endif | ||||
| 48335 | |||||
| 48336 | #define osCancelIo ((BOOL(WINAPI*)(HANDLE))aSyscall[81].pCurrent) | ||||
| 48337 | |||||
| 48338 | #if defined(SQLITE_WIN32_HAS_WIDE) && defined(_WIN32) | ||||
| 48339 | { "GetModuleHandleW", (SYSCALL)GetModuleHandleW, 0 }, | ||||
| 48340 | #else | ||||
| 48341 | { "GetModuleHandleW", (SYSCALL)0, 0 }, | ||||
| 48342 | #endif | ||||
| 48343 | |||||
| 48344 | #define osGetModuleHandleW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[82].pCurrent) | ||||
| 48345 | |||||
| 48346 | #ifndef _WIN32 | ||||
| 48347 | { "getenv", (SYSCALL)getenv, 0 }, | ||||
| 48348 | #else | ||||
| 48349 | { "getenv", (SYSCALL)0, 0 }, | ||||
| 48350 | #endif | ||||
| 48351 | |||||
| 48352 | #define osGetenv ((const char *(*)(const char *))aSyscall[83].pCurrent) | ||||
| 48353 | |||||
| 48354 | #ifndef _WIN32 | ||||
| 48355 | { "getcwd", (SYSCALL)getcwd, 0 }, | ||||
| 48356 | #else | ||||
| 48357 | { "getcwd", (SYSCALL)0, 0 }, | ||||
| 48358 | #endif | ||||
| 48359 | |||||
| 48360 | #define osGetcwd((char*(*)(char*,size_t))aSyscall[3].pCurrent) ((char*(*)(char*,size_t))aSyscall[84].pCurrent) | ||||
| 48361 | |||||
| 48362 | #ifndef _WIN32 | ||||
| 48363 | { "readlink", (SYSCALL)readlink, 0 }, | ||||
| 48364 | #else | ||||
| 48365 | { "readlink", (SYSCALL)0, 0 }, | ||||
| 48366 | #endif | ||||
| 48367 | |||||
| 48368 | #define osReadlink((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) ((ssize_t(*)(const char*,char*,size_t))aSyscall[85].pCurrent) | ||||
| 48369 | |||||
| 48370 | #ifndef _WIN32 | ||||
| 48371 | { "lstat", (SYSCALL)lstat, 0 }, | ||||
| 48372 | #else | ||||
| 48373 | { "lstat", (SYSCALL)0, 0 }, | ||||
| 48374 | #endif | ||||
| 48375 | |||||
| 48376 | #define osLstat((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) ((int(*)(const char*,struct stat*))aSyscall[86].pCurrent) | ||||
| 48377 | |||||
| 48378 | #ifndef _WIN32 | ||||
| 48379 | { "__errno", (SYSCALL)__errno, 0 }, | ||||
| 48380 | #else | ||||
| 48381 | { "__errno", (SYSCALL)0, 0 }, | ||||
| 48382 | #endif | ||||
| 48383 | |||||
| 48384 | #define osErrno (*((int*(*)(void))aSyscall[87].pCurrent)()) | ||||
| 48385 | |||||
| 48386 | #ifndef _WIN32 | ||||
| 48387 | { "cygwin_conv_path", (SYSCALL)cygwin_conv_path, 0 }, | ||||
| 48388 | #else | ||||
| 48389 | { "cygwin_conv_path", (SYSCALL)0, 0 }, | ||||
| 48390 | #endif | ||||
| 48391 | |||||
| 48392 | #define osCygwin_conv_path ((size_t(*)(unsigned int, \ | ||||
| 48393 | const void *, void *, size_t))aSyscall[88].pCurrent) | ||||
| 48394 | |||||
| 48395 | }; /* End of the overrideable system calls */ | ||||
| 48396 | |||||
| 48397 | /* | ||||
| 48398 | ** This is the xSetSystemCall() method of sqlite3_vfs for all of the | ||||
| 48399 | ** "win32" VFSes. Return SQLITE_OK upon successfully updating the | ||||
| 48400 | ** system call pointer, or SQLITE_NOTFOUND if there is no configurable | ||||
| 48401 | ** system call named zName. | ||||
| 48402 | */ | ||||
| 48403 | static int winSetSystemCall( | ||||
| 48404 | sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ | ||||
| 48405 | const char *zName, /* Name of system call to override */ | ||||
| 48406 | sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ | ||||
| 48407 | ){ | ||||
| 48408 | unsigned int i; | ||||
| 48409 | int rc = SQLITE_NOTFOUND12; | ||||
| 48410 | |||||
| 48411 | UNUSED_PARAMETER(pNotUsed)(void)(pNotUsed); | ||||
| 48412 | if( zName==0 ){ | ||||
| 48413 | /* If no zName is given, restore all system calls to their default | ||||
| 48414 | ** settings and return NULL | ||||
| 48415 | */ | ||||
| 48416 | rc = SQLITE_OK0; | ||||
| 48417 | for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ | ||||
| 48418 | if( aSyscall[i].pDefault ){ | ||||
| 48419 | aSyscall[i].pCurrent = aSyscall[i].pDefault; | ||||
| 48420 | } | ||||
| 48421 | } | ||||
| 48422 | }else{ | ||||
| 48423 | /* If zName is specified, operate on only the one system call | ||||
| 48424 | ** specified. | ||||
| 48425 | */ | ||||
| 48426 | for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ | ||||
| 48427 | if( strcmp(zName, aSyscall[i].zName)==0 ){ | ||||
| 48428 | if( aSyscall[i].pDefault==0 ){ | ||||
| 48429 | aSyscall[i].pDefault = aSyscall[i].pCurrent; | ||||
| 48430 | } | ||||
| 48431 | rc = SQLITE_OK0; | ||||
| 48432 | if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault; | ||||
| 48433 | aSyscall[i].pCurrent = pNewFunc; | ||||
| 48434 | break; | ||||
| 48435 | } | ||||
| 48436 | } | ||||
| 48437 | } | ||||
| 48438 | return rc; | ||||
| 48439 | } | ||||
| 48440 | |||||
| 48441 | /* | ||||
| 48442 | ** Return the value of a system call. Return NULL if zName is not a | ||||
| 48443 | ** recognized system call name. NULL is also returned if the system call | ||||
| 48444 | ** is currently undefined. | ||||
| 48445 | */ | ||||
| 48446 | static sqlite3_syscall_ptr winGetSystemCall( | ||||
| 48447 | sqlite3_vfs *pNotUsed, | ||||
| 48448 | const char *zName | ||||
| 48449 | ){ | ||||
| 48450 | unsigned int i; | ||||
| 48451 | |||||
| 48452 | UNUSED_PARAMETER(pNotUsed)(void)(pNotUsed); | ||||
| 48453 | for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){ | ||||
| 48454 | if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent; | ||||
| 48455 | } | ||||
| 48456 | return 0; | ||||
| 48457 | } | ||||
| 48458 | |||||
| 48459 | /* | ||||
| 48460 | ** Return the name of the first system call after zName. If zName==NULL | ||||
| 48461 | ** then return the name of the first system call. Return NULL if zName | ||||
| 48462 | ** is the last system call or if zName is not the name of a valid | ||||
| 48463 | ** system call. | ||||
| 48464 | */ | ||||
| 48465 | static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){ | ||||
| 48466 | int i = -1; | ||||
| 48467 | |||||
| 48468 | UNUSED_PARAMETER(p)(void)(p); | ||||
| 48469 | if( zName ){ | ||||
| 48470 | for(i=0; i<ArraySize(aSyscall)((int)(sizeof(aSyscall)/sizeof(aSyscall[0])))-1; i++){ | ||||
| 48471 | if( strcmp(zName, aSyscall[i].zName)==0 ) break; | ||||
| 48472 | } | ||||
| 48473 | } | ||||
| 48474 | for(i++; i<ArraySize(aSyscall)((int)(sizeof(aSyscall)/sizeof(aSyscall[0]))); i++){ | ||||
| 48475 | if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName; | ||||
| 48476 | } | ||||
| 48477 | return 0; | ||||
| 48478 | } | ||||
| 48479 | |||||
| 48480 | #ifdef SQLITE_WIN32_MALLOC | ||||
| 48481 | /* | ||||
| 48482 | ** If a Win32 native heap has been configured, this function will attempt to | ||||
| 48483 | ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one | ||||
| 48484 | ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The | ||||
| 48485 | ** "pnLargest" argument, if non-zero, will be used to return the size of the | ||||
| 48486 | ** largest committed free block in the heap, in bytes. | ||||
| 48487 | */ | ||||
| 48488 | SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){ | ||||
| 48489 | int rc = SQLITE_OK0; | ||||
| 48490 | UINT nLargest = 0; | ||||
| 48491 | HANDLE hHeap; | ||||
| 48492 | |||||
| 48493 | winMemAssertMagic(); | ||||
| 48494 | hHeap = winMemGetHeap(); | ||||
| 48495 | assert( hHeap!=0 )((void) (0)); | ||||
| 48496 | assert( hHeap!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 48497 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) | ||||
| 48498 | assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) )((void) (0)); | ||||
| 48499 | #endif | ||||
| 48500 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT | ||||
| 48501 | if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){ | ||||
| 48502 | DWORD lastErrno = osGetLastError(); | ||||
| 48503 | if( lastErrno==NO_ERROR ){ | ||||
| 48504 | sqlite3_log(SQLITE_NOMEM7, "failed to HeapCompact (no space), heap=%p", | ||||
| 48505 | (void*)hHeap); | ||||
| 48506 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 48507 | }else{ | ||||
| 48508 | sqlite3_log(SQLITE_ERROR1, "failed to HeapCompact (%lu), heap=%p", | ||||
| 48509 | osGetLastError(), (void*)hHeap); | ||||
| 48510 | rc = SQLITE_ERROR1; | ||||
| 48511 | } | ||||
| 48512 | } | ||||
| 48513 | #else | ||||
| 48514 | sqlite3_log(SQLITE_NOTFOUND12, "failed to HeapCompact, heap=%p", | ||||
| 48515 | (void*)hHeap); | ||||
| 48516 | rc = SQLITE_NOTFOUND12; | ||||
| 48517 | #endif | ||||
| 48518 | if( pnLargest ) *pnLargest = nLargest; | ||||
| 48519 | return rc; | ||||
| 48520 | } | ||||
| 48521 | |||||
| 48522 | /* | ||||
| 48523 | ** If a Win32 native heap has been configured, this function will attempt to | ||||
| 48524 | ** destroy and recreate it. If the Win32 native heap is not isolated and/or | ||||
| 48525 | ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will | ||||
| 48526 | ** be returned and no changes will be made to the Win32 native heap. | ||||
| 48527 | */ | ||||
| 48528 | SQLITE_API int sqlite3_win32_reset_heap(){ | ||||
| 48529 | int rc; | ||||
| 48530 | MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )sqlite3_mutex *pMainMtx; /* The main static mutex */ | ||||
| 48531 | MUTEX_LOGIC( sqlite3_mutex *pMem; )sqlite3_mutex *pMem; /* The memsys static mutex */ | ||||
| 48532 | MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )pMainMtx = sqlite3MutexAlloc(2); | ||||
| 48533 | MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )pMem = sqlite3MutexAlloc(3); | ||||
| 48534 | sqlite3_mutex_enter(pMainMtx); | ||||
| 48535 | sqlite3_mutex_enter(pMem); | ||||
| 48536 | winMemAssertMagic(); | ||||
| 48537 | if( winMemGetHeap()!=NULL((void*)0) && winMemGetOwned() && sqlite3_memory_used()==0 ){ | ||||
| 48538 | /* | ||||
| 48539 | ** At this point, there should be no outstanding memory allocations on | ||||
| 48540 | ** the heap. Also, since both the main and memsys locks are currently | ||||
| 48541 | ** being held by us, no other function (i.e. from another thread) should | ||||
| 48542 | ** be able to even access the heap. Attempt to destroy and recreate our | ||||
| 48543 | ** isolated Win32 native heap now. | ||||
| 48544 | */ | ||||
| 48545 | assert( winMemGetHeap()!=NULL )((void) (0)); | ||||
| 48546 | assert( winMemGetOwned() )((void) (0)); | ||||
| 48547 | assert( sqlite3_memory_used()==0 )((void) (0)); | ||||
| 48548 | winMemShutdown(winMemGetDataPtr()); | ||||
| 48549 | assert( winMemGetHeap()==NULL )((void) (0)); | ||||
| 48550 | assert( !winMemGetOwned() )((void) (0)); | ||||
| 48551 | assert( sqlite3_memory_used()==0 )((void) (0)); | ||||
| 48552 | rc = winMemInit(winMemGetDataPtr()); | ||||
| 48553 | assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL )((void) (0)); | ||||
| 48554 | assert( rc!=SQLITE_OK || winMemGetOwned() )((void) (0)); | ||||
| 48555 | assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 )((void) (0)); | ||||
| 48556 | }else{ | ||||
| 48557 | /* | ||||
| 48558 | ** The Win32 native heap cannot be modified because it may be in use. | ||||
| 48559 | */ | ||||
| 48560 | rc = SQLITE_BUSY5; | ||||
| 48561 | } | ||||
| 48562 | sqlite3_mutex_leave(pMem); | ||||
| 48563 | sqlite3_mutex_leave(pMainMtx); | ||||
| 48564 | return rc; | ||||
| 48565 | } | ||||
| 48566 | #endif /* SQLITE_WIN32_MALLOC */ | ||||
| 48567 | |||||
| 48568 | #ifdef _WIN32 | ||||
| 48569 | /* | ||||
| 48570 | ** This function outputs the specified (ANSI) string to the Win32 debugger | ||||
| 48571 | ** (if available). | ||||
| 48572 | */ | ||||
| 48573 | |||||
| 48574 | SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ | ||||
| 48575 | char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE]; | ||||
| 48576 | int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1))((nBuf)<((SQLITE_WIN32_DBG_BUF_SIZE - 1))?(nBuf):((SQLITE_WIN32_DBG_BUF_SIZE - 1))); /* may be negative. */ | ||||
| 48577 | if( nMin<-1 ) nMin = -1; /* all negative values become -1. */ | ||||
| 48578 | assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE )((void) (0)); | ||||
| 48579 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 48580 | if( !zBuf ){ | ||||
| 48581 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(48581); | ||||
| 48582 | return; | ||||
| 48583 | } | ||||
| 48584 | #endif | ||||
| 48585 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 48586 | if( nMin>0 ){ | ||||
| 48587 | memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); | ||||
| 48588 | memcpy(zDbgBuf, zBuf, nMin); | ||||
| 48589 | osOutputDebugStringA(zDbgBuf); | ||||
| 48590 | }else{ | ||||
| 48591 | osOutputDebugStringA(zBuf); | ||||
| 48592 | } | ||||
| 48593 | #elif defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 48594 | memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); | ||||
| 48595 | if ( osMultiByteToWideChar( | ||||
| 48596 | osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf, | ||||
| 48597 | nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){ | ||||
| 48598 | return; | ||||
| 48599 | } | ||||
| 48600 | osOutputDebugStringW((LPCWSTR)zDbgBuf); | ||||
| 48601 | #else | ||||
| 48602 | if( nMin>0 ){ | ||||
| 48603 | memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); | ||||
| 48604 | memcpy(zDbgBuf, zBuf, nMin); | ||||
| 48605 | fprintf(stderrstderr, "%s", zDbgBuf); | ||||
| 48606 | }else{ | ||||
| 48607 | fprintf(stderrstderr, "%s", zBuf); | ||||
| 48608 | } | ||||
| 48609 | #endif | ||||
| 48610 | } | ||||
| 48611 | #endif /* _WIN32 */ | ||||
| 48612 | |||||
| 48613 | /* | ||||
| 48614 | ** The following routine suspends the current thread for at least ms | ||||
| 48615 | ** milliseconds. This is equivalent to the Win32 Sleep() interface. | ||||
| 48616 | */ | ||||
| 48617 | #if SQLITE_OS_WINRT | ||||
| 48618 | static HANDLE sleepObj = NULL((void*)0); | ||||
| 48619 | #endif | ||||
| 48620 | |||||
| 48621 | SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){ | ||||
| 48622 | #if SQLITE_OS_WINRT | ||||
| 48623 | if ( sleepObj==NULL((void*)0) ){ | ||||
| 48624 | sleepObj = osCreateEventExW(NULL((void*)0), NULL((void*)0), CREATE_EVENT_MANUAL_RESET, | ||||
| 48625 | SYNCHRONIZE); | ||||
| 48626 | } | ||||
| 48627 | assert( sleepObj!=NULL )((void) (0)); | ||||
| 48628 | osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE); | ||||
| 48629 | #else | ||||
| 48630 | osSleep(milliseconds); | ||||
| 48631 | #endif | ||||
| 48632 | } | ||||
| 48633 | |||||
| 48634 | #if SQLITE_MAX_WORKER_THREADS8>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ | ||||
| 48635 | SQLITE_THREADSAFE2>0 | ||||
| 48636 | SQLITE_PRIVATEstatic DWORD sqlite3Win32Wait(HANDLE hObject){ | ||||
| 48637 | DWORD rc; | ||||
| 48638 | while( (rc = osWaitForSingleObjectEx(hObject, INFINITE, | ||||
| 48639 | TRUE))==WAIT_IO_COMPLETION ){} | ||||
| 48640 | return rc; | ||||
| 48641 | } | ||||
| 48642 | #endif | ||||
| 48643 | |||||
| 48644 | /* | ||||
| 48645 | ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, | ||||
| 48646 | ** or WinCE. Return false (zero) for Win95, Win98, or WinME. | ||||
| 48647 | ** | ||||
| 48648 | ** Here is an interesting observation: Win95, Win98, and WinME lack | ||||
| 48649 | ** the LockFileEx() API. But we can still statically link against that | ||||
| 48650 | ** API as long as we don't call it when running Win95/98/ME. A call to | ||||
| 48651 | ** this routine is used to determine if the host is Win95/98/ME or | ||||
| 48652 | ** WinNT/2K/XP so that we will know whether or not we can safely call | ||||
| 48653 | ** the LockFileEx() API. | ||||
| 48654 | */ | ||||
| 48655 | |||||
| 48656 | #if !SQLITE_WIN32_GETVERSIONEX | ||||
| 48657 | # define osIsNT() (1) | ||||
| 48658 | #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 48659 | # define osIsNT() (1) | ||||
| 48660 | #elif !defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 48661 | # define osIsNT() (0) | ||||
| 48662 | #else | ||||
| 48663 | # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt()) | ||||
| 48664 | #endif | ||||
| 48665 | |||||
| 48666 | /* | ||||
| 48667 | ** This function determines if the machine is running a version of Windows | ||||
| 48668 | ** based on the NT kernel. | ||||
| 48669 | */ | ||||
| 48670 | SQLITE_API int sqlite3_win32_is_nt(void){ | ||||
| 48671 | #if SQLITE_OS_WINRT | ||||
| 48672 | /* | ||||
| 48673 | ** NOTE: The WinRT sub-platform is always assumed to be based on the NT | ||||
| 48674 | ** kernel. | ||||
| 48675 | */ | ||||
| 48676 | return 1; | ||||
| 48677 | #elif SQLITE_WIN32_GETVERSIONEX | ||||
| 48678 | if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){ | ||||
| 48679 | #if defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 48680 | OSVERSIONINFOA sInfo; | ||||
| 48681 | sInfo.dwOSVersionInfoSize = sizeof(sInfo); | ||||
| 48682 | osGetVersionExA(&sInfo); | ||||
| 48683 | osInterlockedCompareExchange(&sqlite3_os_type, | ||||
| 48684 | (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); | ||||
| 48685 | #elif defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 48686 | OSVERSIONINFOW sInfo; | ||||
| 48687 | sInfo.dwOSVersionInfoSize = sizeof(sInfo); | ||||
| 48688 | osGetVersionExW(&sInfo); | ||||
| 48689 | osInterlockedCompareExchange(&sqlite3_os_type, | ||||
| 48690 | (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); | ||||
| 48691 | #endif | ||||
| 48692 | } | ||||
| 48693 | return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; | ||||
| 48694 | #elif SQLITE_TEST | ||||
| 48695 | return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2 | ||||
| 48696 | || osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 | ||||
| 48697 | ; | ||||
| 48698 | #else | ||||
| 48699 | /* | ||||
| 48700 | ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are | ||||
| 48701 | ** deprecated are always assumed to be based on the NT kernel. | ||||
| 48702 | */ | ||||
| 48703 | return 1; | ||||
| 48704 | #endif | ||||
| 48705 | } | ||||
| 48706 | |||||
| 48707 | #ifdef SQLITE_WIN32_MALLOC | ||||
| 48708 | /* | ||||
| 48709 | ** Allocate nBytes of memory. | ||||
| 48710 | */ | ||||
| 48711 | static void *winMemMalloc(int nBytes){ | ||||
| 48712 | HANDLE hHeap; | ||||
| 48713 | void *p; | ||||
| 48714 | |||||
| 48715 | winMemAssertMagic(); | ||||
| 48716 | hHeap = winMemGetHeap(); | ||||
| 48717 | assert( hHeap!=0 )((void) (0)); | ||||
| 48718 | assert( hHeap!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 48719 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) | ||||
| 48720 | assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) )((void) (0)); | ||||
| 48721 | #endif | ||||
| 48722 | assert( nBytes>=0 )((void) (0)); | ||||
| 48723 | p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); | ||||
| 48724 | if( !p ){ | ||||
| 48725 | sqlite3_log(SQLITE_NOMEM7, "failed to HeapAlloc %u bytes (%lu), heap=%p", | ||||
| 48726 | nBytes, osGetLastError(), (void*)hHeap); | ||||
| 48727 | } | ||||
| 48728 | return p; | ||||
| 48729 | } | ||||
| 48730 | |||||
| 48731 | /* | ||||
| 48732 | ** Free memory. | ||||
| 48733 | */ | ||||
| 48734 | static void winMemFree(void *pPrior){ | ||||
| 48735 | HANDLE hHeap; | ||||
| 48736 | |||||
| 48737 | winMemAssertMagic(); | ||||
| 48738 | hHeap = winMemGetHeap(); | ||||
| 48739 | assert( hHeap!=0 )((void) (0)); | ||||
| 48740 | assert( hHeap!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 48741 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) | ||||
| 48742 | assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) )((void) (0)); | ||||
| 48743 | #endif | ||||
| 48744 | if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ | ||||
| 48745 | if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){ | ||||
| 48746 | sqlite3_log(SQLITE_NOMEM7, "failed to HeapFree block %p (%lu), heap=%p", | ||||
| 48747 | pPrior, osGetLastError(), (void*)hHeap); | ||||
| 48748 | } | ||||
| 48749 | } | ||||
| 48750 | |||||
| 48751 | /* | ||||
| 48752 | ** Change the size of an existing memory allocation | ||||
| 48753 | */ | ||||
| 48754 | static void *winMemRealloc(void *pPrior, int nBytes){ | ||||
| 48755 | HANDLE hHeap; | ||||
| 48756 | void *p; | ||||
| 48757 | |||||
| 48758 | winMemAssertMagic(); | ||||
| 48759 | hHeap = winMemGetHeap(); | ||||
| 48760 | assert( hHeap!=0 )((void) (0)); | ||||
| 48761 | assert( hHeap!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 48762 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) | ||||
| 48763 | assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) )((void) (0)); | ||||
| 48764 | #endif | ||||
| 48765 | assert( nBytes>=0 )((void) (0)); | ||||
| 48766 | if( !pPrior ){ | ||||
| 48767 | p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes); | ||||
| 48768 | }else{ | ||||
| 48769 | p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes); | ||||
| 48770 | } | ||||
| 48771 | if( !p ){ | ||||
| 48772 | sqlite3_log(SQLITE_NOMEM7, "failed to %s %u bytes (%lu), heap=%p", | ||||
| 48773 | pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(), | ||||
| 48774 | (void*)hHeap); | ||||
| 48775 | } | ||||
| 48776 | return p; | ||||
| 48777 | } | ||||
| 48778 | |||||
| 48779 | /* | ||||
| 48780 | ** Return the size of an outstanding allocation, in bytes. | ||||
| 48781 | */ | ||||
| 48782 | static int winMemSize(void *p){ | ||||
| 48783 | HANDLE hHeap; | ||||
| 48784 | SIZE_T n; | ||||
| 48785 | |||||
| 48786 | winMemAssertMagic(); | ||||
| 48787 | hHeap = winMemGetHeap(); | ||||
| 48788 | assert( hHeap!=0 )((void) (0)); | ||||
| 48789 | assert( hHeap!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 48790 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) | ||||
| 48791 | assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) )((void) (0)); | ||||
| 48792 | #endif | ||||
| 48793 | if( !p ) return 0; | ||||
| 48794 | n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p); | ||||
| 48795 | if( n==(SIZE_T)-1 ){ | ||||
| 48796 | sqlite3_log(SQLITE_NOMEM7, "failed to HeapSize block %p (%lu), heap=%p", | ||||
| 48797 | p, osGetLastError(), (void*)hHeap); | ||||
| 48798 | return 0; | ||||
| 48799 | } | ||||
| 48800 | return (int)n; | ||||
| 48801 | } | ||||
| 48802 | |||||
| 48803 | /* | ||||
| 48804 | ** Round up a request size to the next valid allocation size. | ||||
| 48805 | */ | ||||
| 48806 | static int winMemRoundup(int n){ | ||||
| 48807 | return n; | ||||
| 48808 | } | ||||
| 48809 | |||||
| 48810 | /* | ||||
| 48811 | ** Initialize this module. | ||||
| 48812 | */ | ||||
| 48813 | static int winMemInit(void *pAppData){ | ||||
| 48814 | winMemData *pWinMemData = (winMemData *)pAppData; | ||||
| 48815 | |||||
| 48816 | if( !pWinMemData ) return SQLITE_ERROR1; | ||||
| 48817 | assert( pWinMemData->magic1==WINMEM_MAGIC1 )((void) (0)); | ||||
| 48818 | assert( pWinMemData->magic2==WINMEM_MAGIC2 )((void) (0)); | ||||
| 48819 | |||||
| 48820 | #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE | ||||
| 48821 | if( !pWinMemData->hHeap ){ | ||||
| 48822 | DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE; | ||||
| 48823 | DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfigsqlite3Config.nHeap; | ||||
| 48824 | if( dwMaximumSize==0 ){ | ||||
| 48825 | dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE; | ||||
| 48826 | }else if( dwInitialSize>dwMaximumSize ){ | ||||
| 48827 | dwInitialSize = dwMaximumSize; | ||||
| 48828 | } | ||||
| 48829 | pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS, | ||||
| 48830 | dwInitialSize, dwMaximumSize); | ||||
| 48831 | if( !pWinMemData->hHeap ){ | ||||
| 48832 | sqlite3_log(SQLITE_NOMEM7, | ||||
| 48833 | "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu", | ||||
| 48834 | osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize, | ||||
| 48835 | dwMaximumSize); | ||||
| 48836 | return SQLITE_NOMEM_BKPT7; | ||||
| 48837 | } | ||||
| 48838 | pWinMemData->bOwned = TRUE; | ||||
| 48839 | assert( pWinMemData->bOwned )((void) (0)); | ||||
| 48840 | } | ||||
| 48841 | #else | ||||
| 48842 | pWinMemData->hHeap = osGetProcessHeap(); | ||||
| 48843 | if( !pWinMemData->hHeap ){ | ||||
| 48844 | sqlite3_log(SQLITE_NOMEM7, | ||||
| 48845 | "failed to GetProcessHeap (%lu)", osGetLastError()); | ||||
| 48846 | return SQLITE_NOMEM_BKPT7; | ||||
| 48847 | } | ||||
| 48848 | pWinMemData->bOwned = FALSE; | ||||
| 48849 | assert( !pWinMemData->bOwned )((void) (0)); | ||||
| 48850 | #endif | ||||
| 48851 | assert( pWinMemData->hHeap!=0 )((void) (0)); | ||||
| 48852 | assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 48853 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) | ||||
| 48854 | assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) )((void) (0)); | ||||
| 48855 | #endif | ||||
| 48856 | return SQLITE_OK0; | ||||
| 48857 | } | ||||
| 48858 | |||||
| 48859 | /* | ||||
| 48860 | ** Deinitialize this module. | ||||
| 48861 | */ | ||||
| 48862 | static void winMemShutdown(void *pAppData){ | ||||
| 48863 | winMemData *pWinMemData = (winMemData *)pAppData; | ||||
| 48864 | |||||
| 48865 | if( !pWinMemData ) return; | ||||
| 48866 | assert( pWinMemData->magic1==WINMEM_MAGIC1 )((void) (0)); | ||||
| 48867 | assert( pWinMemData->magic2==WINMEM_MAGIC2 )((void) (0)); | ||||
| 48868 | |||||
| 48869 | if( pWinMemData->hHeap ){ | ||||
| 48870 | assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 48871 | #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) | ||||
| 48872 | assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) )((void) (0)); | ||||
| 48873 | #endif | ||||
| 48874 | if( pWinMemData->bOwned ){ | ||||
| 48875 | if( !osHeapDestroy(pWinMemData->hHeap) ){ | ||||
| 48876 | sqlite3_log(SQLITE_NOMEM7, "failed to HeapDestroy (%lu), heap=%p", | ||||
| 48877 | osGetLastError(), (void*)pWinMemData->hHeap); | ||||
| 48878 | } | ||||
| 48879 | pWinMemData->bOwned = FALSE; | ||||
| 48880 | } | ||||
| 48881 | pWinMemData->hHeap = NULL((void*)0); | ||||
| 48882 | } | ||||
| 48883 | } | ||||
| 48884 | |||||
| 48885 | /* | ||||
| 48886 | ** Populate the low-level memory allocation function pointers in | ||||
| 48887 | ** sqlite3GlobalConfig.m with pointers to the routines in this file. The | ||||
| 48888 | ** arguments specify the block of memory to manage. | ||||
| 48889 | ** | ||||
| 48890 | ** This routine is only called by sqlite3_config(), and therefore | ||||
| 48891 | ** is not required to be threadsafe (it is not). | ||||
| 48892 | */ | ||||
| 48893 | SQLITE_PRIVATEstatic const sqlite3_mem_methods *sqlite3MemGetWin32(void){ | ||||
| 48894 | static const sqlite3_mem_methods winMemMethods = { | ||||
| 48895 | winMemMalloc, | ||||
| 48896 | winMemFree, | ||||
| 48897 | winMemRealloc, | ||||
| 48898 | winMemSize, | ||||
| 48899 | winMemRoundup, | ||||
| 48900 | winMemInit, | ||||
| 48901 | winMemShutdown, | ||||
| 48902 | &win_mem_data | ||||
| 48903 | }; | ||||
| 48904 | return &winMemMethods; | ||||
| 48905 | } | ||||
| 48906 | |||||
| 48907 | SQLITE_PRIVATEstatic void sqlite3MemSetDefault(void){ | ||||
| 48908 | sqlite3_config(SQLITE_CONFIG_MALLOC4, sqlite3MemGetWin32()); | ||||
| 48909 | } | ||||
| 48910 | #endif /* SQLITE_WIN32_MALLOC */ | ||||
| 48911 | |||||
| 48912 | #ifdef _WIN32 | ||||
| 48913 | /* | ||||
| 48914 | ** Convert a UTF-8 string to Microsoft Unicode. | ||||
| 48915 | ** | ||||
| 48916 | ** Space to hold the returned string is obtained from sqlite3_malloc(). | ||||
| 48917 | */ | ||||
| 48918 | static LPWSTR winUtf8ToUnicode(const char *zText){ | ||||
| 48919 | int nChar; | ||||
| 48920 | LPWSTR zWideText; | ||||
| 48921 | |||||
| 48922 | nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL((void*)0), 0); | ||||
| 48923 | if( nChar==0 ){ | ||||
| 48924 | return 0; | ||||
| 48925 | } | ||||
| 48926 | zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) ); | ||||
| 48927 | if( zWideText==0 ){ | ||||
| 48928 | return 0; | ||||
| 48929 | } | ||||
| 48930 | nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText, | ||||
| 48931 | nChar); | ||||
| 48932 | if( nChar==0 ){ | ||||
| 48933 | sqlite3_free(zWideText); | ||||
| 48934 | zWideText = 0; | ||||
| 48935 | } | ||||
| 48936 | return zWideText; | ||||
| 48937 | } | ||||
| 48938 | #endif /* _WIN32 */ | ||||
| 48939 | |||||
| 48940 | /* | ||||
| 48941 | ** Convert a Microsoft Unicode string to UTF-8. | ||||
| 48942 | ** | ||||
| 48943 | ** Space to hold the returned string is obtained from sqlite3_malloc(). | ||||
| 48944 | */ | ||||
| 48945 | static char *winUnicodeToUtf8(LPCWSTR zWideText){ | ||||
| 48946 | int nByte; | ||||
| 48947 | char *zText; | ||||
| 48948 | |||||
| 48949 | nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0); | ||||
| 48950 | if( nByte == 0 ){ | ||||
| 48951 | return 0; | ||||
| 48952 | } | ||||
| 48953 | zText = sqlite3MallocZero( nByte ); | ||||
| 48954 | if( zText==0 ){ | ||||
| 48955 | return 0; | ||||
| 48956 | } | ||||
| 48957 | nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte, | ||||
| 48958 | 0, 0); | ||||
| 48959 | if( nByte == 0 ){ | ||||
| 48960 | sqlite3_free(zText); | ||||
| 48961 | zText = 0; | ||||
| 48962 | } | ||||
| 48963 | return zText; | ||||
| 48964 | } | ||||
| 48965 | |||||
| 48966 | /* | ||||
| 48967 | ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM | ||||
| 48968 | ** code page. | ||||
| 48969 | ** | ||||
| 48970 | ** Space to hold the returned string is obtained from sqlite3_malloc(). | ||||
| 48971 | */ | ||||
| 48972 | static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ | ||||
| 48973 | int nWideChar; | ||||
| 48974 | LPWSTR zMbcsText; | ||||
| 48975 | int codepage = useAnsi ? CP_ACP : CP_OEMCP; | ||||
| 48976 | |||||
| 48977 | nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, NULL((void*)0), | ||||
| 48978 | 0); | ||||
| 48979 | if( nWideChar==0 ){ | ||||
| 48980 | return 0; | ||||
| 48981 | } | ||||
| 48982 | zMbcsText = sqlite3MallocZero( nWideChar*sizeof(WCHAR) ); | ||||
| 48983 | if( zMbcsText==0 ){ | ||||
| 48984 | return 0; | ||||
| 48985 | } | ||||
| 48986 | nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, | ||||
| 48987 | nWideChar); | ||||
| 48988 | if( nWideChar==0 ){ | ||||
| 48989 | sqlite3_free(zMbcsText); | ||||
| 48990 | zMbcsText = 0; | ||||
| 48991 | } | ||||
| 48992 | return zMbcsText; | ||||
| 48993 | } | ||||
| 48994 | |||||
| 48995 | #ifdef _WIN32 | ||||
| 48996 | /* | ||||
| 48997 | ** Convert a Microsoft Unicode string to a multi-byte character string, | ||||
| 48998 | ** using the ANSI or OEM code page. | ||||
| 48999 | ** | ||||
| 49000 | ** Space to hold the returned string is obtained from sqlite3_malloc(). | ||||
| 49001 | */ | ||||
| 49002 | static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){ | ||||
| 49003 | int nByte; | ||||
| 49004 | char *zText; | ||||
| 49005 | int codepage = useAnsi ? CP_ACP : CP_OEMCP; | ||||
| 49006 | |||||
| 49007 | nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0); | ||||
| 49008 | if( nByte == 0 ){ | ||||
| 49009 | return 0; | ||||
| 49010 | } | ||||
| 49011 | zText = sqlite3MallocZero( nByte ); | ||||
| 49012 | if( zText==0 ){ | ||||
| 49013 | return 0; | ||||
| 49014 | } | ||||
| 49015 | nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText, | ||||
| 49016 | nByte, 0, 0); | ||||
| 49017 | if( nByte == 0 ){ | ||||
| 49018 | sqlite3_free(zText); | ||||
| 49019 | zText = 0; | ||||
| 49020 | } | ||||
| 49021 | return zText; | ||||
| 49022 | } | ||||
| 49023 | #endif /* _WIN32 */ | ||||
| 49024 | |||||
| 49025 | /* | ||||
| 49026 | ** Convert a multi-byte character string to UTF-8. | ||||
| 49027 | ** | ||||
| 49028 | ** Space to hold the returned string is obtained from sqlite3_malloc(). | ||||
| 49029 | */ | ||||
| 49030 | static char *winMbcsToUtf8(const char *zText, int useAnsi){ | ||||
| 49031 | char *zTextUtf8; | ||||
| 49032 | LPWSTR zTmpWide; | ||||
| 49033 | |||||
| 49034 | zTmpWide = winMbcsToUnicode(zText, useAnsi); | ||||
| 49035 | if( zTmpWide==0 ){ | ||||
| 49036 | return 0; | ||||
| 49037 | } | ||||
| 49038 | zTextUtf8 = winUnicodeToUtf8(zTmpWide); | ||||
| 49039 | sqlite3_free(zTmpWide); | ||||
| 49040 | return zTextUtf8; | ||||
| 49041 | } | ||||
| 49042 | |||||
| 49043 | #ifdef _WIN32 | ||||
| 49044 | /* | ||||
| 49045 | ** Convert a UTF-8 string to a multi-byte character string. | ||||
| 49046 | ** | ||||
| 49047 | ** Space to hold the returned string is obtained from sqlite3_malloc(). | ||||
| 49048 | */ | ||||
| 49049 | static char *winUtf8ToMbcs(const char *zText, int useAnsi){ | ||||
| 49050 | char *zTextMbcs; | ||||
| 49051 | LPWSTR zTmpWide; | ||||
| 49052 | |||||
| 49053 | zTmpWide = winUtf8ToUnicode(zText); | ||||
| 49054 | if( zTmpWide==0 ){ | ||||
| 49055 | return 0; | ||||
| 49056 | } | ||||
| 49057 | zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi); | ||||
| 49058 | sqlite3_free(zTmpWide); | ||||
| 49059 | return zTextMbcs; | ||||
| 49060 | } | ||||
| 49061 | |||||
| 49062 | /* | ||||
| 49063 | ** This is a public wrapper for the winUtf8ToUnicode() function. | ||||
| 49064 | */ | ||||
| 49065 | SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){ | ||||
| 49066 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 49067 | if( !zText ){ | ||||
| 49068 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(49068); | ||||
| 49069 | return 0; | ||||
| 49070 | } | ||||
| 49071 | #endif | ||||
| 49072 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 49073 | if( sqlite3_initialize() ) return 0; | ||||
| 49074 | #endif | ||||
| 49075 | return winUtf8ToUnicode(zText); | ||||
| 49076 | } | ||||
| 49077 | |||||
| 49078 | /* | ||||
| 49079 | ** This is a public wrapper for the winUnicodeToUtf8() function. | ||||
| 49080 | */ | ||||
| 49081 | SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){ | ||||
| 49082 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 49083 | if( !zWideText ){ | ||||
| 49084 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(49084); | ||||
| 49085 | return 0; | ||||
| 49086 | } | ||||
| 49087 | #endif | ||||
| 49088 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 49089 | if( sqlite3_initialize() ) return 0; | ||||
| 49090 | #endif | ||||
| 49091 | return winUnicodeToUtf8(zWideText); | ||||
| 49092 | } | ||||
| 49093 | #endif /* _WIN32 */ | ||||
| 49094 | |||||
| 49095 | /* | ||||
| 49096 | ** This is a public wrapper for the winMbcsToUtf8() function. | ||||
| 49097 | */ | ||||
| 49098 | SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){ | ||||
| 49099 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 49100 | if( !zText ){ | ||||
| 49101 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(49101); | ||||
| 49102 | return 0; | ||||
| 49103 | } | ||||
| 49104 | #endif | ||||
| 49105 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 49106 | if( sqlite3_initialize() ) return 0; | ||||
| 49107 | #endif | ||||
| 49108 | return winMbcsToUtf8(zText, osAreFileApisANSI()); | ||||
| 49109 | } | ||||
| 49110 | |||||
| 49111 | #ifdef _WIN32 | ||||
| 49112 | /* | ||||
| 49113 | ** This is a public wrapper for the winMbcsToUtf8() function. | ||||
| 49114 | */ | ||||
| 49115 | SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){ | ||||
| 49116 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 49117 | if( !zText ){ | ||||
| 49118 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(49118); | ||||
| 49119 | return 0; | ||||
| 49120 | } | ||||
| 49121 | #endif | ||||
| 49122 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 49123 | if( sqlite3_initialize() ) return 0; | ||||
| 49124 | #endif | ||||
| 49125 | return winMbcsToUtf8(zText, useAnsi); | ||||
| 49126 | } | ||||
| 49127 | |||||
| 49128 | /* | ||||
| 49129 | ** This is a public wrapper for the winUtf8ToMbcs() function. | ||||
| 49130 | */ | ||||
| 49131 | SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){ | ||||
| 49132 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 49133 | if( !zText ){ | ||||
| 49134 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(49134); | ||||
| 49135 | return 0; | ||||
| 49136 | } | ||||
| 49137 | #endif | ||||
| 49138 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 49139 | if( sqlite3_initialize() ) return 0; | ||||
| 49140 | #endif | ||||
| 49141 | return winUtf8ToMbcs(zText, osAreFileApisANSI()); | ||||
| 49142 | } | ||||
| 49143 | |||||
| 49144 | /* | ||||
| 49145 | ** This is a public wrapper for the winUtf8ToMbcs() function. | ||||
| 49146 | */ | ||||
| 49147 | SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){ | ||||
| 49148 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 49149 | if( !zText ){ | ||||
| 49150 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(49150); | ||||
| 49151 | return 0; | ||||
| 49152 | } | ||||
| 49153 | #endif | ||||
| 49154 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 49155 | if( sqlite3_initialize() ) return 0; | ||||
| 49156 | #endif | ||||
| 49157 | return winUtf8ToMbcs(zText, useAnsi); | ||||
| 49158 | } | ||||
| 49159 | |||||
| 49160 | /* | ||||
| 49161 | ** This function is the same as sqlite3_win32_set_directory (below); however, | ||||
| 49162 | ** it accepts a UTF-8 string. | ||||
| 49163 | */ | ||||
| 49164 | SQLITE_API int sqlite3_win32_set_directory8( | ||||
| 49165 | unsigned long type, /* Identifier for directory being set or reset */ | ||||
| 49166 | const char *zValue /* New value for directory being set or reset */ | ||||
| 49167 | ){ | ||||
| 49168 | char **ppDirectory = 0; | ||||
| 49169 | int rc; | ||||
| 49170 | #ifndef SQLITE_OMIT_AUTOINIT | ||||
| 49171 | rc = sqlite3_initialize(); | ||||
| 49172 | if( rc ) return rc; | ||||
| 49173 | #endif | ||||
| 49174 | sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 49175 | if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE1 ){ | ||||
| 49176 | ppDirectory = &sqlite3_data_directory; | ||||
| 49177 | }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE2 ){ | ||||
| 49178 | ppDirectory = &sqlite3_temp_directory; | ||||
| 49179 | } | ||||
| 49180 | assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE((void) (0)) | ||||
| 49181 | || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE((void) (0)) | ||||
| 49182 | )((void) (0)); | ||||
| 49183 | assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) )((void) (0)); | ||||
| 49184 | if( ppDirectory ){ | ||||
| 49185 | char *zCopy = 0; | ||||
| 49186 | if( zValue && zValue[0] ){ | ||||
| 49187 | zCopy = sqlite3_mprintf("%s", zValue); | ||||
| 49188 | if ( zCopy==0 ){ | ||||
| 49189 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 49190 | goto set_directory8_done; | ||||
| 49191 | } | ||||
| 49192 | } | ||||
| 49193 | sqlite3_free(*ppDirectory); | ||||
| 49194 | *ppDirectory = zCopy; | ||||
| 49195 | rc = SQLITE_OK0; | ||||
| 49196 | }else{ | ||||
| 49197 | rc = SQLITE_ERROR1; | ||||
| 49198 | } | ||||
| 49199 | set_directory8_done: | ||||
| 49200 | sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 49201 | return rc; | ||||
| 49202 | } | ||||
| 49203 | |||||
| 49204 | /* | ||||
| 49205 | ** This function is the same as sqlite3_win32_set_directory (below); however, | ||||
| 49206 | ** it accepts a UTF-16 string. | ||||
| 49207 | */ | ||||
| 49208 | SQLITE_API int sqlite3_win32_set_directory16( | ||||
| 49209 | unsigned long type, /* Identifier for directory being set or reset */ | ||||
| 49210 | const void *zValue /* New value for directory being set or reset */ | ||||
| 49211 | ){ | ||||
| 49212 | int rc; | ||||
| 49213 | char *zUtf8 = 0; | ||||
| 49214 | if( zValue ){ | ||||
| 49215 | zUtf8 = sqlite3_win32_unicode_to_utf8(zValue); | ||||
| 49216 | if( zUtf8==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 49217 | } | ||||
| 49218 | rc = sqlite3_win32_set_directory8(type, zUtf8); | ||||
| 49219 | if( zUtf8 ) sqlite3_free(zUtf8); | ||||
| 49220 | return rc; | ||||
| 49221 | } | ||||
| 49222 | |||||
| 49223 | /* | ||||
| 49224 | ** This function sets the data directory or the temporary directory based on | ||||
| 49225 | ** the provided arguments. The type argument must be 1 in order to set the | ||||
| 49226 | ** data directory or 2 in order to set the temporary directory. The zValue | ||||
| 49227 | ** argument is the name of the directory to use. The return value will be | ||||
| 49228 | ** SQLITE_OK if successful. | ||||
| 49229 | */ | ||||
| 49230 | SQLITE_API int sqlite3_win32_set_directory( | ||||
| 49231 | unsigned long type, /* Identifier for directory being set or reset */ | ||||
| 49232 | void *zValue /* New value for directory being set or reset */ | ||||
| 49233 | ){ | ||||
| 49234 | return sqlite3_win32_set_directory16(type, zValue); | ||||
| 49235 | } | ||||
| 49236 | #endif /* _WIN32 */ | ||||
| 49237 | |||||
| 49238 | /* | ||||
| 49239 | ** The return value of winGetLastErrorMsg | ||||
| 49240 | ** is zero if the error message fits in the buffer, or non-zero | ||||
| 49241 | ** otherwise (if the message was truncated). | ||||
| 49242 | */ | ||||
| 49243 | static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ | ||||
| 49244 | /* FormatMessage returns 0 on failure. Otherwise it | ||||
| 49245 | ** returns the number of TCHARs written to the output | ||||
| 49246 | ** buffer, excluding the terminating null char. | ||||
| 49247 | */ | ||||
| 49248 | DWORD dwLen = 0; | ||||
| 49249 | char *zOut = 0; | ||||
| 49250 | |||||
| 49251 | if( osIsNT() ){ | ||||
| 49252 | #if SQLITE_OS_WINRT | ||||
| 49253 | WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1]; | ||||
| 49254 | dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | | ||||
| 49255 | FORMAT_MESSAGE_IGNORE_INSERTS, | ||||
| 49256 | NULL((void*)0), | ||||
| 49257 | lastErrno, | ||||
| 49258 | 0, | ||||
| 49259 | zTempWide, | ||||
| 49260 | SQLITE_WIN32_MAX_ERRMSG_CHARS, | ||||
| 49261 | 0); | ||||
| 49262 | #else | ||||
| 49263 | LPWSTR zTempWide = NULL((void*)0); | ||||
| 49264 | dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | | ||||
| 49265 | FORMAT_MESSAGE_FROM_SYSTEM | | ||||
| 49266 | FORMAT_MESSAGE_IGNORE_INSERTS, | ||||
| 49267 | NULL((void*)0), | ||||
| 49268 | lastErrno, | ||||
| 49269 | 0, | ||||
| 49270 | (LPWSTR) &zTempWide, | ||||
| 49271 | 0, | ||||
| 49272 | 0); | ||||
| 49273 | #endif | ||||
| 49274 | if( dwLen > 0 ){ | ||||
| 49275 | /* allocate a buffer and convert to UTF8 */ | ||||
| 49276 | sqlite3BeginBenignMalloc(); | ||||
| 49277 | zOut = winUnicodeToUtf8(zTempWide); | ||||
| 49278 | sqlite3EndBenignMalloc(); | ||||
| 49279 | #if !SQLITE_OS_WINRT | ||||
| 49280 | /* free the system buffer allocated by FormatMessage */ | ||||
| 49281 | osLocalFree(zTempWide); | ||||
| 49282 | #endif | ||||
| 49283 | } | ||||
| 49284 | } | ||||
| 49285 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 49286 | else{ | ||||
| 49287 | char *zTemp = NULL((void*)0); | ||||
| 49288 | dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | | ||||
| 49289 | FORMAT_MESSAGE_FROM_SYSTEM | | ||||
| 49290 | FORMAT_MESSAGE_IGNORE_INSERTS, | ||||
| 49291 | NULL((void*)0), | ||||
| 49292 | lastErrno, | ||||
| 49293 | 0, | ||||
| 49294 | (LPSTR) &zTemp, | ||||
| 49295 | 0, | ||||
| 49296 | 0); | ||||
| 49297 | if( dwLen > 0 ){ | ||||
| 49298 | /* allocate a buffer and convert to UTF8 */ | ||||
| 49299 | sqlite3BeginBenignMalloc(); | ||||
| 49300 | zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); | ||||
| 49301 | sqlite3EndBenignMalloc(); | ||||
| 49302 | /* free the system buffer allocated by FormatMessage */ | ||||
| 49303 | osLocalFree(zTemp); | ||||
| 49304 | } | ||||
| 49305 | } | ||||
| 49306 | #endif | ||||
| 49307 | if( 0 == dwLen ){ | ||||
| 49308 | sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); | ||||
| 49309 | }else{ | ||||
| 49310 | /* copy a maximum of nBuf chars to output buffer */ | ||||
| 49311 | sqlite3_snprintf(nBuf, zBuf, "%s", zOut); | ||||
| 49312 | /* free the UTF8 buffer */ | ||||
| 49313 | sqlite3_free(zOut); | ||||
| 49314 | } | ||||
| 49315 | return 0; | ||||
| 49316 | } | ||||
| 49317 | |||||
| 49318 | /* | ||||
| 49319 | ** | ||||
| 49320 | ** This function - winLogErrorAtLine() - is only ever called via the macro | ||||
| 49321 | ** winLogError(). | ||||
| 49322 | ** | ||||
| 49323 | ** This routine is invoked after an error occurs in an OS function. | ||||
| 49324 | ** It logs a message using sqlite3_log() containing the current value of | ||||
| 49325 | ** error code and, if possible, the human-readable equivalent from | ||||
| 49326 | ** FormatMessage. | ||||
| 49327 | ** | ||||
| 49328 | ** The first argument passed to the macro should be the error code that | ||||
| 49329 | ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). | ||||
| 49330 | ** The two subsequent arguments should be the name of the OS function that | ||||
| 49331 | ** failed and the associated file-system path, if any. | ||||
| 49332 | */ | ||||
| 49333 | #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__49333) | ||||
| 49334 | static int winLogErrorAtLine( | ||||
| 49335 | int errcode, /* SQLite error code */ | ||||
| 49336 | DWORD lastErrno, /* Win32 last error */ | ||||
| 49337 | const char *zFunc, /* Name of OS function that failed */ | ||||
| 49338 | const char *zPath, /* File path associated with error */ | ||||
| 49339 | int iLine /* Source line number where error occurred */ | ||||
| 49340 | ){ | ||||
| 49341 | char zMsg[500]; /* Human readable error text */ | ||||
| 49342 | int i; /* Loop counter */ | ||||
| 49343 | |||||
| 49344 | zMsg[0] = 0; | ||||
| 49345 | winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg); | ||||
| 49346 | assert( errcode!=SQLITE_OK )((void) (0)); | ||||
| 49347 | if( zPath==0 ) zPath = ""; | ||||
| 49348 | for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){} | ||||
| 49349 | zMsg[i] = 0; | ||||
| 49350 | sqlite3_log(errcode, | ||||
| 49351 | "os_win.c:%d: (%lu) %s(%s) - %s", | ||||
| 49352 | iLine, lastErrno, zFunc, zPath, zMsg | ||||
| 49353 | ); | ||||
| 49354 | |||||
| 49355 | return errcode; | ||||
| 49356 | } | ||||
| 49357 | |||||
| 49358 | /* | ||||
| 49359 | ** The number of times that a ReadFile(), WriteFile(), and DeleteFile() | ||||
| 49360 | ** will be retried following a locking error - probably caused by | ||||
| 49361 | ** antivirus software. Also the initial delay before the first retry. | ||||
| 49362 | ** The delay increases linearly with each retry. | ||||
| 49363 | */ | ||||
| 49364 | #ifndef SQLITE_WIN32_IOERR_RETRY | ||||
| 49365 | # define SQLITE_WIN32_IOERR_RETRY 10 | ||||
| 49366 | #endif | ||||
| 49367 | #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY | ||||
| 49368 | # define SQLITE_WIN32_IOERR_RETRY_DELAY 25 | ||||
| 49369 | #endif | ||||
| 49370 | static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY; | ||||
| 49371 | static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY; | ||||
| 49372 | |||||
| 49373 | /* | ||||
| 49374 | ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O | ||||
| 49375 | ** error code obtained via GetLastError() is eligible to be retried. It | ||||
| 49376 | ** must accept the error code DWORD as its only argument and should return | ||||
| 49377 | ** non-zero if the error code is transient in nature and the operation | ||||
| 49378 | ** responsible for generating the original error might succeed upon being | ||||
| 49379 | ** retried. The argument to this macro should be a variable. | ||||
| 49380 | ** | ||||
| 49381 | ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it | ||||
| 49382 | ** is defined, it will be consulted only when the macro "winIoerrCanRetry1" | ||||
| 49383 | ** returns zero. The "winIoerrCanRetry2" macro is completely optional and | ||||
| 49384 | ** may be used to include additional error codes in the set that should | ||||
| 49385 | ** result in the failing I/O operation being retried by the caller. If | ||||
| 49386 | ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics | ||||
| 49387 | ** identical to those of the "winIoerrCanRetry1" macro. | ||||
| 49388 | */ | ||||
| 49389 | #if !defined(winIoerrCanRetry1) | ||||
| 49390 | #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \ | ||||
| 49391 | ((a)==ERROR_SHARING_VIOLATION) || \ | ||||
| 49392 | ((a)==ERROR_LOCK_VIOLATION) || \ | ||||
| 49393 | ((a)==ERROR_DEV_NOT_EXIST) || \ | ||||
| 49394 | ((a)==ERROR_NETNAME_DELETED) || \ | ||||
| 49395 | ((a)==ERROR_SEM_TIMEOUT) || \ | ||||
| 49396 | ((a)==ERROR_NETWORK_UNREACHABLE)) | ||||
| 49397 | #endif | ||||
| 49398 | |||||
| 49399 | /* | ||||
| 49400 | ** If a ReadFile() or WriteFile() error occurs, invoke this routine | ||||
| 49401 | ** to see if it should be retried. Return TRUE to retry. Return FALSE | ||||
| 49402 | ** to give up with an error. | ||||
| 49403 | */ | ||||
| 49404 | static int winRetryIoerr(int *pnRetry, DWORD *pError){ | ||||
| 49405 | DWORD e = osGetLastError(); | ||||
| 49406 | if( *pnRetry>=winIoerrRetry ){ | ||||
| 49407 | if( pError ){ | ||||
| 49408 | *pError = e; | ||||
| 49409 | } | ||||
| 49410 | return 0; | ||||
| 49411 | } | ||||
| 49412 | if( winIoerrCanRetry1(e) ){ | ||||
| 49413 | sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); | ||||
| 49414 | ++*pnRetry; | ||||
| 49415 | return 1; | ||||
| 49416 | } | ||||
| 49417 | #if defined(winIoerrCanRetry2) | ||||
| 49418 | else if( winIoerrCanRetry2(e) ){ | ||||
| 49419 | sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); | ||||
| 49420 | ++*pnRetry; | ||||
| 49421 | return 1; | ||||
| 49422 | } | ||||
| 49423 | #endif | ||||
| 49424 | if( pError ){ | ||||
| 49425 | *pError = e; | ||||
| 49426 | } | ||||
| 49427 | return 0; | ||||
| 49428 | } | ||||
| 49429 | |||||
| 49430 | /* | ||||
| 49431 | ** Log a I/O error retry episode. | ||||
| 49432 | */ | ||||
| 49433 | static void winLogIoerr(int nRetry, int lineno){ | ||||
| 49434 | if( nRetry ){ | ||||
| 49435 | sqlite3_log(SQLITE_NOTICE27, | ||||
| 49436 | "delayed %dms for lock/sharing conflict at line %d", | ||||
| 49437 | winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno | ||||
| 49438 | ); | ||||
| 49439 | } | ||||
| 49440 | } | ||||
| 49441 | |||||
| 49442 | /* | ||||
| 49443 | ** This #if does not rely on the SQLITE_OS_WINCE define because the | ||||
| 49444 | ** corresponding section in "date.c" cannot use it. | ||||
| 49445 | */ | ||||
| 49446 | #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \ | ||||
| 49447 | (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API) | ||||
| 49448 | /* | ||||
| 49449 | ** The MSVC CRT on Windows CE may not have a localtime() function. | ||||
| 49450 | ** So define a substitute. | ||||
| 49451 | */ | ||||
| 49452 | /* # include <time.h> */ | ||||
| 49453 | struct tm *__cdecl localtime(const time_t *t) | ||||
| 49454 | { | ||||
| 49455 | static struct tm y; | ||||
| 49456 | FILETIME uTm, lTm; | ||||
| 49457 | SYSTEMTIME pTm; | ||||
| 49458 | sqlite3_int64 t64; | ||||
| 49459 | t64 = *t; | ||||
| 49460 | t64 = (t64 + 11644473600)*10000000; | ||||
| 49461 | uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF); | ||||
| 49462 | uTm.dwHighDateTime= (DWORD)(t64 >> 32); | ||||
| 49463 | osFileTimeToLocalFileTime(&uTm,&lTm); | ||||
| 49464 | osFileTimeToSystemTime(&lTm,&pTm); | ||||
| 49465 | y.tm_year = pTm.wYear - 1900; | ||||
| 49466 | y.tm_mon = pTm.wMonth - 1; | ||||
| 49467 | y.tm_wday = pTm.wDayOfWeek; | ||||
| 49468 | y.tm_mday = pTm.wDay; | ||||
| 49469 | y.tm_hour = pTm.wHour; | ||||
| 49470 | y.tm_min = pTm.wMinute; | ||||
| 49471 | y.tm_sec = pTm.wSecond; | ||||
| 49472 | return &y; | ||||
| 49473 | } | ||||
| 49474 | #endif | ||||
| 49475 | |||||
| 49476 | #if SQLITE_OS_WINCE | ||||
| 49477 | /************************************************************************* | ||||
| 49478 | ** This section contains code for WinCE only. | ||||
| 49479 | */ | ||||
| 49480 | #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)__builtin_offsetof(winFile, h)] | ||||
| 49481 | |||||
| 49482 | /* | ||||
| 49483 | ** Acquire a lock on the handle h | ||||
| 49484 | */ | ||||
| 49485 | static void winceMutexAcquire(HANDLE h){ | ||||
| 49486 | DWORD dwErr; | ||||
| 49487 | do { | ||||
| 49488 | dwErr = osWaitForSingleObject(h, INFINITE); | ||||
| 49489 | } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED); | ||||
| 49490 | } | ||||
| 49491 | /* | ||||
| 49492 | ** Release a lock acquired by winceMutexAcquire() | ||||
| 49493 | */ | ||||
| 49494 | #define winceMutexRelease(h) ReleaseMutex(h) | ||||
| 49495 | |||||
| 49496 | /* | ||||
| 49497 | ** Create the mutex and shared memory used for locking in the file | ||||
| 49498 | ** descriptor pFile | ||||
| 49499 | */ | ||||
| 49500 | static int winceCreateLock(const char *zFilename, winFile *pFile){ | ||||
| 49501 | LPWSTR zTok; | ||||
| 49502 | LPWSTR zName; | ||||
| 49503 | DWORD lastErrno; | ||||
| 49504 | BOOL bLogged = FALSE; | ||||
| 49505 | BOOL bInit = TRUE; | ||||
| 49506 | |||||
| 49507 | zName = winUtf8ToUnicode(zFilename); | ||||
| 49508 | if( zName==0 ){ | ||||
| 49509 | /* out of memory */ | ||||
| 49510 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 49511 | } | ||||
| 49512 | |||||
| 49513 | /* Initialize the local lockdata */ | ||||
| 49514 | memset(&pFile->local, 0, sizeof(pFile->local)); | ||||
| 49515 | |||||
| 49516 | /* Replace the backslashes from the filename and lowercase it | ||||
| 49517 | ** to derive a mutex name. */ | ||||
| 49518 | zTok = osCharLowerW(zName); | ||||
| 49519 | for (;*zTok;zTok++){ | ||||
| 49520 | if (*zTok == '\\') *zTok = '_'; | ||||
| 49521 | } | ||||
| 49522 | |||||
| 49523 | /* Create/open the named mutex */ | ||||
| 49524 | pFile->hMutex = osCreateMutexW(NULL((void*)0), FALSE, zName); | ||||
| 49525 | if (!pFile->hMutex){ | ||||
| 49526 | pFile->lastErrno = osGetLastError(); | ||||
| 49527 | sqlite3_free(zName); | ||||
| 49528 | return winLogError(SQLITE_IOERR10, pFile->lastErrno, | ||||
| 49529 | "winceCreateLock1", zFilename); | ||||
| 49530 | } | ||||
| 49531 | |||||
| 49532 | /* Acquire the mutex before continuing */ | ||||
| 49533 | winceMutexAcquire(pFile->hMutex); | ||||
| 49534 | |||||
| 49535 | /* Since the names of named mutexes, semaphores, file mappings etc are | ||||
| 49536 | ** case-sensitive, take advantage of that by uppercasing the mutex name | ||||
| 49537 | ** and using that as the shared filemapping name. | ||||
| 49538 | */ | ||||
| 49539 | osCharUpperW(zName); | ||||
| 49540 | pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL((void*)0), | ||||
| 49541 | PAGE_READWRITE, 0, sizeof(winceLock), | ||||
| 49542 | zName); | ||||
| 49543 | |||||
| 49544 | /* Set a flag that indicates we're the first to create the memory so it | ||||
| 49545 | ** must be zero-initialized */ | ||||
| 49546 | lastErrno = osGetLastError(); | ||||
| 49547 | if (lastErrno == ERROR_ALREADY_EXISTS){ | ||||
| 49548 | bInit = FALSE; | ||||
| 49549 | } | ||||
| 49550 | |||||
| 49551 | sqlite3_free(zName); | ||||
| 49552 | |||||
| 49553 | /* If we succeeded in making the shared memory handle, map it. */ | ||||
| 49554 | if( pFile->hShared ){ | ||||
| 49555 | pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, | ||||
| 49556 | FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock)); | ||||
| 49557 | /* If mapping failed, close the shared memory handle and erase it */ | ||||
| 49558 | if( !pFile->shared ){ | ||||
| 49559 | pFile->lastErrno = osGetLastError(); | ||||
| 49560 | winLogError(SQLITE_IOERR10, pFile->lastErrno, | ||||
| 49561 | "winceCreateLock2", zFilename); | ||||
| 49562 | bLogged = TRUE; | ||||
| 49563 | osCloseHandle(pFile->hShared); | ||||
| 49564 | pFile->hShared = NULL((void*)0); | ||||
| 49565 | } | ||||
| 49566 | } | ||||
| 49567 | |||||
| 49568 | /* If shared memory could not be created, then close the mutex and fail */ | ||||
| 49569 | if( pFile->hShared==NULL((void*)0) ){ | ||||
| 49570 | if( !bLogged ){ | ||||
| 49571 | pFile->lastErrno = lastErrno; | ||||
| 49572 | winLogError(SQLITE_IOERR10, pFile->lastErrno, | ||||
| 49573 | "winceCreateLock3", zFilename); | ||||
| 49574 | bLogged = TRUE; | ||||
| 49575 | } | ||||
| 49576 | winceMutexRelease(pFile->hMutex); | ||||
| 49577 | osCloseHandle(pFile->hMutex); | ||||
| 49578 | pFile->hMutex = NULL((void*)0); | ||||
| 49579 | return SQLITE_IOERR10; | ||||
| 49580 | } | ||||
| 49581 | |||||
| 49582 | /* Initialize the shared memory if we're supposed to */ | ||||
| 49583 | if( bInit ){ | ||||
| 49584 | memset(pFile->shared, 0, sizeof(winceLock)); | ||||
| 49585 | } | ||||
| 49586 | |||||
| 49587 | winceMutexRelease(pFile->hMutex); | ||||
| 49588 | return SQLITE_OK0; | ||||
| 49589 | } | ||||
| 49590 | |||||
| 49591 | /* | ||||
| 49592 | ** Destroy the part of winFile that deals with wince locks | ||||
| 49593 | */ | ||||
| 49594 | static void winceDestroyLock(winFile *pFile){ | ||||
| 49595 | if (pFile->hMutex){ | ||||
| 49596 | /* Acquire the mutex */ | ||||
| 49597 | winceMutexAcquire(pFile->hMutex); | ||||
| 49598 | |||||
| 49599 | /* The following blocks should probably assert in debug mode, but they | ||||
| 49600 | are to cleanup in case any locks remained open */ | ||||
| 49601 | if (pFile->local.nReaders){ | ||||
| 49602 | pFile->shared->nReaders --; | ||||
| 49603 | } | ||||
| 49604 | if (pFile->local.bReserved){ | ||||
| 49605 | pFile->shared->bReserved = FALSE; | ||||
| 49606 | } | ||||
| 49607 | if (pFile->local.bPending){ | ||||
| 49608 | pFile->shared->bPending = FALSE; | ||||
| 49609 | } | ||||
| 49610 | if (pFile->local.bExclusive){ | ||||
| 49611 | pFile->shared->bExclusive = FALSE; | ||||
| 49612 | } | ||||
| 49613 | |||||
| 49614 | /* De-reference and close our copy of the shared memory handle */ | ||||
| 49615 | osUnmapViewOfFile(pFile->shared); | ||||
| 49616 | osCloseHandle(pFile->hShared); | ||||
| 49617 | |||||
| 49618 | /* Done with the mutex */ | ||||
| 49619 | winceMutexRelease(pFile->hMutex); | ||||
| 49620 | osCloseHandle(pFile->hMutex); | ||||
| 49621 | pFile->hMutex = NULL((void*)0); | ||||
| 49622 | } | ||||
| 49623 | } | ||||
| 49624 | |||||
| 49625 | /* | ||||
| 49626 | ** An implementation of the LockFile() API of Windows for CE | ||||
| 49627 | */ | ||||
| 49628 | static BOOL winceLockFile( | ||||
| 49629 | LPHANDLE phFile, | ||||
| 49630 | DWORD dwFileOffsetLow, | ||||
| 49631 | DWORD dwFileOffsetHigh, | ||||
| 49632 | DWORD nNumberOfBytesToLockLow, | ||||
| 49633 | DWORD nNumberOfBytesToLockHigh | ||||
| 49634 | ){ | ||||
| 49635 | winFile *pFile = HANDLE_TO_WINFILE(phFile); | ||||
| 49636 | BOOL bReturn = FALSE; | ||||
| 49637 | |||||
| 49638 | UNUSED_PARAMETER(dwFileOffsetHigh)(void)(dwFileOffsetHigh); | ||||
| 49639 | UNUSED_PARAMETER(nNumberOfBytesToLockHigh)(void)(nNumberOfBytesToLockHigh); | ||||
| 49640 | |||||
| 49641 | if (!pFile->hMutex) return TRUE; | ||||
| 49642 | winceMutexAcquire(pFile->hMutex); | ||||
| 49643 | |||||
| 49644 | /* Wanting an exclusive lock? */ | ||||
| 49645 | if (dwFileOffsetLow == (DWORD)SHARED_FIRST(sqlite3PendingByte+2) | ||||
| 49646 | && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE510){ | ||||
| 49647 | if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){ | ||||
| 49648 | pFile->shared->bExclusive = TRUE; | ||||
| 49649 | pFile->local.bExclusive = TRUE; | ||||
| 49650 | bReturn = TRUE; | ||||
| 49651 | } | ||||
| 49652 | } | ||||
| 49653 | |||||
| 49654 | /* Want a read-only lock? */ | ||||
| 49655 | else if (dwFileOffsetLow == (DWORD)SHARED_FIRST(sqlite3PendingByte+2) && | ||||
| 49656 | nNumberOfBytesToLockLow == 1){ | ||||
| 49657 | if (pFile->shared->bExclusive == 0){ | ||||
| 49658 | pFile->local.nReaders ++; | ||||
| 49659 | if (pFile->local.nReaders == 1){ | ||||
| 49660 | pFile->shared->nReaders ++; | ||||
| 49661 | } | ||||
| 49662 | bReturn = TRUE; | ||||
| 49663 | } | ||||
| 49664 | } | ||||
| 49665 | |||||
| 49666 | /* Want a pending lock? */ | ||||
| 49667 | else if (dwFileOffsetLow == (DWORD)PENDING_BYTEsqlite3PendingByte | ||||
| 49668 | && nNumberOfBytesToLockLow == 1){ | ||||
| 49669 | /* If no pending lock has been acquired, then acquire it */ | ||||
| 49670 | if (pFile->shared->bPending == 0) { | ||||
| 49671 | pFile->shared->bPending = TRUE; | ||||
| 49672 | pFile->local.bPending = TRUE; | ||||
| 49673 | bReturn = TRUE; | ||||
| 49674 | } | ||||
| 49675 | } | ||||
| 49676 | |||||
| 49677 | /* Want a reserved lock? */ | ||||
| 49678 | else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE(sqlite3PendingByte+1) | ||||
| 49679 | && nNumberOfBytesToLockLow == 1){ | ||||
| 49680 | if (pFile->shared->bReserved == 0) { | ||||
| 49681 | pFile->shared->bReserved = TRUE; | ||||
| 49682 | pFile->local.bReserved = TRUE; | ||||
| 49683 | bReturn = TRUE; | ||||
| 49684 | } | ||||
| 49685 | } | ||||
| 49686 | |||||
| 49687 | winceMutexRelease(pFile->hMutex); | ||||
| 49688 | return bReturn; | ||||
| 49689 | } | ||||
| 49690 | |||||
| 49691 | /* | ||||
| 49692 | ** An implementation of the UnlockFile API of Windows for CE | ||||
| 49693 | */ | ||||
| 49694 | static BOOL winceUnlockFile( | ||||
| 49695 | LPHANDLE phFile, | ||||
| 49696 | DWORD dwFileOffsetLow, | ||||
| 49697 | DWORD dwFileOffsetHigh, | ||||
| 49698 | DWORD nNumberOfBytesToUnlockLow, | ||||
| 49699 | DWORD nNumberOfBytesToUnlockHigh | ||||
| 49700 | ){ | ||||
| 49701 | winFile *pFile = HANDLE_TO_WINFILE(phFile); | ||||
| 49702 | BOOL bReturn = FALSE; | ||||
| 49703 | |||||
| 49704 | UNUSED_PARAMETER(dwFileOffsetHigh)(void)(dwFileOffsetHigh); | ||||
| 49705 | UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh)(void)(nNumberOfBytesToUnlockHigh); | ||||
| 49706 | |||||
| 49707 | if (!pFile->hMutex) return TRUE; | ||||
| 49708 | winceMutexAcquire(pFile->hMutex); | ||||
| 49709 | |||||
| 49710 | /* Releasing a reader lock or an exclusive lock */ | ||||
| 49711 | if (dwFileOffsetLow == (DWORD)SHARED_FIRST(sqlite3PendingByte+2)){ | ||||
| 49712 | /* Did we have an exclusive lock? */ | ||||
| 49713 | if (pFile->local.bExclusive){ | ||||
| 49714 | assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE)((void) (0)); | ||||
| 49715 | pFile->local.bExclusive = FALSE; | ||||
| 49716 | pFile->shared->bExclusive = FALSE; | ||||
| 49717 | bReturn = TRUE; | ||||
| 49718 | } | ||||
| 49719 | |||||
| 49720 | /* Did we just have a reader lock? */ | ||||
| 49721 | else if (pFile->local.nReaders){ | ||||
| 49722 | assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE((void) (0)) | ||||
| 49723 | || nNumberOfBytesToUnlockLow == 1)((void) (0)); | ||||
| 49724 | pFile->local.nReaders --; | ||||
| 49725 | if (pFile->local.nReaders == 0) | ||||
| 49726 | { | ||||
| 49727 | pFile->shared->nReaders --; | ||||
| 49728 | } | ||||
| 49729 | bReturn = TRUE; | ||||
| 49730 | } | ||||
| 49731 | } | ||||
| 49732 | |||||
| 49733 | /* Releasing a pending lock */ | ||||
| 49734 | else if (dwFileOffsetLow == (DWORD)PENDING_BYTEsqlite3PendingByte | ||||
| 49735 | && nNumberOfBytesToUnlockLow == 1){ | ||||
| 49736 | if (pFile->local.bPending){ | ||||
| 49737 | pFile->local.bPending = FALSE; | ||||
| 49738 | pFile->shared->bPending = FALSE; | ||||
| 49739 | bReturn = TRUE; | ||||
| 49740 | } | ||||
| 49741 | } | ||||
| 49742 | /* Releasing a reserved lock */ | ||||
| 49743 | else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE(sqlite3PendingByte+1) | ||||
| 49744 | && nNumberOfBytesToUnlockLow == 1){ | ||||
| 49745 | if (pFile->local.bReserved) { | ||||
| 49746 | pFile->local.bReserved = FALSE; | ||||
| 49747 | pFile->shared->bReserved = FALSE; | ||||
| 49748 | bReturn = TRUE; | ||||
| 49749 | } | ||||
| 49750 | } | ||||
| 49751 | |||||
| 49752 | winceMutexRelease(pFile->hMutex); | ||||
| 49753 | return bReturn; | ||||
| 49754 | } | ||||
| 49755 | /* | ||||
| 49756 | ** End of the special code for wince | ||||
| 49757 | *****************************************************************************/ | ||||
| 49758 | #endif /* SQLITE_OS_WINCE */ | ||||
| 49759 | |||||
| 49760 | /* | ||||
| 49761 | ** Lock a file region. | ||||
| 49762 | */ | ||||
| 49763 | static BOOL winLockFile( | ||||
| 49764 | LPHANDLE phFile, | ||||
| 49765 | DWORD flags, | ||||
| 49766 | DWORD offsetLow, | ||||
| 49767 | DWORD offsetHigh, | ||||
| 49768 | DWORD numBytesLow, | ||||
| 49769 | DWORD numBytesHigh | ||||
| 49770 | ){ | ||||
| 49771 | #if SQLITE_OS_WINCE | ||||
| 49772 | /* | ||||
| 49773 | ** NOTE: Windows CE is handled differently here due its lack of the Win32 | ||||
| 49774 | ** API LockFile. | ||||
| 49775 | */ | ||||
| 49776 | return winceLockFile(phFile, offsetLow, offsetHigh, | ||||
| 49777 | numBytesLow, numBytesHigh); | ||||
| 49778 | #else | ||||
| 49779 | if( osIsNT() ){ | ||||
| 49780 | OVERLAPPED ovlp; | ||||
| 49781 | memset(&ovlp, 0, sizeof(OVERLAPPED)); | ||||
| 49782 | ovlp.Offset = offsetLow; | ||||
| 49783 | ovlp.OffsetHigh = offsetHigh; | ||||
| 49784 | return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp); | ||||
| 49785 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 49786 | }else{ | ||||
| 49787 | return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow, | ||||
| 49788 | numBytesHigh); | ||||
| 49789 | #endif | ||||
| 49790 | } | ||||
| 49791 | #endif | ||||
| 49792 | } | ||||
| 49793 | |||||
| 49794 | /* | ||||
| 49795 | ** Lock a region of nByte bytes starting at offset offset of file hFile. | ||||
| 49796 | ** Take an EXCLUSIVE lock if parameter bExclusive is true, or a SHARED lock | ||||
| 49797 | ** otherwise. If nMs is greater than zero and the lock cannot be obtained | ||||
| 49798 | ** immediately, block for that many ms before giving up. | ||||
| 49799 | ** | ||||
| 49800 | ** This function returns SQLITE_OK if the lock is obtained successfully. If | ||||
| 49801 | ** some other process holds the lock, SQLITE_BUSY is returned if nMs==0, or | ||||
| 49802 | ** SQLITE_BUSY_TIMEOUT otherwise. Or, if an error occurs, SQLITE_IOERR. | ||||
| 49803 | */ | ||||
| 49804 | static int winHandleLockTimeout( | ||||
| 49805 | HANDLE hFile, | ||||
| 49806 | DWORD offset, | ||||
| 49807 | DWORD nByte, | ||||
| 49808 | int bExcl, | ||||
| 49809 | DWORD nMs | ||||
| 49810 | ){ | ||||
| 49811 | DWORD flags = LOCKFILE_FAIL_IMMEDIATELY | (bExcl?LOCKFILE_EXCLUSIVE_LOCK:0); | ||||
| 49812 | int rc = SQLITE_OK0; | ||||
| 49813 | BOOL ret; | ||||
| 49814 | |||||
| 49815 | if( !osIsNT() ){ | ||||
| 49816 | ret = winLockFile(&hFile, flags, offset, 0, nByte, 0); | ||||
| 49817 | }else{ | ||||
| 49818 | OVERLAPPED ovlp; | ||||
| 49819 | memset(&ovlp, 0, sizeof(OVERLAPPED)); | ||||
| 49820 | ovlp.Offset = offset; | ||||
| 49821 | |||||
| 49822 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 49823 | if( nMs!=0 ){ | ||||
| 49824 | flags &= ~LOCKFILE_FAIL_IMMEDIATELY; | ||||
| 49825 | } | ||||
| 49826 | ovlp.hEvent = osCreateEvent(NULL((void*)0), TRUE, FALSE, NULL((void*)0)); | ||||
| 49827 | if( ovlp.hEvent==NULL((void*)0) ){ | ||||
| 49828 | return SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 49829 | } | ||||
| 49830 | #endif | ||||
| 49831 | |||||
| 49832 | ret = osLockFileEx(hFile, flags, 0, nByte, 0, &ovlp); | ||||
| 49833 | |||||
| 49834 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 49835 | /* If SQLITE_ENABLE_SETLK_TIMEOUT is defined, then the file-handle was | ||||
| 49836 | ** opened with FILE_FLAG_OVERHEAD specified. In this case, the call to | ||||
| 49837 | ** LockFileEx() may fail because the request is still pending. This can | ||||
| 49838 | ** happen even if LOCKFILE_FAIL_IMMEDIATELY was specified. | ||||
| 49839 | ** | ||||
| 49840 | ** If nMs is 0, then LOCKFILE_FAIL_IMMEDIATELY was set in the flags | ||||
| 49841 | ** passed to LockFileEx(). In this case, if the operation is pending, | ||||
| 49842 | ** block indefinitely until it is finished. | ||||
| 49843 | ** | ||||
| 49844 | ** Otherwise, wait for up to nMs ms for the operation to finish. nMs | ||||
| 49845 | ** may be set to INFINITE. | ||||
| 49846 | */ | ||||
| 49847 | if( !ret && GetLastError()==ERROR_IO_PENDING ){ | ||||
| 49848 | DWORD nDelay = (nMs==0 ? INFINITE : nMs); | ||||
| 49849 | DWORD res = osWaitForSingleObject(ovlp.hEvent, nDelay); | ||||
| 49850 | if( res==WAIT_OBJECT_0 ){ | ||||
| 49851 | ret = TRUE; | ||||
| 49852 | }else if( res==WAIT_TIMEOUT ){ | ||||
| 49853 | #if SQLITE_ENABLE_SETLK_TIMEOUT==1 | ||||
| 49854 | rc = SQLITE_BUSY_TIMEOUT(5 | (3<<8)); | ||||
| 49855 | #else | ||||
| 49856 | rc = SQLITE_BUSY5; | ||||
| 49857 | #endif | ||||
| 49858 | }else{ | ||||
| 49859 | /* Some other error has occurred */ | ||||
| 49860 | rc = SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 49861 | } | ||||
| 49862 | |||||
| 49863 | /* If it is still pending, cancel the LockFileEx() call. */ | ||||
| 49864 | osCancelIo(hFile); | ||||
| 49865 | } | ||||
| 49866 | |||||
| 49867 | osCloseHandle(ovlp.hEvent); | ||||
| 49868 | #endif | ||||
| 49869 | } | ||||
| 49870 | |||||
| 49871 | if( rc==SQLITE_OK0 && !ret ){ | ||||
| 49872 | rc = SQLITE_BUSY5; | ||||
| 49873 | } | ||||
| 49874 | return rc; | ||||
| 49875 | } | ||||
| 49876 | |||||
| 49877 | /* | ||||
| 49878 | ** Unlock a file region. | ||||
| 49879 | */ | ||||
| 49880 | static BOOL winUnlockFile( | ||||
| 49881 | LPHANDLE phFile, | ||||
| 49882 | DWORD offsetLow, | ||||
| 49883 | DWORD offsetHigh, | ||||
| 49884 | DWORD numBytesLow, | ||||
| 49885 | DWORD numBytesHigh | ||||
| 49886 | ){ | ||||
| 49887 | #if SQLITE_OS_WINCE | ||||
| 49888 | /* | ||||
| 49889 | ** NOTE: Windows CE is handled differently here due its lack of the Win32 | ||||
| 49890 | ** API UnlockFile. | ||||
| 49891 | */ | ||||
| 49892 | return winceUnlockFile(phFile, offsetLow, offsetHigh, | ||||
| 49893 | numBytesLow, numBytesHigh); | ||||
| 49894 | #else | ||||
| 49895 | if( osIsNT() ){ | ||||
| 49896 | OVERLAPPED ovlp; | ||||
| 49897 | memset(&ovlp, 0, sizeof(OVERLAPPED)); | ||||
| 49898 | ovlp.Offset = offsetLow; | ||||
| 49899 | ovlp.OffsetHigh = offsetHigh; | ||||
| 49900 | return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp); | ||||
| 49901 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 49902 | }else{ | ||||
| 49903 | return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow, | ||||
| 49904 | numBytesHigh); | ||||
| 49905 | #endif | ||||
| 49906 | } | ||||
| 49907 | #endif | ||||
| 49908 | } | ||||
| 49909 | |||||
| 49910 | /* | ||||
| 49911 | ** Remove an nByte lock starting at offset iOff from HANDLE h. | ||||
| 49912 | */ | ||||
| 49913 | static int winHandleUnlock(HANDLE h, int iOff, int nByte){ | ||||
| 49914 | BOOL ret = winUnlockFile(&h, iOff, 0, nByte, 0); | ||||
| 49915 | return (ret ? SQLITE_OK0 : SQLITE_IOERR_UNLOCK(10 | (8<<8))); | ||||
| 49916 | } | ||||
| 49917 | |||||
| 49918 | /***************************************************************************** | ||||
| 49919 | ** The next group of routines implement the I/O methods specified | ||||
| 49920 | ** by the sqlite3_io_methods object. | ||||
| 49921 | ******************************************************************************/ | ||||
| 49922 | |||||
| 49923 | /* | ||||
| 49924 | ** Some Microsoft compilers lack this definition. | ||||
| 49925 | */ | ||||
| 49926 | #ifndef INVALID_SET_FILE_POINTER | ||||
| 49927 | # define INVALID_SET_FILE_POINTER ((DWORD)-1) | ||||
| 49928 | #endif | ||||
| 49929 | |||||
| 49930 | /* | ||||
| 49931 | ** Seek the file handle h to offset nByte of the file. | ||||
| 49932 | ** | ||||
| 49933 | ** If successful, return SQLITE_OK. Or, if an error occurs, return an SQLite | ||||
| 49934 | ** error code. | ||||
| 49935 | */ | ||||
| 49936 | static int winHandleSeek(HANDLE h, sqlite3_int64 iOffset){ | ||||
| 49937 | int rc = SQLITE_OK0; /* Return value */ | ||||
| 49938 | |||||
| 49939 | #if !SQLITE_OS_WINRT | ||||
| 49940 | LONG upperBits; /* Most sig. 32 bits of new offset */ | ||||
| 49941 | LONG lowerBits; /* Least sig. 32 bits of new offset */ | ||||
| 49942 | DWORD dwRet; /* Value returned by SetFilePointer() */ | ||||
| 49943 | |||||
| 49944 | upperBits = (LONG)((iOffset>>32) & 0x7fffffff); | ||||
| 49945 | lowerBits = (LONG)(iOffset & 0xffffffff); | ||||
| 49946 | |||||
| 49947 | dwRet = osSetFilePointer(h, lowerBits, &upperBits, FILE_BEGIN); | ||||
| 49948 | |||||
| 49949 | /* API oddity: If successful, SetFilePointer() returns a dword | ||||
| 49950 | ** containing the lower 32-bits of the new file-offset. Or, if it fails, | ||||
| 49951 | ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, | ||||
| 49952 | ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine | ||||
| 49953 | ** whether an error has actually occurred, it is also necessary to call | ||||
| 49954 | ** GetLastError(). */ | ||||
| 49955 | if( dwRet==INVALID_SET_FILE_POINTER ){ | ||||
| 49956 | DWORD lastErrno = osGetLastError(); | ||||
| 49957 | if( lastErrno!=NO_ERROR ){ | ||||
| 49958 | rc = SQLITE_IOERR_SEEK(10 | (22<<8)); | ||||
| 49959 | } | ||||
| 49960 | } | ||||
| 49961 | #else | ||||
| 49962 | /* This implementation works for WinRT. */ | ||||
| 49963 | LARGE_INTEGER x; /* The new offset */ | ||||
| 49964 | BOOL bRet; /* Value returned by SetFilePointerEx() */ | ||||
| 49965 | |||||
| 49966 | x.QuadPart = iOffset; | ||||
| 49967 | bRet = osSetFilePointerEx(h, x, 0, FILE_BEGIN); | ||||
| 49968 | |||||
| 49969 | if(!bRet){ | ||||
| 49970 | rc = SQLITE_IOERR_SEEK(10 | (22<<8)); | ||||
| 49971 | } | ||||
| 49972 | #endif | ||||
| 49973 | |||||
| 49974 | OSTRACE(("SEEK file=%p, offset=%lld rc=%s\n", h, iOffset, sqlite3ErrName(rc))); | ||||
| 49975 | return rc; | ||||
| 49976 | } | ||||
| 49977 | |||||
| 49978 | /* | ||||
| 49979 | ** Move the current position of the file handle passed as the first | ||||
| 49980 | ** argument to offset iOffset within the file. If successful, return 0. | ||||
| 49981 | ** Otherwise, set pFile->lastErrno and return non-zero. | ||||
| 49982 | */ | ||||
| 49983 | static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ | ||||
| 49984 | int rc; | ||||
| 49985 | |||||
| 49986 | rc = winHandleSeek(pFile->h, iOffset); | ||||
| 49987 | if( rc!=SQLITE_OK0 ){ | ||||
| 49988 | pFile->lastErrno = osGetLastError(); | ||||
| 49989 | winLogError(rc, pFile->lastErrno, "winSeekFile", pFile->zPath); | ||||
| 49990 | } | ||||
| 49991 | return rc; | ||||
| 49992 | } | ||||
| 49993 | |||||
| 49994 | |||||
| 49995 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 49996 | /* Forward references to VFS helper methods used for memory mapped files */ | ||||
| 49997 | static int winMapfile(winFile*, sqlite3_int64); | ||||
| 49998 | static int winUnmapfile(winFile*); | ||||
| 49999 | #endif | ||||
| 50000 | |||||
| 50001 | /* | ||||
| 50002 | ** Close a file. | ||||
| 50003 | ** | ||||
| 50004 | ** It is reported that an attempt to close a handle might sometimes | ||||
| 50005 | ** fail. This is a very unreasonable result, but Windows is notorious | ||||
| 50006 | ** for being unreasonable so I do not doubt that it might happen. If | ||||
| 50007 | ** the close fails, we pause for 100 milliseconds and try again. As | ||||
| 50008 | ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before | ||||
| 50009 | ** giving up and returning an error. | ||||
| 50010 | */ | ||||
| 50011 | #define MX_CLOSE_ATTEMPT 3 | ||||
| 50012 | static int winClose(sqlite3_file *id){ | ||||
| 50013 | int rc, cnt = 0; | ||||
| 50014 | winFile *pFile = (winFile*)id; | ||||
| 50015 | |||||
| 50016 | assert( id!=0 )((void) (0)); | ||||
| 50017 | #ifndef SQLITE_OMIT_WAL | ||||
| 50018 | assert( pFile->pShm==0 )((void) (0)); | ||||
| 50019 | #endif | ||||
| 50020 | assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE )((void) (0)); | ||||
| 50021 | OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n", | ||||
| 50022 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50023 | |||||
| 50024 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 50025 | winUnmapfile(pFile); | ||||
| 50026 | #endif | ||||
| 50027 | |||||
| 50028 | do{ | ||||
| 50029 | rc = osCloseHandle(pFile->h); | ||||
| 50030 | /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ | ||||
| 50031 | }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) ); | ||||
| 50032 | #if SQLITE_OS_WINCE | ||||
| 50033 | #define WINCE_DELETION_ATTEMPTS 3 | ||||
| 50034 | { | ||||
| 50035 | winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData; | ||||
| 50036 | if( pAppData==NULL((void*)0) || !pAppData->bNoLock ){ | ||||
| 50037 | winceDestroyLock(pFile); | ||||
| 50038 | } | ||||
| 50039 | } | ||||
| 50040 | if( pFile->zDeleteOnClose ){ | ||||
| 50041 | int cnt = 0; | ||||
| 50042 | while( | ||||
| 50043 | osDeleteFileW(pFile->zDeleteOnClose)==0 | ||||
| 50044 | && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff | ||||
| 50045 | && cnt++ < WINCE_DELETION_ATTEMPTS | ||||
| 50046 | ){ | ||||
| 50047 | sqlite3_win32_sleep(100); /* Wait a little before trying again */ | ||||
| 50048 | } | ||||
| 50049 | sqlite3_free(pFile->zDeleteOnClose); | ||||
| 50050 | } | ||||
| 50051 | #endif | ||||
| 50052 | if( rc ){ | ||||
| 50053 | pFile->h = NULL((void*)0); | ||||
| 50054 | } | ||||
| 50055 | OpenCounter(-1); | ||||
| 50056 | OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n", | ||||
| 50057 | osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed")); | ||||
| 50058 | return rc ? SQLITE_OK0 | ||||
| 50059 | : winLogError(SQLITE_IOERR_CLOSE(10 | (16<<8)), osGetLastError(), | ||||
| 50060 | "winClose", pFile->zPath); | ||||
| 50061 | } | ||||
| 50062 | |||||
| 50063 | /* | ||||
| 50064 | ** Read data from a file into a buffer. Return SQLITE_OK if all | ||||
| 50065 | ** bytes were read successfully and SQLITE_IOERR if anything goes | ||||
| 50066 | ** wrong. | ||||
| 50067 | */ | ||||
| 50068 | static int winRead( | ||||
| 50069 | sqlite3_file *id, /* File to read from */ | ||||
| 50070 | void *pBuf, /* Write content into this buffer */ | ||||
| 50071 | int amt, /* Number of bytes to read */ | ||||
| 50072 | sqlite3_int64 offset /* Begin reading at this offset */ | ||||
| 50073 | ){ | ||||
| 50074 | #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) | ||||
| 50075 | OVERLAPPED overlapped; /* The offset for ReadFile. */ | ||||
| 50076 | #endif | ||||
| 50077 | winFile *pFile = (winFile*)id; /* file handle */ | ||||
| 50078 | DWORD nRead; /* Number of bytes actually read from file */ | ||||
| 50079 | int nRetry = 0; /* Number of retrys */ | ||||
| 50080 | |||||
| 50081 | assert( id!=0 )((void) (0)); | ||||
| 50082 | assert( amt>0 )((void) (0)); | ||||
| 50083 | assert( offset>=0 )((void) (0)); | ||||
| 50084 | SimulateIOError(return SQLITE_IOERR_READ); | ||||
| 50085 | OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " | ||||
| 50086 | "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, | ||||
| 50087 | pFile->h, pBuf, amt, offset, pFile->locktype)); | ||||
| 50088 | |||||
| 50089 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 50090 | /* Deal with as much of this read request as possible by transferring | ||||
| 50091 | ** data from the memory mapping using memcpy(). */ | ||||
| 50092 | if( offset<pFile->mmapSize ){ | ||||
| 50093 | if( offset+amt <= pFile->mmapSize ){ | ||||
| 50094 | memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); | ||||
| 50095 | OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", | ||||
| 50096 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50097 | return SQLITE_OK0; | ||||
| 50098 | }else{ | ||||
| 50099 | int nCopy = (int)(pFile->mmapSize - offset); | ||||
| 50100 | memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); | ||||
| 50101 | pBuf = &((u8 *)pBuf)[nCopy]; | ||||
| 50102 | amt -= nCopy; | ||||
| 50103 | offset += nCopy; | ||||
| 50104 | } | ||||
| 50105 | } | ||||
| 50106 | #endif | ||||
| 50107 | |||||
| 50108 | #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) | ||||
| 50109 | if( winSeekFile(pFile, offset) ){ | ||||
| 50110 | OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", | ||||
| 50111 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50112 | return SQLITE_FULL13; | ||||
| 50113 | } | ||||
| 50114 | while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){ | ||||
| 50115 | #else | ||||
| 50116 | memset(&overlapped, 0, sizeof(OVERLAPPED)); | ||||
| 50117 | overlapped.Offset = (LONG)(offset & 0xffffffff); | ||||
| 50118 | overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); | ||||
| 50119 | while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) && | ||||
| 50120 | osGetLastError()!=ERROR_HANDLE_EOF ){ | ||||
| 50121 | #endif | ||||
| 50122 | DWORD lastErrno; | ||||
| 50123 | if( winRetryIoerr(&nRetry, &lastErrno) ) continue; | ||||
| 50124 | pFile->lastErrno = lastErrno; | ||||
| 50125 | OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n", | ||||
| 50126 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50127 | return winLogError(SQLITE_IOERR_READ(10 | (1<<8)), pFile->lastErrno, | ||||
| 50128 | "winRead", pFile->zPath); | ||||
| 50129 | } | ||||
| 50130 | winLogIoerr(nRetry, __LINE__50130); | ||||
| 50131 | if( nRead<(DWORD)amt ){ | ||||
| 50132 | /* Unread parts of the buffer must be zero-filled */ | ||||
| 50133 | memset(&((char*)pBuf)[nRead], 0, amt-nRead); | ||||
| 50134 | OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n", | ||||
| 50135 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50136 | return SQLITE_IOERR_SHORT_READ(10 | (2<<8)); | ||||
| 50137 | } | ||||
| 50138 | |||||
| 50139 | OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", | ||||
| 50140 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50141 | return SQLITE_OK0; | ||||
| 50142 | } | ||||
| 50143 | |||||
| 50144 | /* | ||||
| 50145 | ** Write data from a buffer into a file. Return SQLITE_OK on success | ||||
| 50146 | ** or some other error code on failure. | ||||
| 50147 | */ | ||||
| 50148 | static int winWrite( | ||||
| 50149 | sqlite3_file *id, /* File to write into */ | ||||
| 50150 | const void *pBuf, /* The bytes to be written */ | ||||
| 50151 | int amt, /* Number of bytes to write */ | ||||
| 50152 | sqlite3_int64 offset /* Offset into the file to begin writing at */ | ||||
| 50153 | ){ | ||||
| 50154 | int rc = 0; /* True if error has occurred, else false */ | ||||
| 50155 | winFile *pFile = (winFile*)id; /* File handle */ | ||||
| 50156 | int nRetry = 0; /* Number of retries */ | ||||
| 50157 | |||||
| 50158 | assert( amt>0 )((void) (0)); | ||||
| 50159 | assert( pFile )((void) (0)); | ||||
| 50160 | SimulateIOError(return SQLITE_IOERR_WRITE); | ||||
| 50161 | SimulateDiskfullError(return SQLITE_FULL); | ||||
| 50162 | |||||
| 50163 | OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, " | ||||
| 50164 | "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile, | ||||
| 50165 | pFile->h, pBuf, amt, offset, pFile->locktype)); | ||||
| 50166 | |||||
| 50167 | #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 50168 | /* Deal with as much of this write request as possible by transferring | ||||
| 50169 | ** data from the memory mapping using memcpy(). */ | ||||
| 50170 | if( offset<pFile->mmapSize ){ | ||||
| 50171 | if( offset+amt <= pFile->mmapSize ){ | ||||
| 50172 | memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); | ||||
| 50173 | OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", | ||||
| 50174 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50175 | return SQLITE_OK0; | ||||
| 50176 | }else{ | ||||
| 50177 | int nCopy = (int)(pFile->mmapSize - offset); | ||||
| 50178 | memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); | ||||
| 50179 | pBuf = &((u8 *)pBuf)[nCopy]; | ||||
| 50180 | amt -= nCopy; | ||||
| 50181 | offset += nCopy; | ||||
| 50182 | } | ||||
| 50183 | } | ||||
| 50184 | #endif | ||||
| 50185 | |||||
| 50186 | #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) | ||||
| 50187 | rc = winSeekFile(pFile, offset); | ||||
| 50188 | if( rc==0 ){ | ||||
| 50189 | #else | ||||
| 50190 | { | ||||
| 50191 | #endif | ||||
| 50192 | #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) | ||||
| 50193 | OVERLAPPED overlapped; /* The offset for WriteFile. */ | ||||
| 50194 | #endif | ||||
| 50195 | u8 *aRem = (u8 *)pBuf; /* Data yet to be written */ | ||||
| 50196 | int nRem = amt; /* Number of bytes yet to be written */ | ||||
| 50197 | DWORD nWrite; /* Bytes written by each WriteFile() call */ | ||||
| 50198 | DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */ | ||||
| 50199 | |||||
| 50200 | #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) | ||||
| 50201 | memset(&overlapped, 0, sizeof(OVERLAPPED)); | ||||
| 50202 | overlapped.Offset = (LONG)(offset & 0xffffffff); | ||||
| 50203 | overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); | ||||
| 50204 | #endif | ||||
| 50205 | |||||
| 50206 | while( nRem>0 ){ | ||||
| 50207 | #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) | ||||
| 50208 | if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){ | ||||
| 50209 | #else | ||||
| 50210 | if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){ | ||||
| 50211 | #endif | ||||
| 50212 | if( winRetryIoerr(&nRetry, &lastErrno) ) continue; | ||||
| 50213 | break; | ||||
| 50214 | } | ||||
| 50215 | assert( nWrite==0 || nWrite<=(DWORD)nRem )((void) (0)); | ||||
| 50216 | if( nWrite==0 || nWrite>(DWORD)nRem ){ | ||||
| 50217 | lastErrno = osGetLastError(); | ||||
| 50218 | break; | ||||
| 50219 | } | ||||
| 50220 | #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) | ||||
| 50221 | offset += nWrite; | ||||
| 50222 | overlapped.Offset = (LONG)(offset & 0xffffffff); | ||||
| 50223 | overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); | ||||
| 50224 | #endif | ||||
| 50225 | aRem += nWrite; | ||||
| 50226 | nRem -= nWrite; | ||||
| 50227 | } | ||||
| 50228 | if( nRem>0 ){ | ||||
| 50229 | pFile->lastErrno = lastErrno; | ||||
| 50230 | rc = 1; | ||||
| 50231 | } | ||||
| 50232 | } | ||||
| 50233 | |||||
| 50234 | if( rc ){ | ||||
| 50235 | if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ) | ||||
| 50236 | || ( pFile->lastErrno==ERROR_DISK_FULL )){ | ||||
| 50237 | OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", | ||||
| 50238 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50239 | return winLogError(SQLITE_FULL13, pFile->lastErrno, | ||||
| 50240 | "winWrite1", pFile->zPath); | ||||
| 50241 | } | ||||
| 50242 | OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n", | ||||
| 50243 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50244 | return winLogError(SQLITE_IOERR_WRITE(10 | (3<<8)), pFile->lastErrno, | ||||
| 50245 | "winWrite2", pFile->zPath); | ||||
| 50246 | }else{ | ||||
| 50247 | winLogIoerr(nRetry, __LINE__50247); | ||||
| 50248 | } | ||||
| 50249 | OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", | ||||
| 50250 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50251 | return SQLITE_OK0; | ||||
| 50252 | } | ||||
| 50253 | |||||
| 50254 | /* | ||||
| 50255 | ** Truncate the file opened by handle h to nByte bytes in size. | ||||
| 50256 | */ | ||||
| 50257 | static int winHandleTruncate(HANDLE h, sqlite3_int64 nByte){ | ||||
| 50258 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 50259 | rc = winHandleSeek(h, nByte); | ||||
| 50260 | if( rc==SQLITE_OK0 ){ | ||||
| 50261 | if( 0==osSetEndOfFile(h) ){ | ||||
| 50262 | rc = SQLITE_IOERR_TRUNCATE(10 | (6<<8)); | ||||
| 50263 | } | ||||
| 50264 | } | ||||
| 50265 | return rc; | ||||
| 50266 | } | ||||
| 50267 | |||||
| 50268 | /* | ||||
| 50269 | ** Determine the size in bytes of the file opened by the handle passed as | ||||
| 50270 | ** the first argument. | ||||
| 50271 | */ | ||||
| 50272 | static int winHandleSize(HANDLE h, sqlite3_int64 *pnByte){ | ||||
| 50273 | int rc = SQLITE_OK0; | ||||
| 50274 | |||||
| 50275 | #if SQLITE_OS_WINRT | ||||
| 50276 | FILE_STANDARD_INFO info; | ||||
| 50277 | BOOL b; | ||||
| 50278 | b = osGetFileInformationByHandleEx(h, FileStandardInfo, &info, sizeof(info)); | ||||
| 50279 | if( b ){ | ||||
| 50280 | *pnByte = info.EndOfFile.QuadPart; | ||||
| 50281 | }else{ | ||||
| 50282 | rc = SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 50283 | } | ||||
| 50284 | #else | ||||
| 50285 | DWORD upperBits = 0; | ||||
| 50286 | DWORD lowerBits = 0; | ||||
| 50287 | |||||
| 50288 | assert( pnByte )((void) (0)); | ||||
| 50289 | lowerBits = osGetFileSize(h, &upperBits); | ||||
| 50290 | *pnByte = (((sqlite3_int64)upperBits)<<32) + lowerBits; | ||||
| 50291 | if( lowerBits==INVALID_FILE_SIZE && osGetLastError()!=NO_ERROR ){ | ||||
| 50292 | rc = SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 50293 | } | ||||
| 50294 | #endif | ||||
| 50295 | |||||
| 50296 | return rc; | ||||
| 50297 | } | ||||
| 50298 | |||||
| 50299 | /* | ||||
| 50300 | ** Close the handle passed as the only argument. | ||||
| 50301 | */ | ||||
| 50302 | static void winHandleClose(HANDLE h){ | ||||
| 50303 | if( h!=INVALID_HANDLE_VALUE ){ | ||||
| 50304 | osCloseHandle(h); | ||||
| 50305 | } | ||||
| 50306 | } | ||||
| 50307 | |||||
| 50308 | /* | ||||
| 50309 | ** Truncate an open file to a specified size | ||||
| 50310 | */ | ||||
| 50311 | static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){ | ||||
| 50312 | winFile *pFile = (winFile*)id; /* File handle object */ | ||||
| 50313 | int rc = SQLITE_OK0; /* Return code for this function */ | ||||
| 50314 | DWORD lastErrno; | ||||
| 50315 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 50316 | sqlite3_int64 oldMmapSize; | ||||
| 50317 | if( pFile->nFetchOut>0 ){ | ||||
| 50318 | /* File truncation is a no-op if there are outstanding memory mapped | ||||
| 50319 | ** pages. This is because truncating the file means temporarily unmapping | ||||
| 50320 | ** the file, and that might delete memory out from under existing cursors. | ||||
| 50321 | ** | ||||
| 50322 | ** This can result in incremental vacuum not truncating the file, | ||||
| 50323 | ** if there is an active read cursor when the incremental vacuum occurs. | ||||
| 50324 | ** No real harm comes of this - the database file is not corrupted, | ||||
| 50325 | ** though some folks might complain that the file is bigger than it | ||||
| 50326 | ** needs to be. | ||||
| 50327 | ** | ||||
| 50328 | ** The only feasible work-around is to defer the truncation until after | ||||
| 50329 | ** all references to memory-mapped content are closed. That is doable, | ||||
| 50330 | ** but involves adding a few branches in the common write code path which | ||||
| 50331 | ** could slow down normal operations slightly. Hence, we have decided for | ||||
| 50332 | ** now to simply make transactions a no-op if there are pending reads. We | ||||
| 50333 | ** can maybe revisit this decision in the future. | ||||
| 50334 | */ | ||||
| 50335 | return SQLITE_OK0; | ||||
| 50336 | } | ||||
| 50337 | #endif | ||||
| 50338 | |||||
| 50339 | assert( pFile )((void) (0)); | ||||
| 50340 | SimulateIOError(return SQLITE_IOERR_TRUNCATE); | ||||
| 50341 | OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n", | ||||
| 50342 | osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype)); | ||||
| 50343 | |||||
| 50344 | /* If the user has configured a chunk-size for this file, truncate the | ||||
| 50345 | ** file so that it consists of an integer number of chunks (i.e. the | ||||
| 50346 | ** actual file size after the operation may be larger than the requested | ||||
| 50347 | ** size). | ||||
| 50348 | */ | ||||
| 50349 | if( pFile->szChunk>0 ){ | ||||
| 50350 | nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; | ||||
| 50351 | } | ||||
| 50352 | |||||
| 50353 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 50354 | if( pFile->pMapRegion ){ | ||||
| 50355 | oldMmapSize = pFile->mmapSize; | ||||
| 50356 | }else{ | ||||
| 50357 | oldMmapSize = 0; | ||||
| 50358 | } | ||||
| 50359 | winUnmapfile(pFile); | ||||
| 50360 | #endif | ||||
| 50361 | |||||
| 50362 | /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */ | ||||
| 50363 | if( winSeekFile(pFile, nByte) ){ | ||||
| 50364 | rc = winLogError(SQLITE_IOERR_TRUNCATE(10 | (6<<8)), pFile->lastErrno, | ||||
| 50365 | "winTruncate1", pFile->zPath); | ||||
| 50366 | }else if( 0==osSetEndOfFile(pFile->h) && | ||||
| 50367 | ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){ | ||||
| 50368 | pFile->lastErrno = lastErrno; | ||||
| 50369 | rc = winLogError(SQLITE_IOERR_TRUNCATE(10 | (6<<8)), pFile->lastErrno, | ||||
| 50370 | "winTruncate2", pFile->zPath); | ||||
| 50371 | } | ||||
| 50372 | |||||
| 50373 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 50374 | if( rc==SQLITE_OK0 && oldMmapSize>0 ){ | ||||
| 50375 | if( oldMmapSize>nByte ){ | ||||
| 50376 | winMapfile(pFile, -1); | ||||
| 50377 | }else{ | ||||
| 50378 | winMapfile(pFile, oldMmapSize); | ||||
| 50379 | } | ||||
| 50380 | } | ||||
| 50381 | #endif | ||||
| 50382 | |||||
| 50383 | OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n", | ||||
| 50384 | osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc))); | ||||
| 50385 | return rc; | ||||
| 50386 | } | ||||
| 50387 | |||||
| 50388 | #ifdef SQLITE_TEST | ||||
| 50389 | /* | ||||
| 50390 | ** Count the number of fullsyncs and normal syncs. This is used to test | ||||
| 50391 | ** that syncs and fullsyncs are occurring at the right times. | ||||
| 50392 | */ | ||||
| 50393 | SQLITE_API int sqlite3_sync_count = 0; | ||||
| 50394 | SQLITE_API int sqlite3_fullsync_count = 0; | ||||
| 50395 | #endif | ||||
| 50396 | |||||
| 50397 | /* | ||||
| 50398 | ** Make sure all writes to a particular file are committed to disk. | ||||
| 50399 | */ | ||||
| 50400 | static int winSync(sqlite3_file *id, int flags){ | ||||
| 50401 | #ifndef SQLITE_NO_SYNC | ||||
| 50402 | /* | ||||
| 50403 | ** Used only when SQLITE_NO_SYNC is not defined. | ||||
| 50404 | */ | ||||
| 50405 | BOOL rc; | ||||
| 50406 | #endif | ||||
| 50407 | #if !defined(NDEBUG1) || !defined(SQLITE_NO_SYNC) || \ | ||||
| 50408 | defined(SQLITE_HAVE_OS_TRACE) | ||||
| 50409 | /* | ||||
| 50410 | ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or | ||||
| 50411 | ** OSTRACE() macros. | ||||
| 50412 | */ | ||||
| 50413 | winFile *pFile = (winFile*)id; | ||||
| 50414 | #else | ||||
| 50415 | UNUSED_PARAMETER(id)(void)(id); | ||||
| 50416 | #endif | ||||
| 50417 | |||||
| 50418 | assert( pFile )((void) (0)); | ||||
| 50419 | /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ | ||||
| 50420 | assert((flags&0x0F)==SQLITE_SYNC_NORMAL((void) (0)) | ||||
| 50421 | || (flags&0x0F)==SQLITE_SYNC_FULL((void) (0)) | ||||
| 50422 | )((void) (0)); | ||||
| 50423 | |||||
| 50424 | /* Unix cannot, but some systems may return SQLITE_FULL from here. This | ||||
| 50425 | ** line is to test that doing so does not cause any problems. | ||||
| 50426 | */ | ||||
| 50427 | SimulateDiskfullError( return SQLITE_FULL ); | ||||
| 50428 | |||||
| 50429 | OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n", | ||||
| 50430 | osGetCurrentProcessId(), pFile, pFile->h, flags, | ||||
| 50431 | pFile->locktype)); | ||||
| 50432 | |||||
| 50433 | #ifndef SQLITE_TEST | ||||
| 50434 | UNUSED_PARAMETER(flags)(void)(flags); | ||||
| 50435 | #else | ||||
| 50436 | if( (flags&0x0F)==SQLITE_SYNC_FULL0x00003 ){ | ||||
| 50437 | sqlite3_fullsync_count++; | ||||
| 50438 | } | ||||
| 50439 | sqlite3_sync_count++; | ||||
| 50440 | #endif | ||||
| 50441 | |||||
| 50442 | /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a | ||||
| 50443 | ** no-op | ||||
| 50444 | */ | ||||
| 50445 | #ifdef SQLITE_NO_SYNC | ||||
| 50446 | OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", | ||||
| 50447 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50448 | return SQLITE_OK0; | ||||
| 50449 | #else | ||||
| 50450 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 50451 | if( pFile->pMapRegion ){ | ||||
| 50452 | if( osFlushViewOfFile(pFile->pMapRegion, 0) ){ | ||||
| 50453 | OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " | ||||
| 50454 | "rc=SQLITE_OK\n", osGetCurrentProcessId(), | ||||
| 50455 | pFile, pFile->pMapRegion)); | ||||
| 50456 | }else{ | ||||
| 50457 | pFile->lastErrno = osGetLastError(); | ||||
| 50458 | OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " | ||||
| 50459 | "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), | ||||
| 50460 | pFile, pFile->pMapRegion)); | ||||
| 50461 | return winLogError(SQLITE_IOERR_MMAP(10 | (24<<8)), pFile->lastErrno, | ||||
| 50462 | "winSync1", pFile->zPath); | ||||
| 50463 | } | ||||
| 50464 | } | ||||
| 50465 | #endif | ||||
| 50466 | rc = osFlushFileBuffers(pFile->h); | ||||
| 50467 | SimulateIOError( rc=FALSE ); | ||||
| 50468 | if( rc ){ | ||||
| 50469 | OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", | ||||
| 50470 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50471 | return SQLITE_OK0; | ||||
| 50472 | }else{ | ||||
| 50473 | pFile->lastErrno = osGetLastError(); | ||||
| 50474 | OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n", | ||||
| 50475 | osGetCurrentProcessId(), pFile, pFile->h)); | ||||
| 50476 | return winLogError(SQLITE_IOERR_FSYNC(10 | (4<<8)), pFile->lastErrno, | ||||
| 50477 | "winSync2", pFile->zPath); | ||||
| 50478 | } | ||||
| 50479 | #endif | ||||
| 50480 | } | ||||
| 50481 | |||||
| 50482 | /* | ||||
| 50483 | ** Determine the current size of a file in bytes | ||||
| 50484 | */ | ||||
| 50485 | static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ | ||||
| 50486 | winFile *pFile = (winFile*)id; | ||||
| 50487 | int rc = SQLITE_OK0; | ||||
| 50488 | |||||
| 50489 | assert( id!=0 )((void) (0)); | ||||
| 50490 | assert( pSize!=0 )((void) (0)); | ||||
| 50491 | SimulateIOError(return SQLITE_IOERR_FSTAT); | ||||
| 50492 | OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize)); | ||||
| 50493 | |||||
| 50494 | #if SQLITE_OS_WINRT | ||||
| 50495 | { | ||||
| 50496 | FILE_STANDARD_INFO info; | ||||
| 50497 | if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo, | ||||
| 50498 | &info, sizeof(info)) ){ | ||||
| 50499 | *pSize = info.EndOfFile.QuadPart; | ||||
| 50500 | }else{ | ||||
| 50501 | pFile->lastErrno = osGetLastError(); | ||||
| 50502 | rc = winLogError(SQLITE_IOERR_FSTAT(10 | (7<<8)), pFile->lastErrno, | ||||
| 50503 | "winFileSize", pFile->zPath); | ||||
| 50504 | } | ||||
| 50505 | } | ||||
| 50506 | #else | ||||
| 50507 | { | ||||
| 50508 | DWORD upperBits; | ||||
| 50509 | DWORD lowerBits; | ||||
| 50510 | DWORD lastErrno; | ||||
| 50511 | |||||
| 50512 | lowerBits = osGetFileSize(pFile->h, &upperBits); | ||||
| 50513 | *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; | ||||
| 50514 | if( (lowerBits == INVALID_FILE_SIZE) | ||||
| 50515 | && ((lastErrno = osGetLastError())!=NO_ERROR) ){ | ||||
| 50516 | pFile->lastErrno = lastErrno; | ||||
| 50517 | rc = winLogError(SQLITE_IOERR_FSTAT(10 | (7<<8)), pFile->lastErrno, | ||||
| 50518 | "winFileSize", pFile->zPath); | ||||
| 50519 | } | ||||
| 50520 | } | ||||
| 50521 | #endif | ||||
| 50522 | OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", | ||||
| 50523 | pFile->h, pSize, *pSize, sqlite3ErrName(rc))); | ||||
| 50524 | return rc; | ||||
| 50525 | } | ||||
| 50526 | |||||
| 50527 | /* | ||||
| 50528 | ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems. | ||||
| 50529 | */ | ||||
| 50530 | #ifndef LOCKFILE_FAIL_IMMEDIATELY | ||||
| 50531 | # define LOCKFILE_FAIL_IMMEDIATELY 1 | ||||
| 50532 | #endif | ||||
| 50533 | |||||
| 50534 | #ifndef LOCKFILE_EXCLUSIVE_LOCK | ||||
| 50535 | # define LOCKFILE_EXCLUSIVE_LOCK 2 | ||||
| 50536 | #endif | ||||
| 50537 | |||||
| 50538 | /* | ||||
| 50539 | ** Historically, SQLite has used both the LockFile and LockFileEx functions. | ||||
| 50540 | ** When the LockFile function was used, it was always expected to fail | ||||
| 50541 | ** immediately if the lock could not be obtained. Also, it always expected to | ||||
| 50542 | ** obtain an exclusive lock. These flags are used with the LockFileEx function | ||||
| 50543 | ** and reflect those expectations; therefore, they should not be changed. | ||||
| 50544 | */ | ||||
| 50545 | #ifndef SQLITE_LOCKFILE_FLAGS | ||||
| 50546 | # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \ | ||||
| 50547 | LOCKFILE_EXCLUSIVE_LOCK) | ||||
| 50548 | #endif | ||||
| 50549 | |||||
| 50550 | /* | ||||
| 50551 | ** Currently, SQLite never calls the LockFileEx function without wanting the | ||||
| 50552 | ** call to fail immediately if the lock cannot be obtained. | ||||
| 50553 | */ | ||||
| 50554 | #ifndef SQLITE_LOCKFILEEX_FLAGS | ||||
| 50555 | # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY) | ||||
| 50556 | #endif | ||||
| 50557 | |||||
| 50558 | /* | ||||
| 50559 | ** Acquire a reader lock. | ||||
| 50560 | ** Different API routines are called depending on whether or not this | ||||
| 50561 | ** is Win9x or WinNT. | ||||
| 50562 | */ | ||||
| 50563 | static int winGetReadLock(winFile *pFile, int bBlock){ | ||||
| 50564 | int res; | ||||
| 50565 | DWORD mask = ~(bBlock ? LOCKFILE_FAIL_IMMEDIATELY : 0); | ||||
| 50566 | OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); | ||||
| 50567 | if( osIsNT() ){ | ||||
| 50568 | #if SQLITE_OS_WINCE | ||||
| 50569 | /* | ||||
| 50570 | ** NOTE: Windows CE is handled differently here due its lack of the Win32 | ||||
| 50571 | ** API LockFileEx. | ||||
| 50572 | */ | ||||
| 50573 | res = winceLockFile(&pFile->h, SHARED_FIRST(sqlite3PendingByte+2), 0, 1, 0); | ||||
| 50574 | #else | ||||
| 50575 | res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS&mask, SHARED_FIRST(sqlite3PendingByte+2), 0, | ||||
| 50576 | SHARED_SIZE510, 0); | ||||
| 50577 | #endif | ||||
| 50578 | } | ||||
| 50579 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 50580 | else{ | ||||
| 50581 | int lk; | ||||
| 50582 | sqlite3_randomness(sizeof(lk), &lk); | ||||
| 50583 | pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE510 - 1)); | ||||
| 50584 | res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS&mask, | ||||
| 50585 | SHARED_FIRST(sqlite3PendingByte+2)+pFile->sharedLockByte, 0, 1, 0); | ||||
| 50586 | } | ||||
| 50587 | #endif | ||||
| 50588 | if( res == 0 ){ | ||||
| 50589 | pFile->lastErrno = osGetLastError(); | ||||
| 50590 | /* No need to log a failure to lock */ | ||||
| 50591 | } | ||||
| 50592 | OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res)); | ||||
| 50593 | return res; | ||||
| 50594 | } | ||||
| 50595 | |||||
| 50596 | /* | ||||
| 50597 | ** Undo a readlock | ||||
| 50598 | */ | ||||
| 50599 | static int winUnlockReadLock(winFile *pFile){ | ||||
| 50600 | int res; | ||||
| 50601 | DWORD lastErrno; | ||||
| 50602 | OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); | ||||
| 50603 | if( osIsNT() ){ | ||||
| 50604 | res = winUnlockFile(&pFile->h, SHARED_FIRST(sqlite3PendingByte+2), 0, SHARED_SIZE510, 0); | ||||
| 50605 | } | ||||
| 50606 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 50607 | else{ | ||||
| 50608 | res = winUnlockFile(&pFile->h, SHARED_FIRST(sqlite3PendingByte+2)+pFile->sharedLockByte, 0, 1, 0); | ||||
| 50609 | } | ||||
| 50610 | #endif | ||||
| 50611 | if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){ | ||||
| 50612 | pFile->lastErrno = lastErrno; | ||||
| 50613 | winLogError(SQLITE_IOERR_UNLOCK(10 | (8<<8)), pFile->lastErrno, | ||||
| 50614 | "winUnlockReadLock", pFile->zPath); | ||||
| 50615 | } | ||||
| 50616 | OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res)); | ||||
| 50617 | return res; | ||||
| 50618 | } | ||||
| 50619 | |||||
| 50620 | /* | ||||
| 50621 | ** Lock the file with the lock specified by parameter locktype - one | ||||
| 50622 | ** of the following: | ||||
| 50623 | ** | ||||
| 50624 | ** (1) SHARED_LOCK | ||||
| 50625 | ** (2) RESERVED_LOCK | ||||
| 50626 | ** (3) PENDING_LOCK | ||||
| 50627 | ** (4) EXCLUSIVE_LOCK | ||||
| 50628 | ** | ||||
| 50629 | ** Sometimes when requesting one lock state, additional lock states | ||||
| 50630 | ** are inserted in between. The locking might fail on one of the later | ||||
| 50631 | ** transitions leaving the lock state different from what it started but | ||||
| 50632 | ** still short of its goal. The following chart shows the allowed | ||||
| 50633 | ** transitions and the inserted intermediate states: | ||||
| 50634 | ** | ||||
| 50635 | ** UNLOCKED -> SHARED | ||||
| 50636 | ** SHARED -> RESERVED | ||||
| 50637 | ** SHARED -> (PENDING) -> EXCLUSIVE | ||||
| 50638 | ** RESERVED -> (PENDING) -> EXCLUSIVE | ||||
| 50639 | ** PENDING -> EXCLUSIVE | ||||
| 50640 | ** | ||||
| 50641 | ** This routine will only increase a lock. The winUnlock() routine | ||||
| 50642 | ** erases all locks at once and returns us immediately to locking level 0. | ||||
| 50643 | ** It is not possible to lower the locking level one step at a time. You | ||||
| 50644 | ** must go straight to locking level 0. | ||||
| 50645 | */ | ||||
| 50646 | static int winLock(sqlite3_file *id, int locktype){ | ||||
| 50647 | int rc = SQLITE_OK0; /* Return code from subroutines */ | ||||
| 50648 | int res = 1; /* Result of a Windows lock call */ | ||||
| 50649 | int newLocktype; /* Set pFile->locktype to this value before exiting */ | ||||
| 50650 | int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */ | ||||
| 50651 | winFile *pFile = (winFile*)id; | ||||
| 50652 | DWORD lastErrno = NO_ERROR; | ||||
| 50653 | |||||
| 50654 | assert( id!=0 )((void) (0)); | ||||
| 50655 | OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n", | ||||
| 50656 | pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); | ||||
| 50657 | |||||
| 50658 | /* If there is already a lock of this type or more restrictive on the | ||||
| 50659 | ** OsFile, do nothing. Don't use the end_lock: exit path, as | ||||
| 50660 | ** sqlite3OsEnterMutex() hasn't been called yet. | ||||
| 50661 | */ | ||||
| 50662 | if( pFile->locktype>=locktype ){ | ||||
| 50663 | OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50664 | return SQLITE_OK0; | ||||
| 50665 | } | ||||
| 50666 | |||||
| 50667 | /* Do not allow any kind of write-lock on a read-only database | ||||
| 50668 | */ | ||||
| 50669 | if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK2 ){ | ||||
| 50670 | return SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 50671 | } | ||||
| 50672 | |||||
| 50673 | /* Make sure the locking sequence is correct | ||||
| 50674 | */ | ||||
| 50675 | assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK )((void) (0)); | ||||
| 50676 | assert( locktype!=PENDING_LOCK )((void) (0)); | ||||
| 50677 | assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK )((void) (0)); | ||||
| 50678 | |||||
| 50679 | /* Lock the PENDING_LOCK byte if we need to acquire an EXCLUSIVE lock or | ||||
| 50680 | ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of | ||||
| 50681 | ** the PENDING_LOCK byte is temporary. | ||||
| 50682 | */ | ||||
| 50683 | newLocktype = pFile->locktype; | ||||
| 50684 | if( locktype==SHARED_LOCK1 | ||||
| 50685 | || (locktype==EXCLUSIVE_LOCK4 && pFile->locktype==RESERVED_LOCK2) | ||||
| 50686 | ){ | ||||
| 50687 | int cnt = 3; | ||||
| 50688 | |||||
| 50689 | /* Flags for the LockFileEx() call. This should be an exclusive lock if | ||||
| 50690 | ** this call is to obtain EXCLUSIVE, or a shared lock if this call is to | ||||
| 50691 | ** obtain SHARED. */ | ||||
| 50692 | int flags = LOCKFILE_FAIL_IMMEDIATELY; | ||||
| 50693 | if( locktype==EXCLUSIVE_LOCK4 ){ | ||||
| 50694 | flags |= LOCKFILE_EXCLUSIVE_LOCK; | ||||
| 50695 | } | ||||
| 50696 | while( cnt>0 ){ | ||||
| 50697 | /* Try 3 times to get the pending lock. This is needed to work | ||||
| 50698 | ** around problems caused by indexing and/or anti-virus software on | ||||
| 50699 | ** Windows systems. | ||||
| 50700 | ** | ||||
| 50701 | ** If you are using this code as a model for alternative VFSes, do not | ||||
| 50702 | ** copy this retry logic. It is a hack intended for Windows only. */ | ||||
| 50703 | res = winLockFile(&pFile->h, flags, PENDING_BYTEsqlite3PendingByte, 0, 1, 0); | ||||
| 50704 | if( res ) break; | ||||
| 50705 | |||||
| 50706 | lastErrno = osGetLastError(); | ||||
| 50707 | OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n", | ||||
| 50708 | pFile->h, cnt, res | ||||
| 50709 | )); | ||||
| 50710 | |||||
| 50711 | if( lastErrno==ERROR_INVALID_HANDLE ){ | ||||
| 50712 | pFile->lastErrno = lastErrno; | ||||
| 50713 | rc = SQLITE_IOERR_LOCK(10 | (15<<8)); | ||||
| 50714 | OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", | ||||
| 50715 | pFile->h, cnt, sqlite3ErrName(rc) | ||||
| 50716 | )); | ||||
| 50717 | return rc; | ||||
| 50718 | } | ||||
| 50719 | |||||
| 50720 | cnt--; | ||||
| 50721 | if( cnt>0 ) sqlite3_win32_sleep(1); | ||||
| 50722 | } | ||||
| 50723 | gotPendingLock = res; | ||||
| 50724 | } | ||||
| 50725 | |||||
| 50726 | /* Acquire a shared lock | ||||
| 50727 | */ | ||||
| 50728 | if( locktype==SHARED_LOCK1 && res ){ | ||||
| 50729 | assert( pFile->locktype==NO_LOCK )((void) (0)); | ||||
| 50730 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 50731 | res = winGetReadLock(pFile, pFile->bBlockOnConnect); | ||||
| 50732 | #else | ||||
| 50733 | res = winGetReadLock(pFile, 0); | ||||
| 50734 | #endif | ||||
| 50735 | if( res ){ | ||||
| 50736 | newLocktype = SHARED_LOCK1; | ||||
| 50737 | }else{ | ||||
| 50738 | lastErrno = osGetLastError(); | ||||
| 50739 | } | ||||
| 50740 | } | ||||
| 50741 | |||||
| 50742 | /* Acquire a RESERVED lock | ||||
| 50743 | */ | ||||
| 50744 | if( locktype==RESERVED_LOCK2 && res ){ | ||||
| 50745 | assert( pFile->locktype==SHARED_LOCK )((void) (0)); | ||||
| 50746 | res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE(sqlite3PendingByte+1), 0, 1, 0); | ||||
| 50747 | if( res ){ | ||||
| 50748 | newLocktype = RESERVED_LOCK2; | ||||
| 50749 | }else{ | ||||
| 50750 | lastErrno = osGetLastError(); | ||||
| 50751 | } | ||||
| 50752 | } | ||||
| 50753 | |||||
| 50754 | /* Acquire a PENDING lock | ||||
| 50755 | */ | ||||
| 50756 | if( locktype==EXCLUSIVE_LOCK4 && res ){ | ||||
| 50757 | newLocktype = PENDING_LOCK3; | ||||
| 50758 | gotPendingLock = 0; | ||||
| 50759 | } | ||||
| 50760 | |||||
| 50761 | /* Acquire an EXCLUSIVE lock | ||||
| 50762 | */ | ||||
| 50763 | if( locktype==EXCLUSIVE_LOCK4 && res ){ | ||||
| 50764 | assert( pFile->locktype>=SHARED_LOCK )((void) (0)); | ||||
| 50765 | (void)winUnlockReadLock(pFile); | ||||
| 50766 | res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST(sqlite3PendingByte+2), 0, | ||||
| 50767 | SHARED_SIZE510, 0); | ||||
| 50768 | if( res ){ | ||||
| 50769 | newLocktype = EXCLUSIVE_LOCK4; | ||||
| 50770 | }else{ | ||||
| 50771 | lastErrno = osGetLastError(); | ||||
| 50772 | winGetReadLock(pFile, 0); | ||||
| 50773 | } | ||||
| 50774 | } | ||||
| 50775 | |||||
| 50776 | /* If we are holding a PENDING lock that ought to be released, then | ||||
| 50777 | ** release it now. | ||||
| 50778 | */ | ||||
| 50779 | if( gotPendingLock && locktype==SHARED_LOCK1 ){ | ||||
| 50780 | winUnlockFile(&pFile->h, PENDING_BYTEsqlite3PendingByte, 0, 1, 0); | ||||
| 50781 | } | ||||
| 50782 | |||||
| 50783 | /* Update the state of the lock has held in the file descriptor then | ||||
| 50784 | ** return the appropriate result code. | ||||
| 50785 | */ | ||||
| 50786 | if( res ){ | ||||
| 50787 | rc = SQLITE_OK0; | ||||
| 50788 | }else{ | ||||
| 50789 | pFile->lastErrno = lastErrno; | ||||
| 50790 | rc = SQLITE_BUSY5; | ||||
| 50791 | OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n", | ||||
| 50792 | pFile->h, locktype, newLocktype)); | ||||
| 50793 | } | ||||
| 50794 | pFile->locktype = (u8)newLocktype; | ||||
| 50795 | OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n", | ||||
| 50796 | pFile->h, pFile->locktype, sqlite3ErrName(rc))); | ||||
| 50797 | return rc; | ||||
| 50798 | } | ||||
| 50799 | |||||
| 50800 | /* | ||||
| 50801 | ** This routine checks if there is a RESERVED lock held on the specified | ||||
| 50802 | ** file by this or any other process. If such a lock is held, return | ||||
| 50803 | ** non-zero, otherwise zero. | ||||
| 50804 | */ | ||||
| 50805 | static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ | ||||
| 50806 | int res; | ||||
| 50807 | winFile *pFile = (winFile*)id; | ||||
| 50808 | |||||
| 50809 | SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); | ||||
| 50810 | OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut)); | ||||
| 50811 | |||||
| 50812 | assert( id!=0 )((void) (0)); | ||||
| 50813 | if( pFile->locktype>=RESERVED_LOCK2 ){ | ||||
| 50814 | res = 1; | ||||
| 50815 | OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res)); | ||||
| 50816 | }else{ | ||||
| 50817 | res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE(sqlite3PendingByte+1),0,1,0); | ||||
| 50818 | if( res ){ | ||||
| 50819 | winUnlockFile(&pFile->h, RESERVED_BYTE(sqlite3PendingByte+1), 0, 1, 0); | ||||
| 50820 | } | ||||
| 50821 | res = !res; | ||||
| 50822 | OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res)); | ||||
| 50823 | } | ||||
| 50824 | *pResOut = res; | ||||
| 50825 | OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", | ||||
| 50826 | pFile->h, pResOut, *pResOut)); | ||||
| 50827 | return SQLITE_OK0; | ||||
| 50828 | } | ||||
| 50829 | |||||
| 50830 | /* | ||||
| 50831 | ** Lower the locking level on file descriptor id to locktype. locktype | ||||
| 50832 | ** must be either NO_LOCK or SHARED_LOCK. | ||||
| 50833 | ** | ||||
| 50834 | ** If the locking level of the file descriptor is already at or below | ||||
| 50835 | ** the requested locking level, this routine is a no-op. | ||||
| 50836 | ** | ||||
| 50837 | ** It is not possible for this routine to fail if the second argument | ||||
| 50838 | ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine | ||||
| 50839 | ** might return SQLITE_IOERR; | ||||
| 50840 | */ | ||||
| 50841 | static int winUnlock(sqlite3_file *id, int locktype){ | ||||
| 50842 | int type; | ||||
| 50843 | winFile *pFile = (winFile*)id; | ||||
| 50844 | int rc = SQLITE_OK0; | ||||
| 50845 | assert( pFile!=0 )((void) (0)); | ||||
| 50846 | assert( locktype<=SHARED_LOCK )((void) (0)); | ||||
| 50847 | OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n", | ||||
| 50848 | pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); | ||||
| 50849 | type = pFile->locktype; | ||||
| 50850 | if( type>=EXCLUSIVE_LOCK4 ){ | ||||
| 50851 | winUnlockFile(&pFile->h, SHARED_FIRST(sqlite3PendingByte+2), 0, SHARED_SIZE510, 0); | ||||
| 50852 | if( locktype==SHARED_LOCK1 && !winGetReadLock(pFile, 0) ){ | ||||
| 50853 | /* This should never happen. We should always be able to | ||||
| 50854 | ** reacquire the read lock */ | ||||
| 50855 | rc = winLogError(SQLITE_IOERR_UNLOCK(10 | (8<<8)), osGetLastError(), | ||||
| 50856 | "winUnlock", pFile->zPath); | ||||
| 50857 | } | ||||
| 50858 | } | ||||
| 50859 | if( type>=RESERVED_LOCK2 ){ | ||||
| 50860 | winUnlockFile(&pFile->h, RESERVED_BYTE(sqlite3PendingByte+1), 0, 1, 0); | ||||
| 50861 | } | ||||
| 50862 | if( locktype==NO_LOCK0 && type>=SHARED_LOCK1 ){ | ||||
| 50863 | winUnlockReadLock(pFile); | ||||
| 50864 | } | ||||
| 50865 | if( type>=PENDING_LOCK3 ){ | ||||
| 50866 | winUnlockFile(&pFile->h, PENDING_BYTEsqlite3PendingByte, 0, 1, 0); | ||||
| 50867 | } | ||||
| 50868 | pFile->locktype = (u8)locktype; | ||||
| 50869 | OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n", | ||||
| 50870 | pFile->h, pFile->locktype, sqlite3ErrName(rc))); | ||||
| 50871 | return rc; | ||||
| 50872 | } | ||||
| 50873 | |||||
| 50874 | /****************************************************************************** | ||||
| 50875 | ****************************** No-op Locking ********************************** | ||||
| 50876 | ** | ||||
| 50877 | ** Of the various locking implementations available, this is by far the | ||||
| 50878 | ** simplest: locking is ignored. No attempt is made to lock the database | ||||
| 50879 | ** file for reading or writing. | ||||
| 50880 | ** | ||||
| 50881 | ** This locking mode is appropriate for use on read-only databases | ||||
| 50882 | ** (ex: databases that are burned into CD-ROM, for example.) It can | ||||
| 50883 | ** also be used if the application employs some external mechanism to | ||||
| 50884 | ** prevent simultaneous access of the same database by two or more | ||||
| 50885 | ** database connections. But there is a serious risk of database | ||||
| 50886 | ** corruption if this locking mode is used in situations where multiple | ||||
| 50887 | ** database connections are accessing the same database file at the same | ||||
| 50888 | ** time and one or more of those connections are writing. | ||||
| 50889 | */ | ||||
| 50890 | |||||
| 50891 | static int winNolockLock(sqlite3_file *id, int locktype){ | ||||
| 50892 | UNUSED_PARAMETER(id)(void)(id); | ||||
| 50893 | UNUSED_PARAMETER(locktype)(void)(locktype); | ||||
| 50894 | return SQLITE_OK0; | ||||
| 50895 | } | ||||
| 50896 | |||||
| 50897 | static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){ | ||||
| 50898 | UNUSED_PARAMETER(id)(void)(id); | ||||
| 50899 | UNUSED_PARAMETER(pResOut)(void)(pResOut); | ||||
| 50900 | return SQLITE_OK0; | ||||
| 50901 | } | ||||
| 50902 | |||||
| 50903 | static int winNolockUnlock(sqlite3_file *id, int locktype){ | ||||
| 50904 | UNUSED_PARAMETER(id)(void)(id); | ||||
| 50905 | UNUSED_PARAMETER(locktype)(void)(locktype); | ||||
| 50906 | return SQLITE_OK0; | ||||
| 50907 | } | ||||
| 50908 | |||||
| 50909 | /******************* End of the no-op lock implementation ********************* | ||||
| 50910 | ******************************************************************************/ | ||||
| 50911 | |||||
| 50912 | /* | ||||
| 50913 | ** If *pArg is initially negative then this is a query. Set *pArg to | ||||
| 50914 | ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. | ||||
| 50915 | ** | ||||
| 50916 | ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. | ||||
| 50917 | */ | ||||
| 50918 | static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ | ||||
| 50919 | if( *pArg<0 ){ | ||||
| 50920 | *pArg = (pFile->ctrlFlags & mask)!=0; | ||||
| 50921 | }else if( (*pArg)==0 ){ | ||||
| 50922 | pFile->ctrlFlags &= ~mask; | ||||
| 50923 | }else{ | ||||
| 50924 | pFile->ctrlFlags |= mask; | ||||
| 50925 | } | ||||
| 50926 | } | ||||
| 50927 | |||||
| 50928 | /* Forward references to VFS helper methods used for temporary files */ | ||||
| 50929 | static int winGetTempname(sqlite3_vfs *, char **); | ||||
| 50930 | static int winIsDir(const void *); | ||||
| 50931 | static BOOL winIsLongPathPrefix(const char *); | ||||
| 50932 | static BOOL winIsDriveLetterAndColon(const char *); | ||||
| 50933 | |||||
| 50934 | /* | ||||
| 50935 | ** Control and query of the open file handle. | ||||
| 50936 | */ | ||||
| 50937 | static int winFileControl(sqlite3_file *id, int op, void *pArg){ | ||||
| 50938 | winFile *pFile = (winFile*)id; | ||||
| 50939 | OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg)); | ||||
| 50940 | switch( op ){ | ||||
| 50941 | case SQLITE_FCNTL_LOCKSTATE1: { | ||||
| 50942 | *(int*)pArg = pFile->locktype; | ||||
| 50943 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50944 | return SQLITE_OK0; | ||||
| 50945 | } | ||||
| 50946 | case SQLITE_FCNTL_LAST_ERRNO4: { | ||||
| 50947 | *(int*)pArg = (int)pFile->lastErrno; | ||||
| 50948 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50949 | return SQLITE_OK0; | ||||
| 50950 | } | ||||
| 50951 | case SQLITE_FCNTL_CHUNK_SIZE6: { | ||||
| 50952 | pFile->szChunk = *(int *)pArg; | ||||
| 50953 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50954 | return SQLITE_OK0; | ||||
| 50955 | } | ||||
| 50956 | case SQLITE_FCNTL_SIZE_HINT5: { | ||||
| 50957 | if( pFile->szChunk>0 ){ | ||||
| 50958 | sqlite3_int64 oldSz; | ||||
| 50959 | int rc = winFileSize(id, &oldSz); | ||||
| 50960 | if( rc==SQLITE_OK0 ){ | ||||
| 50961 | sqlite3_int64 newSz = *(sqlite3_int64*)pArg; | ||||
| 50962 | if( newSz>oldSz ){ | ||||
| 50963 | SimulateIOErrorBenign(1); | ||||
| 50964 | rc = winTruncate(id, newSz); | ||||
| 50965 | SimulateIOErrorBenign(0); | ||||
| 50966 | } | ||||
| 50967 | } | ||||
| 50968 | OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); | ||||
| 50969 | return rc; | ||||
| 50970 | } | ||||
| 50971 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50972 | return SQLITE_OK0; | ||||
| 50973 | } | ||||
| 50974 | case SQLITE_FCNTL_PERSIST_WAL10: { | ||||
| 50975 | winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg); | ||||
| 50976 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50977 | return SQLITE_OK0; | ||||
| 50978 | } | ||||
| 50979 | case SQLITE_FCNTL_POWERSAFE_OVERWRITE13: { | ||||
| 50980 | winModeBit(pFile, WINFILE_PSOW, (int*)pArg); | ||||
| 50981 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50982 | return SQLITE_OK0; | ||||
| 50983 | } | ||||
| 50984 | case SQLITE_FCNTL_VFSNAME12: { | ||||
| 50985 | *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); | ||||
| 50986 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 50987 | return SQLITE_OK0; | ||||
| 50988 | } | ||||
| 50989 | case SQLITE_FCNTL_WIN32_AV_RETRY9: { | ||||
| 50990 | int *a = (int*)pArg; | ||||
| 50991 | if( a[0]>0 ){ | ||||
| 50992 | winIoerrRetry = a[0]; | ||||
| 50993 | }else{ | ||||
| 50994 | a[0] = winIoerrRetry; | ||||
| 50995 | } | ||||
| 50996 | if( a[1]>0 ){ | ||||
| 50997 | winIoerrRetryDelay = a[1]; | ||||
| 50998 | }else{ | ||||
| 50999 | a[1] = winIoerrRetryDelay; | ||||
| 51000 | } | ||||
| 51001 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 51002 | return SQLITE_OK0; | ||||
| 51003 | } | ||||
| 51004 | case SQLITE_FCNTL_WIN32_GET_HANDLE29: { | ||||
| 51005 | LPHANDLE phFile = (LPHANDLE)pArg; | ||||
| 51006 | *phFile = pFile->h; | ||||
| 51007 | OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); | ||||
| 51008 | return SQLITE_OK0; | ||||
| 51009 | } | ||||
| 51010 | #ifdef SQLITE_TEST | ||||
| 51011 | case SQLITE_FCNTL_WIN32_SET_HANDLE23: { | ||||
| 51012 | LPHANDLE phFile = (LPHANDLE)pArg; | ||||
| 51013 | HANDLE hOldFile = pFile->h; | ||||
| 51014 | pFile->h = *phFile; | ||||
| 51015 | *phFile = hOldFile; | ||||
| 51016 | OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n", | ||||
| 51017 | hOldFile, pFile->h)); | ||||
| 51018 | return SQLITE_OK0; | ||||
| 51019 | } | ||||
| 51020 | #endif | ||||
| 51021 | case SQLITE_FCNTL_NULL_IO43: { | ||||
| 51022 | (void)osCloseHandle(pFile->h); | ||||
| 51023 | pFile->h = NULL((void*)0); | ||||
| 51024 | return SQLITE_OK0; | ||||
| 51025 | } | ||||
| 51026 | case SQLITE_FCNTL_TEMPFILENAME16: { | ||||
| 51027 | char *zTFile = 0; | ||||
| 51028 | int rc = winGetTempname(pFile->pVfs, &zTFile); | ||||
| 51029 | if( rc==SQLITE_OK0 ){ | ||||
| 51030 | *(char**)pArg = zTFile; | ||||
| 51031 | } | ||||
| 51032 | OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); | ||||
| 51033 | return rc; | ||||
| 51034 | } | ||||
| 51035 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 51036 | case SQLITE_FCNTL_MMAP_SIZE18: { | ||||
| 51037 | i64 newLimit = *(i64*)pArg; | ||||
| 51038 | int rc = SQLITE_OK0; | ||||
| 51039 | if( newLimit>sqlite3GlobalConfigsqlite3Config.mxMmap ){ | ||||
| 51040 | newLimit = sqlite3GlobalConfigsqlite3Config.mxMmap; | ||||
| 51041 | } | ||||
| 51042 | |||||
| 51043 | /* The value of newLimit may be eventually cast to (SIZE_T) and passed | ||||
| 51044 | ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at | ||||
| 51045 | ** least a 64-bit type. */ | ||||
| 51046 | if( newLimit>0 && sizeof(SIZE_T)<8 ){ | ||||
| 51047 | newLimit = (newLimit & 0x7FFFFFFF); | ||||
| 51048 | } | ||||
| 51049 | |||||
| 51050 | *(i64*)pArg = pFile->mmapSizeMax; | ||||
| 51051 | if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ | ||||
| 51052 | pFile->mmapSizeMax = newLimit; | ||||
| 51053 | if( pFile->mmapSize>0 ){ | ||||
| 51054 | winUnmapfile(pFile); | ||||
| 51055 | rc = winMapfile(pFile, -1); | ||||
| 51056 | } | ||||
| 51057 | } | ||||
| 51058 | OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); | ||||
| 51059 | return rc; | ||||
| 51060 | } | ||||
| 51061 | #endif | ||||
| 51062 | |||||
| 51063 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 51064 | case SQLITE_FCNTL_LOCK_TIMEOUT34: { | ||||
| 51065 | int iOld = pFile->iBusyTimeout; | ||||
| 51066 | int iNew = *(int*)pArg; | ||||
| 51067 | #if SQLITE_ENABLE_SETLK_TIMEOUT==1 | ||||
| 51068 | pFile->iBusyTimeout = (iNew < 0) ? INFINITE : (DWORD)iNew; | ||||
| 51069 | #elif SQLITE_ENABLE_SETLK_TIMEOUT==2 | ||||
| 51070 | pFile->iBusyTimeout = (DWORD)(!!iNew); | ||||
| 51071 | #else | ||||
| 51072 | # error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2" | ||||
| 51073 | #endif | ||||
| 51074 | *(int*)pArg = iOld; | ||||
| 51075 | return SQLITE_OK0; | ||||
| 51076 | } | ||||
| 51077 | case SQLITE_FCNTL_BLOCK_ON_CONNECT44: { | ||||
| 51078 | int iNew = *(int*)pArg; | ||||
| 51079 | pFile->bBlockOnConnect = iNew; | ||||
| 51080 | return SQLITE_OK0; | ||||
| 51081 | } | ||||
| 51082 | #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ | ||||
| 51083 | |||||
| 51084 | } | ||||
| 51085 | OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h)); | ||||
| 51086 | return SQLITE_NOTFOUND12; | ||||
| 51087 | } | ||||
| 51088 | |||||
| 51089 | /* | ||||
| 51090 | ** Return the sector size in bytes of the underlying block device for | ||||
| 51091 | ** the specified file. This is almost always 512 bytes, but may be | ||||
| 51092 | ** larger for some devices. | ||||
| 51093 | ** | ||||
| 51094 | ** SQLite code assumes this function cannot fail. It also assumes that | ||||
| 51095 | ** if two files are created in the same file-system directory (i.e. | ||||
| 51096 | ** a database and its journal file) that the sector size will be the | ||||
| 51097 | ** same for both. | ||||
| 51098 | */ | ||||
| 51099 | static int winSectorSize(sqlite3_file *id){ | ||||
| 51100 | (void)id; | ||||
| 51101 | return SQLITE_DEFAULT_SECTOR_SIZE4096; | ||||
| 51102 | } | ||||
| 51103 | |||||
| 51104 | /* | ||||
| 51105 | ** Return a vector of device characteristics. | ||||
| 51106 | */ | ||||
| 51107 | static int winDeviceCharacteristics(sqlite3_file *id){ | ||||
| 51108 | winFile *p = (winFile*)id; | ||||
| 51109 | return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN0x00000800 | SQLITE_IOCAP_SUBPAGE_READ0x00008000 | | ||||
| 51110 | ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE0x00001000:0); | ||||
| 51111 | } | ||||
| 51112 | |||||
| 51113 | /* | ||||
| 51114 | ** Windows will only let you create file view mappings | ||||
| 51115 | ** on allocation size granularity boundaries. | ||||
| 51116 | ** During sqlite3_os_init() we do a GetSystemInfo() | ||||
| 51117 | ** to get the granularity size. | ||||
| 51118 | */ | ||||
| 51119 | static SYSTEM_INFO winSysInfo; | ||||
| 51120 | |||||
| 51121 | #ifndef SQLITE_OMIT_WAL | ||||
| 51122 | |||||
| 51123 | /* | ||||
| 51124 | ** Helper functions to obtain and relinquish the global mutex. The | ||||
| 51125 | ** global mutex is used to protect the winLockInfo objects used by | ||||
| 51126 | ** this file, all of which may be shared by multiple threads. | ||||
| 51127 | ** | ||||
| 51128 | ** Function winShmMutexHeld() is used to assert() that the global mutex | ||||
| 51129 | ** is held when required. This function is only used as part of assert() | ||||
| 51130 | ** statements. e.g. | ||||
| 51131 | ** | ||||
| 51132 | ** winShmEnterMutex() | ||||
| 51133 | ** assert( winShmMutexHeld() ); | ||||
| 51134 | ** winShmLeaveMutex() | ||||
| 51135 | */ | ||||
| 51136 | static sqlite3_mutex *winBigLock = 0; | ||||
| 51137 | static void winShmEnterMutex(void){ | ||||
| 51138 | sqlite3_mutex_enter(winBigLock); | ||||
| 51139 | } | ||||
| 51140 | static void winShmLeaveMutex(void){ | ||||
| 51141 | sqlite3_mutex_leave(winBigLock); | ||||
| 51142 | } | ||||
| 51143 | #ifndef NDEBUG1 | ||||
| 51144 | static int winShmMutexHeld(void) { | ||||
| 51145 | return sqlite3_mutex_held(winBigLock); | ||||
| 51146 | } | ||||
| 51147 | #endif | ||||
| 51148 | |||||
| 51149 | /* | ||||
| 51150 | ** Object used to represent a single file opened and mmapped to provide | ||||
| 51151 | ** shared memory. When multiple threads all reference the same | ||||
| 51152 | ** log-summary, each thread has its own winFile object, but they all | ||||
| 51153 | ** point to a single instance of this object. In other words, each | ||||
| 51154 | ** log-summary is opened only once per process. | ||||
| 51155 | ** | ||||
| 51156 | ** winShmMutexHeld() must be true when creating or destroying | ||||
| 51157 | ** this object or while reading or writing the following fields: | ||||
| 51158 | ** | ||||
| 51159 | ** nRef | ||||
| 51160 | ** pNext | ||||
| 51161 | ** | ||||
| 51162 | ** The following fields are read-only after the object is created: | ||||
| 51163 | ** | ||||
| 51164 | ** zFilename | ||||
| 51165 | ** | ||||
| 51166 | ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and | ||||
| 51167 | ** winShmMutexHeld() is true when reading or writing any other field | ||||
| 51168 | ** in this structure. | ||||
| 51169 | ** | ||||
| 51170 | ** File-handle hSharedShm is used to (a) take the DMS lock, (b) truncate | ||||
| 51171 | ** the *-shm file if the DMS-locking protocol demands it, and (c) map | ||||
| 51172 | ** regions of the *-shm file into memory using MapViewOfFile() or | ||||
| 51173 | ** similar. Other locks are taken by individual clients using the | ||||
| 51174 | ** winShm.hShm handles. | ||||
| 51175 | */ | ||||
| 51176 | struct winShmNode { | ||||
| 51177 | sqlite3_mutex *mutex; /* Mutex to access this object */ | ||||
| 51178 | char *zFilename; /* Name of the file */ | ||||
| 51179 | HANDLE hSharedShm; /* File handle open on zFilename */ | ||||
| 51180 | |||||
| 51181 | int isUnlocked; /* DMS lock has not yet been obtained */ | ||||
| 51182 | int isReadonly; /* True if read-only */ | ||||
| 51183 | int szRegion; /* Size of shared-memory regions */ | ||||
| 51184 | int nRegion; /* Size of array apRegion */ | ||||
| 51185 | |||||
| 51186 | struct ShmRegion { | ||||
| 51187 | HANDLE hMap; /* File handle from CreateFileMapping */ | ||||
| 51188 | void *pMap; | ||||
| 51189 | } *aRegion; | ||||
| 51190 | DWORD lastErrno; /* The Windows errno from the last I/O error */ | ||||
| 51191 | |||||
| 51192 | int nRef; /* Number of winShm objects pointing to this */ | ||||
| 51193 | winShmNode *pNext; /* Next in list of all winShmNode objects */ | ||||
| 51194 | #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) | ||||
| 51195 | u8 nextShmId; /* Next available winShm.id value */ | ||||
| 51196 | #endif | ||||
| 51197 | }; | ||||
| 51198 | |||||
| 51199 | /* | ||||
| 51200 | ** A global array of all winShmNode objects. | ||||
| 51201 | ** | ||||
| 51202 | ** The winShmMutexHeld() must be true while reading or writing this list. | ||||
| 51203 | */ | ||||
| 51204 | static winShmNode *winShmNodeList = 0; | ||||
| 51205 | |||||
| 51206 | /* | ||||
| 51207 | ** Structure used internally by this VFS to record the state of an | ||||
| 51208 | ** open shared memory connection. There is one such structure for each | ||||
| 51209 | ** winFile open on a wal mode database. | ||||
| 51210 | */ | ||||
| 51211 | struct winShm { | ||||
| 51212 | winShmNode *pShmNode; /* The underlying winShmNode object */ | ||||
| 51213 | u16 sharedMask; /* Mask of shared locks held */ | ||||
| 51214 | u16 exclMask; /* Mask of exclusive locks held */ | ||||
| 51215 | HANDLE hShm; /* File-handle on *-shm file. For locking. */ | ||||
| 51216 | int bReadonly; /* True if hShm is opened read-only */ | ||||
| 51217 | #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) | ||||
| 51218 | u8 id; /* Id of this connection with its winShmNode */ | ||||
| 51219 | #endif | ||||
| 51220 | }; | ||||
| 51221 | |||||
| 51222 | /* | ||||
| 51223 | ** Constants used for locking | ||||
| 51224 | */ | ||||
| 51225 | #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK8)*4) /* first lock byte */ | ||||
| 51226 | #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK8) /* deadman switch */ | ||||
| 51227 | |||||
| 51228 | /* Forward references to VFS methods */ | ||||
| 51229 | static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*); | ||||
| 51230 | static int winDelete(sqlite3_vfs *,const char*,int); | ||||
| 51231 | |||||
| 51232 | /* | ||||
| 51233 | ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0. | ||||
| 51234 | ** | ||||
| 51235 | ** This is not a VFS shared-memory method; it is a utility function called | ||||
| 51236 | ** by VFS shared-memory methods. | ||||
| 51237 | */ | ||||
| 51238 | static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ | ||||
| 51239 | winShmNode **pp; | ||||
| 51240 | winShmNode *p; | ||||
| 51241 | assert( winShmMutexHeld() )((void) (0)); | ||||
| 51242 | OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n", | ||||
| 51243 | osGetCurrentProcessId(), deleteFlag)); | ||||
| 51244 | pp = &winShmNodeList; | ||||
| 51245 | while( (p = *pp)!=0 ){ | ||||
| 51246 | if( p->nRef==0 ){ | ||||
| 51247 | int i; | ||||
| 51248 | if( p->mutex ){ sqlite3_mutex_free(p->mutex); } | ||||
| 51249 | for(i=0; i<p->nRegion; i++){ | ||||
| 51250 | BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap); | ||||
| 51251 | OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n", | ||||
| 51252 | osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); | ||||
| 51253 | UNUSED_VARIABLE_VALUE(bRc); | ||||
| 51254 | bRc = osCloseHandle(p->aRegion[i].hMap); | ||||
| 51255 | OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n", | ||||
| 51256 | osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); | ||||
| 51257 | UNUSED_VARIABLE_VALUE(bRc); | ||||
| 51258 | } | ||||
| 51259 | winHandleClose(p->hSharedShm); | ||||
| 51260 | if( deleteFlag ){ | ||||
| 51261 | SimulateIOErrorBenign(1); | ||||
| 51262 | sqlite3BeginBenignMalloc(); | ||||
| 51263 | winDelete(pVfs, p->zFilename, 0); | ||||
| 51264 | sqlite3EndBenignMalloc(); | ||||
| 51265 | SimulateIOErrorBenign(0); | ||||
| 51266 | } | ||||
| 51267 | *pp = p->pNext; | ||||
| 51268 | sqlite3_free(p->aRegion); | ||||
| 51269 | sqlite3_free(p); | ||||
| 51270 | }else{ | ||||
| 51271 | pp = &p->pNext; | ||||
| 51272 | } | ||||
| 51273 | } | ||||
| 51274 | } | ||||
| 51275 | |||||
| 51276 | /* | ||||
| 51277 | ** The DMS lock has not yet been taken on the shm file associated with | ||||
| 51278 | ** pShmNode. Take the lock. Truncate the *-shm file if required. | ||||
| 51279 | ** Return SQLITE_OK if successful, or an SQLite error code otherwise. | ||||
| 51280 | */ | ||||
| 51281 | static int winLockSharedMemory(winShmNode *pShmNode, DWORD nMs){ | ||||
| 51282 | HANDLE h = pShmNode->hSharedShm; | ||||
| 51283 | int rc = SQLITE_OK0; | ||||
| 51284 | |||||
| 51285 | assert( sqlite3_mutex_held(pShmNode->mutex) )((void) (0)); | ||||
| 51286 | rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 1, 0); | ||||
| 51287 | if( rc==SQLITE_OK0 ){ | ||||
| 51288 | /* We have an EXCLUSIVE lock on the DMS byte. This means that this | ||||
| 51289 | ** is the first process to open the file. Truncate it to zero bytes | ||||
| 51290 | ** in this case. */ | ||||
| 51291 | if( pShmNode->isReadonly ){ | ||||
| 51292 | rc = SQLITE_READONLY_CANTINIT(8 | (5<<8)); | ||||
| 51293 | }else{ | ||||
| 51294 | rc = winHandleTruncate(h, 0); | ||||
| 51295 | } | ||||
| 51296 | |||||
| 51297 | /* Release the EXCLUSIVE lock acquired above. */ | ||||
| 51298 | winUnlockFile(&h, WIN_SHM_DMS, 0, 1, 0); | ||||
| 51299 | }else if( (rc & 0xFF)==SQLITE_BUSY5 ){ | ||||
| 51300 | rc = SQLITE_OK0; | ||||
| 51301 | } | ||||
| 51302 | |||||
| 51303 | if( rc==SQLITE_OK0 ){ | ||||
| 51304 | /* Take a SHARED lock on the DMS byte. */ | ||||
| 51305 | rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 0, nMs); | ||||
| 51306 | if( rc==SQLITE_OK0 ){ | ||||
| 51307 | pShmNode->isUnlocked = 0; | ||||
| 51308 | } | ||||
| 51309 | } | ||||
| 51310 | |||||
| 51311 | return rc; | ||||
| 51312 | } | ||||
| 51313 | |||||
| 51314 | |||||
| 51315 | /* | ||||
| 51316 | ** Convert a UTF-8 filename into whatever form the underlying | ||||
| 51317 | ** operating system wants filenames in. Space to hold the result | ||||
| 51318 | ** is obtained from malloc and must be freed by the calling | ||||
| 51319 | ** function | ||||
| 51320 | ** | ||||
| 51321 | ** On Cygwin, 3 possible input forms are accepted: | ||||
| 51322 | ** - If the filename starts with "<drive>:/" or "<drive>:\", | ||||
| 51323 | ** it is converted to UTF-16 as-is. | ||||
| 51324 | ** - If the filename contains '/', it is assumed to be a | ||||
| 51325 | ** Cygwin absolute path, it is converted to a win32 | ||||
| 51326 | ** absolute path in UTF-16. | ||||
| 51327 | ** - Otherwise it must be a filename only, the win32 filename | ||||
| 51328 | ** is returned in UTF-16. | ||||
| 51329 | ** Note: If the function cygwin_conv_path() fails, only | ||||
| 51330 | ** UTF-8 -> UTF-16 conversion will be done. This can only | ||||
| 51331 | ** happen when the file path >32k, in which case winUtf8ToUnicode() | ||||
| 51332 | ** will fail too. | ||||
| 51333 | */ | ||||
| 51334 | static void *winConvertFromUtf8Filename(const char *zFilename){ | ||||
| 51335 | void *zConverted = 0; | ||||
| 51336 | if( osIsNT() ){ | ||||
| 51337 | #ifdef __CYGWIN__ | ||||
| 51338 | int nChar; | ||||
| 51339 | LPWSTR zWideFilename; | ||||
| 51340 | |||||
| 51341 | if( osCygwin_conv_path && !(winIsDriveLetterAndColon(zFilename) | ||||
| 51342 | && winIsDirSep(zFilename[2])) ){ | ||||
| 51343 | i64 nByte; | ||||
| 51344 | int convertflag = CCP_POSIX_TO_WIN_W; | ||||
| 51345 | if( !strchr(zFilename, '/') ) convertflag |= CCP_RELATIVE; | ||||
| 51346 | nByte = (i64)osCygwin_conv_path(convertflag, | ||||
| 51347 | zFilename, 0, 0); | ||||
| 51348 | if( nByte>0 ){ | ||||
| 51349 | zConverted = sqlite3MallocZero(12+(u64)nByte); | ||||
| 51350 | if ( zConverted==0 ){ | ||||
| 51351 | return zConverted; | ||||
| 51352 | } | ||||
| 51353 | zWideFilename = zConverted; | ||||
| 51354 | /* Filenames should be prefixed, except when converted | ||||
| 51355 | * full path already starts with "\\?\". */ | ||||
| 51356 | if( osCygwin_conv_path(convertflag, zFilename, | ||||
| 51357 | zWideFilename+4, nByte)==0 ){ | ||||
| 51358 | if( (convertflag&CCP_RELATIVE) ){ | ||||
| 51359 | memmove(zWideFilename, zWideFilename+4, nByte); | ||||
| 51360 | }else if( memcmp(zWideFilename+4, L"\\\\", 4) ){ | ||||
| 51361 | memcpy(zWideFilename, L"\\\\?\\", 8); | ||||
| 51362 | }else if( zWideFilename[6]!='?' ){ | ||||
| 51363 | memmove(zWideFilename+6, zWideFilename+4, nByte); | ||||
| 51364 | memcpy(zWideFilename, L"\\\\?\\UNC", 14); | ||||
| 51365 | }else{ | ||||
| 51366 | memmove(zWideFilename, zWideFilename+4, nByte); | ||||
| 51367 | } | ||||
| 51368 | return zConverted; | ||||
| 51369 | } | ||||
| 51370 | sqlite3_free(zConverted); | ||||
| 51371 | } | ||||
| 51372 | } | ||||
| 51373 | nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL((void*)0), 0); | ||||
| 51374 | if( nChar==0 ){ | ||||
| 51375 | return 0; | ||||
| 51376 | } | ||||
| 51377 | zWideFilename = sqlite3MallocZero( nChar*sizeof(WCHAR)+12 ); | ||||
| 51378 | if( zWideFilename==0 ){ | ||||
| 51379 | return 0; | ||||
| 51380 | } | ||||
| 51381 | nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, | ||||
| 51382 | zWideFilename, nChar); | ||||
| 51383 | if( nChar==0 ){ | ||||
| 51384 | sqlite3_free(zWideFilename); | ||||
| 51385 | zWideFilename = 0; | ||||
| 51386 | }else if( nChar>MAX_PATH | ||||
| 51387 | && winIsDriveLetterAndColon(zFilename) | ||||
| 51388 | && winIsDirSep(zFilename[2]) ){ | ||||
| 51389 | memmove(zWideFilename+4, zWideFilename, nChar*sizeof(WCHAR)); | ||||
| 51390 | zWideFilename[2] = '\\'; | ||||
| 51391 | memcpy(zWideFilename, L"\\\\?\\", 8); | ||||
| 51392 | }else if( nChar>MAX_PATH | ||||
| 51393 | && winIsDirSep(zFilename[0]) && winIsDirSep(zFilename[1]) | ||||
| 51394 | && zFilename[2] != '?' ){ | ||||
| 51395 | memmove(zWideFilename+6, zWideFilename, nChar*sizeof(WCHAR)); | ||||
| 51396 | memcpy(zWideFilename, L"\\\\?\\UNC", 14); | ||||
| 51397 | } | ||||
| 51398 | zConverted = zWideFilename; | ||||
| 51399 | #else | ||||
| 51400 | zConverted = winUtf8ToUnicode(zFilename); | ||||
| 51401 | #endif /* __CYGWIN__ */ | ||||
| 51402 | } | ||||
| 51403 | #if defined(SQLITE_WIN32_HAS_ANSI) && defined(_WIN32) | ||||
| 51404 | else{ | ||||
| 51405 | zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI()); | ||||
| 51406 | } | ||||
| 51407 | #endif | ||||
| 51408 | /* caller will handle out of memory */ | ||||
| 51409 | return zConverted; | ||||
| 51410 | } | ||||
| 51411 | |||||
| 51412 | /* | ||||
| 51413 | ** This function is used to open a handle on a *-shm file. | ||||
| 51414 | ** | ||||
| 51415 | ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined at build time, then the file | ||||
| 51416 | ** is opened with FILE_FLAG_OVERLAPPED specified. If not, it is not. | ||||
| 51417 | */ | ||||
| 51418 | static int winHandleOpen( | ||||
| 51419 | const char *zUtf8, /* File to open */ | ||||
| 51420 | int *pbReadonly, /* IN/OUT: True for readonly handle */ | ||||
| 51421 | HANDLE *ph /* OUT: New HANDLE for file */ | ||||
| 51422 | ){ | ||||
| 51423 | int rc = SQLITE_OK0; | ||||
| 51424 | void *zConverted = 0; | ||||
| 51425 | int bReadonly = *pbReadonly; | ||||
| 51426 | HANDLE h = INVALID_HANDLE_VALUE; | ||||
| 51427 | |||||
| 51428 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 51429 | const DWORD flag_overlapped = FILE_FLAG_OVERLAPPED; | ||||
| 51430 | #else | ||||
| 51431 | const DWORD flag_overlapped = 0; | ||||
| 51432 | #endif | ||||
| 51433 | |||||
| 51434 | /* Convert the filename to the system encoding. */ | ||||
| 51435 | zConverted = winConvertFromUtf8Filename(zUtf8); | ||||
| 51436 | if( zConverted==0 ){ | ||||
| 51437 | OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8)); | ||||
| 51438 | rc = SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 51439 | goto winopenfile_out; | ||||
| 51440 | } | ||||
| 51441 | |||||
| 51442 | /* Ensure the file we are trying to open is not actually a directory. */ | ||||
| 51443 | if( winIsDir(zConverted) ){ | ||||
| 51444 | OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8)); | ||||
| 51445 | rc = SQLITE_CANTOPEN_ISDIR(14 | (2<<8)); | ||||
| 51446 | goto winopenfile_out; | ||||
| 51447 | } | ||||
| 51448 | |||||
| 51449 | /* TODO: platforms. | ||||
| 51450 | ** TODO: retry-on-ioerr. | ||||
| 51451 | */ | ||||
| 51452 | if( osIsNT() ){ | ||||
| 51453 | #if SQLITE_OS_WINRT | ||||
| 51454 | CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; | ||||
| 51455 | memset(&extendedParameters, 0, sizeof(extendedParameters)); | ||||
| 51456 | extendedParameters.dwSize = sizeof(extendedParameters); | ||||
| 51457 | extendedParameters.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; | ||||
| 51458 | extendedParameters.dwFileFlags = flag_overlapped; | ||||
| 51459 | extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; | ||||
| 51460 | h = osCreateFile2((LPCWSTR)zConverted, | ||||
| 51461 | (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)),/* dwDesiredAccess */ | ||||
| 51462 | FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */ | ||||
| 51463 | OPEN_ALWAYS, /* dwCreationDisposition */ | ||||
| 51464 | &extendedParameters | ||||
| 51465 | ); | ||||
| 51466 | #else | ||||
| 51467 | h = osCreateFileW((LPCWSTR)zConverted, /* lpFileName */ | ||||
| 51468 | (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)), /* dwDesiredAccess */ | ||||
| 51469 | FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */ | ||||
| 51470 | NULL((void*)0), /* lpSecurityAttributes */ | ||||
| 51471 | OPEN_ALWAYS, /* dwCreationDisposition */ | ||||
| 51472 | FILE_ATTRIBUTE_NORMAL|flag_overlapped, | ||||
| 51473 | NULL((void*)0) | ||||
| 51474 | ); | ||||
| 51475 | #endif | ||||
| 51476 | }else{ | ||||
| 51477 | /* Due to pre-processor directives earlier in this file, | ||||
| 51478 | ** SQLITE_WIN32_HAS_ANSI is always defined if osIsNT() is false. */ | ||||
| 51479 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 51480 | h = osCreateFileA((LPCSTR)zConverted, | ||||
| 51481 | (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)), /* dwDesiredAccess */ | ||||
| 51482 | FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */ | ||||
| 51483 | NULL((void*)0), /* lpSecurityAttributes */ | ||||
| 51484 | OPEN_ALWAYS, /* dwCreationDisposition */ | ||||
| 51485 | FILE_ATTRIBUTE_NORMAL|flag_overlapped, | ||||
| 51486 | NULL((void*)0) | ||||
| 51487 | ); | ||||
| 51488 | #endif | ||||
| 51489 | } | ||||
| 51490 | |||||
| 51491 | if( h==INVALID_HANDLE_VALUE ){ | ||||
| 51492 | if( bReadonly==0 ){ | ||||
| 51493 | bReadonly = 1; | ||||
| 51494 | rc = winHandleOpen(zUtf8, &bReadonly, &h); | ||||
| 51495 | }else{ | ||||
| 51496 | rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(51496); | ||||
| 51497 | } | ||||
| 51498 | } | ||||
| 51499 | |||||
| 51500 | winopenfile_out: | ||||
| 51501 | sqlite3_free(zConverted); | ||||
| 51502 | *pbReadonly = bReadonly; | ||||
| 51503 | *ph = h; | ||||
| 51504 | return rc; | ||||
| 51505 | } | ||||
| 51506 | |||||
| 51507 | |||||
| 51508 | /* | ||||
| 51509 | ** Open the shared-memory area associated with database file pDbFd. | ||||
| 51510 | */ | ||||
| 51511 | static int winOpenSharedMemory(winFile *pDbFd){ | ||||
| 51512 | struct winShm *p; /* The connection to be opened */ | ||||
| 51513 | winShmNode *pShmNode = 0; /* The underlying mmapped file */ | ||||
| 51514 | int rc = SQLITE_OK0; /* Result code */ | ||||
| 51515 | winShmNode *pNew; /* Newly allocated winShmNode */ | ||||
| 51516 | int nName; /* Size of zName in bytes */ | ||||
| 51517 | |||||
| 51518 | assert( pDbFd->pShm==0 )((void) (0)); /* Not previously opened */ | ||||
| 51519 | |||||
| 51520 | /* Allocate space for the new sqlite3_shm object. Also speculatively | ||||
| 51521 | ** allocate space for a new winShmNode and filename. */ | ||||
| 51522 | p = sqlite3MallocZero( sizeof(*p) ); | ||||
| 51523 | if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 51524 | nName = sqlite3Strlen30(pDbFd->zPath); | ||||
| 51525 | pNew = sqlite3MallocZero( sizeof(*pShmNode) + (i64)nName + 17 ); | ||||
| 51526 | if( pNew==0 ){ | ||||
| 51527 | sqlite3_free(p); | ||||
| 51528 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 51529 | } | ||||
| 51530 | pNew->zFilename = (char*)&pNew[1]; | ||||
| 51531 | pNew->hSharedShm = INVALID_HANDLE_VALUE; | ||||
| 51532 | pNew->isUnlocked = 1; | ||||
| 51533 | sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); | ||||
| 51534 | sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); | ||||
| 51535 | |||||
| 51536 | /* Open a file-handle on the *-shm file for this connection. This file-handle | ||||
| 51537 | ** is only used for locking. The mapping of the *-shm file is created using | ||||
| 51538 | ** the shared file handle in winShmNode.hSharedShm. */ | ||||
| 51539 | p->bReadonly = sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0); | ||||
| 51540 | rc = winHandleOpen(pNew->zFilename, &p->bReadonly, &p->hShm); | ||||
| 51541 | |||||
| 51542 | /* Look to see if there is an existing winShmNode that can be used. | ||||
| 51543 | ** If no matching winShmNode currently exists, then create a new one. */ | ||||
| 51544 | winShmEnterMutex(); | ||||
| 51545 | for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){ | ||||
| 51546 | /* TBD need to come up with better match here. Perhaps | ||||
| 51547 | ** use FILE_ID_BOTH_DIR_INFO Structure. */ | ||||
| 51548 | if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; | ||||
| 51549 | } | ||||
| 51550 | if( pShmNode==0 ){ | ||||
| 51551 | pShmNode = pNew; | ||||
| 51552 | |||||
| 51553 | /* Allocate a mutex for this winShmNode object, if one is required. */ | ||||
| 51554 | if( sqlite3GlobalConfigsqlite3Config.bCoreMutex ){ | ||||
| 51555 | pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST0); | ||||
| 51556 | if( pShmNode->mutex==0 ) rc = SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 51557 | } | ||||
| 51558 | |||||
| 51559 | /* Open a file-handle to use for mappings, and for the DMS lock. */ | ||||
| 51560 | if( rc==SQLITE_OK0 ){ | ||||
| 51561 | HANDLE h = INVALID_HANDLE_VALUE; | ||||
| 51562 | pShmNode->isReadonly = p->bReadonly; | ||||
| 51563 | rc = winHandleOpen(pNew->zFilename, &pShmNode->isReadonly, &h); | ||||
| 51564 | pShmNode->hSharedShm = h; | ||||
| 51565 | } | ||||
| 51566 | |||||
| 51567 | /* If successful, link the new winShmNode into the global list. If an | ||||
| 51568 | ** error occurred, free the object. */ | ||||
| 51569 | if( rc==SQLITE_OK0 ){ | ||||
| 51570 | pShmNode->pNext = winShmNodeList; | ||||
| 51571 | winShmNodeList = pShmNode; | ||||
| 51572 | pNew = 0; | ||||
| 51573 | }else{ | ||||
| 51574 | sqlite3_mutex_free(pShmNode->mutex); | ||||
| 51575 | if( pShmNode->hSharedShm!=INVALID_HANDLE_VALUE ){ | ||||
| 51576 | osCloseHandle(pShmNode->hSharedShm); | ||||
| 51577 | } | ||||
| 51578 | } | ||||
| 51579 | } | ||||
| 51580 | |||||
| 51581 | /* If no error has occurred, link the winShm object to the winShmNode and | ||||
| 51582 | ** the winShm to pDbFd. */ | ||||
| 51583 | if( rc==SQLITE_OK0 ){ | ||||
| 51584 | p->pShmNode = pShmNode; | ||||
| 51585 | pShmNode->nRef++; | ||||
| 51586 | #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) | ||||
| 51587 | p->id = pShmNode->nextShmId++; | ||||
| 51588 | #endif | ||||
| 51589 | pDbFd->pShm = p; | ||||
| 51590 | }else if( p ){ | ||||
| 51591 | winHandleClose(p->hShm); | ||||
| 51592 | sqlite3_free(p); | ||||
| 51593 | } | ||||
| 51594 | |||||
| 51595 | assert( rc!=SQLITE_OK || pShmNode->isUnlocked==0 || pShmNode->nRegion==0 )((void) (0)); | ||||
| 51596 | winShmLeaveMutex(); | ||||
| 51597 | sqlite3_free(pNew); | ||||
| 51598 | return rc; | ||||
| 51599 | } | ||||
| 51600 | |||||
| 51601 | /* | ||||
| 51602 | ** Close a connection to shared-memory. Delete the underlying | ||||
| 51603 | ** storage if deleteFlag is true. | ||||
| 51604 | */ | ||||
| 51605 | static int winShmUnmap( | ||||
| 51606 | sqlite3_file *fd, /* Database holding shared memory */ | ||||
| 51607 | int deleteFlag /* Delete after closing if true */ | ||||
| 51608 | ){ | ||||
| 51609 | winFile *pDbFd; /* Database holding shared-memory */ | ||||
| 51610 | winShm *p; /* The connection to be closed */ | ||||
| 51611 | winShmNode *pShmNode; /* The underlying shared-memory file */ | ||||
| 51612 | |||||
| 51613 | pDbFd = (winFile*)fd; | ||||
| 51614 | p = pDbFd->pShm; | ||||
| 51615 | if( p==0 ) return SQLITE_OK0; | ||||
| 51616 | if( p->hShm!=INVALID_HANDLE_VALUE ){ | ||||
| 51617 | osCloseHandle(p->hShm); | ||||
| 51618 | } | ||||
| 51619 | |||||
| 51620 | pShmNode = p->pShmNode; | ||||
| 51621 | winShmEnterMutex(); | ||||
| 51622 | |||||
| 51623 | /* If pShmNode->nRef has reached 0, then close the underlying | ||||
| 51624 | ** shared-memory file, too. */ | ||||
| 51625 | assert( pShmNode->nRef>0 )((void) (0)); | ||||
| 51626 | pShmNode->nRef--; | ||||
| 51627 | if( pShmNode->nRef==0 ){ | ||||
| 51628 | winShmPurge(pDbFd->pVfs, deleteFlag); | ||||
| 51629 | } | ||||
| 51630 | winShmLeaveMutex(); | ||||
| 51631 | |||||
| 51632 | /* Free the connection p */ | ||||
| 51633 | sqlite3_free(p); | ||||
| 51634 | pDbFd->pShm = 0; | ||||
| 51635 | return SQLITE_OK0; | ||||
| 51636 | } | ||||
| 51637 | |||||
| 51638 | /* | ||||
| 51639 | ** Change the lock state for a shared-memory segment. | ||||
| 51640 | */ | ||||
| 51641 | static int winShmLock( | ||||
| 51642 | sqlite3_file *fd, /* Database file holding the shared memory */ | ||||
| 51643 | int ofst, /* First lock to acquire or release */ | ||||
| 51644 | int n, /* Number of locks to acquire or release */ | ||||
| 51645 | int flags /* What to do with the lock */ | ||||
| 51646 | ){ | ||||
| 51647 | winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */ | ||||
| 51648 | winShm *p = pDbFd->pShm; /* The shared memory being locked */ | ||||
| 51649 | winShmNode *pShmNode; | ||||
| 51650 | int rc = SQLITE_OK0; /* Result code */ | ||||
| 51651 | u16 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); /* Mask of locks to [un]take */ | ||||
| 51652 | |||||
| 51653 | if( p==0 ) return SQLITE_IOERR_SHMLOCK(10 | (20<<8)); | ||||
| 51654 | pShmNode = p->pShmNode; | ||||
| 51655 | if( NEVER(pShmNode==0)(pShmNode==0) ) return SQLITE_IOERR_SHMLOCK(10 | (20<<8)); | ||||
| 51656 | |||||
| 51657 | assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK )((void) (0)); | ||||
| 51658 | assert( n>=1 )((void) (0)); | ||||
| 51659 | assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)((void) (0)) | ||||
| 51660 | || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)((void) (0)) | ||||
| 51661 | || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)((void) (0)) | ||||
| 51662 | || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) )((void) (0)); | ||||
| 51663 | assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 )((void) (0)); | ||||
| 51664 | |||||
| 51665 | /* Check that, if this to be a blocking lock, no locks that occur later | ||||
| 51666 | ** in the following list than the lock being obtained are already held: | ||||
| 51667 | ** | ||||
| 51668 | ** 1. Recovery lock (ofst==2). | ||||
| 51669 | ** 2. Checkpointer lock (ofst==1). | ||||
| 51670 | ** 3. Write lock (ofst==0). | ||||
| 51671 | ** 4. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK). | ||||
| 51672 | ** | ||||
| 51673 | ** In other words, if this is a blocking lock, none of the locks that | ||||
| 51674 | ** occur later in the above list than the lock being obtained may be | ||||
| 51675 | ** held. | ||||
| 51676 | */ | ||||
| 51677 | #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG) | ||||
| 51678 | { | ||||
| 51679 | u16 lockMask = (p->exclMask|p->sharedMask); | ||||
| 51680 | assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (((void) (0)) | ||||
| 51681 | (ofst!=2 || lockMask==0)((void) (0)) | ||||
| 51682 | && (ofst!=1 || lockMask==0 || lockMask==2)((void) (0)) | ||||
| 51683 | && (ofst!=0 || lockMask<3)((void) (0)) | ||||
| 51684 | && (ofst<3 || lockMask<(1<<ofst))((void) (0)) | ||||
| 51685 | ))((void) (0)); | ||||
| 51686 | } | ||||
| 51687 | #endif | ||||
| 51688 | |||||
| 51689 | /* Check if there is any work to do. There are three cases: | ||||
| 51690 | ** | ||||
| 51691 | ** a) An unlock operation where there are locks to unlock, | ||||
| 51692 | ** b) An shared lock where the requested lock is not already held | ||||
| 51693 | ** c) An exclusive lock where the requested lock is not already held | ||||
| 51694 | ** | ||||
| 51695 | ** The SQLite core never requests an exclusive lock that it already holds. | ||||
| 51696 | ** This is assert()ed immediately below. */ | ||||
| 51697 | assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)((void) (0)) | ||||
| 51698 | || 0==(p->exclMask & mask)((void) (0)) | ||||
| 51699 | )((void) (0)); | ||||
| 51700 | if( ((flags & SQLITE_SHM_UNLOCK1) && ((p->exclMask|p->sharedMask) & mask)) | ||||
| 51701 | || (flags==(SQLITE_SHM_SHARED4|SQLITE_SHM_LOCK2) && 0==(p->sharedMask & mask)) | ||||
| 51702 | || (flags==(SQLITE_SHM_EXCLUSIVE8|SQLITE_SHM_LOCK2)) | ||||
| 51703 | ){ | ||||
| 51704 | |||||
| 51705 | if( flags & SQLITE_SHM_UNLOCK1 ){ | ||||
| 51706 | /* Case (a) - unlock. */ | ||||
| 51707 | |||||
| 51708 | assert( (p->exclMask & p->sharedMask)==0 )((void) (0)); | ||||
| 51709 | assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask )((void) (0)); | ||||
| 51710 | assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask )((void) (0)); | ||||
| 51711 | |||||
| 51712 | rc = winHandleUnlock(p->hShm, ofst+WIN_SHM_BASE, n); | ||||
| 51713 | |||||
| 51714 | /* If successful, also clear the bits in sharedMask/exclMask */ | ||||
| 51715 | if( rc==SQLITE_OK0 ){ | ||||
| 51716 | p->exclMask = (p->exclMask & ~mask); | ||||
| 51717 | p->sharedMask = (p->sharedMask & ~mask); | ||||
| 51718 | } | ||||
| 51719 | }else{ | ||||
| 51720 | int bExcl = ((flags & SQLITE_SHM_EXCLUSIVE8) ? 1 : 0); | ||||
| 51721 | DWORD nMs = winFileBusyTimeout(pDbFd); | ||||
| 51722 | rc = winHandleLockTimeout(p->hShm, ofst+WIN_SHM_BASE, n, bExcl, nMs); | ||||
| 51723 | if( rc==SQLITE_OK0 ){ | ||||
| 51724 | if( bExcl ){ | ||||
| 51725 | p->exclMask = (p->exclMask | mask); | ||||
| 51726 | }else{ | ||||
| 51727 | p->sharedMask = (p->sharedMask | mask); | ||||
| 51728 | } | ||||
| 51729 | } | ||||
| 51730 | } | ||||
| 51731 | } | ||||
| 51732 | |||||
| 51733 | OSTRACE(( | ||||
| 51734 | "SHM-LOCK(%d,%d,%d) pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x," | ||||
| 51735 | " rc=%s\n", | ||||
| 51736 | ofst, n, flags, | ||||
| 51737 | osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, | ||||
| 51738 | sqlite3ErrName(rc)) | ||||
| 51739 | ); | ||||
| 51740 | return rc; | ||||
| 51741 | } | ||||
| 51742 | |||||
| 51743 | /* | ||||
| 51744 | ** Implement a memory barrier or memory fence on shared memory. | ||||
| 51745 | ** | ||||
| 51746 | ** All loads and stores begun before the barrier must complete before | ||||
| 51747 | ** any load or store begun after the barrier. | ||||
| 51748 | */ | ||||
| 51749 | static void winShmBarrier( | ||||
| 51750 | sqlite3_file *fd /* Database holding the shared memory */ | ||||
| 51751 | ){ | ||||
| 51752 | UNUSED_PARAMETER(fd)(void)(fd); | ||||
| 51753 | sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ | ||||
| 51754 | winShmEnterMutex(); /* Also mutex, for redundancy */ | ||||
| 51755 | winShmLeaveMutex(); | ||||
| 51756 | } | ||||
| 51757 | |||||
| 51758 | /* | ||||
| 51759 | ** This function is called to obtain a pointer to region iRegion of the | ||||
| 51760 | ** shared-memory associated with the database file fd. Shared-memory regions | ||||
| 51761 | ** are numbered starting from zero. Each shared-memory region is szRegion | ||||
| 51762 | ** bytes in size. | ||||
| 51763 | ** | ||||
| 51764 | ** If an error occurs, an error code is returned and *pp is set to NULL. | ||||
| 51765 | ** | ||||
| 51766 | ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory | ||||
| 51767 | ** region has not been allocated (by any client, including one running in a | ||||
| 51768 | ** separate process), then *pp is set to NULL and SQLITE_OK returned. If | ||||
| 51769 | ** isWrite is non-zero and the requested shared-memory region has not yet | ||||
| 51770 | ** been allocated, it is allocated by this function. | ||||
| 51771 | ** | ||||
| 51772 | ** If the shared-memory region has already been allocated or is allocated by | ||||
| 51773 | ** this call as described above, then it is mapped into this processes | ||||
| 51774 | ** address space (if it is not already), *pp is set to point to the mapped | ||||
| 51775 | ** memory and SQLITE_OK returned. | ||||
| 51776 | */ | ||||
| 51777 | static int winShmMap( | ||||
| 51778 | sqlite3_file *fd, /* Handle open on database file */ | ||||
| 51779 | int iRegion, /* Region to retrieve */ | ||||
| 51780 | int szRegion, /* Size of regions */ | ||||
| 51781 | int isWrite, /* True to extend file if necessary */ | ||||
| 51782 | void volatile **pp /* OUT: Mapped memory */ | ||||
| 51783 | ){ | ||||
| 51784 | winFile *pDbFd = (winFile*)fd; | ||||
| 51785 | winShm *pShm = pDbFd->pShm; | ||||
| 51786 | winShmNode *pShmNode; | ||||
| 51787 | DWORD protect = PAGE_READWRITE; | ||||
| 51788 | DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ; | ||||
| 51789 | int rc = SQLITE_OK0; | ||||
| 51790 | |||||
| 51791 | if( !pShm ){ | ||||
| 51792 | rc = winOpenSharedMemory(pDbFd); | ||||
| 51793 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 51794 | pShm = pDbFd->pShm; | ||||
| 51795 | assert( pShm!=0 )((void) (0)); | ||||
| 51796 | } | ||||
| 51797 | pShmNode = pShm->pShmNode; | ||||
| 51798 | |||||
| 51799 | sqlite3_mutex_enter(pShmNode->mutex); | ||||
| 51800 | if( pShmNode->isUnlocked ){ | ||||
| 51801 | /* Take the DMS lock. */ | ||||
| 51802 | assert( pShmNode->nRegion==0 )((void) (0)); | ||||
| 51803 | rc = winLockSharedMemory(pShmNode, winFileBusyTimeout(pDbFd)); | ||||
| 51804 | if( rc!=SQLITE_OK0 ) goto shmpage_out; | ||||
| 51805 | } | ||||
| 51806 | |||||
| 51807 | assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 )((void) (0)); | ||||
| 51808 | if( pShmNode->nRegion<=iRegion ){ | ||||
| 51809 | HANDLE hShared = pShmNode->hSharedShm; | ||||
| 51810 | struct ShmRegion *apNew; /* New aRegion[] array */ | ||||
| 51811 | int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ | ||||
| 51812 | sqlite3_int64 sz; /* Current size of wal-index file */ | ||||
| 51813 | |||||
| 51814 | pShmNode->szRegion = szRegion; | ||||
| 51815 | |||||
| 51816 | /* The requested region is not mapped into this processes address space. | ||||
| 51817 | ** Check to see if it has been allocated (i.e. if the wal-index file is | ||||
| 51818 | ** large enough to contain the requested region). | ||||
| 51819 | */ | ||||
| 51820 | rc = winHandleSize(hShared, &sz); | ||||
| 51821 | if( rc!=SQLITE_OK0 ){ | ||||
| 51822 | rc = winLogError(rc, osGetLastError(), "winShmMap1", pDbFd->zPath); | ||||
| 51823 | goto shmpage_out; | ||||
| 51824 | } | ||||
| 51825 | |||||
| 51826 | if( sz<nByte ){ | ||||
| 51827 | /* The requested memory region does not exist. If isWrite is set to | ||||
| 51828 | ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned. | ||||
| 51829 | ** | ||||
| 51830 | ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate | ||||
| 51831 | ** the requested memory region. */ | ||||
| 51832 | if( !isWrite ) goto shmpage_out; | ||||
| 51833 | rc = winHandleTruncate(hShared, nByte); | ||||
| 51834 | if( rc!=SQLITE_OK0 ){ | ||||
| 51835 | rc = winLogError(rc, osGetLastError(), "winShmMap2", pDbFd->zPath); | ||||
| 51836 | goto shmpage_out; | ||||
| 51837 | } | ||||
| 51838 | } | ||||
| 51839 | |||||
| 51840 | /* Map the requested memory region into this processes address space. */ | ||||
| 51841 | apNew = (struct ShmRegion*)sqlite3_realloc64( | ||||
| 51842 | pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) | ||||
| 51843 | ); | ||||
| 51844 | if( !apNew ){ | ||||
| 51845 | rc = SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 51846 | goto shmpage_out; | ||||
| 51847 | } | ||||
| 51848 | pShmNode->aRegion = apNew; | ||||
| 51849 | |||||
| 51850 | if( pShmNode->isReadonly ){ | ||||
| 51851 | protect = PAGE_READONLY; | ||||
| 51852 | flags = FILE_MAP_READ; | ||||
| 51853 | } | ||||
| 51854 | |||||
| 51855 | while( pShmNode->nRegion<=iRegion ){ | ||||
| 51856 | HANDLE hMap = NULL((void*)0); /* file-mapping handle */ | ||||
| 51857 | void *pMap = 0; /* Mapped memory region */ | ||||
| 51858 | |||||
| 51859 | #if SQLITE_OS_WINRT | ||||
| 51860 | hMap = osCreateFileMappingFromApp(hShared, NULL((void*)0), protect, nByte, NULL((void*)0)); | ||||
| 51861 | #elif defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 51862 | hMap = osCreateFileMappingW(hShared, NULL((void*)0), protect, 0, nByte, NULL((void*)0)); | ||||
| 51863 | #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA | ||||
| 51864 | hMap = osCreateFileMappingA(hShared, NULL((void*)0), protect, 0, nByte, NULL((void*)0)); | ||||
| 51865 | #endif | ||||
| 51866 | |||||
| 51867 | OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n", | ||||
| 51868 | osGetCurrentProcessId(), pShmNode->nRegion, nByte, | ||||
| 51869 | hMap ? "ok" : "failed")); | ||||
| 51870 | if( hMap ){ | ||||
| 51871 | int iOffset = pShmNode->nRegion*szRegion; | ||||
| 51872 | int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; | ||||
| 51873 | #if SQLITE_OS_WINRT | ||||
| 51874 | pMap = osMapViewOfFileFromApp(hMap, flags, | ||||
| 51875 | iOffset - iOffsetShift, szRegion + iOffsetShift | ||||
| 51876 | ); | ||||
| 51877 | #else | ||||
| 51878 | pMap = osMapViewOfFile(hMap, flags, | ||||
| 51879 | 0, iOffset - iOffsetShift, szRegion + iOffsetShift | ||||
| 51880 | ); | ||||
| 51881 | #endif | ||||
| 51882 | OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n", | ||||
| 51883 | osGetCurrentProcessId(), pShmNode->nRegion, iOffset, | ||||
| 51884 | szRegion, pMap ? "ok" : "failed")); | ||||
| 51885 | } | ||||
| 51886 | if( !pMap ){ | ||||
| 51887 | pShmNode->lastErrno = osGetLastError(); | ||||
| 51888 | rc = winLogError(SQLITE_IOERR_SHMMAP(10 | (21<<8)), pShmNode->lastErrno, | ||||
| 51889 | "winShmMap3", pDbFd->zPath); | ||||
| 51890 | if( hMap ) osCloseHandle(hMap); | ||||
| 51891 | goto shmpage_out; | ||||
| 51892 | } | ||||
| 51893 | |||||
| 51894 | pShmNode->aRegion[pShmNode->nRegion].pMap = pMap; | ||||
| 51895 | pShmNode->aRegion[pShmNode->nRegion].hMap = hMap; | ||||
| 51896 | pShmNode->nRegion++; | ||||
| 51897 | } | ||||
| 51898 | } | ||||
| 51899 | |||||
| 51900 | shmpage_out: | ||||
| 51901 | if( pShmNode->nRegion>iRegion ){ | ||||
| 51902 | int iOffset = iRegion*szRegion; | ||||
| 51903 | int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; | ||||
| 51904 | char *p = (char *)pShmNode->aRegion[iRegion].pMap; | ||||
| 51905 | *pp = (void *)&p[iOffsetShift]; | ||||
| 51906 | }else{ | ||||
| 51907 | *pp = 0; | ||||
| 51908 | } | ||||
| 51909 | if( pShmNode->isReadonly && rc==SQLITE_OK0 ){ | ||||
| 51910 | rc = SQLITE_READONLY8; | ||||
| 51911 | } | ||||
| 51912 | sqlite3_mutex_leave(pShmNode->mutex); | ||||
| 51913 | return rc; | ||||
| 51914 | } | ||||
| 51915 | |||||
| 51916 | #else | ||||
| 51917 | # define winShmMap 0 | ||||
| 51918 | # define winShmLock 0 | ||||
| 51919 | # define winShmBarrier 0 | ||||
| 51920 | # define winShmUnmap 0 | ||||
| 51921 | #endif /* #ifndef SQLITE_OMIT_WAL */ | ||||
| 51922 | |||||
| 51923 | /* | ||||
| 51924 | ** Cleans up the mapped region of the specified file, if any. | ||||
| 51925 | */ | ||||
| 51926 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 51927 | static int winUnmapfile(winFile *pFile){ | ||||
| 51928 | assert( pFile!=0 )((void) (0)); | ||||
| 51929 | OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, " | ||||
| 51930 | "mmapSize=%lld, mmapSizeMax=%lld\n", | ||||
| 51931 | osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion, | ||||
| 51932 | pFile->mmapSize, pFile->mmapSizeMax)); | ||||
| 51933 | if( pFile->pMapRegion ){ | ||||
| 51934 | if( !osUnmapViewOfFile(pFile->pMapRegion) ){ | ||||
| 51935 | pFile->lastErrno = osGetLastError(); | ||||
| 51936 | OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, " | ||||
| 51937 | "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile, | ||||
| 51938 | pFile->pMapRegion)); | ||||
| 51939 | return winLogError(SQLITE_IOERR_MMAP(10 | (24<<8)), pFile->lastErrno, | ||||
| 51940 | "winUnmapfile1", pFile->zPath); | ||||
| 51941 | } | ||||
| 51942 | pFile->pMapRegion = 0; | ||||
| 51943 | pFile->mmapSize = 0; | ||||
| 51944 | } | ||||
| 51945 | if( pFile->hMap!=NULL((void*)0) ){ | ||||
| 51946 | if( !osCloseHandle(pFile->hMap) ){ | ||||
| 51947 | pFile->lastErrno = osGetLastError(); | ||||
| 51948 | OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n", | ||||
| 51949 | osGetCurrentProcessId(), pFile, pFile->hMap)); | ||||
| 51950 | return winLogError(SQLITE_IOERR_MMAP(10 | (24<<8)), pFile->lastErrno, | ||||
| 51951 | "winUnmapfile2", pFile->zPath); | ||||
| 51952 | } | ||||
| 51953 | pFile->hMap = NULL((void*)0); | ||||
| 51954 | } | ||||
| 51955 | OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", | ||||
| 51956 | osGetCurrentProcessId(), pFile)); | ||||
| 51957 | return SQLITE_OK0; | ||||
| 51958 | } | ||||
| 51959 | |||||
| 51960 | /* | ||||
| 51961 | ** Memory map or remap the file opened by file-descriptor pFd (if the file | ||||
| 51962 | ** is already mapped, the existing mapping is replaced by the new). Or, if | ||||
| 51963 | ** there already exists a mapping for this file, and there are still | ||||
| 51964 | ** outstanding xFetch() references to it, this function is a no-op. | ||||
| 51965 | ** | ||||
| 51966 | ** If parameter nByte is non-negative, then it is the requested size of | ||||
| 51967 | ** the mapping to create. Otherwise, if nByte is less than zero, then the | ||||
| 51968 | ** requested size is the size of the file on disk. The actual size of the | ||||
| 51969 | ** created mapping is either the requested size or the value configured | ||||
| 51970 | ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller. | ||||
| 51971 | ** | ||||
| 51972 | ** SQLITE_OK is returned if no error occurs (even if the mapping is not | ||||
| 51973 | ** recreated as a result of outstanding references) or an SQLite error | ||||
| 51974 | ** code otherwise. | ||||
| 51975 | */ | ||||
| 51976 | static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ | ||||
| 51977 | sqlite3_int64 nMap = nByte; | ||||
| 51978 | int rc; | ||||
| 51979 | |||||
| 51980 | assert( nMap>=0 || pFd->nFetchOut==0 )((void) (0)); | ||||
| 51981 | OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n", | ||||
| 51982 | osGetCurrentProcessId(), pFd, nByte)); | ||||
| 51983 | |||||
| 51984 | if( pFd->nFetchOut>0 ) return SQLITE_OK0; | ||||
| 51985 | |||||
| 51986 | if( nMap<0 ){ | ||||
| 51987 | rc = winFileSize((sqlite3_file*)pFd, &nMap); | ||||
| 51988 | if( rc ){ | ||||
| 51989 | OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n", | ||||
| 51990 | osGetCurrentProcessId(), pFd)); | ||||
| 51991 | return SQLITE_IOERR_FSTAT(10 | (7<<8)); | ||||
| 51992 | } | ||||
| 51993 | } | ||||
| 51994 | if( nMap>pFd->mmapSizeMax ){ | ||||
| 51995 | nMap = pFd->mmapSizeMax; | ||||
| 51996 | } | ||||
| 51997 | nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1); | ||||
| 51998 | |||||
| 51999 | if( nMap==0 && pFd->mmapSize>0 ){ | ||||
| 52000 | winUnmapfile(pFd); | ||||
| 52001 | } | ||||
| 52002 | if( nMap!=pFd->mmapSize ){ | ||||
| 52003 | void *pNew = 0; | ||||
| 52004 | DWORD protect = PAGE_READONLY; | ||||
| 52005 | DWORD flags = FILE_MAP_READ; | ||||
| 52006 | |||||
| 52007 | winUnmapfile(pFd); | ||||
| 52008 | #ifdef SQLITE_MMAP_READWRITE | ||||
| 52009 | if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){ | ||||
| 52010 | protect = PAGE_READWRITE; | ||||
| 52011 | flags |= FILE_MAP_WRITE; | ||||
| 52012 | } | ||||
| 52013 | #endif | ||||
| 52014 | #if SQLITE_OS_WINRT | ||||
| 52015 | pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL((void*)0), protect, nMap, NULL((void*)0)); | ||||
| 52016 | #elif defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 52017 | pFd->hMap = osCreateFileMappingW(pFd->h, NULL((void*)0), protect, | ||||
| 52018 | (DWORD)((nMap>>32) & 0xffffffff), | ||||
| 52019 | (DWORD)(nMap & 0xffffffff), NULL((void*)0)); | ||||
| 52020 | #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA | ||||
| 52021 | pFd->hMap = osCreateFileMappingA(pFd->h, NULL((void*)0), protect, | ||||
| 52022 | (DWORD)((nMap>>32) & 0xffffffff), | ||||
| 52023 | (DWORD)(nMap & 0xffffffff), NULL((void*)0)); | ||||
| 52024 | #endif | ||||
| 52025 | if( pFd->hMap==NULL((void*)0) ){ | ||||
| 52026 | pFd->lastErrno = osGetLastError(); | ||||
| 52027 | rc = winLogError(SQLITE_IOERR_MMAP(10 | (24<<8)), pFd->lastErrno, | ||||
| 52028 | "winMapfile1", pFd->zPath); | ||||
| 52029 | /* Log the error, but continue normal operation using xRead/xWrite */ | ||||
| 52030 | OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n", | ||||
| 52031 | osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); | ||||
| 52032 | return SQLITE_OK0; | ||||
| 52033 | } | ||||
| 52034 | assert( (nMap % winSysInfo.dwPageSize)==0 )((void) (0)); | ||||
| 52035 | assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff )((void) (0)); | ||||
| 52036 | #if SQLITE_OS_WINRT | ||||
| 52037 | pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap); | ||||
| 52038 | #else | ||||
| 52039 | pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap); | ||||
| 52040 | #endif | ||||
| 52041 | if( pNew==NULL((void*)0) ){ | ||||
| 52042 | osCloseHandle(pFd->hMap); | ||||
| 52043 | pFd->hMap = NULL((void*)0); | ||||
| 52044 | pFd->lastErrno = osGetLastError(); | ||||
| 52045 | rc = winLogError(SQLITE_IOERR_MMAP(10 | (24<<8)), pFd->lastErrno, | ||||
| 52046 | "winMapfile2", pFd->zPath); | ||||
| 52047 | /* Log the error, but continue normal operation using xRead/xWrite */ | ||||
| 52048 | OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n", | ||||
| 52049 | osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); | ||||
| 52050 | return SQLITE_OK0; | ||||
| 52051 | } | ||||
| 52052 | pFd->pMapRegion = pNew; | ||||
| 52053 | pFd->mmapSize = nMap; | ||||
| 52054 | } | ||||
| 52055 | |||||
| 52056 | OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", | ||||
| 52057 | osGetCurrentProcessId(), pFd)); | ||||
| 52058 | return SQLITE_OK0; | ||||
| 52059 | } | ||||
| 52060 | #endif /* SQLITE_MAX_MMAP_SIZE>0 */ | ||||
| 52061 | |||||
| 52062 | /* | ||||
| 52063 | ** If possible, return a pointer to a mapping of file fd starting at offset | ||||
| 52064 | ** iOff. The mapping must be valid for at least nAmt bytes. | ||||
| 52065 | ** | ||||
| 52066 | ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. | ||||
| 52067 | ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. | ||||
| 52068 | ** Finally, if an error does occur, return an SQLite error code. The final | ||||
| 52069 | ** value of *pp is undefined in this case. | ||||
| 52070 | ** | ||||
| 52071 | ** If this function does return a pointer, the caller must eventually | ||||
| 52072 | ** release the reference by calling winUnfetch(). | ||||
| 52073 | */ | ||||
| 52074 | static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ | ||||
| 52075 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 52076 | winFile *pFd = (winFile*)fd; /* The underlying database file */ | ||||
| 52077 | #endif | ||||
| 52078 | *pp = 0; | ||||
| 52079 | |||||
| 52080 | OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n", | ||||
| 52081 | osGetCurrentProcessId(), fd, iOff, nAmt, pp)); | ||||
| 52082 | |||||
| 52083 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 52084 | if( pFd->mmapSizeMax>0 ){ | ||||
| 52085 | /* Ensure that there is always at least a 256 byte buffer of addressable | ||||
| 52086 | ** memory following the returned page. If the database is corrupt, | ||||
| 52087 | ** SQLite may overread the page slightly (in practice only a few bytes, | ||||
| 52088 | ** but 256 is safe, round, number). */ | ||||
| 52089 | const int nEofBuffer = 256; | ||||
| 52090 | if( pFd->pMapRegion==0 ){ | ||||
| 52091 | int rc = winMapfile(pFd, -1); | ||||
| 52092 | if( rc!=SQLITE_OK0 ){ | ||||
| 52093 | OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n", | ||||
| 52094 | osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); | ||||
| 52095 | return rc; | ||||
| 52096 | } | ||||
| 52097 | } | ||||
| 52098 | if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){ | ||||
| 52099 | assert( pFd->pMapRegion!=0 )((void) (0)); | ||||
| 52100 | *pp = &((u8 *)pFd->pMapRegion)[iOff]; | ||||
| 52101 | pFd->nFetchOut++; | ||||
| 52102 | } | ||||
| 52103 | } | ||||
| 52104 | #endif | ||||
| 52105 | |||||
| 52106 | OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n", | ||||
| 52107 | osGetCurrentProcessId(), fd, pp, *pp)); | ||||
| 52108 | return SQLITE_OK0; | ||||
| 52109 | } | ||||
| 52110 | |||||
| 52111 | /* | ||||
| 52112 | ** If the third argument is non-NULL, then this function releases a | ||||
| 52113 | ** reference obtained by an earlier call to winFetch(). The second | ||||
| 52114 | ** argument passed to this function must be the same as the corresponding | ||||
| 52115 | ** argument that was passed to the winFetch() invocation. | ||||
| 52116 | ** | ||||
| 52117 | ** Or, if the third argument is NULL, then this function is being called | ||||
| 52118 | ** to inform the VFS layer that, according to POSIX, any existing mapping | ||||
| 52119 | ** may now be invalid and should be unmapped. | ||||
| 52120 | */ | ||||
| 52121 | static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ | ||||
| 52122 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 52123 | winFile *pFd = (winFile*)fd; /* The underlying database file */ | ||||
| 52124 | |||||
| 52125 | /* If p==0 (unmap the entire file) then there must be no outstanding | ||||
| 52126 | ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), | ||||
| 52127 | ** then there must be at least one outstanding. */ | ||||
| 52128 | assert( (p==0)==(pFd->nFetchOut==0) )((void) (0)); | ||||
| 52129 | |||||
| 52130 | /* If p!=0, it must match the iOff value. */ | ||||
| 52131 | assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] )((void) (0)); | ||||
| 52132 | |||||
| 52133 | OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n", | ||||
| 52134 | osGetCurrentProcessId(), pFd, iOff, p)); | ||||
| 52135 | |||||
| 52136 | if( p ){ | ||||
| 52137 | pFd->nFetchOut--; | ||||
| 52138 | }else{ | ||||
| 52139 | /* FIXME: If Windows truly always prevents truncating or deleting a | ||||
| 52140 | ** file while a mapping is held, then the following winUnmapfile() call | ||||
| 52141 | ** is unnecessary can be omitted - potentially improving | ||||
| 52142 | ** performance. */ | ||||
| 52143 | winUnmapfile(pFd); | ||||
| 52144 | } | ||||
| 52145 | |||||
| 52146 | assert( pFd->nFetchOut>=0 )((void) (0)); | ||||
| 52147 | #endif | ||||
| 52148 | |||||
| 52149 | OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n", | ||||
| 52150 | osGetCurrentProcessId(), fd)); | ||||
| 52151 | return SQLITE_OK0; | ||||
| 52152 | } | ||||
| 52153 | |||||
| 52154 | /* | ||||
| 52155 | ** Here ends the implementation of all sqlite3_file methods. | ||||
| 52156 | ** | ||||
| 52157 | ********************** End sqlite3_file Methods ******************************* | ||||
| 52158 | ******************************************************************************/ | ||||
| 52159 | |||||
| 52160 | /* | ||||
| 52161 | ** This vector defines all the methods that can operate on an | ||||
| 52162 | ** sqlite3_file for win32. | ||||
| 52163 | */ | ||||
| 52164 | static const sqlite3_io_methods winIoMethod = { | ||||
| 52165 | 3, /* iVersion */ | ||||
| 52166 | winClose, /* xClose */ | ||||
| 52167 | winRead, /* xRead */ | ||||
| 52168 | winWrite, /* xWrite */ | ||||
| 52169 | winTruncate, /* xTruncate */ | ||||
| 52170 | winSync, /* xSync */ | ||||
| 52171 | winFileSize, /* xFileSize */ | ||||
| 52172 | winLock, /* xLock */ | ||||
| 52173 | winUnlock, /* xUnlock */ | ||||
| 52174 | winCheckReservedLock, /* xCheckReservedLock */ | ||||
| 52175 | winFileControl, /* xFileControl */ | ||||
| 52176 | winSectorSize, /* xSectorSize */ | ||||
| 52177 | winDeviceCharacteristics, /* xDeviceCharacteristics */ | ||||
| 52178 | winShmMap, /* xShmMap */ | ||||
| 52179 | winShmLock, /* xShmLock */ | ||||
| 52180 | winShmBarrier, /* xShmBarrier */ | ||||
| 52181 | winShmUnmap, /* xShmUnmap */ | ||||
| 52182 | winFetch, /* xFetch */ | ||||
| 52183 | winUnfetch /* xUnfetch */ | ||||
| 52184 | }; | ||||
| 52185 | |||||
| 52186 | /* | ||||
| 52187 | ** This vector defines all the methods that can operate on an | ||||
| 52188 | ** sqlite3_file for win32 without performing any locking. | ||||
| 52189 | */ | ||||
| 52190 | static const sqlite3_io_methods winIoNolockMethod = { | ||||
| 52191 | 3, /* iVersion */ | ||||
| 52192 | winClose, /* xClose */ | ||||
| 52193 | winRead, /* xRead */ | ||||
| 52194 | winWrite, /* xWrite */ | ||||
| 52195 | winTruncate, /* xTruncate */ | ||||
| 52196 | winSync, /* xSync */ | ||||
| 52197 | winFileSize, /* xFileSize */ | ||||
| 52198 | winNolockLock, /* xLock */ | ||||
| 52199 | winNolockUnlock, /* xUnlock */ | ||||
| 52200 | winNolockCheckReservedLock, /* xCheckReservedLock */ | ||||
| 52201 | winFileControl, /* xFileControl */ | ||||
| 52202 | winSectorSize, /* xSectorSize */ | ||||
| 52203 | winDeviceCharacteristics, /* xDeviceCharacteristics */ | ||||
| 52204 | winShmMap, /* xShmMap */ | ||||
| 52205 | winShmLock, /* xShmLock */ | ||||
| 52206 | winShmBarrier, /* xShmBarrier */ | ||||
| 52207 | winShmUnmap, /* xShmUnmap */ | ||||
| 52208 | winFetch, /* xFetch */ | ||||
| 52209 | winUnfetch /* xUnfetch */ | ||||
| 52210 | }; | ||||
| 52211 | |||||
| 52212 | static winVfsAppData winAppData = { | ||||
| 52213 | &winIoMethod, /* pMethod */ | ||||
| 52214 | 0, /* pAppData */ | ||||
| 52215 | 0 /* bNoLock */ | ||||
| 52216 | }; | ||||
| 52217 | |||||
| 52218 | static winVfsAppData winNolockAppData = { | ||||
| 52219 | &winIoNolockMethod, /* pMethod */ | ||||
| 52220 | 0, /* pAppData */ | ||||
| 52221 | 1 /* bNoLock */ | ||||
| 52222 | }; | ||||
| 52223 | |||||
| 52224 | /**************************************************************************** | ||||
| 52225 | **************************** sqlite3_vfs methods **************************** | ||||
| 52226 | ** | ||||
| 52227 | ** This division contains the implementation of methods on the | ||||
| 52228 | ** sqlite3_vfs object. | ||||
| 52229 | */ | ||||
| 52230 | |||||
| 52231 | /* | ||||
| 52232 | ** This function returns non-zero if the specified UTF-8 string buffer | ||||
| 52233 | ** ends with a directory separator character or one was successfully | ||||
| 52234 | ** added to it. | ||||
| 52235 | */ | ||||
| 52236 | static int winMakeEndInDirSep(int nBuf, char *zBuf){ | ||||
| 52237 | if( zBuf ){ | ||||
| 52238 | int nLen = sqlite3Strlen30(zBuf); | ||||
| 52239 | if( nLen>0 ){ | ||||
| 52240 | if( winIsDirSep(zBuf[nLen-1]) ){ | ||||
| 52241 | return 1; | ||||
| 52242 | }else if( nLen+1<nBuf ){ | ||||
| 52243 | if( !osGetenv ){ | ||||
| 52244 | zBuf[nLen] = winGetDirSep(); | ||||
| 52245 | }else if( winIsDriveLetterAndColon(zBuf) && winIsDirSep(zBuf[2]) ){ | ||||
| 52246 | zBuf[nLen] = '\\'; | ||||
| 52247 | zBuf[2]='\\'; | ||||
| 52248 | }else{ | ||||
| 52249 | zBuf[nLen] = '/'; | ||||
| 52250 | } | ||||
| 52251 | zBuf[nLen+1] = '\0'; | ||||
| 52252 | return 1; | ||||
| 52253 | } | ||||
| 52254 | } | ||||
| 52255 | } | ||||
| 52256 | return 0; | ||||
| 52257 | } | ||||
| 52258 | |||||
| 52259 | /* | ||||
| 52260 | ** If sqlite3_temp_directory is defined, take the mutex and return true. | ||||
| 52261 | ** | ||||
| 52262 | ** If sqlite3_temp_directory is NULL (undefined), omit the mutex and | ||||
| 52263 | ** return false. | ||||
| 52264 | */ | ||||
| 52265 | static int winTempDirDefined(void){ | ||||
| 52266 | sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 52267 | if( sqlite3_temp_directory!=0 ) return 1; | ||||
| 52268 | sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 52269 | return 0; | ||||
| 52270 | } | ||||
| 52271 | |||||
| 52272 | /* | ||||
| 52273 | ** Create a temporary file name and store the resulting pointer into pzBuf. | ||||
| 52274 | ** The pointer returned in pzBuf must be freed via sqlite3_free(). | ||||
| 52275 | */ | ||||
| 52276 | static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ | ||||
| 52277 | static const char zChars[] = | ||||
| 52278 | "abcdefghijklmnopqrstuvwxyz" | ||||
| 52279 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||||
| 52280 | "0123456789"; | ||||
| 52281 | size_t i, j; | ||||
| 52282 | DWORD pid; | ||||
| 52283 | int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX"etilqs_"); | ||||
| 52284 | i64 nMax, nBuf, nDir, nLen; | ||||
| 52285 | char *zBuf; | ||||
| 52286 | |||||
| 52287 | /* It's odd to simulate an io-error here, but really this is just | ||||
| 52288 | ** using the io-error infrastructure to test that SQLite handles this | ||||
| 52289 | ** function failing. | ||||
| 52290 | */ | ||||
| 52291 | SimulateIOError( return SQLITE_IOERR ); | ||||
| 52292 | |||||
| 52293 | /* Allocate a temporary buffer to store the fully qualified file | ||||
| 52294 | ** name for the temporary file. If this fails, we cannot continue. | ||||
| 52295 | */ | ||||
| 52296 | nMax = pVfs->mxPathname; | ||||
| 52297 | nBuf = 2 + (i64)nMax; | ||||
| 52298 | zBuf = sqlite3MallocZero( nBuf ); | ||||
| 52299 | if( !zBuf ){ | ||||
| 52300 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); | ||||
| 52301 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52302 | } | ||||
| 52303 | |||||
| 52304 | /* Figure out the effective temporary directory. First, check if one | ||||
| 52305 | ** has been explicitly set by the application; otherwise, use the one | ||||
| 52306 | ** configured by the operating system. | ||||
| 52307 | */ | ||||
| 52308 | nDir = nMax - (nPre + 15); | ||||
| 52309 | assert( nDir>0 )((void) (0)); | ||||
| 52310 | if( winTempDirDefined() ){ | ||||
| 52311 | int nDirLen = sqlite3Strlen30(sqlite3_temp_directory); | ||||
| 52312 | if( nDirLen>0 ){ | ||||
| 52313 | if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){ | ||||
| 52314 | nDirLen++; | ||||
| 52315 | } | ||||
| 52316 | if( nDirLen>nDir ){ | ||||
| 52317 | sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 52318 | sqlite3_free(zBuf); | ||||
| 52319 | OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); | ||||
| 52320 | return winLogError(SQLITE_ERROR1, 0, "winGetTempname1", 0); | ||||
| 52321 | } | ||||
| 52322 | sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory); | ||||
| 52323 | } | ||||
| 52324 | sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR11)); | ||||
| 52325 | } | ||||
| 52326 | |||||
| 52327 | #if defined(__CYGWIN__) | ||||
| 52328 | else if( osGetenv!=NULL((void*)0) ){ | ||||
| 52329 | static const char *azDirs[] = { | ||||
| 52330 | 0, /* getenv("SQLITE_TMPDIR") */ | ||||
| 52331 | 0, /* getenv("TMPDIR") */ | ||||
| 52332 | 0, /* getenv("TMP") */ | ||||
| 52333 | 0, /* getenv("TEMP") */ | ||||
| 52334 | 0, /* getenv("USERPROFILE") */ | ||||
| 52335 | "/var/tmp", | ||||
| 52336 | "/usr/tmp", | ||||
| 52337 | "/tmp", | ||||
| 52338 | ".", | ||||
| 52339 | 0 /* List terminator */ | ||||
| 52340 | }; | ||||
| 52341 | unsigned int i; | ||||
| 52342 | const char *zDir = 0; | ||||
| 52343 | |||||
| 52344 | if( !azDirs[0] ) azDirs[0] = osGetenv("SQLITE_TMPDIR"); | ||||
| 52345 | if( !azDirs[1] ) azDirs[1] = osGetenv("TMPDIR"); | ||||
| 52346 | if( !azDirs[2] ) azDirs[2] = osGetenv("TMP"); | ||||
| 52347 | if( !azDirs[3] ) azDirs[3] = osGetenv("TEMP"); | ||||
| 52348 | if( !azDirs[4] ) azDirs[4] = osGetenv("USERPROFILE"); | ||||
| 52349 | for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){ | ||||
| 52350 | void *zConverted; | ||||
| 52351 | if( zDir==0 ) continue; | ||||
| 52352 | /* If the path starts with a drive letter followed by the colon | ||||
| 52353 | ** character, assume it is already a native Win32 path; otherwise, | ||||
| 52354 | ** it must be converted to a native Win32 path via the Cygwin API | ||||
| 52355 | ** prior to using it. | ||||
| 52356 | */ | ||||
| 52357 | { | ||||
| 52358 | zConverted = winConvertFromUtf8Filename(zDir); | ||||
| 52359 | if( !zConverted ){ | ||||
| 52360 | sqlite3_free(zBuf); | ||||
| 52361 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); | ||||
| 52362 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52363 | } | ||||
| 52364 | if( winIsDir(zConverted) ){ | ||||
| 52365 | sqlite3_snprintf(nMax, zBuf, "%s", zDir); | ||||
| 52366 | sqlite3_free(zConverted); | ||||
| 52367 | break; | ||||
| 52368 | } | ||||
| 52369 | sqlite3_free(zConverted); | ||||
| 52370 | } | ||||
| 52371 | } | ||||
| 52372 | } | ||||
| 52373 | #endif | ||||
| 52374 | |||||
| 52375 | #if !SQLITE_OS_WINRT && defined(_WIN32) | ||||
| 52376 | else if( osIsNT() ){ | ||||
| 52377 | char *zMulti; | ||||
| 52378 | LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) ); | ||||
| 52379 | if( !zWidePath ){ | ||||
| 52380 | sqlite3_free(zBuf); | ||||
| 52381 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); | ||||
| 52382 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52383 | } | ||||
| 52384 | if( osGetTempPathW(nMax, zWidePath)==0 ){ | ||||
| 52385 | sqlite3_free(zWidePath); | ||||
| 52386 | sqlite3_free(zBuf); | ||||
| 52387 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); | ||||
| 52388 | return winLogError(SQLITE_IOERR_GETTEMPPATH(10 | (25<<8)), osGetLastError(), | ||||
| 52389 | "winGetTempname2", 0); | ||||
| 52390 | } | ||||
| 52391 | zMulti = winUnicodeToUtf8(zWidePath); | ||||
| 52392 | if( zMulti ){ | ||||
| 52393 | sqlite3_snprintf(nMax, zBuf, "%s", zMulti); | ||||
| 52394 | sqlite3_free(zMulti); | ||||
| 52395 | sqlite3_free(zWidePath); | ||||
| 52396 | }else{ | ||||
| 52397 | sqlite3_free(zWidePath); | ||||
| 52398 | sqlite3_free(zBuf); | ||||
| 52399 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); | ||||
| 52400 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52401 | } | ||||
| 52402 | } | ||||
| 52403 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 52404 | else{ | ||||
| 52405 | char *zUtf8; | ||||
| 52406 | char *zMbcsPath = sqlite3MallocZero( nMax ); | ||||
| 52407 | if( !zMbcsPath ){ | ||||
| 52408 | sqlite3_free(zBuf); | ||||
| 52409 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); | ||||
| 52410 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52411 | } | ||||
| 52412 | if( osGetTempPathA(nMax, zMbcsPath)==0 ){ | ||||
| 52413 | sqlite3_free(zBuf); | ||||
| 52414 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); | ||||
| 52415 | return winLogError(SQLITE_IOERR_GETTEMPPATH(10 | (25<<8)), osGetLastError(), | ||||
| 52416 | "winGetTempname3", 0); | ||||
| 52417 | } | ||||
| 52418 | zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI()); | ||||
| 52419 | if( zUtf8 ){ | ||||
| 52420 | sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); | ||||
| 52421 | sqlite3_free(zUtf8); | ||||
| 52422 | }else{ | ||||
| 52423 | sqlite3_free(zBuf); | ||||
| 52424 | OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); | ||||
| 52425 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52426 | } | ||||
| 52427 | } | ||||
| 52428 | #endif /* SQLITE_WIN32_HAS_ANSI */ | ||||
| 52429 | #endif /* !SQLITE_OS_WINRT */ | ||||
| 52430 | |||||
| 52431 | /* | ||||
| 52432 | ** Check to make sure the temporary directory ends with an appropriate | ||||
| 52433 | ** separator. If it does not and there is not enough space left to add | ||||
| 52434 | ** one, fail. | ||||
| 52435 | */ | ||||
| 52436 | if( !winMakeEndInDirSep(nDir+1, zBuf) ){ | ||||
| 52437 | sqlite3_free(zBuf); | ||||
| 52438 | OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); | ||||
| 52439 | return winLogError(SQLITE_ERROR1, 0, "winGetTempname4", 0); | ||||
| 52440 | } | ||||
| 52441 | |||||
| 52442 | /* | ||||
| 52443 | ** Check that the output buffer is large enough for the temporary file | ||||
| 52444 | ** name in the following format: | ||||
| 52445 | ** | ||||
| 52446 | ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0" | ||||
| 52447 | ** | ||||
| 52448 | ** If not, return SQLITE_ERROR. The number 17 is used here in order to | ||||
| 52449 | ** account for the space used by the 15 character random suffix and the | ||||
| 52450 | ** two trailing NUL characters. The final directory separator character | ||||
| 52451 | ** has already added if it was not already present. | ||||
| 52452 | */ | ||||
| 52453 | nLen = sqlite3Strlen30(zBuf); | ||||
| 52454 | if( (nLen + nPre + 17) > nBuf ){ | ||||
| 52455 | sqlite3_free(zBuf); | ||||
| 52456 | OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); | ||||
| 52457 | return winLogError(SQLITE_ERROR1, 0, "winGetTempname5", 0); | ||||
| 52458 | } | ||||
| 52459 | |||||
| 52460 | sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX"etilqs_"); | ||||
| 52461 | |||||
| 52462 | j = sqlite3Strlen30(zBuf); | ||||
| 52463 | sqlite3_randomness(15, &zBuf[j]); | ||||
| 52464 | pid = osGetCurrentProcessId(); | ||||
| 52465 | for(i=0; i<15; i++, j++){ | ||||
| 52466 | zBuf[j] += pid & 0xff; | ||||
| 52467 | pid >>= 8; | ||||
| 52468 | zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; | ||||
| 52469 | } | ||||
| 52470 | zBuf[j] = 0; | ||||
| 52471 | zBuf[j+1] = 0; | ||||
| 52472 | *pzBuf = zBuf; | ||||
| 52473 | |||||
| 52474 | OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf)); | ||||
| 52475 | return SQLITE_OK0; | ||||
| 52476 | } | ||||
| 52477 | |||||
| 52478 | /* | ||||
| 52479 | ** Return TRUE if the named file is really a directory. Return false if | ||||
| 52480 | ** it is something other than a directory, or if there is any kind of memory | ||||
| 52481 | ** allocation failure. | ||||
| 52482 | */ | ||||
| 52483 | static int winIsDir(const void *zConverted){ | ||||
| 52484 | DWORD attr; | ||||
| 52485 | int rc = 0; | ||||
| 52486 | DWORD lastErrno; | ||||
| 52487 | |||||
| 52488 | if( osIsNT() ){ | ||||
| 52489 | int cnt = 0; | ||||
| 52490 | WIN32_FILE_ATTRIBUTE_DATA sAttrData; | ||||
| 52491 | memset(&sAttrData, 0, sizeof(sAttrData)); | ||||
| 52492 | while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, | ||||
| 52493 | GetFileExInfoStandard, | ||||
| 52494 | &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} | ||||
| 52495 | if( !rc ){ | ||||
| 52496 | return 0; /* Invalid name? */ | ||||
| 52497 | } | ||||
| 52498 | attr = sAttrData.dwFileAttributes; | ||||
| 52499 | #if SQLITE_OS_WINCE==0 && defined(SQLITE_WIN32_HAS_ANSI) | ||||
| 52500 | }else{ | ||||
| 52501 | attr = osGetFileAttributesA((char*)zConverted); | ||||
| 52502 | #endif | ||||
| 52503 | } | ||||
| 52504 | return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); | ||||
| 52505 | } | ||||
| 52506 | |||||
| 52507 | /* forward reference */ | ||||
| 52508 | static int winAccess( | ||||
| 52509 | sqlite3_vfs *pVfs, /* Not used on win32 */ | ||||
| 52510 | const char *zFilename, /* Name of file to check */ | ||||
| 52511 | int flags, /* Type of test to make on this file */ | ||||
| 52512 | int *pResOut /* OUT: Result */ | ||||
| 52513 | ); | ||||
| 52514 | |||||
| 52515 | /* | ||||
| 52516 | ** The Windows version of xAccess() accepts an extra bit in the flags | ||||
| 52517 | ** parameter that prevents an anti-virus retry loop. | ||||
| 52518 | */ | ||||
| 52519 | #define NORETRY 0x4000 | ||||
| 52520 | |||||
| 52521 | /* | ||||
| 52522 | ** Open a file. | ||||
| 52523 | */ | ||||
| 52524 | static int winOpen( | ||||
| 52525 | sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */ | ||||
| 52526 | const char *zName, /* Name of the file (UTF-8) */ | ||||
| 52527 | sqlite3_file *id, /* Write the SQLite file handle here */ | ||||
| 52528 | int flags, /* Open mode flags */ | ||||
| 52529 | int *pOutFlags /* Status return flags */ | ||||
| 52530 | ){ | ||||
| 52531 | HANDLE h; | ||||
| 52532 | DWORD lastErrno = 0; | ||||
| 52533 | DWORD dwDesiredAccess; | ||||
| 52534 | DWORD dwShareMode; | ||||
| 52535 | DWORD dwCreationDisposition; | ||||
| 52536 | DWORD dwFlagsAndAttributes = 0; | ||||
| 52537 | #if SQLITE_OS_WINCE | ||||
| 52538 | int isTemp = 0; | ||||
| 52539 | #endif | ||||
| 52540 | winVfsAppData *pAppData; | ||||
| 52541 | winFile *pFile = (winFile*)id; | ||||
| 52542 | void *zConverted; /* Filename in OS encoding */ | ||||
| 52543 | const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */ | ||||
| 52544 | int cnt = 0; | ||||
| 52545 | int isRO = 0; /* file is known to be accessible readonly */ | ||||
| 52546 | |||||
| 52547 | /* If argument zPath is a NULL pointer, this function is required to open | ||||
| 52548 | ** a temporary file. Use this buffer to store the file name in. | ||||
| 52549 | */ | ||||
| 52550 | char *zTmpname = 0; /* For temporary filename, if necessary. */ | ||||
| 52551 | |||||
| 52552 | int rc = SQLITE_OK0; /* Function Return Code */ | ||||
| 52553 | #if !defined(NDEBUG1) || SQLITE_OS_WINCE | ||||
| 52554 | int eType = flags&0x0FFF00; /* Type of file to open */ | ||||
| 52555 | #endif | ||||
| 52556 | |||||
| 52557 | int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE0x00000010); | ||||
| 52558 | int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE0x00000008); | ||||
| 52559 | int isCreate = (flags & SQLITE_OPEN_CREATE0x00000004); | ||||
| 52560 | int isReadonly = (flags & SQLITE_OPEN_READONLY0x00000001); | ||||
| 52561 | int isReadWrite = (flags & SQLITE_OPEN_READWRITE0x00000002); | ||||
| 52562 | |||||
| 52563 | #ifndef NDEBUG1 | ||||
| 52564 | int isOpenJournal = (isCreate && ( | ||||
| 52565 | eType==SQLITE_OPEN_SUPER_JOURNAL0x00004000 | ||||
| 52566 | || eType==SQLITE_OPEN_MAIN_JOURNAL0x00000800 | ||||
| 52567 | || eType==SQLITE_OPEN_WAL0x00080000 | ||||
| 52568 | )); | ||||
| 52569 | #endif | ||||
| 52570 | |||||
| 52571 | OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n", | ||||
| 52572 | zUtf8Name, id, flags, pOutFlags)); | ||||
| 52573 | |||||
| 52574 | /* Check the following statements are true: | ||||
| 52575 | ** | ||||
| 52576 | ** (a) Exactly one of the READWRITE and READONLY flags must be set, and | ||||
| 52577 | ** (b) if CREATE is set, then READWRITE must also be set, and | ||||
| 52578 | ** (c) if EXCLUSIVE is set, then CREATE must also be set. | ||||
| 52579 | ** (d) if DELETEONCLOSE is set, then CREATE must also be set. | ||||
| 52580 | */ | ||||
| 52581 | assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly))((void) (0)); | ||||
| 52582 | assert(isCreate==0 || isReadWrite)((void) (0)); | ||||
| 52583 | assert(isExclusive==0 || isCreate)((void) (0)); | ||||
| 52584 | assert(isDelete==0 || isCreate)((void) (0)); | ||||
| 52585 | |||||
| 52586 | /* The main DB, main journal, WAL file and super-journal are never | ||||
| 52587 | ** automatically deleted. Nor are they ever temporary files. */ | ||||
| 52588 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB )((void) (0)); | ||||
| 52589 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL )((void) (0)); | ||||
| 52590 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL )((void) (0)); | ||||
| 52591 | assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL )((void) (0)); | ||||
| 52592 | |||||
| 52593 | /* Assert that the upper layer has set one of the "file-type" flags. */ | ||||
| 52594 | assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB((void) (0)) | ||||
| 52595 | || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL((void) (0)) | ||||
| 52596 | || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_SUPER_JOURNAL((void) (0)) | ||||
| 52597 | || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL((void) (0)) | ||||
| 52598 | )((void) (0)); | ||||
| 52599 | |||||
| 52600 | assert( pFile!=0 )((void) (0)); | ||||
| 52601 | memset(pFile, 0, sizeof(winFile)); | ||||
| 52602 | pFile->h = INVALID_HANDLE_VALUE; | ||||
| 52603 | |||||
| 52604 | #if SQLITE_OS_WINRT | ||||
| 52605 | if( !zUtf8Name && !sqlite3_temp_directory ){ | ||||
| 52606 | sqlite3_log(SQLITE_ERROR1, | ||||
| 52607 | "sqlite3_temp_directory variable should be set for WinRT"); | ||||
| 52608 | } | ||||
| 52609 | #endif | ||||
| 52610 | |||||
| 52611 | /* If the second argument to this function is NULL, generate a | ||||
| 52612 | ** temporary file name to use | ||||
| 52613 | */ | ||||
| 52614 | if( !zUtf8Name ){ | ||||
| 52615 | assert( isDelete && !isOpenJournal )((void) (0)); | ||||
| 52616 | rc = winGetTempname(pVfs, &zTmpname); | ||||
| 52617 | if( rc!=SQLITE_OK0 ){ | ||||
| 52618 | OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc))); | ||||
| 52619 | return rc; | ||||
| 52620 | } | ||||
| 52621 | zUtf8Name = zTmpname; | ||||
| 52622 | } | ||||
| 52623 | |||||
| 52624 | /* Database filenames are double-zero terminated if they are not | ||||
| 52625 | ** URIs with parameters. Hence, they can always be passed into | ||||
| 52626 | ** sqlite3_uri_parameter(). | ||||
| 52627 | */ | ||||
| 52628 | assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||((void) (0)) | ||||
| 52629 | zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 )((void) (0)); | ||||
| 52630 | |||||
| 52631 | /* Convert the filename to the system encoding. */ | ||||
| 52632 | zConverted = winConvertFromUtf8Filename(zUtf8Name); | ||||
| 52633 | if( zConverted==0 ){ | ||||
| 52634 | sqlite3_free(zTmpname); | ||||
| 52635 | OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name)); | ||||
| 52636 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52637 | } | ||||
| 52638 | |||||
| 52639 | if( winIsDir(zConverted) ){ | ||||
| 52640 | sqlite3_free(zConverted); | ||||
| 52641 | sqlite3_free(zTmpname); | ||||
| 52642 | OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name)); | ||||
| 52643 | return SQLITE_CANTOPEN_ISDIR(14 | (2<<8)); | ||||
| 52644 | } | ||||
| 52645 | |||||
| 52646 | if( isReadWrite ){ | ||||
| 52647 | dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; | ||||
| 52648 | }else{ | ||||
| 52649 | dwDesiredAccess = GENERIC_READ; | ||||
| 52650 | } | ||||
| 52651 | |||||
| 52652 | /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is | ||||
| 52653 | ** created. SQLite doesn't use it to indicate "exclusive access" | ||||
| 52654 | ** as it is usually understood. | ||||
| 52655 | */ | ||||
| 52656 | if( isExclusive ){ | ||||
| 52657 | /* Creates a new file, only if it does not already exist. */ | ||||
| 52658 | /* If the file exists, it fails. */ | ||||
| 52659 | dwCreationDisposition = CREATE_NEW; | ||||
| 52660 | }else if( isCreate ){ | ||||
| 52661 | /* Open existing file, or create if it doesn't exist */ | ||||
| 52662 | dwCreationDisposition = OPEN_ALWAYS; | ||||
| 52663 | }else{ | ||||
| 52664 | /* Opens a file, only if it exists. */ | ||||
| 52665 | dwCreationDisposition = OPEN_EXISTING; | ||||
| 52666 | } | ||||
| 52667 | |||||
| 52668 | if( 0==sqlite3_uri_boolean(zName, "exclusive", 0) ){ | ||||
| 52669 | dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; | ||||
| 52670 | }else{ | ||||
| 52671 | dwShareMode = 0; | ||||
| 52672 | } | ||||
| 52673 | |||||
| 52674 | if( isDelete ){ | ||||
| 52675 | #if SQLITE_OS_WINCE | ||||
| 52676 | dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; | ||||
| 52677 | isTemp = 1; | ||||
| 52678 | #else | ||||
| 52679 | dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY | ||||
| 52680 | | FILE_ATTRIBUTE_HIDDEN | ||||
| 52681 | | FILE_FLAG_DELETE_ON_CLOSE; | ||||
| 52682 | #endif | ||||
| 52683 | }else{ | ||||
| 52684 | dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; | ||||
| 52685 | } | ||||
| 52686 | /* Reports from the internet are that performance is always | ||||
| 52687 | ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ | ||||
| 52688 | #if SQLITE_OS_WINCE | ||||
| 52689 | dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; | ||||
| 52690 | #endif | ||||
| 52691 | |||||
| 52692 | if( osIsNT() ){ | ||||
| 52693 | #if SQLITE_OS_WINRT | ||||
| 52694 | CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; | ||||
| 52695 | extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); | ||||
| 52696 | extendedParameters.dwFileAttributes = | ||||
| 52697 | dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK; | ||||
| 52698 | extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK; | ||||
| 52699 | extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; | ||||
| 52700 | extendedParameters.lpSecurityAttributes = NULL((void*)0); | ||||
| 52701 | extendedParameters.hTemplateFile = NULL((void*)0); | ||||
| 52702 | do{ | ||||
| 52703 | h = osCreateFile2((LPCWSTR)zConverted, | ||||
| 52704 | dwDesiredAccess, | ||||
| 52705 | dwShareMode, | ||||
| 52706 | dwCreationDisposition, | ||||
| 52707 | &extendedParameters); | ||||
| 52708 | if( h!=INVALID_HANDLE_VALUE ) break; | ||||
| 52709 | if( isReadWrite ){ | ||||
| 52710 | int rc2; | ||||
| 52711 | sqlite3BeginBenignMalloc(); | ||||
| 52712 | rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ2|NORETRY, &isRO); | ||||
| 52713 | sqlite3EndBenignMalloc(); | ||||
| 52714 | if( rc2==SQLITE_OK0 && isRO ) break; | ||||
| 52715 | } | ||||
| 52716 | }while( winRetryIoerr(&cnt, &lastErrno) ); | ||||
| 52717 | #else | ||||
| 52718 | do{ | ||||
| 52719 | h = osCreateFileW((LPCWSTR)zConverted, | ||||
| 52720 | dwDesiredAccess, | ||||
| 52721 | dwShareMode, NULL((void*)0), | ||||
| 52722 | dwCreationDisposition, | ||||
| 52723 | dwFlagsAndAttributes, | ||||
| 52724 | NULL((void*)0)); | ||||
| 52725 | if( h!=INVALID_HANDLE_VALUE ) break; | ||||
| 52726 | if( isReadWrite ){ | ||||
| 52727 | int rc2; | ||||
| 52728 | sqlite3BeginBenignMalloc(); | ||||
| 52729 | rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ2|NORETRY, &isRO); | ||||
| 52730 | sqlite3EndBenignMalloc(); | ||||
| 52731 | if( rc2==SQLITE_OK0 && isRO ) break; | ||||
| 52732 | } | ||||
| 52733 | }while( winRetryIoerr(&cnt, &lastErrno) ); | ||||
| 52734 | #endif | ||||
| 52735 | } | ||||
| 52736 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 52737 | else{ | ||||
| 52738 | do{ | ||||
| 52739 | h = osCreateFileA((LPCSTR)zConverted, | ||||
| 52740 | dwDesiredAccess, | ||||
| 52741 | dwShareMode, NULL((void*)0), | ||||
| 52742 | dwCreationDisposition, | ||||
| 52743 | dwFlagsAndAttributes, | ||||
| 52744 | NULL((void*)0)); | ||||
| 52745 | if( h!=INVALID_HANDLE_VALUE ) break; | ||||
| 52746 | if( isReadWrite ){ | ||||
| 52747 | int rc2; | ||||
| 52748 | sqlite3BeginBenignMalloc(); | ||||
| 52749 | rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ2|NORETRY, &isRO); | ||||
| 52750 | sqlite3EndBenignMalloc(); | ||||
| 52751 | if( rc2==SQLITE_OK0 && isRO ) break; | ||||
| 52752 | } | ||||
| 52753 | }while( winRetryIoerr(&cnt, &lastErrno) ); | ||||
| 52754 | } | ||||
| 52755 | #endif | ||||
| 52756 | winLogIoerr(cnt, __LINE__52756); | ||||
| 52757 | |||||
| 52758 | OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name, | ||||
| 52759 | dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); | ||||
| 52760 | |||||
| 52761 | if( h==INVALID_HANDLE_VALUE ){ | ||||
| 52762 | sqlite3_free(zConverted); | ||||
| 52763 | sqlite3_free(zTmpname); | ||||
| 52764 | if( isReadWrite && isRO && !isExclusive ){ | ||||
| 52765 | return winOpen(pVfs, zName, id, | ||||
| 52766 | ((flags|SQLITE_OPEN_READONLY0x00000001) & | ||||
| 52767 | ~(SQLITE_OPEN_CREATE0x00000004|SQLITE_OPEN_READWRITE0x00000002)), | ||||
| 52768 | pOutFlags); | ||||
| 52769 | }else{ | ||||
| 52770 | pFile->lastErrno = lastErrno; | ||||
| 52771 | winLogError(SQLITE_CANTOPEN14, pFile->lastErrno, "winOpen", zUtf8Name); | ||||
| 52772 | return SQLITE_CANTOPEN_BKPTsqlite3CantopenError(52772); | ||||
| 52773 | } | ||||
| 52774 | } | ||||
| 52775 | |||||
| 52776 | if( pOutFlags ){ | ||||
| 52777 | if( isReadWrite ){ | ||||
| 52778 | *pOutFlags = SQLITE_OPEN_READWRITE0x00000002; | ||||
| 52779 | }else{ | ||||
| 52780 | *pOutFlags = SQLITE_OPEN_READONLY0x00000001; | ||||
| 52781 | } | ||||
| 52782 | } | ||||
| 52783 | |||||
| 52784 | OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, " | ||||
| 52785 | "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ? | ||||
| 52786 | *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); | ||||
| 52787 | |||||
| 52788 | pAppData = (winVfsAppData*)pVfs->pAppData; | ||||
| 52789 | |||||
| 52790 | #if SQLITE_OS_WINCE | ||||
| 52791 | { | ||||
| 52792 | if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB0x00000100 | ||||
| 52793 | && ((pAppData==NULL((void*)0)) || !pAppData->bNoLock) | ||||
| 52794 | && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK0 | ||||
| 52795 | ){ | ||||
| 52796 | osCloseHandle(h); | ||||
| 52797 | sqlite3_free(zConverted); | ||||
| 52798 | sqlite3_free(zTmpname); | ||||
| 52799 | OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc))); | ||||
| 52800 | return rc; | ||||
| 52801 | } | ||||
| 52802 | } | ||||
| 52803 | if( isTemp ){ | ||||
| 52804 | pFile->zDeleteOnClose = zConverted; | ||||
| 52805 | }else | ||||
| 52806 | #endif | ||||
| 52807 | { | ||||
| 52808 | sqlite3_free(zConverted); | ||||
| 52809 | } | ||||
| 52810 | |||||
| 52811 | sqlite3_free(zTmpname); | ||||
| 52812 | id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod; | ||||
| 52813 | pFile->pVfs = pVfs; | ||||
| 52814 | pFile->h = h; | ||||
| 52815 | if( isReadonly ){ | ||||
| 52816 | pFile->ctrlFlags |= WINFILE_RDONLY; | ||||
| 52817 | } | ||||
| 52818 | if( (flags & SQLITE_OPEN_MAIN_DB0x00000100) | ||||
| 52819 | && sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE1) | ||||
| 52820 | ){ | ||||
| 52821 | pFile->ctrlFlags |= WINFILE_PSOW; | ||||
| 52822 | } | ||||
| 52823 | pFile->lastErrno = NO_ERROR; | ||||
| 52824 | pFile->zPath = zName; | ||||
| 52825 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 52826 | pFile->hMap = NULL((void*)0); | ||||
| 52827 | pFile->pMapRegion = 0; | ||||
| 52828 | pFile->mmapSize = 0; | ||||
| 52829 | pFile->mmapSizeMax = sqlite3GlobalConfigsqlite3Config.szMmap; | ||||
| 52830 | #endif | ||||
| 52831 | |||||
| 52832 | OpenCounter(+1); | ||||
| 52833 | return rc; | ||||
| 52834 | } | ||||
| 52835 | |||||
| 52836 | /* | ||||
| 52837 | ** Delete the named file. | ||||
| 52838 | ** | ||||
| 52839 | ** Note that Windows does not allow a file to be deleted if some other | ||||
| 52840 | ** process has it open. Sometimes a virus scanner or indexing program | ||||
| 52841 | ** will open a journal file shortly after it is created in order to do | ||||
| 52842 | ** whatever it does. While this other process is holding the | ||||
| 52843 | ** file open, we will be unable to delete it. To work around this | ||||
| 52844 | ** problem, we delay 100 milliseconds and try to delete again. Up | ||||
| 52845 | ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving | ||||
| 52846 | ** up and returning an error. | ||||
| 52847 | */ | ||||
| 52848 | static int winDelete( | ||||
| 52849 | sqlite3_vfs *pVfs, /* Not used on win32 */ | ||||
| 52850 | const char *zFilename, /* Name of file to delete */ | ||||
| 52851 | int syncDir /* Not used on win32 */ | ||||
| 52852 | ){ | ||||
| 52853 | int cnt = 0; | ||||
| 52854 | int rc; | ||||
| 52855 | DWORD attr; | ||||
| 52856 | DWORD lastErrno = 0; | ||||
| 52857 | void *zConverted; | ||||
| 52858 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 52859 | UNUSED_PARAMETER(syncDir)(void)(syncDir); | ||||
| 52860 | |||||
| 52861 | SimulateIOError(return SQLITE_IOERR_DELETE); | ||||
| 52862 | OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir)); | ||||
| 52863 | |||||
| 52864 | zConverted = winConvertFromUtf8Filename(zFilename); | ||||
| 52865 | if( zConverted==0 ){ | ||||
| 52866 | OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); | ||||
| 52867 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52868 | } | ||||
| 52869 | if( osIsNT() ){ | ||||
| 52870 | do { | ||||
| 52871 | #if SQLITE_OS_WINRT | ||||
| 52872 | WIN32_FILE_ATTRIBUTE_DATA sAttrData; | ||||
| 52873 | memset(&sAttrData, 0, sizeof(sAttrData)); | ||||
| 52874 | if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard, | ||||
| 52875 | &sAttrData) ){ | ||||
| 52876 | attr = sAttrData.dwFileAttributes; | ||||
| 52877 | }else{ | ||||
| 52878 | lastErrno = osGetLastError(); | ||||
| 52879 | if( lastErrno==ERROR_FILE_NOT_FOUND | ||||
| 52880 | || lastErrno==ERROR_PATH_NOT_FOUND ){ | ||||
| 52881 | rc = SQLITE_IOERR_DELETE_NOENT(10 | (23<<8)); /* Already gone? */ | ||||
| 52882 | }else{ | ||||
| 52883 | rc = SQLITE_ERROR1; | ||||
| 52884 | } | ||||
| 52885 | break; | ||||
| 52886 | } | ||||
| 52887 | #else | ||||
| 52888 | attr = osGetFileAttributesW(zConverted); | ||||
| 52889 | #endif | ||||
| 52890 | if ( attr==INVALID_FILE_ATTRIBUTES ){ | ||||
| 52891 | lastErrno = osGetLastError(); | ||||
| 52892 | if( lastErrno==ERROR_FILE_NOT_FOUND | ||||
| 52893 | || lastErrno==ERROR_PATH_NOT_FOUND ){ | ||||
| 52894 | rc = SQLITE_IOERR_DELETE_NOENT(10 | (23<<8)); /* Already gone? */ | ||||
| 52895 | }else{ | ||||
| 52896 | rc = SQLITE_ERROR1; | ||||
| 52897 | } | ||||
| 52898 | break; | ||||
| 52899 | } | ||||
| 52900 | if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ | ||||
| 52901 | rc = SQLITE_ERROR1; /* Files only. */ | ||||
| 52902 | break; | ||||
| 52903 | } | ||||
| 52904 | if ( osDeleteFileW(zConverted) ){ | ||||
| 52905 | rc = SQLITE_OK0; /* Deleted OK. */ | ||||
| 52906 | break; | ||||
| 52907 | } | ||||
| 52908 | if ( !winRetryIoerr(&cnt, &lastErrno) ){ | ||||
| 52909 | rc = SQLITE_ERROR1; /* No more retries. */ | ||||
| 52910 | break; | ||||
| 52911 | } | ||||
| 52912 | } while(1); | ||||
| 52913 | } | ||||
| 52914 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 52915 | else{ | ||||
| 52916 | do { | ||||
| 52917 | attr = osGetFileAttributesA(zConverted); | ||||
| 52918 | if ( attr==INVALID_FILE_ATTRIBUTES ){ | ||||
| 52919 | lastErrno = osGetLastError(); | ||||
| 52920 | if( lastErrno==ERROR_FILE_NOT_FOUND | ||||
| 52921 | || lastErrno==ERROR_PATH_NOT_FOUND ){ | ||||
| 52922 | rc = SQLITE_IOERR_DELETE_NOENT(10 | (23<<8)); /* Already gone? */ | ||||
| 52923 | }else{ | ||||
| 52924 | rc = SQLITE_ERROR1; | ||||
| 52925 | } | ||||
| 52926 | break; | ||||
| 52927 | } | ||||
| 52928 | if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ | ||||
| 52929 | rc = SQLITE_ERROR1; /* Files only. */ | ||||
| 52930 | break; | ||||
| 52931 | } | ||||
| 52932 | if ( osDeleteFileA(zConverted) ){ | ||||
| 52933 | rc = SQLITE_OK0; /* Deleted OK. */ | ||||
| 52934 | break; | ||||
| 52935 | } | ||||
| 52936 | if ( !winRetryIoerr(&cnt, &lastErrno) ){ | ||||
| 52937 | rc = SQLITE_ERROR1; /* No more retries. */ | ||||
| 52938 | break; | ||||
| 52939 | } | ||||
| 52940 | } while(1); | ||||
| 52941 | } | ||||
| 52942 | #endif | ||||
| 52943 | if( rc && rc!=SQLITE_IOERR_DELETE_NOENT(10 | (23<<8)) ){ | ||||
| 52944 | rc = winLogError(SQLITE_IOERR_DELETE(10 | (10<<8)), lastErrno, "winDelete", zFilename); | ||||
| 52945 | }else{ | ||||
| 52946 | winLogIoerr(cnt, __LINE__52946); | ||||
| 52947 | } | ||||
| 52948 | sqlite3_free(zConverted); | ||||
| 52949 | OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc))); | ||||
| 52950 | return rc; | ||||
| 52951 | } | ||||
| 52952 | |||||
| 52953 | /* | ||||
| 52954 | ** Check the existence and status of a file. | ||||
| 52955 | */ | ||||
| 52956 | static int winAccess( | ||||
| 52957 | sqlite3_vfs *pVfs, /* Not used on win32 */ | ||||
| 52958 | const char *zFilename, /* Name of file to check */ | ||||
| 52959 | int flags, /* Type of test to make on this file */ | ||||
| 52960 | int *pResOut /* OUT: Result */ | ||||
| 52961 | ){ | ||||
| 52962 | DWORD attr; | ||||
| 52963 | int rc = 0; | ||||
| 52964 | DWORD lastErrno = 0; | ||||
| 52965 | void *zConverted; | ||||
| 52966 | int noRetry = 0; /* Do not use winRetryIoerr() */ | ||||
| 52967 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 52968 | |||||
| 52969 | if( (flags & NORETRY)!=0 ){ | ||||
| 52970 | noRetry = 1; | ||||
| 52971 | flags &= ~NORETRY; | ||||
| 52972 | } | ||||
| 52973 | |||||
| 52974 | SimulateIOError( return SQLITE_IOERR_ACCESS; ); | ||||
| 52975 | OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n", | ||||
| 52976 | zFilename, flags, pResOut)); | ||||
| 52977 | |||||
| 52978 | if( zFilename==0 ){ | ||||
| 52979 | *pResOut = 0; | ||||
| 52980 | OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", | ||||
| 52981 | zFilename, pResOut, *pResOut)); | ||||
| 52982 | return SQLITE_OK0; | ||||
| 52983 | } | ||||
| 52984 | |||||
| 52985 | zConverted = winConvertFromUtf8Filename(zFilename); | ||||
| 52986 | if( zConverted==0 ){ | ||||
| 52987 | OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); | ||||
| 52988 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 52989 | } | ||||
| 52990 | if( osIsNT() ){ | ||||
| 52991 | int cnt = 0; | ||||
| 52992 | WIN32_FILE_ATTRIBUTE_DATA sAttrData; | ||||
| 52993 | memset(&sAttrData, 0, sizeof(sAttrData)); | ||||
| 52994 | while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, | ||||
| 52995 | GetFileExInfoStandard, | ||||
| 52996 | &sAttrData)) | ||||
| 52997 | && !noRetry | ||||
| 52998 | && winRetryIoerr(&cnt, &lastErrno) | ||||
| 52999 | ){ /* Loop until true */} | ||||
| 53000 | if( rc ){ | ||||
| 53001 | /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file | ||||
| 53002 | ** as if it does not exist. | ||||
| 53003 | */ | ||||
| 53004 | if( flags==SQLITE_ACCESS_EXISTS0 | ||||
| 53005 | && sAttrData.nFileSizeHigh==0 | ||||
| 53006 | && sAttrData.nFileSizeLow==0 ){ | ||||
| 53007 | attr = INVALID_FILE_ATTRIBUTES; | ||||
| 53008 | }else{ | ||||
| 53009 | attr = sAttrData.dwFileAttributes; | ||||
| 53010 | } | ||||
| 53011 | }else{ | ||||
| 53012 | winLogIoerr(cnt, __LINE__53012); | ||||
| 53013 | if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ | ||||
| 53014 | sqlite3_free(zConverted); | ||||
| 53015 | return winLogError(SQLITE_IOERR_ACCESS(10 | (13<<8)), lastErrno, "winAccess", | ||||
| 53016 | zFilename); | ||||
| 53017 | }else{ | ||||
| 53018 | attr = INVALID_FILE_ATTRIBUTES; | ||||
| 53019 | } | ||||
| 53020 | } | ||||
| 53021 | } | ||||
| 53022 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 53023 | else{ | ||||
| 53024 | attr = osGetFileAttributesA((char*)zConverted); | ||||
| 53025 | } | ||||
| 53026 | #endif | ||||
| 53027 | sqlite3_free(zConverted); | ||||
| 53028 | switch( flags ){ | ||||
| 53029 | case SQLITE_ACCESS_READ2: | ||||
| 53030 | case SQLITE_ACCESS_EXISTS0: | ||||
| 53031 | rc = attr!=INVALID_FILE_ATTRIBUTES; | ||||
| 53032 | break; | ||||
| 53033 | case SQLITE_ACCESS_READWRITE1: | ||||
| 53034 | rc = attr!=INVALID_FILE_ATTRIBUTES && | ||||
| 53035 | (attr & FILE_ATTRIBUTE_READONLY)==0; | ||||
| 53036 | break; | ||||
| 53037 | default: | ||||
| 53038 | assert(!"Invalid flags argument")((void) (0)); | ||||
| 53039 | } | ||||
| 53040 | *pResOut = rc; | ||||
| 53041 | OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", | ||||
| 53042 | zFilename, pResOut, *pResOut)); | ||||
| 53043 | return SQLITE_OK0; | ||||
| 53044 | } | ||||
| 53045 | |||||
| 53046 | /* | ||||
| 53047 | ** Returns non-zero if the specified path name starts with the "long path" | ||||
| 53048 | ** prefix. | ||||
| 53049 | */ | ||||
| 53050 | static BOOL winIsLongPathPrefix( | ||||
| 53051 | const char *zPathname | ||||
| 53052 | ){ | ||||
| 53053 | return ( zPathname[0]=='\\' && zPathname[1]=='\\' | ||||
| 53054 | && zPathname[2]=='?' && zPathname[3]=='\\' ); | ||||
| 53055 | } | ||||
| 53056 | |||||
| 53057 | /* | ||||
| 53058 | ** Returns non-zero if the specified path name starts with a drive letter | ||||
| 53059 | ** followed by a colon character. | ||||
| 53060 | */ | ||||
| 53061 | static BOOL winIsDriveLetterAndColon( | ||||
| 53062 | const char *zPathname | ||||
| 53063 | ){ | ||||
| 53064 | return ( sqlite3Isalpha(zPathname[0])(sqlite3CtypeMap[(unsigned char)(zPathname[0])]&0x02) && zPathname[1]==':' ); | ||||
| 53065 | } | ||||
| 53066 | |||||
| 53067 | #ifdef _WIN32 | ||||
| 53068 | /* | ||||
| 53069 | ** Returns non-zero if the specified path name should be used verbatim. If | ||||
| 53070 | ** non-zero is returned from this function, the calling function must simply | ||||
| 53071 | ** use the provided path name verbatim -OR- resolve it into a full path name | ||||
| 53072 | ** using the GetFullPathName Win32 API function (if available). | ||||
| 53073 | */ | ||||
| 53074 | static BOOL winIsVerbatimPathname( | ||||
| 53075 | const char *zPathname | ||||
| 53076 | ){ | ||||
| 53077 | /* | ||||
| 53078 | ** If the path name starts with a forward slash or a backslash, it is either | ||||
| 53079 | ** a legal UNC name, a volume relative path, or an absolute path name in the | ||||
| 53080 | ** "Unix" format on Windows. There is no easy way to differentiate between | ||||
| 53081 | ** the final two cases; therefore, we return the safer return value of TRUE | ||||
| 53082 | ** so that callers of this function will simply use it verbatim. | ||||
| 53083 | */ | ||||
| 53084 | if ( winIsDirSep(zPathname[0]) ){ | ||||
| 53085 | return TRUE; | ||||
| 53086 | } | ||||
| 53087 | |||||
| 53088 | /* | ||||
| 53089 | ** If the path name starts with a letter and a colon it is either a volume | ||||
| 53090 | ** relative path or an absolute path. Callers of this function must not | ||||
| 53091 | ** attempt to treat it as a relative path name (i.e. they should simply use | ||||
| 53092 | ** it verbatim). | ||||
| 53093 | */ | ||||
| 53094 | if ( winIsDriveLetterAndColon(zPathname) ){ | ||||
| 53095 | return TRUE; | ||||
| 53096 | } | ||||
| 53097 | |||||
| 53098 | /* | ||||
| 53099 | ** If we get to this point, the path name should almost certainly be a purely | ||||
| 53100 | ** relative one (i.e. not a UNC name, not absolute, and not volume relative). | ||||
| 53101 | */ | ||||
| 53102 | return FALSE; | ||||
| 53103 | } | ||||
| 53104 | #endif /* _WIN32 */ | ||||
| 53105 | |||||
| 53106 | #ifdef __CYGWIN__ | ||||
| 53107 | /* | ||||
| 53108 | ** Simplify a filename into its canonical form | ||||
| 53109 | ** by making the following changes: | ||||
| 53110 | ** | ||||
| 53111 | ** * convert any '/' to '\' (win32) or reverse (Cygwin) | ||||
| 53112 | ** * removing any trailing and duplicate / (except for UNC paths) | ||||
| 53113 | ** * convert /./ into just / | ||||
| 53114 | ** | ||||
| 53115 | ** Changes are made in-place. Return the new name length. | ||||
| 53116 | ** | ||||
| 53117 | ** The original filename is in z[0..]. If the path is shortened, | ||||
| 53118 | ** no-longer used bytes will be written by '\0'. | ||||
| 53119 | */ | ||||
| 53120 | static void winSimplifyName(char *z){ | ||||
| 53121 | int i, j; | ||||
| 53122 | for(i=j=0; z[i]; ++i){ | ||||
| 53123 | if( winIsDirSep(z[i]) ){ | ||||
| 53124 | #if !defined(SQLITE_TEST) | ||||
| 53125 | /* Some test-cases assume that "./foo" and "foo" are different */ | ||||
| 53126 | if( z[i+1]=='.' && winIsDirSep(z[i+2]) ){ | ||||
| 53127 | ++i; | ||||
| 53128 | continue; | ||||
| 53129 | } | ||||
| 53130 | #endif | ||||
| 53131 | if( !z[i+1] || (winIsDirSep(z[i+1]) && (i!=0)) ){ | ||||
| 53132 | continue; | ||||
| 53133 | } | ||||
| 53134 | z[j++] = osGetenv?'/':'\\'; | ||||
| 53135 | }else{ | ||||
| 53136 | z[j++] = z[i]; | ||||
| 53137 | } | ||||
| 53138 | } | ||||
| 53139 | while(j<i) z[j++] = '\0'; | ||||
| 53140 | } | ||||
| 53141 | |||||
| 53142 | #define SQLITE_MAX_SYMLINKS100 100 | ||||
| 53143 | |||||
| 53144 | static int mkFullPathname( | ||||
| 53145 | const char *zPath, /* Input path */ | ||||
| 53146 | char *zOut, /* Output buffer */ | ||||
| 53147 | int nOut /* Allocated size of buffer zOut */ | ||||
| 53148 | ){ | ||||
| 53149 | int nPath = sqlite3Strlen30(zPath); | ||||
| 53150 | int iOff = 0; | ||||
| 53151 | if( zPath[0]!='/' ){ | ||||
| 53152 | if( osGetcwd((char*(*)(char*,size_t))aSyscall[3].pCurrent)(zOut, nOut-2)==0 ){ | ||||
| 53153 | return winLogError(SQLITE_CANTOPEN_BKPTsqlite3CantopenError(53153), (DWORD)osErrno, "getcwd", zPath); | ||||
| 53154 | } | ||||
| 53155 | iOff = sqlite3Strlen30(zOut); | ||||
| 53156 | zOut[iOff++] = '/'; | ||||
| 53157 | } | ||||
| 53158 | if( (iOff+nPath+1)>nOut ){ | ||||
| 53159 | /* SQLite assumes that xFullPathname() nul-terminates the output buffer | ||||
| 53160 | ** even if it returns an error. */ | ||||
| 53161 | zOut[iOff] = '\0'; | ||||
| 53162 | return SQLITE_CANTOPEN_BKPTsqlite3CantopenError(53162); | ||||
| 53163 | } | ||||
| 53164 | sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); | ||||
| 53165 | return SQLITE_OK0; | ||||
| 53166 | } | ||||
| 53167 | #endif /* __CYGWIN__ */ | ||||
| 53168 | |||||
| 53169 | /* | ||||
| 53170 | ** Turn a relative pathname into a full pathname. Write the full | ||||
| 53171 | ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname | ||||
| 53172 | ** bytes in size. | ||||
| 53173 | */ | ||||
| 53174 | static int winFullPathnameNoMutex( | ||||
| 53175 | sqlite3_vfs *pVfs, /* Pointer to vfs object */ | ||||
| 53176 | const char *zRelative, /* Possibly relative input path */ | ||||
| 53177 | int nFull, /* Size of output buffer in bytes */ | ||||
| 53178 | char *zFull /* Output buffer */ | ||||
| 53179 | ){ | ||||
| 53180 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT | ||||
| 53181 | int nByte; | ||||
| 53182 | void *zConverted; | ||||
| 53183 | char *zOut; | ||||
| 53184 | #endif | ||||
| 53185 | |||||
| 53186 | /* If this path name begins with "/X:" or "\\?\", where "X" is any | ||||
| 53187 | ** alphabetic character, discard the initial "/" from the pathname. | ||||
| 53188 | */ | ||||
| 53189 | if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1) | ||||
| 53190 | || winIsLongPathPrefix(zRelative+1)) ){ | ||||
| 53191 | zRelative++; | ||||
| 53192 | } | ||||
| 53193 | |||||
| 53194 | SimulateIOError( return SQLITE_ERROR ); | ||||
| 53195 | |||||
| 53196 | #ifdef __CYGWIN__ | ||||
| 53197 | if( osGetcwd((char*(*)(char*,size_t))aSyscall[3].pCurrent) ){ | ||||
| 53198 | zFull[nFull-1] = '\0'; | ||||
| 53199 | if( !winIsDriveLetterAndColon(zRelative) || !winIsDirSep(zRelative[2]) ){ | ||||
| 53200 | int rc = SQLITE_OK0; | ||||
| 53201 | int nLink = 1; /* Number of symbolic links followed so far */ | ||||
| 53202 | const char *zIn = zRelative; /* Input path for each iteration of loop */ | ||||
| 53203 | char *zDel = 0; | ||||
| 53204 | struct stat buf; | ||||
| 53205 | |||||
| 53206 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53207 | |||||
| 53208 | do { | ||||
| 53209 | /* Call lstat() on path zIn. Set bLink to true if the path is a symbolic | ||||
| 53210 | ** link, or false otherwise. */ | ||||
| 53211 | int bLink = 0; | ||||
| 53212 | if( osLstat((int(*)(const char*,struct stat*))aSyscall[27].pCurrent) && osReadlink((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent) ) { | ||||
| 53213 | if( osLstat((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)(zIn, &buf)!=0 ){ | ||||
| 53214 | int myErrno = osErrno; | ||||
| 53215 | if( myErrno!=ENOENT2 ){ | ||||
| 53216 | rc = winLogError(SQLITE_CANTOPEN_BKPTsqlite3CantopenError(53216), (DWORD)myErrno, "lstat", zIn); | ||||
| 53217 | } | ||||
| 53218 | }else{ | ||||
| 53219 | bLink = ((buf.st_mode & 0170000) == 0120000); | ||||
| 53220 | } | ||||
| 53221 | |||||
| 53222 | if( bLink ){ | ||||
| 53223 | if( zDel==0 ){ | ||||
| 53224 | zDel = sqlite3MallocZero(nFull); | ||||
| 53225 | if( zDel==0 ) rc = SQLITE_NOMEM7; | ||||
| 53226 | }else if( ++nLink>SQLITE_MAX_SYMLINKS100 ){ | ||||
| 53227 | rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(53227); | ||||
| 53228 | } | ||||
| 53229 | |||||
| 53230 | if( rc==SQLITE_OK0 ){ | ||||
| 53231 | nByte = osReadlink((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)(zIn, zDel, nFull-1); | ||||
| 53232 | if( nByte ==(DWORD)-1 ){ | ||||
| 53233 | rc = winLogError(SQLITE_CANTOPEN_BKPTsqlite3CantopenError(53233), (DWORD)osErrno, "readlink", zIn); | ||||
| 53234 | }else{ | ||||
| 53235 | if( zDel[0]!='/' ){ | ||||
| 53236 | int n; | ||||
| 53237 | for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); | ||||
| 53238 | if( nByte+n+1>nFull ){ | ||||
| 53239 | rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(53239); | ||||
| 53240 | }else{ | ||||
| 53241 | memmove(&zDel[n], zDel, nByte+1); | ||||
| 53242 | memcpy(zDel, zIn, n); | ||||
| 53243 | nByte += n; | ||||
| 53244 | } | ||||
| 53245 | } | ||||
| 53246 | zDel[nByte] = '\0'; | ||||
| 53247 | } | ||||
| 53248 | } | ||||
| 53249 | |||||
| 53250 | zIn = zDel; | ||||
| 53251 | } | ||||
| 53252 | } | ||||
| 53253 | |||||
| 53254 | assert( rc!=SQLITE_OK || zIn!=zFull || zIn[0]=='/' )((void) (0)); | ||||
| 53255 | if( rc==SQLITE_OK0 && zIn!=zFull ){ | ||||
| 53256 | rc = mkFullPathname(zIn, zFull, nFull); | ||||
| 53257 | } | ||||
| 53258 | if( bLink==0 ) break; | ||||
| 53259 | zIn = zFull; | ||||
| 53260 | }while( rc==SQLITE_OK0 ); | ||||
| 53261 | |||||
| 53262 | sqlite3_free(zDel); | ||||
| 53263 | winSimplifyName(zFull); | ||||
| 53264 | return rc; | ||||
| 53265 | } | ||||
| 53266 | } | ||||
| 53267 | #endif /* __CYGWIN__ */ | ||||
| 53268 | |||||
| 53269 | #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && defined(_WIN32) | ||||
| 53270 | SimulateIOError( return SQLITE_ERROR ); | ||||
| 53271 | /* WinCE has no concept of a relative pathname, or so I am told. */ | ||||
| 53272 | /* WinRT has no way to convert a relative path to an absolute one. */ | ||||
| 53273 | if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ | ||||
| 53274 | /* | ||||
| 53275 | ** NOTE: We are dealing with a relative path name and the data | ||||
| 53276 | ** directory has been set. Therefore, use it as the basis | ||||
| 53277 | ** for converting the relative path name to an absolute | ||||
| 53278 | ** one by prepending the data directory and a backslash. | ||||
| 53279 | */ | ||||
| 53280 | sqlite3_snprintf(MIN(nFull, pVfs->mxPathname)((nFull)<(pVfs->mxPathname)?(nFull):(pVfs->mxPathname )), zFull, "%s%c%s", | ||||
| 53281 | sqlite3_data_directory, winGetDirSep(), zRelative); | ||||
| 53282 | }else{ | ||||
| 53283 | sqlite3_snprintf(MIN(nFull, pVfs->mxPathname)((nFull)<(pVfs->mxPathname)?(nFull):(pVfs->mxPathname )), zFull, "%s", zRelative); | ||||
| 53284 | } | ||||
| 53285 | return SQLITE_OK0; | ||||
| 53286 | #endif | ||||
| 53287 | |||||
| 53288 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT | ||||
| 53289 | #if defined(_WIN32) | ||||
| 53290 | /* It's odd to simulate an io-error here, but really this is just | ||||
| 53291 | ** using the io-error infrastructure to test that SQLite handles this | ||||
| 53292 | ** function failing. This function could fail if, for example, the | ||||
| 53293 | ** current working directory has been unlinked. | ||||
| 53294 | */ | ||||
| 53295 | SimulateIOError( return SQLITE_ERROR ); | ||||
| 53296 | if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ | ||||
| 53297 | /* | ||||
| 53298 | ** NOTE: We are dealing with a relative path name and the data | ||||
| 53299 | ** directory has been set. Therefore, use it as the basis | ||||
| 53300 | ** for converting the relative path name to an absolute | ||||
| 53301 | ** one by prepending the data directory and a backslash. | ||||
| 53302 | */ | ||||
| 53303 | sqlite3_snprintf(MIN(nFull, pVfs->mxPathname)((nFull)<(pVfs->mxPathname)?(nFull):(pVfs->mxPathname )), zFull, "%s%c%s", | ||||
| 53304 | sqlite3_data_directory, winGetDirSep(), zRelative); | ||||
| 53305 | return SQLITE_OK0; | ||||
| 53306 | } | ||||
| 53307 | #endif | ||||
| 53308 | zConverted = winConvertFromUtf8Filename(zRelative); | ||||
| 53309 | if( zConverted==0 ){ | ||||
| 53310 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 53311 | } | ||||
| 53312 | if( osIsNT() ){ | ||||
| 53313 | LPWSTR zTemp; | ||||
| 53314 | nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0); | ||||
| 53315 | if( nByte==0 ){ | ||||
| 53316 | sqlite3_free(zConverted); | ||||
| 53317 | return winLogError(SQLITE_CANTOPEN_FULLPATH(14 | (3<<8)), osGetLastError(), | ||||
| 53318 | "winFullPathname1", zRelative); | ||||
| 53319 | } | ||||
| 53320 | nByte += 3; | ||||
| 53321 | zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); | ||||
| 53322 | if( zTemp==0 ){ | ||||
| 53323 | sqlite3_free(zConverted); | ||||
| 53324 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 53325 | } | ||||
| 53326 | nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0); | ||||
| 53327 | if( nByte==0 ){ | ||||
| 53328 | sqlite3_free(zConverted); | ||||
| 53329 | sqlite3_free(zTemp); | ||||
| 53330 | return winLogError(SQLITE_CANTOPEN_FULLPATH(14 | (3<<8)), osGetLastError(), | ||||
| 53331 | "winFullPathname2", zRelative); | ||||
| 53332 | } | ||||
| 53333 | sqlite3_free(zConverted); | ||||
| 53334 | zOut = winUnicodeToUtf8(zTemp); | ||||
| 53335 | sqlite3_free(zTemp); | ||||
| 53336 | } | ||||
| 53337 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 53338 | else{ | ||||
| 53339 | char *zTemp; | ||||
| 53340 | nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0); | ||||
| 53341 | if( nByte==0 ){ | ||||
| 53342 | sqlite3_free(zConverted); | ||||
| 53343 | return winLogError(SQLITE_CANTOPEN_FULLPATH(14 | (3<<8)), osGetLastError(), | ||||
| 53344 | "winFullPathname3", zRelative); | ||||
| 53345 | } | ||||
| 53346 | zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) + 3*sizeof(zTemp[0]) ); | ||||
| 53347 | if( zTemp==0 ){ | ||||
| 53348 | sqlite3_free(zConverted); | ||||
| 53349 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 53350 | } | ||||
| 53351 | nByte = osGetFullPathNameA((char*)zConverted, nByte+3, zTemp, 0); | ||||
| 53352 | if( nByte==0 ){ | ||||
| 53353 | sqlite3_free(zConverted); | ||||
| 53354 | sqlite3_free(zTemp); | ||||
| 53355 | return winLogError(SQLITE_CANTOPEN_FULLPATH(14 | (3<<8)), osGetLastError(), | ||||
| 53356 | "winFullPathname4", zRelative); | ||||
| 53357 | } | ||||
| 53358 | sqlite3_free(zConverted); | ||||
| 53359 | zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); | ||||
| 53360 | sqlite3_free(zTemp); | ||||
| 53361 | } | ||||
| 53362 | #endif | ||||
| 53363 | if( zOut ){ | ||||
| 53364 | #ifdef __CYGWIN__ | ||||
| 53365 | if( memcmp(zOut, "\\\\?\\", 4) ){ | ||||
| 53366 | sqlite3_snprintf(MIN(nFull, pVfs->mxPathname)((nFull)<(pVfs->mxPathname)?(nFull):(pVfs->mxPathname )), zFull, "%s", zOut); | ||||
| 53367 | }else if( memcmp(zOut+4, "UNC\\", 4) ){ | ||||
| 53368 | sqlite3_snprintf(MIN(nFull, pVfs->mxPathname)((nFull)<(pVfs->mxPathname)?(nFull):(pVfs->mxPathname )), zFull, "%s", zOut+4); | ||||
| 53369 | }else{ | ||||
| 53370 | char *p = zOut+6; | ||||
| 53371 | *p = '\\'; | ||||
| 53372 | if( osGetcwd((char*(*)(char*,size_t))aSyscall[3].pCurrent) ){ | ||||
| 53373 | /* On Cygwin, UNC paths use forward slashes */ | ||||
| 53374 | while( *p ){ | ||||
| 53375 | if( *p=='\\' ) *p = '/'; | ||||
| 53376 | ++p; | ||||
| 53377 | } | ||||
| 53378 | } | ||||
| 53379 | sqlite3_snprintf(MIN(nFull, pVfs->mxPathname)((nFull)<(pVfs->mxPathname)?(nFull):(pVfs->mxPathname )), zFull, "%s", zOut+6); | ||||
| 53380 | } | ||||
| 53381 | #else | ||||
| 53382 | sqlite3_snprintf(MIN(nFull, pVfs->mxPathname)((nFull)<(pVfs->mxPathname)?(nFull):(pVfs->mxPathname )), zFull, "%s", zOut); | ||||
| 53383 | #endif /* __CYGWIN__ */ | ||||
| 53384 | sqlite3_free(zOut); | ||||
| 53385 | return SQLITE_OK0; | ||||
| 53386 | }else{ | ||||
| 53387 | return SQLITE_IOERR_NOMEM_BKPT(10 | (12<<8)); | ||||
| 53388 | } | ||||
| 53389 | #endif | ||||
| 53390 | } | ||||
| 53391 | static int winFullPathname( | ||||
| 53392 | sqlite3_vfs *pVfs, /* Pointer to vfs object */ | ||||
| 53393 | const char *zRelative, /* Possibly relative input path */ | ||||
| 53394 | int nFull, /* Size of output buffer in bytes */ | ||||
| 53395 | char *zFull /* Output buffer */ | ||||
| 53396 | ){ | ||||
| 53397 | int rc; | ||||
| 53398 | MUTEX_LOGIC( sqlite3_mutex *pMutex; )sqlite3_mutex *pMutex; | ||||
| 53399 | MUTEX_LOGIC( pMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_TEMPDIR); )pMutex = sqlite3MutexAlloc(11); | ||||
| 53400 | sqlite3_mutex_enter(pMutex); | ||||
| 53401 | rc = winFullPathnameNoMutex(pVfs, zRelative, nFull, zFull); | ||||
| 53402 | sqlite3_mutex_leave(pMutex); | ||||
| 53403 | return rc; | ||||
| 53404 | } | ||||
| 53405 | |||||
| 53406 | #ifndef SQLITE_OMIT_LOAD_EXTENSION1 | ||||
| 53407 | /* | ||||
| 53408 | ** Interfaces for opening a shared library, finding entry points | ||||
| 53409 | ** within the shared library, and closing the shared library. | ||||
| 53410 | */ | ||||
| 53411 | static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ | ||||
| 53412 | HANDLE h; | ||||
| 53413 | void *zConverted = winConvertFromUtf8Filename(zFilename); | ||||
| 53414 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53415 | if( zConverted==0 ){ | ||||
| 53416 | OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); | ||||
| 53417 | return 0; | ||||
| 53418 | } | ||||
| 53419 | if( osIsNT() ){ | ||||
| 53420 | #if SQLITE_OS_WINRT | ||||
| 53421 | h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0); | ||||
| 53422 | #else | ||||
| 53423 | h = osLoadLibraryW((LPCWSTR)zConverted); | ||||
| 53424 | #endif | ||||
| 53425 | } | ||||
| 53426 | #ifdef SQLITE_WIN32_HAS_ANSI | ||||
| 53427 | else{ | ||||
| 53428 | h = osLoadLibraryA((char*)zConverted); | ||||
| 53429 | } | ||||
| 53430 | #endif | ||||
| 53431 | OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h)); | ||||
| 53432 | sqlite3_free(zConverted); | ||||
| 53433 | return (void*)h; | ||||
| 53434 | } | ||||
| 53435 | static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ | ||||
| 53436 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53437 | winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); | ||||
| 53438 | } | ||||
| 53439 | static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ | ||||
| 53440 | FARPROC proc; | ||||
| 53441 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53442 | proc = osGetProcAddressA((HANDLE)pH, zSym); | ||||
| 53443 | OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n", | ||||
| 53444 | (void*)pH, zSym, (void*)proc)); | ||||
| 53445 | return (void(*)(void))proc; | ||||
| 53446 | } | ||||
| 53447 | static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ | ||||
| 53448 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53449 | osFreeLibrary((HANDLE)pHandle); | ||||
| 53450 | OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle)); | ||||
| 53451 | } | ||||
| 53452 | #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ | ||||
| 53453 | #define winDlOpen 0 | ||||
| 53454 | #define winDlError 0 | ||||
| 53455 | #define winDlSym 0 | ||||
| 53456 | #define winDlClose 0 | ||||
| 53457 | #endif | ||||
| 53458 | |||||
| 53459 | /* State information for the randomness gatherer. */ | ||||
| 53460 | typedef struct EntropyGatherer EntropyGatherer; | ||||
| 53461 | struct EntropyGatherer { | ||||
| 53462 | unsigned char *a; /* Gather entropy into this buffer */ | ||||
| 53463 | int na; /* Size of a[] in bytes */ | ||||
| 53464 | int i; /* XOR next input into a[i] */ | ||||
| 53465 | int nXor; /* Number of XOR operations done */ | ||||
| 53466 | }; | ||||
| 53467 | |||||
| 53468 | #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) | ||||
| 53469 | /* Mix sz bytes of entropy into p. */ | ||||
| 53470 | static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){ | ||||
| 53471 | int j, k; | ||||
| 53472 | for(j=0, k=p->i; j<sz; j++){ | ||||
| 53473 | p->a[k++] ^= x[j]; | ||||
| 53474 | if( k>=p->na ) k = 0; | ||||
| 53475 | } | ||||
| 53476 | p->i = k; | ||||
| 53477 | p->nXor += sz; | ||||
| 53478 | } | ||||
| 53479 | #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */ | ||||
| 53480 | |||||
| 53481 | /* | ||||
| 53482 | ** Write up to nBuf bytes of randomness into zBuf. | ||||
| 53483 | */ | ||||
| 53484 | static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ | ||||
| 53485 | #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) | ||||
| 53486 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53487 | memset(zBuf, 0, nBuf); | ||||
| 53488 | return nBuf; | ||||
| 53489 | #else | ||||
| 53490 | EntropyGatherer e; | ||||
| 53491 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53492 | memset(zBuf, 0, nBuf); | ||||
| 53493 | e.a = (unsigned char*)zBuf; | ||||
| 53494 | e.na = nBuf; | ||||
| 53495 | e.nXor = 0; | ||||
| 53496 | e.i = 0; | ||||
| 53497 | { | ||||
| 53498 | SYSTEMTIME x; | ||||
| 53499 | osGetSystemTime(&x); | ||||
| 53500 | xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME)); | ||||
| 53501 | } | ||||
| 53502 | { | ||||
| 53503 | DWORD pid = osGetCurrentProcessId(); | ||||
| 53504 | xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD)); | ||||
| 53505 | } | ||||
| 53506 | #if SQLITE_OS_WINRT | ||||
| 53507 | { | ||||
| 53508 | ULONGLONG cnt = osGetTickCount64(); | ||||
| 53509 | xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG)); | ||||
| 53510 | } | ||||
| 53511 | #else | ||||
| 53512 | { | ||||
| 53513 | DWORD cnt = osGetTickCount(); | ||||
| 53514 | xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD)); | ||||
| 53515 | } | ||||
| 53516 | #endif /* SQLITE_OS_WINRT */ | ||||
| 53517 | { | ||||
| 53518 | LARGE_INTEGER i; | ||||
| 53519 | osQueryPerformanceCounter(&i); | ||||
| 53520 | xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER)); | ||||
| 53521 | } | ||||
| 53522 | #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID | ||||
| 53523 | { | ||||
| 53524 | UUID id; | ||||
| 53525 | memset(&id, 0, sizeof(UUID)); | ||||
| 53526 | osUuidCreate(&id); | ||||
| 53527 | xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); | ||||
| 53528 | memset(&id, 0, sizeof(UUID)); | ||||
| 53529 | osUuidCreateSequential(&id); | ||||
| 53530 | xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); | ||||
| 53531 | } | ||||
| 53532 | #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */ | ||||
| 53533 | return e.nXor>nBuf ? nBuf : e.nXor; | ||||
| 53534 | #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */ | ||||
| 53535 | } | ||||
| 53536 | |||||
| 53537 | |||||
| 53538 | /* | ||||
| 53539 | ** Sleep for a little while. Return the amount of time slept. | ||||
| 53540 | */ | ||||
| 53541 | static int winSleep(sqlite3_vfs *pVfs, int microsec){ | ||||
| 53542 | sqlite3_win32_sleep((microsec+999)/1000); | ||||
| 53543 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53544 | return ((microsec+999)/1000)*1000; | ||||
| 53545 | } | ||||
| 53546 | |||||
| 53547 | /* | ||||
| 53548 | ** The following variable, if set to a non-zero value, is interpreted as | ||||
| 53549 | ** the number of seconds since 1970 and is used to set the result of | ||||
| 53550 | ** sqlite3OsCurrentTime() during testing. | ||||
| 53551 | */ | ||||
| 53552 | #ifdef SQLITE_TEST | ||||
| 53553 | SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ | ||||
| 53554 | #endif | ||||
| 53555 | |||||
| 53556 | /* | ||||
| 53557 | ** Find the current time (in Universal Coordinated Time). Write into *piNow | ||||
| 53558 | ** the current time and date as a Julian Day number times 86_400_000. In | ||||
| 53559 | ** other words, write into *piNow the number of milliseconds since the Julian | ||||
| 53560 | ** epoch of noon in Greenwich on November 24, 4714 B.C according to the | ||||
| 53561 | ** proleptic Gregorian calendar. | ||||
| 53562 | ** | ||||
| 53563 | ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date | ||||
| 53564 | ** cannot be found. | ||||
| 53565 | */ | ||||
| 53566 | static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ | ||||
| 53567 | /* FILETIME structure is a 64-bit value representing the number of | ||||
| 53568 | 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). | ||||
| 53569 | */ | ||||
| 53570 | FILETIME ft; | ||||
| 53571 | static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000; | ||||
| 53572 | #ifdef SQLITE_TEST | ||||
| 53573 | static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; | ||||
| 53574 | #endif | ||||
| 53575 | /* 2^32 - to avoid use of LL and warnings in gcc */ | ||||
| 53576 | static const sqlite3_int64 max32BitValue = | ||||
| 53577 | (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + | ||||
| 53578 | (sqlite3_int64)294967296; | ||||
| 53579 | |||||
| 53580 | #if SQLITE_OS_WINCE | ||||
| 53581 | SYSTEMTIME time; | ||||
| 53582 | osGetSystemTime(&time); | ||||
| 53583 | /* if SystemTimeToFileTime() fails, it returns zero. */ | ||||
| 53584 | if (!osSystemTimeToFileTime(&time,&ft)){ | ||||
| 53585 | return SQLITE_ERROR1; | ||||
| 53586 | } | ||||
| 53587 | #else | ||||
| 53588 | osGetSystemTimeAsFileTime( &ft ); | ||||
| 53589 | #endif | ||||
| 53590 | |||||
| 53591 | *piNow = winFiletimeEpoch + | ||||
| 53592 | ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + | ||||
| 53593 | (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; | ||||
| 53594 | |||||
| 53595 | #ifdef SQLITE_TEST | ||||
| 53596 | if( sqlite3_current_time ){ | ||||
| 53597 | *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; | ||||
| 53598 | } | ||||
| 53599 | #endif | ||||
| 53600 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53601 | return SQLITE_OK0; | ||||
| 53602 | } | ||||
| 53603 | |||||
| 53604 | /* | ||||
| 53605 | ** Find the current time (in Universal Coordinated Time). Write the | ||||
| 53606 | ** current time and date as a Julian Day number into *prNow and | ||||
| 53607 | ** return 0. Return 1 if the time and date cannot be found. | ||||
| 53608 | */ | ||||
| 53609 | static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ | ||||
| 53610 | int rc; | ||||
| 53611 | sqlite3_int64 i; | ||||
| 53612 | rc = winCurrentTimeInt64(pVfs, &i); | ||||
| 53613 | if( !rc ){ | ||||
| 53614 | *prNow = i/86400000.0; | ||||
| 53615 | } | ||||
| 53616 | return rc; | ||||
| 53617 | } | ||||
| 53618 | |||||
| 53619 | /* | ||||
| 53620 | ** The idea is that this function works like a combination of | ||||
| 53621 | ** GetLastError() and FormatMessage() on Windows (or errno and | ||||
| 53622 | ** strerror_r() on Unix). After an error is returned by an OS | ||||
| 53623 | ** function, SQLite calls this function with zBuf pointing to | ||||
| 53624 | ** a buffer of nBuf bytes. The OS layer should populate the | ||||
| 53625 | ** buffer with a nul-terminated UTF-8 encoded error message | ||||
| 53626 | ** describing the last IO error to have occurred within the calling | ||||
| 53627 | ** thread. | ||||
| 53628 | ** | ||||
| 53629 | ** If the error message is too large for the supplied buffer, | ||||
| 53630 | ** it should be truncated. The return value of xGetLastError | ||||
| 53631 | ** is zero if the error message fits in the buffer, or non-zero | ||||
| 53632 | ** otherwise (if the message was truncated). If non-zero is returned, | ||||
| 53633 | ** then it is not necessary to include the nul-terminator character | ||||
| 53634 | ** in the output buffer. | ||||
| 53635 | ** | ||||
| 53636 | ** Not supplying an error message will have no adverse effect | ||||
| 53637 | ** on SQLite. It is fine to have an implementation that never | ||||
| 53638 | ** returns an error message: | ||||
| 53639 | ** | ||||
| 53640 | ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ | ||||
| 53641 | ** assert(zBuf[0]=='\0'); | ||||
| 53642 | ** return 0; | ||||
| 53643 | ** } | ||||
| 53644 | ** | ||||
| 53645 | ** However if an error message is supplied, it will be incorporated | ||||
| 53646 | ** by sqlite into the error message available to the user using | ||||
| 53647 | ** sqlite3_errmsg(), possibly making IO errors easier to debug. | ||||
| 53648 | */ | ||||
| 53649 | static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ | ||||
| 53650 | DWORD e = osGetLastError(); | ||||
| 53651 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 53652 | if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf); | ||||
| 53653 | return e; | ||||
| 53654 | } | ||||
| 53655 | |||||
| 53656 | /* | ||||
| 53657 | ** Initialize and deinitialize the operating system interface. | ||||
| 53658 | */ | ||||
| 53659 | SQLITE_API int sqlite3_os_init(void){ | ||||
| 53660 | static sqlite3_vfs winVfs = { | ||||
| 53661 | 3, /* iVersion */ | ||||
| 53662 | sizeof(winFile), /* szOsFile */ | ||||
| 53663 | SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ | ||||
| 53664 | 0, /* pNext */ | ||||
| 53665 | "win32", /* zName */ | ||||
| 53666 | &winAppData, /* pAppData */ | ||||
| 53667 | winOpen, /* xOpen */ | ||||
| 53668 | winDelete, /* xDelete */ | ||||
| 53669 | winAccess, /* xAccess */ | ||||
| 53670 | winFullPathname, /* xFullPathname */ | ||||
| 53671 | winDlOpen, /* xDlOpen */ | ||||
| 53672 | winDlError, /* xDlError */ | ||||
| 53673 | winDlSym, /* xDlSym */ | ||||
| 53674 | winDlClose, /* xDlClose */ | ||||
| 53675 | winRandomness, /* xRandomness */ | ||||
| 53676 | winSleep, /* xSleep */ | ||||
| 53677 | winCurrentTime, /* xCurrentTime */ | ||||
| 53678 | winGetLastError, /* xGetLastError */ | ||||
| 53679 | winCurrentTimeInt64, /* xCurrentTimeInt64 */ | ||||
| 53680 | winSetSystemCall, /* xSetSystemCall */ | ||||
| 53681 | winGetSystemCall, /* xGetSystemCall */ | ||||
| 53682 | winNextSystemCall, /* xNextSystemCall */ | ||||
| 53683 | }; | ||||
| 53684 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 53685 | static sqlite3_vfs winLongPathVfs = { | ||||
| 53686 | 3, /* iVersion */ | ||||
| 53687 | sizeof(winFile), /* szOsFile */ | ||||
| 53688 | SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ | ||||
| 53689 | 0, /* pNext */ | ||||
| 53690 | "win32-longpath", /* zName */ | ||||
| 53691 | &winAppData, /* pAppData */ | ||||
| 53692 | winOpen, /* xOpen */ | ||||
| 53693 | winDelete, /* xDelete */ | ||||
| 53694 | winAccess, /* xAccess */ | ||||
| 53695 | winFullPathname, /* xFullPathname */ | ||||
| 53696 | winDlOpen, /* xDlOpen */ | ||||
| 53697 | winDlError, /* xDlError */ | ||||
| 53698 | winDlSym, /* xDlSym */ | ||||
| 53699 | winDlClose, /* xDlClose */ | ||||
| 53700 | winRandomness, /* xRandomness */ | ||||
| 53701 | winSleep, /* xSleep */ | ||||
| 53702 | winCurrentTime, /* xCurrentTime */ | ||||
| 53703 | winGetLastError, /* xGetLastError */ | ||||
| 53704 | winCurrentTimeInt64, /* xCurrentTimeInt64 */ | ||||
| 53705 | winSetSystemCall, /* xSetSystemCall */ | ||||
| 53706 | winGetSystemCall, /* xGetSystemCall */ | ||||
| 53707 | winNextSystemCall, /* xNextSystemCall */ | ||||
| 53708 | }; | ||||
| 53709 | #endif | ||||
| 53710 | static sqlite3_vfs winNolockVfs = { | ||||
| 53711 | 3, /* iVersion */ | ||||
| 53712 | sizeof(winFile), /* szOsFile */ | ||||
| 53713 | SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ | ||||
| 53714 | 0, /* pNext */ | ||||
| 53715 | "win32-none", /* zName */ | ||||
| 53716 | &winNolockAppData, /* pAppData */ | ||||
| 53717 | winOpen, /* xOpen */ | ||||
| 53718 | winDelete, /* xDelete */ | ||||
| 53719 | winAccess, /* xAccess */ | ||||
| 53720 | winFullPathname, /* xFullPathname */ | ||||
| 53721 | winDlOpen, /* xDlOpen */ | ||||
| 53722 | winDlError, /* xDlError */ | ||||
| 53723 | winDlSym, /* xDlSym */ | ||||
| 53724 | winDlClose, /* xDlClose */ | ||||
| 53725 | winRandomness, /* xRandomness */ | ||||
| 53726 | winSleep, /* xSleep */ | ||||
| 53727 | winCurrentTime, /* xCurrentTime */ | ||||
| 53728 | winGetLastError, /* xGetLastError */ | ||||
| 53729 | winCurrentTimeInt64, /* xCurrentTimeInt64 */ | ||||
| 53730 | winSetSystemCall, /* xSetSystemCall */ | ||||
| 53731 | winGetSystemCall, /* xGetSystemCall */ | ||||
| 53732 | winNextSystemCall, /* xNextSystemCall */ | ||||
| 53733 | }; | ||||
| 53734 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 53735 | static sqlite3_vfs winLongPathNolockVfs = { | ||||
| 53736 | 3, /* iVersion */ | ||||
| 53737 | sizeof(winFile), /* szOsFile */ | ||||
| 53738 | SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ | ||||
| 53739 | 0, /* pNext */ | ||||
| 53740 | "win32-longpath-none", /* zName */ | ||||
| 53741 | &winNolockAppData, /* pAppData */ | ||||
| 53742 | winOpen, /* xOpen */ | ||||
| 53743 | winDelete, /* xDelete */ | ||||
| 53744 | winAccess, /* xAccess */ | ||||
| 53745 | winFullPathname, /* xFullPathname */ | ||||
| 53746 | winDlOpen, /* xDlOpen */ | ||||
| 53747 | winDlError, /* xDlError */ | ||||
| 53748 | winDlSym, /* xDlSym */ | ||||
| 53749 | winDlClose, /* xDlClose */ | ||||
| 53750 | winRandomness, /* xRandomness */ | ||||
| 53751 | winSleep, /* xSleep */ | ||||
| 53752 | winCurrentTime, /* xCurrentTime */ | ||||
| 53753 | winGetLastError, /* xGetLastError */ | ||||
| 53754 | winCurrentTimeInt64, /* xCurrentTimeInt64 */ | ||||
| 53755 | winSetSystemCall, /* xSetSystemCall */ | ||||
| 53756 | winGetSystemCall, /* xGetSystemCall */ | ||||
| 53757 | winNextSystemCall, /* xNextSystemCall */ | ||||
| 53758 | }; | ||||
| 53759 | #endif | ||||
| 53760 | |||||
| 53761 | /* Double-check that the aSyscall[] array has been constructed | ||||
| 53762 | ** correctly. See ticket [bb3a86e890c8e96ab] */ | ||||
| 53763 | assert( ArraySize(aSyscall)==89 )((void) (0)); | ||||
| 53764 | |||||
| 53765 | /* get memory map allocation granularity */ | ||||
| 53766 | memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); | ||||
| 53767 | #if SQLITE_OS_WINRT | ||||
| 53768 | osGetNativeSystemInfo(&winSysInfo); | ||||
| 53769 | #else | ||||
| 53770 | osGetSystemInfo(&winSysInfo); | ||||
| 53771 | #endif | ||||
| 53772 | assert( winSysInfo.dwAllocationGranularity>0 )((void) (0)); | ||||
| 53773 | assert( winSysInfo.dwPageSize>0 )((void) (0)); | ||||
| 53774 | |||||
| 53775 | sqlite3_vfs_register(&winVfs, 1); | ||||
| 53776 | |||||
| 53777 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 53778 | sqlite3_vfs_register(&winLongPathVfs, 0); | ||||
| 53779 | #endif | ||||
| 53780 | |||||
| 53781 | sqlite3_vfs_register(&winNolockVfs, 0); | ||||
| 53782 | |||||
| 53783 | #if defined(SQLITE_WIN32_HAS_WIDE) | ||||
| 53784 | sqlite3_vfs_register(&winLongPathNolockVfs, 0); | ||||
| 53785 | #endif | ||||
| 53786 | |||||
| 53787 | #ifndef SQLITE_OMIT_WAL | ||||
| 53788 | winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS111); | ||||
| 53789 | #endif | ||||
| 53790 | |||||
| 53791 | return SQLITE_OK0; | ||||
| 53792 | } | ||||
| 53793 | |||||
| 53794 | SQLITE_API int sqlite3_os_end(void){ | ||||
| 53795 | #if SQLITE_OS_WINRT | ||||
| 53796 | if( sleepObj!=NULL((void*)0) ){ | ||||
| 53797 | osCloseHandle(sleepObj); | ||||
| 53798 | sleepObj = NULL((void*)0); | ||||
| 53799 | } | ||||
| 53800 | #endif | ||||
| 53801 | |||||
| 53802 | #ifndef SQLITE_OMIT_WAL | ||||
| 53803 | winBigLock = 0; | ||||
| 53804 | #endif | ||||
| 53805 | |||||
| 53806 | return SQLITE_OK0; | ||||
| 53807 | } | ||||
| 53808 | |||||
| 53809 | #endif /* SQLITE_OS_WIN */ | ||||
| 53810 | |||||
| 53811 | /************** End of os_win.c **********************************************/ | ||||
| 53812 | /************** Begin file memdb.c *******************************************/ | ||||
| 53813 | /* | ||||
| 53814 | ** 2016-09-07 | ||||
| 53815 | ** | ||||
| 53816 | ** The author disclaims copyright to this source code. In place of | ||||
| 53817 | ** a legal notice, here is a blessing: | ||||
| 53818 | ** | ||||
| 53819 | ** May you do good and not evil. | ||||
| 53820 | ** May you find forgiveness for yourself and forgive others. | ||||
| 53821 | ** May you share freely, never taking more than you give. | ||||
| 53822 | ** | ||||
| 53823 | ****************************************************************************** | ||||
| 53824 | ** | ||||
| 53825 | ** This file implements an in-memory VFS. A database is held as a contiguous | ||||
| 53826 | ** block of memory. | ||||
| 53827 | ** | ||||
| 53828 | ** This file also implements interface sqlite3_serialize() and | ||||
| 53829 | ** sqlite3_deserialize(). | ||||
| 53830 | */ | ||||
| 53831 | /* #include "sqliteInt.h" */ | ||||
| 53832 | #ifndef SQLITE_OMIT_DESERIALIZE | ||||
| 53833 | |||||
| 53834 | /* | ||||
| 53835 | ** Forward declaration of objects used by this utility | ||||
| 53836 | */ | ||||
| 53837 | typedef struct sqlite3_vfs MemVfs; | ||||
| 53838 | typedef struct MemFile MemFile; | ||||
| 53839 | typedef struct MemStore MemStore; | ||||
| 53840 | |||||
| 53841 | /* Access to a lower-level VFS that (might) implement dynamic loading, | ||||
| 53842 | ** access to randomness, etc. | ||||
| 53843 | */ | ||||
| 53844 | #define ORIGVFS(p)((sqlite3_vfs*)((p)->pAppData)) ((sqlite3_vfs*)((p)->pAppData)) | ||||
| 53845 | |||||
| 53846 | /* Storage for a memdb file. | ||||
| 53847 | ** | ||||
| 53848 | ** An memdb object can be shared or separate. Shared memdb objects can be | ||||
| 53849 | ** used by more than one database connection. Mutexes are used by shared | ||||
| 53850 | ** memdb objects to coordinate access. Separate memdb objects are only | ||||
| 53851 | ** connected to a single database connection and do not require additional | ||||
| 53852 | ** mutexes. | ||||
| 53853 | ** | ||||
| 53854 | ** Shared memdb objects have .zFName!=0 and .pMutex!=0. They are created | ||||
| 53855 | ** using "file:/name?vfs=memdb". The first character of the name must be | ||||
| 53856 | ** "/" or else the object will be a separate memdb object. All shared | ||||
| 53857 | ** memdb objects are stored in memdb_g.apMemStore[] in an arbitrary order. | ||||
| 53858 | ** | ||||
| 53859 | ** Separate memdb objects are created using a name that does not begin | ||||
| 53860 | ** with "/" or using sqlite3_deserialize(). | ||||
| 53861 | ** | ||||
| 53862 | ** Access rules for shared MemStore objects: | ||||
| 53863 | ** | ||||
| 53864 | ** * .zFName is initialized when the object is created and afterwards | ||||
| 53865 | ** is unchanged until the object is destroyed. So it can be accessed | ||||
| 53866 | ** at any time as long as we know the object is not being destroyed, | ||||
| 53867 | ** which means while either the SQLITE_MUTEX_STATIC_VFS1 or | ||||
| 53868 | ** .pMutex is held or the object is not part of memdb_g.apMemStore[]. | ||||
| 53869 | ** | ||||
| 53870 | ** * Can .pMutex can only be changed while holding the | ||||
| 53871 | ** SQLITE_MUTEX_STATIC_VFS1 mutex or while the object is not part | ||||
| 53872 | ** of memdb_g.apMemStore[]. | ||||
| 53873 | ** | ||||
| 53874 | ** * Other fields can only be changed while holding the .pMutex mutex | ||||
| 53875 | ** or when the .nRef is less than zero and the object is not part of | ||||
| 53876 | ** memdb_g.apMemStore[]. | ||||
| 53877 | ** | ||||
| 53878 | ** * The .aData pointer has the added requirement that it can can only | ||||
| 53879 | ** be changed (for resizing) when nMmap is zero. | ||||
| 53880 | ** | ||||
| 53881 | */ | ||||
| 53882 | struct MemStore { | ||||
| 53883 | sqlite3_int64 sz; /* Size of the file */ | ||||
| 53884 | sqlite3_int64 szAlloc; /* Space allocated to aData */ | ||||
| 53885 | sqlite3_int64 szMax; /* Maximum allowed size of the file */ | ||||
| 53886 | unsigned char *aData; /* content of the file */ | ||||
| 53887 | sqlite3_mutex *pMutex; /* Used by shared stores only */ | ||||
| 53888 | int nMmap; /* Number of memory mapped pages */ | ||||
| 53889 | unsigned mFlags; /* Flags */ | ||||
| 53890 | int nRdLock; /* Number of readers */ | ||||
| 53891 | int nWrLock; /* Number of writers. (Always 0 or 1) */ | ||||
| 53892 | int nRef; /* Number of users of this MemStore */ | ||||
| 53893 | char *zFName; /* The filename for shared stores */ | ||||
| 53894 | }; | ||||
| 53895 | |||||
| 53896 | /* An open file */ | ||||
| 53897 | struct MemFile { | ||||
| 53898 | sqlite3_file base; /* IO methods */ | ||||
| 53899 | MemStore *pStore; /* The storage */ | ||||
| 53900 | int eLock; /* Most recent lock against this file */ | ||||
| 53901 | }; | ||||
| 53902 | |||||
| 53903 | /* | ||||
| 53904 | ** File-scope variables for holding the memdb files that are accessible | ||||
| 53905 | ** to multiple database connections in separate threads. | ||||
| 53906 | ** | ||||
| 53907 | ** Must hold SQLITE_MUTEX_STATIC_VFS1 to access any part of this object. | ||||
| 53908 | */ | ||||
| 53909 | static struct MemFS { | ||||
| 53910 | int nMemStore; /* Number of shared MemStore objects */ | ||||
| 53911 | MemStore **apMemStore; /* Array of all shared MemStore objects */ | ||||
| 53912 | } memdb_g; | ||||
| 53913 | |||||
| 53914 | /* | ||||
| 53915 | ** Methods for MemFile | ||||
| 53916 | */ | ||||
| 53917 | static int memdbClose(sqlite3_file*); | ||||
| 53918 | static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); | ||||
| 53919 | static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); | ||||
| 53920 | static int memdbTruncate(sqlite3_file*, sqlite3_int64 size); | ||||
| 53921 | static int memdbSync(sqlite3_file*, int flags); | ||||
| 53922 | static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize); | ||||
| 53923 | static int memdbLock(sqlite3_file*, int); | ||||
| 53924 | static int memdbUnlock(sqlite3_file*, int); | ||||
| 53925 | /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */ | ||||
| 53926 | static int memdbFileControl(sqlite3_file*, int op, void *pArg); | ||||
| 53927 | /* static int memdbSectorSize(sqlite3_file*); // not used */ | ||||
| 53928 | static int memdbDeviceCharacteristics(sqlite3_file*); | ||||
| 53929 | static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); | ||||
| 53930 | static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p); | ||||
| 53931 | |||||
| 53932 | /* | ||||
| 53933 | ** Methods for MemVfs | ||||
| 53934 | */ | ||||
| 53935 | static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); | ||||
| 53936 | /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */ | ||||
| 53937 | static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *); | ||||
| 53938 | static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); | ||||
| 53939 | static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename); | ||||
| 53940 | static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg); | ||||
| 53941 | static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void); | ||||
| 53942 | static void memdbDlClose(sqlite3_vfs*, void*); | ||||
| 53943 | static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut); | ||||
| 53944 | static int memdbSleep(sqlite3_vfs*, int microseconds); | ||||
| 53945 | /* static int memdbCurrentTime(sqlite3_vfs*, double*); */ | ||||
| 53946 | static int memdbGetLastError(sqlite3_vfs*, int, char *); | ||||
| 53947 | static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); | ||||
| 53948 | |||||
| 53949 | static sqlite3_vfs memdb_vfs = { | ||||
| 53950 | 2, /* iVersion */ | ||||
| 53951 | 0, /* szOsFile (set when registered) */ | ||||
| 53952 | 1024, /* mxPathname */ | ||||
| 53953 | 0, /* pNext */ | ||||
| 53954 | "memdb", /* zName */ | ||||
| 53955 | 0, /* pAppData (set when registered) */ | ||||
| 53956 | memdbOpen, /* xOpen */ | ||||
| 53957 | 0, /* memdbDelete, */ /* xDelete */ | ||||
| 53958 | memdbAccess, /* xAccess */ | ||||
| 53959 | memdbFullPathname, /* xFullPathname */ | ||||
| 53960 | memdbDlOpen, /* xDlOpen */ | ||||
| 53961 | memdbDlError, /* xDlError */ | ||||
| 53962 | memdbDlSym, /* xDlSym */ | ||||
| 53963 | memdbDlClose, /* xDlClose */ | ||||
| 53964 | memdbRandomness, /* xRandomness */ | ||||
| 53965 | memdbSleep, /* xSleep */ | ||||
| 53966 | 0, /* memdbCurrentTime, */ /* xCurrentTime */ | ||||
| 53967 | memdbGetLastError, /* xGetLastError */ | ||||
| 53968 | memdbCurrentTimeInt64, /* xCurrentTimeInt64 */ | ||||
| 53969 | 0, /* xSetSystemCall */ | ||||
| 53970 | 0, /* xGetSystemCall */ | ||||
| 53971 | 0, /* xNextSystemCall */ | ||||
| 53972 | }; | ||||
| 53973 | |||||
| 53974 | static const sqlite3_io_methods memdb_io_methods = { | ||||
| 53975 | 3, /* iVersion */ | ||||
| 53976 | memdbClose, /* xClose */ | ||||
| 53977 | memdbRead, /* xRead */ | ||||
| 53978 | memdbWrite, /* xWrite */ | ||||
| 53979 | memdbTruncate, /* xTruncate */ | ||||
| 53980 | memdbSync, /* xSync */ | ||||
| 53981 | memdbFileSize, /* xFileSize */ | ||||
| 53982 | memdbLock, /* xLock */ | ||||
| 53983 | memdbUnlock, /* xUnlock */ | ||||
| 53984 | 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */ | ||||
| 53985 | memdbFileControl, /* xFileControl */ | ||||
| 53986 | 0, /* memdbSectorSize,*/ /* xSectorSize */ | ||||
| 53987 | memdbDeviceCharacteristics, /* xDeviceCharacteristics */ | ||||
| 53988 | 0, /* xShmMap */ | ||||
| 53989 | 0, /* xShmLock */ | ||||
| 53990 | 0, /* xShmBarrier */ | ||||
| 53991 | 0, /* xShmUnmap */ | ||||
| 53992 | memdbFetch, /* xFetch */ | ||||
| 53993 | memdbUnfetch /* xUnfetch */ | ||||
| 53994 | }; | ||||
| 53995 | |||||
| 53996 | /* | ||||
| 53997 | ** Enter/leave the mutex on a MemStore | ||||
| 53998 | */ | ||||
| 53999 | #if defined(SQLITE_THREADSAFE2) && SQLITE_THREADSAFE2==0 | ||||
| 54000 | static void memdbEnter(MemStore *p){ | ||||
| 54001 | UNUSED_PARAMETER(p)(void)(p); | ||||
| 54002 | } | ||||
| 54003 | static void memdbLeave(MemStore *p){ | ||||
| 54004 | UNUSED_PARAMETER(p)(void)(p); | ||||
| 54005 | } | ||||
| 54006 | #else | ||||
| 54007 | static void memdbEnter(MemStore *p){ | ||||
| 54008 | sqlite3_mutex_enter(p->pMutex); | ||||
| 54009 | } | ||||
| 54010 | static void memdbLeave(MemStore *p){ | ||||
| 54011 | sqlite3_mutex_leave(p->pMutex); | ||||
| 54012 | } | ||||
| 54013 | #endif | ||||
| 54014 | |||||
| 54015 | |||||
| 54016 | |||||
| 54017 | /* | ||||
| 54018 | ** Close an memdb-file. | ||||
| 54019 | ** Free the underlying MemStore object when its refcount drops to zero | ||||
| 54020 | ** or less. | ||||
| 54021 | */ | ||||
| 54022 | static int memdbClose(sqlite3_file *pFile){ | ||||
| 54023 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54024 | if( p->zFName ){ | ||||
| 54025 | int i; | ||||
| 54026 | #ifndef SQLITE_MUTEX_OMIT | ||||
| 54027 | sqlite3_mutex *pVfsMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS111); | ||||
| 54028 | #endif | ||||
| 54029 | sqlite3_mutex_enter(pVfsMutex); | ||||
| 54030 | for(i=0; ALWAYS(i<memdb_g.nMemStore)(i<memdb_g.nMemStore); i++){ | ||||
| 54031 | if( memdb_g.apMemStore[i]==p ){ | ||||
| 54032 | memdbEnter(p); | ||||
| 54033 | if( p->nRef==1 ){ | ||||
| 54034 | memdb_g.apMemStore[i] = memdb_g.apMemStore[--memdb_g.nMemStore]; | ||||
| 54035 | if( memdb_g.nMemStore==0 ){ | ||||
| 54036 | sqlite3_free(memdb_g.apMemStore); | ||||
| 54037 | memdb_g.apMemStore = 0; | ||||
| 54038 | } | ||||
| 54039 | } | ||||
| 54040 | break; | ||||
| 54041 | } | ||||
| 54042 | } | ||||
| 54043 | sqlite3_mutex_leave(pVfsMutex); | ||||
| 54044 | }else{ | ||||
| 54045 | memdbEnter(p); | ||||
| 54046 | } | ||||
| 54047 | p->nRef--; | ||||
| 54048 | if( p->nRef<=0 ){ | ||||
| 54049 | if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE1 ){ | ||||
| 54050 | sqlite3_free(p->aData); | ||||
| 54051 | } | ||||
| 54052 | memdbLeave(p); | ||||
| 54053 | sqlite3_mutex_free(p->pMutex); | ||||
| 54054 | sqlite3_free(p); | ||||
| 54055 | }else{ | ||||
| 54056 | memdbLeave(p); | ||||
| 54057 | } | ||||
| 54058 | return SQLITE_OK0; | ||||
| 54059 | } | ||||
| 54060 | |||||
| 54061 | /* | ||||
| 54062 | ** Read data from an memdb-file. | ||||
| 54063 | */ | ||||
| 54064 | static int memdbRead( | ||||
| 54065 | sqlite3_file *pFile, | ||||
| 54066 | void *zBuf, | ||||
| 54067 | int iAmt, | ||||
| 54068 | sqlite_int64 iOfst | ||||
| 54069 | ){ | ||||
| 54070 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54071 | memdbEnter(p); | ||||
| 54072 | if( iOfst+iAmt>p->sz ){ | ||||
| 54073 | memset(zBuf, 0, iAmt); | ||||
| 54074 | if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst); | ||||
| 54075 | memdbLeave(p); | ||||
| 54076 | return SQLITE_IOERR_SHORT_READ(10 | (2<<8)); | ||||
| 54077 | } | ||||
| 54078 | memcpy(zBuf, p->aData+iOfst, iAmt); | ||||
| 54079 | memdbLeave(p); | ||||
| 54080 | return SQLITE_OK0; | ||||
| 54081 | } | ||||
| 54082 | |||||
| 54083 | /* | ||||
| 54084 | ** Try to enlarge the memory allocation to hold at least sz bytes | ||||
| 54085 | */ | ||||
| 54086 | static int memdbEnlarge(MemStore *p, sqlite3_int64 newSz){ | ||||
| 54087 | unsigned char *pNew; | ||||
| 54088 | if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE2)==0 || NEVER(p->nMmap>0)(p->nMmap>0) ){ | ||||
| 54089 | return SQLITE_FULL13; | ||||
| 54090 | } | ||||
| 54091 | if( newSz>p->szMax ){ | ||||
| 54092 | return SQLITE_FULL13; | ||||
| 54093 | } | ||||
| 54094 | newSz *= 2; | ||||
| 54095 | if( newSz>p->szMax ) newSz = p->szMax; | ||||
| 54096 | pNew = sqlite3Realloc(p->aData, newSz); | ||||
| 54097 | if( pNew==0 ) return SQLITE_IOERR_NOMEM(10 | (12<<8)); | ||||
| 54098 | p->aData = pNew; | ||||
| 54099 | p->szAlloc = newSz; | ||||
| 54100 | return SQLITE_OK0; | ||||
| 54101 | } | ||||
| 54102 | |||||
| 54103 | /* | ||||
| 54104 | ** Write data to an memdb-file. | ||||
| 54105 | */ | ||||
| 54106 | static int memdbWrite( | ||||
| 54107 | sqlite3_file *pFile, | ||||
| 54108 | const void *z, | ||||
| 54109 | int iAmt, | ||||
| 54110 | sqlite_int64 iOfst | ||||
| 54111 | ){ | ||||
| 54112 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54113 | memdbEnter(p); | ||||
| 54114 | if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY)(p->mFlags & 4) ){ | ||||
| 54115 | /* Can't happen: memdbLock() will return SQLITE_READONLY before | ||||
| 54116 | ** reaching this point */ | ||||
| 54117 | memdbLeave(p); | ||||
| 54118 | return SQLITE_IOERR_WRITE(10 | (3<<8)); | ||||
| 54119 | } | ||||
| 54120 | if( iOfst+iAmt>p->sz ){ | ||||
| 54121 | int rc; | ||||
| 54122 | if( iOfst+iAmt>p->szAlloc | ||||
| 54123 | && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK0 | ||||
| 54124 | ){ | ||||
| 54125 | memdbLeave(p); | ||||
| 54126 | return rc; | ||||
| 54127 | } | ||||
| 54128 | if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz); | ||||
| 54129 | p->sz = iOfst+iAmt; | ||||
| 54130 | } | ||||
| 54131 | memcpy(p->aData+iOfst, z, iAmt); | ||||
| 54132 | memdbLeave(p); | ||||
| 54133 | return SQLITE_OK0; | ||||
| 54134 | } | ||||
| 54135 | |||||
| 54136 | /* | ||||
| 54137 | ** Truncate an memdb-file. | ||||
| 54138 | ** | ||||
| 54139 | ** In rollback mode (which is always the case for memdb, as it does not | ||||
| 54140 | ** support WAL mode) the truncate() method is only used to reduce | ||||
| 54141 | ** the size of a file, never to increase the size. | ||||
| 54142 | */ | ||||
| 54143 | static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){ | ||||
| 54144 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54145 | int rc = SQLITE_OK0; | ||||
| 54146 | memdbEnter(p); | ||||
| 54147 | if( size>p->sz ){ | ||||
| 54148 | /* This can only happen with a corrupt wal mode db */ | ||||
| 54149 | rc = SQLITE_CORRUPT11; | ||||
| 54150 | }else{ | ||||
| 54151 | p->sz = size; | ||||
| 54152 | } | ||||
| 54153 | memdbLeave(p); | ||||
| 54154 | return rc; | ||||
| 54155 | } | ||||
| 54156 | |||||
| 54157 | /* | ||||
| 54158 | ** Sync an memdb-file. | ||||
| 54159 | */ | ||||
| 54160 | static int memdbSync(sqlite3_file *pFile, int flags){ | ||||
| 54161 | UNUSED_PARAMETER(pFile)(void)(pFile); | ||||
| 54162 | UNUSED_PARAMETER(flags)(void)(flags); | ||||
| 54163 | return SQLITE_OK0; | ||||
| 54164 | } | ||||
| 54165 | |||||
| 54166 | /* | ||||
| 54167 | ** Return the current file-size of an memdb-file. | ||||
| 54168 | */ | ||||
| 54169 | static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ | ||||
| 54170 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54171 | memdbEnter(p); | ||||
| 54172 | *pSize = p->sz; | ||||
| 54173 | memdbLeave(p); | ||||
| 54174 | return SQLITE_OK0; | ||||
| 54175 | } | ||||
| 54176 | |||||
| 54177 | /* | ||||
| 54178 | ** Lock an memdb-file. | ||||
| 54179 | */ | ||||
| 54180 | static int memdbLock(sqlite3_file *pFile, int eLock){ | ||||
| 54181 | MemFile *pThis = (MemFile*)pFile; | ||||
| 54182 | MemStore *p = pThis->pStore; | ||||
| 54183 | int rc = SQLITE_OK0; | ||||
| 54184 | if( eLock<=pThis->eLock ) return SQLITE_OK0; | ||||
| 54185 | memdbEnter(p); | ||||
| 54186 | |||||
| 54187 | assert( p->nWrLock==0 || p->nWrLock==1 )((void) (0)); | ||||
| 54188 | assert( pThis->eLock<=SQLITE_LOCK_SHARED || p->nWrLock==1 )((void) (0)); | ||||
| 54189 | assert( pThis->eLock==SQLITE_LOCK_NONE || p->nRdLock>=1 )((void) (0)); | ||||
| 54190 | |||||
| 54191 | if( eLock>SQLITE_LOCK_SHARED1 && (p->mFlags & SQLITE_DESERIALIZE_READONLY4) ){ | ||||
| 54192 | rc = SQLITE_READONLY8; | ||||
| 54193 | }else{ | ||||
| 54194 | switch( eLock ){ | ||||
| 54195 | case SQLITE_LOCK_SHARED1: { | ||||
| 54196 | assert( pThis->eLock==SQLITE_LOCK_NONE )((void) (0)); | ||||
| 54197 | if( p->nWrLock>0 ){ | ||||
| 54198 | rc = SQLITE_BUSY5; | ||||
| 54199 | }else{ | ||||
| 54200 | p->nRdLock++; | ||||
| 54201 | } | ||||
| 54202 | break; | ||||
| 54203 | }; | ||||
| 54204 | |||||
| 54205 | case SQLITE_LOCK_RESERVED2: | ||||
| 54206 | case SQLITE_LOCK_PENDING3: { | ||||
| 54207 | assert( pThis->eLock>=SQLITE_LOCK_SHARED )((void) (0)); | ||||
| 54208 | if( ALWAYS(pThis->eLock==SQLITE_LOCK_SHARED)(pThis->eLock==1) ){ | ||||
| 54209 | if( p->nWrLock>0 ){ | ||||
| 54210 | rc = SQLITE_BUSY5; | ||||
| 54211 | }else{ | ||||
| 54212 | p->nWrLock = 1; | ||||
| 54213 | } | ||||
| 54214 | } | ||||
| 54215 | break; | ||||
| 54216 | } | ||||
| 54217 | |||||
| 54218 | default: { | ||||
| 54219 | assert( eLock==SQLITE_LOCK_EXCLUSIVE )((void) (0)); | ||||
| 54220 | assert( pThis->eLock>=SQLITE_LOCK_SHARED )((void) (0)); | ||||
| 54221 | if( p->nRdLock>1 ){ | ||||
| 54222 | rc = SQLITE_BUSY5; | ||||
| 54223 | }else if( pThis->eLock==SQLITE_LOCK_SHARED1 ){ | ||||
| 54224 | p->nWrLock = 1; | ||||
| 54225 | } | ||||
| 54226 | break; | ||||
| 54227 | } | ||||
| 54228 | } | ||||
| 54229 | } | ||||
| 54230 | if( rc==SQLITE_OK0 ) pThis->eLock = eLock; | ||||
| 54231 | memdbLeave(p); | ||||
| 54232 | return rc; | ||||
| 54233 | } | ||||
| 54234 | |||||
| 54235 | /* | ||||
| 54236 | ** Unlock an memdb-file. | ||||
| 54237 | */ | ||||
| 54238 | static int memdbUnlock(sqlite3_file *pFile, int eLock){ | ||||
| 54239 | MemFile *pThis = (MemFile*)pFile; | ||||
| 54240 | MemStore *p = pThis->pStore; | ||||
| 54241 | if( eLock>=pThis->eLock ) return SQLITE_OK0; | ||||
| 54242 | memdbEnter(p); | ||||
| 54243 | |||||
| 54244 | assert( eLock==SQLITE_LOCK_SHARED || eLock==SQLITE_LOCK_NONE )((void) (0)); | ||||
| 54245 | if( eLock==SQLITE_LOCK_SHARED1 ){ | ||||
| 54246 | if( ALWAYS(pThis->eLock>SQLITE_LOCK_SHARED)(pThis->eLock>1) ){ | ||||
| 54247 | p->nWrLock--; | ||||
| 54248 | } | ||||
| 54249 | }else{ | ||||
| 54250 | if( pThis->eLock>SQLITE_LOCK_SHARED1 ){ | ||||
| 54251 | p->nWrLock--; | ||||
| 54252 | } | ||||
| 54253 | p->nRdLock--; | ||||
| 54254 | } | ||||
| 54255 | |||||
| 54256 | pThis->eLock = eLock; | ||||
| 54257 | memdbLeave(p); | ||||
| 54258 | return SQLITE_OK0; | ||||
| 54259 | } | ||||
| 54260 | |||||
| 54261 | #if 0 | ||||
| 54262 | /* | ||||
| 54263 | ** This interface is only used for crash recovery, which does not | ||||
| 54264 | ** occur on an in-memory database. | ||||
| 54265 | */ | ||||
| 54266 | static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){ | ||||
| 54267 | *pResOut = 0; | ||||
| 54268 | return SQLITE_OK0; | ||||
| 54269 | } | ||||
| 54270 | #endif | ||||
| 54271 | |||||
| 54272 | |||||
| 54273 | /* | ||||
| 54274 | ** File control method. For custom operations on an memdb-file. | ||||
| 54275 | */ | ||||
| 54276 | static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){ | ||||
| 54277 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54278 | int rc = SQLITE_NOTFOUND12; | ||||
| 54279 | memdbEnter(p); | ||||
| 54280 | if( op==SQLITE_FCNTL_VFSNAME12 ){ | ||||
| 54281 | *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz); | ||||
| 54282 | rc = SQLITE_OK0; | ||||
| 54283 | } | ||||
| 54284 | if( op==SQLITE_FCNTL_SIZE_LIMIT36 ){ | ||||
| 54285 | sqlite3_int64 iLimit = *(sqlite3_int64*)pArg; | ||||
| 54286 | if( iLimit<p->sz ){ | ||||
| 54287 | if( iLimit<0 ){ | ||||
| 54288 | iLimit = p->szMax; | ||||
| 54289 | }else{ | ||||
| 54290 | iLimit = p->sz; | ||||
| 54291 | } | ||||
| 54292 | } | ||||
| 54293 | p->szMax = iLimit; | ||||
| 54294 | *(sqlite3_int64*)pArg = iLimit; | ||||
| 54295 | rc = SQLITE_OK0; | ||||
| 54296 | } | ||||
| 54297 | memdbLeave(p); | ||||
| 54298 | return rc; | ||||
| 54299 | } | ||||
| 54300 | |||||
| 54301 | #if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */ | ||||
| 54302 | /* | ||||
| 54303 | ** Return the sector-size in bytes for an memdb-file. | ||||
| 54304 | */ | ||||
| 54305 | static int memdbSectorSize(sqlite3_file *pFile){ | ||||
| 54306 | return 1024; | ||||
| 54307 | } | ||||
| 54308 | #endif | ||||
| 54309 | |||||
| 54310 | /* | ||||
| 54311 | ** Return the device characteristic flags supported by an memdb-file. | ||||
| 54312 | */ | ||||
| 54313 | static int memdbDeviceCharacteristics(sqlite3_file *pFile){ | ||||
| 54314 | UNUSED_PARAMETER(pFile)(void)(pFile); | ||||
| 54315 | return SQLITE_IOCAP_ATOMIC0x00000001 | | ||||
| 54316 | SQLITE_IOCAP_POWERSAFE_OVERWRITE0x00001000 | | ||||
| 54317 | SQLITE_IOCAP_SAFE_APPEND0x00000200 | | ||||
| 54318 | SQLITE_IOCAP_SEQUENTIAL0x00000400; | ||||
| 54319 | } | ||||
| 54320 | |||||
| 54321 | /* Fetch a page of a memory-mapped file */ | ||||
| 54322 | static int memdbFetch( | ||||
| 54323 | sqlite3_file *pFile, | ||||
| 54324 | sqlite3_int64 iOfst, | ||||
| 54325 | int iAmt, | ||||
| 54326 | void **pp | ||||
| 54327 | ){ | ||||
| 54328 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54329 | memdbEnter(p); | ||||
| 54330 | if( iOfst+iAmt>p->sz || (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE2)!=0 ){ | ||||
| 54331 | *pp = 0; | ||||
| 54332 | }else{ | ||||
| 54333 | p->nMmap++; | ||||
| 54334 | *pp = (void*)(p->aData + iOfst); | ||||
| 54335 | } | ||||
| 54336 | memdbLeave(p); | ||||
| 54337 | return SQLITE_OK0; | ||||
| 54338 | } | ||||
| 54339 | |||||
| 54340 | /* Release a memory-mapped page */ | ||||
| 54341 | static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){ | ||||
| 54342 | MemStore *p = ((MemFile*)pFile)->pStore; | ||||
| 54343 | UNUSED_PARAMETER(iOfst)(void)(iOfst); | ||||
| 54344 | UNUSED_PARAMETER(pPage)(void)(pPage); | ||||
| 54345 | memdbEnter(p); | ||||
| 54346 | p->nMmap--; | ||||
| 54347 | memdbLeave(p); | ||||
| 54348 | return SQLITE_OK0; | ||||
| 54349 | } | ||||
| 54350 | |||||
| 54351 | /* | ||||
| 54352 | ** Open an mem file handle. | ||||
| 54353 | */ | ||||
| 54354 | static int memdbOpen( | ||||
| 54355 | sqlite3_vfs *pVfs, | ||||
| 54356 | const char *zName, | ||||
| 54357 | sqlite3_file *pFd, | ||||
| 54358 | int flags, | ||||
| 54359 | int *pOutFlags | ||||
| 54360 | ){ | ||||
| 54361 | MemFile *pFile = (MemFile*)pFd; | ||||
| 54362 | MemStore *p = 0; | ||||
| 54363 | int szName; | ||||
| 54364 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 54365 | |||||
| 54366 | memset(pFile, 0, sizeof(*pFile)); | ||||
| 54367 | szName = sqlite3Strlen30(zName); | ||||
| 54368 | if( szName>1 && (zName[0]=='/' || zName[0]=='\\') ){ | ||||
| 54369 | int i; | ||||
| 54370 | #ifndef SQLITE_MUTEX_OMIT | ||||
| 54371 | sqlite3_mutex *pVfsMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS111); | ||||
| 54372 | #endif | ||||
| 54373 | sqlite3_mutex_enter(pVfsMutex); | ||||
| 54374 | for(i=0; i<memdb_g.nMemStore; i++){ | ||||
| 54375 | if( strcmp(memdb_g.apMemStore[i]->zFName,zName)==0 ){ | ||||
| 54376 | p = memdb_g.apMemStore[i]; | ||||
| 54377 | break; | ||||
| 54378 | } | ||||
| 54379 | } | ||||
| 54380 | if( p==0 ){ | ||||
| 54381 | MemStore **apNew; | ||||
| 54382 | p = sqlite3Malloc( sizeof(*p) + (i64)szName + 3 ); | ||||
| 54383 | if( p==0 ){ | ||||
| 54384 | sqlite3_mutex_leave(pVfsMutex); | ||||
| 54385 | return SQLITE_NOMEM7; | ||||
| 54386 | } | ||||
| 54387 | apNew = sqlite3Realloc(memdb_g.apMemStore, | ||||
| 54388 | sizeof(apNew[0])*(1+(i64)memdb_g.nMemStore) ); | ||||
| 54389 | if( apNew==0 ){ | ||||
| 54390 | sqlite3_free(p); | ||||
| 54391 | sqlite3_mutex_leave(pVfsMutex); | ||||
| 54392 | return SQLITE_NOMEM7; | ||||
| 54393 | } | ||||
| 54394 | apNew[memdb_g.nMemStore++] = p; | ||||
| 54395 | memdb_g.apMemStore = apNew; | ||||
| 54396 | memset(p, 0, sizeof(*p)); | ||||
| 54397 | p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE2|SQLITE_DESERIALIZE_FREEONCLOSE1; | ||||
| 54398 | p->szMax = sqlite3GlobalConfigsqlite3Config.mxMemdbSize; | ||||
| 54399 | p->zFName = (char*)&p[1]; | ||||
| 54400 | memcpy(p->zFName, zName, szName+1); | ||||
| 54401 | p->pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST0); | ||||
| 54402 | if( p->pMutex==0 ){ | ||||
| 54403 | memdb_g.nMemStore--; | ||||
| 54404 | sqlite3_free(p); | ||||
| 54405 | sqlite3_mutex_leave(pVfsMutex); | ||||
| 54406 | return SQLITE_NOMEM7; | ||||
| 54407 | } | ||||
| 54408 | p->nRef = 1; | ||||
| 54409 | memdbEnter(p); | ||||
| 54410 | }else{ | ||||
| 54411 | memdbEnter(p); | ||||
| 54412 | p->nRef++; | ||||
| 54413 | } | ||||
| 54414 | sqlite3_mutex_leave(pVfsMutex); | ||||
| 54415 | }else{ | ||||
| 54416 | p = sqlite3Malloc( sizeof(*p) ); | ||||
| 54417 | if( p==0 ){ | ||||
| 54418 | return SQLITE_NOMEM7; | ||||
| 54419 | } | ||||
| 54420 | memset(p, 0, sizeof(*p)); | ||||
| 54421 | p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE2 | SQLITE_DESERIALIZE_FREEONCLOSE1; | ||||
| 54422 | p->szMax = sqlite3GlobalConfigsqlite3Config.mxMemdbSize; | ||||
| 54423 | } | ||||
| 54424 | pFile->pStore = p; | ||||
| 54425 | if( pOutFlags!=0 ){ | ||||
| 54426 | *pOutFlags = flags | SQLITE_OPEN_MEMORY0x00000080; | ||||
| 54427 | } | ||||
| 54428 | pFd->pMethods = &memdb_io_methods; | ||||
| 54429 | memdbLeave(p); | ||||
| 54430 | return SQLITE_OK0; | ||||
| 54431 | } | ||||
| 54432 | |||||
| 54433 | #if 0 /* Only used to delete rollback journals, super-journals, and WAL | ||||
| 54434 | ** files, none of which exist in memdb. So this routine is never used */ | ||||
| 54435 | /* | ||||
| 54436 | ** Delete the file located at zPath. If the dirSync argument is true, | ||||
| 54437 | ** ensure the file-system modifications are synced to disk before | ||||
| 54438 | ** returning. | ||||
| 54439 | */ | ||||
| 54440 | static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ | ||||
| 54441 | return SQLITE_IOERR_DELETE(10 | (10<<8)); | ||||
| 54442 | } | ||||
| 54443 | #endif | ||||
| 54444 | |||||
| 54445 | /* | ||||
| 54446 | ** Test for access permissions. Return true if the requested permission | ||||
| 54447 | ** is available, or false otherwise. | ||||
| 54448 | ** | ||||
| 54449 | ** With memdb, no files ever exist on disk. So always return false. | ||||
| 54450 | */ | ||||
| 54451 | static int memdbAccess( | ||||
| 54452 | sqlite3_vfs *pVfs, | ||||
| 54453 | const char *zPath, | ||||
| 54454 | int flags, | ||||
| 54455 | int *pResOut | ||||
| 54456 | ){ | ||||
| 54457 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 54458 | UNUSED_PARAMETER(zPath)(void)(zPath); | ||||
| 54459 | UNUSED_PARAMETER(flags)(void)(flags); | ||||
| 54460 | *pResOut = 0; | ||||
| 54461 | return SQLITE_OK0; | ||||
| 54462 | } | ||||
| 54463 | |||||
| 54464 | /* | ||||
| 54465 | ** Populate buffer zOut with the full canonical pathname corresponding | ||||
| 54466 | ** to the pathname in zPath. zOut is guaranteed to point to a buffer | ||||
| 54467 | ** of at least (INST_MAX_PATHNAME+1) bytes. | ||||
| 54468 | */ | ||||
| 54469 | static int memdbFullPathname( | ||||
| 54470 | sqlite3_vfs *pVfs, | ||||
| 54471 | const char *zPath, | ||||
| 54472 | int nOut, | ||||
| 54473 | char *zOut | ||||
| 54474 | ){ | ||||
| 54475 | UNUSED_PARAMETER(pVfs)(void)(pVfs); | ||||
| 54476 | sqlite3_snprintf(nOut, zOut, "%s", zPath); | ||||
| 54477 | return SQLITE_OK0; | ||||
| 54478 | } | ||||
| 54479 | |||||
| 54480 | /* | ||||
| 54481 | ** Open the dynamic library located at zPath and return a handle. | ||||
| 54482 | */ | ||||
| 54483 | static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){ | ||||
| 54484 | return ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xDlOpen(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), zPath); | ||||
| 54485 | } | ||||
| 54486 | |||||
| 54487 | /* | ||||
| 54488 | ** Populate the buffer zErrMsg (size nByte bytes) with a human readable | ||||
| 54489 | ** utf-8 string describing the most recent error encountered associated | ||||
| 54490 | ** with dynamic libraries. | ||||
| 54491 | */ | ||||
| 54492 | static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ | ||||
| 54493 | ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xDlError(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), nByte, zErrMsg); | ||||
| 54494 | } | ||||
| 54495 | |||||
| 54496 | /* | ||||
| 54497 | ** Return a pointer to the symbol zSymbol in the dynamic library pHandle. | ||||
| 54498 | */ | ||||
| 54499 | static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ | ||||
| 54500 | return ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xDlSym(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), p, zSym); | ||||
| 54501 | } | ||||
| 54502 | |||||
| 54503 | /* | ||||
| 54504 | ** Close the dynamic library handle pHandle. | ||||
| 54505 | */ | ||||
| 54506 | static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){ | ||||
| 54507 | ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xDlClose(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), pHandle); | ||||
| 54508 | } | ||||
| 54509 | |||||
| 54510 | /* | ||||
| 54511 | ** Populate the buffer pointed to by zBufOut with nByte bytes of | ||||
| 54512 | ** random data. | ||||
| 54513 | */ | ||||
| 54514 | static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ | ||||
| 54515 | return ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xRandomness(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), nByte, zBufOut); | ||||
| 54516 | } | ||||
| 54517 | |||||
| 54518 | /* | ||||
| 54519 | ** Sleep for nMicro microseconds. Return the number of microseconds | ||||
| 54520 | ** actually slept. | ||||
| 54521 | */ | ||||
| 54522 | static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){ | ||||
| 54523 | return ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xSleep(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), nMicro); | ||||
| 54524 | } | ||||
| 54525 | |||||
| 54526 | #if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */ | ||||
| 54527 | /* | ||||
| 54528 | ** Return the current time as a Julian Day number in *pTimeOut. | ||||
| 54529 | */ | ||||
| 54530 | static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ | ||||
| 54531 | return ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xCurrentTime(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), pTimeOut); | ||||
| 54532 | } | ||||
| 54533 | #endif | ||||
| 54534 | |||||
| 54535 | static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){ | ||||
| 54536 | return ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xGetLastError(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), a, b); | ||||
| 54537 | } | ||||
| 54538 | static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){ | ||||
| 54539 | return ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData))->xCurrentTimeInt64(ORIGVFS(pVfs)((sqlite3_vfs*)((pVfs)->pAppData)), p); | ||||
| 54540 | } | ||||
| 54541 | |||||
| 54542 | /* | ||||
| 54543 | ** Translate a database connection pointer and schema name into a | ||||
| 54544 | ** MemFile pointer. | ||||
| 54545 | */ | ||||
| 54546 | static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){ | ||||
| 54547 | MemFile *p = 0; | ||||
| 54548 | MemStore *pStore; | ||||
| 54549 | int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER7, &p); | ||||
| 54550 | if( rc ) return 0; | ||||
| 54551 | if( p->base.pMethods!=&memdb_io_methods ) return 0; | ||||
| 54552 | pStore = p->pStore; | ||||
| 54553 | memdbEnter(pStore); | ||||
| 54554 | if( pStore->zFName!=0 ) p = 0; | ||||
| 54555 | memdbLeave(pStore); | ||||
| 54556 | return p; | ||||
| 54557 | } | ||||
| 54558 | |||||
| 54559 | /* | ||||
| 54560 | ** Return the serialization of a database | ||||
| 54561 | */ | ||||
| 54562 | SQLITE_API unsigned char *sqlite3_serialize( | ||||
| 54563 | sqlite3 *db, /* The database connection */ | ||||
| 54564 | const char *zSchema, /* Which database within the connection */ | ||||
| 54565 | sqlite3_int64 *piSize, /* Write size here, if not NULL */ | ||||
| 54566 | unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */ | ||||
| 54567 | ){ | ||||
| 54568 | MemFile *p; | ||||
| 54569 | int iDb; | ||||
| 54570 | Btree *pBt; | ||||
| 54571 | sqlite3_int64 sz; | ||||
| 54572 | int szPage = 0; | ||||
| 54573 | sqlite3_stmt *pStmt = 0; | ||||
| 54574 | unsigned char *pOut; | ||||
| 54575 | char *zSql; | ||||
| 54576 | int rc; | ||||
| 54577 | |||||
| 54578 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 54579 | if( !sqlite3SafetyCheckOk(db) ){ | ||||
| 54580 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(54580); | ||||
| 54581 | return 0; | ||||
| 54582 | } | ||||
| 54583 | #endif | ||||
| 54584 | |||||
| 54585 | if( zSchema==0 ) zSchema = db->aDb[0].zDbSName; | ||||
| 54586 | p = memdbFromDbSchema(db, zSchema); | ||||
| 54587 | iDb = sqlite3FindDbName(db, zSchema); | ||||
| 54588 | if( piSize ) *piSize = -1; | ||||
| 54589 | if( iDb<0 ) return 0; | ||||
| 54590 | if( p ){ | ||||
| 54591 | MemStore *pStore = p->pStore; | ||||
| 54592 | assert( pStore->pMutex==0 )((void) (0)); | ||||
| 54593 | if( piSize ) *piSize = pStore->sz; | ||||
| 54594 | if( mFlags & SQLITE_SERIALIZE_NOCOPY0x001 ){ | ||||
| 54595 | pOut = pStore->aData; | ||||
| 54596 | }else{ | ||||
| 54597 | pOut = sqlite3_malloc64( pStore->sz ); | ||||
| 54598 | if( pOut ) memcpy(pOut, pStore->aData, pStore->sz); | ||||
| 54599 | } | ||||
| 54600 | return pOut; | ||||
| 54601 | } | ||||
| 54602 | pBt = db->aDb[iDb].pBt; | ||||
| 54603 | if( pBt==0 ) return 0; | ||||
| 54604 | szPage = sqlite3BtreeGetPageSize(pBt); | ||||
| 54605 | zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema); | ||||
| 54606 | rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM7; | ||||
| 54607 | sqlite3_free(zSql); | ||||
| 54608 | if( rc ) return 0; | ||||
| 54609 | rc = sqlite3_step(pStmt); | ||||
| 54610 | if( rc!=SQLITE_ROW100 ){ | ||||
| 54611 | pOut = 0; | ||||
| 54612 | }else{ | ||||
| 54613 | sz = sqlite3_column_int64(pStmt, 0)*szPage; | ||||
| 54614 | if( sz==0 ){ | ||||
| 54615 | sqlite3_reset(pStmt); | ||||
| 54616 | sqlite3_exec(db, "BEGIN IMMEDIATE; COMMIT;", 0, 0, 0); | ||||
| 54617 | rc = sqlite3_step(pStmt); | ||||
| 54618 | if( rc==SQLITE_ROW100 ){ | ||||
| 54619 | sz = sqlite3_column_int64(pStmt, 0)*szPage; | ||||
| 54620 | } | ||||
| 54621 | } | ||||
| 54622 | if( piSize ) *piSize = sz; | ||||
| 54623 | if( mFlags & SQLITE_SERIALIZE_NOCOPY0x001 ){ | ||||
| 54624 | pOut = 0; | ||||
| 54625 | }else{ | ||||
| 54626 | pOut = sqlite3_malloc64( sz ); | ||||
| 54627 | if( pOut ){ | ||||
| 54628 | int nPage = sqlite3_column_int(pStmt, 0); | ||||
| 54629 | Pager *pPager = sqlite3BtreePager(pBt); | ||||
| 54630 | int pgno; | ||||
| 54631 | for(pgno=1; pgno<=nPage; pgno++){ | ||||
| 54632 | DbPage *pPage = 0; | ||||
| 54633 | unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1); | ||||
| 54634 | rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0); | ||||
| 54635 | if( rc==SQLITE_OK0 ){ | ||||
| 54636 | memcpy(pTo, sqlite3PagerGetData(pPage), szPage); | ||||
| 54637 | }else{ | ||||
| 54638 | memset(pTo, 0, szPage); | ||||
| 54639 | } | ||||
| 54640 | sqlite3PagerUnref(pPage); | ||||
| 54641 | } | ||||
| 54642 | } | ||||
| 54643 | } | ||||
| 54644 | } | ||||
| 54645 | sqlite3_finalize(pStmt); | ||||
| 54646 | return pOut; | ||||
| 54647 | } | ||||
| 54648 | |||||
| 54649 | /* Convert zSchema to a MemDB and initialize its content. | ||||
| 54650 | */ | ||||
| 54651 | SQLITE_API int sqlite3_deserialize( | ||||
| 54652 | sqlite3 *db, /* The database connection */ | ||||
| 54653 | const char *zSchema, /* Which DB to reopen with the deserialization */ | ||||
| 54654 | unsigned char *pData, /* The serialized database content */ | ||||
| 54655 | sqlite3_int64 szDb, /* Number bytes in the deserialization */ | ||||
| 54656 | sqlite3_int64 szBuf, /* Total size of buffer pData[] */ | ||||
| 54657 | unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ | ||||
| 54658 | ){ | ||||
| 54659 | MemFile *p; | ||||
| 54660 | char *zSql; | ||||
| 54661 | sqlite3_stmt *pStmt = 0; | ||||
| 54662 | int rc; | ||||
| 54663 | int iDb; | ||||
| 54664 | |||||
| 54665 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 54666 | if( !sqlite3SafetyCheckOk(db) ){ | ||||
| 54667 | return SQLITE_MISUSE_BKPTsqlite3MisuseError(54667); | ||||
| 54668 | } | ||||
| 54669 | if( szDb<0 ) return SQLITE_MISUSE_BKPTsqlite3MisuseError(54669); | ||||
| 54670 | if( szBuf<0 ) return SQLITE_MISUSE_BKPTsqlite3MisuseError(54670); | ||||
| 54671 | #endif | ||||
| 54672 | |||||
| 54673 | sqlite3_mutex_enter(db->mutex); | ||||
| 54674 | if( zSchema==0 ) zSchema = db->aDb[0].zDbSName; | ||||
| 54675 | iDb = sqlite3FindDbName(db, zSchema); | ||||
| 54676 | testcase( iDb==1 ); | ||||
| 54677 | if( iDb<2 && iDb!=0 ){ | ||||
| 54678 | rc = SQLITE_ERROR1; | ||||
| 54679 | goto end_deserialize; | ||||
| 54680 | } | ||||
| 54681 | zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema); | ||||
| 54682 | if( zSql==0 ){ | ||||
| 54683 | rc = SQLITE_NOMEM7; | ||||
| 54684 | }else{ | ||||
| 54685 | rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); | ||||
| 54686 | sqlite3_free(zSql); | ||||
| 54687 | } | ||||
| 54688 | if( rc ) goto end_deserialize; | ||||
| 54689 | db->init.iDb = (u8)iDb; | ||||
| 54690 | db->init.reopenMemdb = 1; | ||||
| 54691 | rc = sqlite3_step(pStmt); | ||||
| 54692 | db->init.reopenMemdb = 0; | ||||
| 54693 | if( rc!=SQLITE_DONE101 ){ | ||||
| 54694 | rc = SQLITE_ERROR1; | ||||
| 54695 | goto end_deserialize; | ||||
| 54696 | } | ||||
| 54697 | p = memdbFromDbSchema(db, zSchema); | ||||
| 54698 | if( p==0 ){ | ||||
| 54699 | rc = SQLITE_ERROR1; | ||||
| 54700 | }else{ | ||||
| 54701 | MemStore *pStore = p->pStore; | ||||
| 54702 | pStore->aData = pData; | ||||
| 54703 | pData = 0; | ||||
| 54704 | pStore->sz = szDb; | ||||
| 54705 | pStore->szAlloc = szBuf; | ||||
| 54706 | pStore->szMax = szBuf; | ||||
| 54707 | if( pStore->szMax<sqlite3GlobalConfigsqlite3Config.mxMemdbSize ){ | ||||
| 54708 | pStore->szMax = sqlite3GlobalConfigsqlite3Config.mxMemdbSize; | ||||
| 54709 | } | ||||
| 54710 | pStore->mFlags = mFlags; | ||||
| 54711 | rc = SQLITE_OK0; | ||||
| 54712 | } | ||||
| 54713 | |||||
| 54714 | end_deserialize: | ||||
| 54715 | sqlite3_finalize(pStmt); | ||||
| 54716 | if( pData && (mFlags & SQLITE_DESERIALIZE_FREEONCLOSE1)!=0 ){ | ||||
| 54717 | sqlite3_free(pData); | ||||
| 54718 | } | ||||
| 54719 | sqlite3_mutex_leave(db->mutex); | ||||
| 54720 | return rc; | ||||
| 54721 | } | ||||
| 54722 | |||||
| 54723 | /* | ||||
| 54724 | ** Return true if the VFS is the memvfs. | ||||
| 54725 | */ | ||||
| 54726 | SQLITE_PRIVATEstatic int sqlite3IsMemdb(const sqlite3_vfs *pVfs){ | ||||
| 54727 | return pVfs==&memdb_vfs; | ||||
| 54728 | } | ||||
| 54729 | |||||
| 54730 | /* | ||||
| 54731 | ** This routine is called when the extension is loaded. | ||||
| 54732 | ** Register the new VFS. | ||||
| 54733 | */ | ||||
| 54734 | SQLITE_PRIVATEstatic int sqlite3MemdbInit(void){ | ||||
| 54735 | sqlite3_vfs *pLower = sqlite3_vfs_find(0); | ||||
| 54736 | unsigned int sz; | ||||
| 54737 | if( NEVER(pLower==0)(pLower==0) ) return SQLITE_ERROR1; | ||||
| 54738 | sz = pLower->szOsFile; | ||||
| 54739 | memdb_vfs.pAppData = pLower; | ||||
| 54740 | /* The following conditional can only be true when compiled for | ||||
| 54741 | ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0. We always leave | ||||
| 54742 | ** it in, to be safe, but it is marked as NO_TEST since there | ||||
| 54743 | ** is no way to reach it under most builds. */ | ||||
| 54744 | if( sz<sizeof(MemFile) ) sz = sizeof(MemFile); /*NO_TEST*/ | ||||
| 54745 | memdb_vfs.szOsFile = sz; | ||||
| 54746 | return sqlite3_vfs_register(&memdb_vfs, 0); | ||||
| 54747 | } | ||||
| 54748 | #endif /* SQLITE_OMIT_DESERIALIZE */ | ||||
| 54749 | |||||
| 54750 | /************** End of memdb.c ***********************************************/ | ||||
| 54751 | /************** Begin file bitvec.c ******************************************/ | ||||
| 54752 | /* | ||||
| 54753 | ** 2008 February 16 | ||||
| 54754 | ** | ||||
| 54755 | ** The author disclaims copyright to this source code. In place of | ||||
| 54756 | ** a legal notice, here is a blessing: | ||||
| 54757 | ** | ||||
| 54758 | ** May you do good and not evil. | ||||
| 54759 | ** May you find forgiveness for yourself and forgive others. | ||||
| 54760 | ** May you share freely, never taking more than you give. | ||||
| 54761 | ** | ||||
| 54762 | ************************************************************************* | ||||
| 54763 | ** This file implements an object that represents a fixed-length | ||||
| 54764 | ** bitmap. Bits are numbered starting with 1. | ||||
| 54765 | ** | ||||
| 54766 | ** A bitmap is used to record which pages of a database file have been | ||||
| 54767 | ** journalled during a transaction, or which pages have the "dont-write" | ||||
| 54768 | ** property. Usually only a few pages are meet either condition. | ||||
| 54769 | ** So the bitmap is usually sparse and has low cardinality. | ||||
| 54770 | ** But sometimes (for example when during a DROP of a large table) most | ||||
| 54771 | ** or all of the pages in a database can get journalled. In those cases, | ||||
| 54772 | ** the bitmap becomes dense with high cardinality. The algorithm needs | ||||
| 54773 | ** to handle both cases well. | ||||
| 54774 | ** | ||||
| 54775 | ** The size of the bitmap is fixed when the object is created. | ||||
| 54776 | ** | ||||
| 54777 | ** All bits are clear when the bitmap is created. Individual bits | ||||
| 54778 | ** may be set or cleared one at a time. | ||||
| 54779 | ** | ||||
| 54780 | ** Test operations are about 100 times more common that set operations. | ||||
| 54781 | ** Clear operations are exceedingly rare. There are usually between | ||||
| 54782 | ** 5 and 500 set operations per Bitvec object, though the number of sets can | ||||
| 54783 | ** sometimes grow into tens of thousands or larger. The size of the | ||||
| 54784 | ** Bitvec object is the number of pages in the database file at the | ||||
| 54785 | ** start of a transaction, and is thus usually less than a few thousand, | ||||
| 54786 | ** but can be as large as 2 billion for a really big database. | ||||
| 54787 | */ | ||||
| 54788 | /* #include "sqliteInt.h" */ | ||||
| 54789 | |||||
| 54790 | /* Size of the Bitvec structure in bytes. */ | ||||
| 54791 | #define BITVEC_SZ512 512 | ||||
| 54792 | |||||
| 54793 | /* Round the union size down to the nearest pointer boundary, since that's how | ||||
| 54794 | ** it will be aligned within the Bitvec struct. */ | ||||
| 54795 | #define BITVEC_USIZE(((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) \ | ||||
| 54796 | (((BITVEC_SZ512-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) | ||||
| 54797 | |||||
| 54798 | /* Type of the array "element" for the bitmap representation. | ||||
| 54799 | ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. | ||||
| 54800 | ** Setting this to the "natural word" size of your CPU may improve | ||||
| 54801 | ** performance. */ | ||||
| 54802 | #define BITVEC_TELEMu8 u8 | ||||
| 54803 | /* Size, in bits, of the bitmap element. */ | ||||
| 54804 | #define BITVEC_SZELEM8 8 | ||||
| 54805 | /* Number of elements in a bitmap array. */ | ||||
| 54806 | #define BITVEC_NELEM((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u8)) (BITVEC_USIZE(((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof(BITVEC_TELEMu8)) | ||||
| 54807 | /* Number of bits in the bitmap array. */ | ||||
| 54808 | #define BITVEC_NBIT(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u8))*8) (BITVEC_NELEM((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u8))*BITVEC_SZELEM8) | ||||
| 54809 | |||||
| 54810 | /* Number of u32 values in hash table. */ | ||||
| 54811 | #define BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32)) (BITVEC_USIZE(((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof(u32)) | ||||
| 54812 | /* Maximum number of entries in hash table before | ||||
| 54813 | ** sub-dividing and re-hashing. */ | ||||
| 54814 | #define BITVEC_MXHASH(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u32))/2) (BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32))/2) | ||||
| 54815 | /* Hashing function for the aHash representation. | ||||
| 54816 | ** Empirical testing showed that the *37 multiplier | ||||
| 54817 | ** (an arbitrary prime)in the hash function provided | ||||
| 54818 | ** no fewer collisions than the no-op *1. */ | ||||
| 54819 | #define BITVEC_HASH(X)(((X)*1)%((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec *))/sizeof(u32))) (((X)*1)%BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32))) | ||||
| 54820 | |||||
| 54821 | #define BITVEC_NPTR((u32)((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec *))/sizeof(Bitvec *))) ((u32)(BITVEC_USIZE(((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof(Bitvec *))) | ||||
| 54822 | |||||
| 54823 | |||||
| 54824 | /* | ||||
| 54825 | ** A bitmap is an instance of the following structure. | ||||
| 54826 | ** | ||||
| 54827 | ** This bitmap records the existence of zero or more bits | ||||
| 54828 | ** with values between 1 and iSize, inclusive. | ||||
| 54829 | ** | ||||
| 54830 | ** There are three possible representations of the bitmap. | ||||
| 54831 | ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight | ||||
| 54832 | ** bitmap. The least significant bit is bit 1. | ||||
| 54833 | ** | ||||
| 54834 | ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is | ||||
| 54835 | ** a hash table that will hold up to BITVEC_MXHASH distinct values. | ||||
| 54836 | ** | ||||
| 54837 | ** Otherwise, the value i is redirected into one of BITVEC_NPTR | ||||
| 54838 | ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap | ||||
| 54839 | ** handles up to iDivisor separate values of i. apSub[0] holds | ||||
| 54840 | ** values between 1 and iDivisor. apSub[1] holds values between | ||||
| 54841 | ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between | ||||
| 54842 | ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized | ||||
| 54843 | ** to hold deal with values between 1 and iDivisor. | ||||
| 54844 | */ | ||||
| 54845 | struct Bitvec { | ||||
| 54846 | u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ | ||||
| 54847 | u32 nSet; /* Number of bits that are set - only valid for aHash | ||||
| 54848 | ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, | ||||
| 54849 | ** this would be 125. */ | ||||
| 54850 | u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ | ||||
| 54851 | /* Should >=0 for apSub element. */ | ||||
| 54852 | /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ | ||||
| 54853 | /* For a BITVEC_SZ of 512, this would be 34,359,739. */ | ||||
| 54854 | union { | ||||
| 54855 | BITVEC_TELEMu8 aBitmap[BITVEC_NELEM((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u8))]; /* Bitmap representation */ | ||||
| 54856 | u32 aHash[BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32))]; /* Hash table representation */ | ||||
| 54857 | Bitvec *apSub[BITVEC_NPTR((u32)((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec *))/sizeof(Bitvec *)))]; /* Recursive representation */ | ||||
| 54858 | } u; | ||||
| 54859 | }; | ||||
| 54860 | |||||
| 54861 | /* | ||||
| 54862 | ** Create a new bitmap object able to handle bits between 0 and iSize, | ||||
| 54863 | ** inclusive. Return a pointer to the new object. Return NULL if | ||||
| 54864 | ** malloc fails. | ||||
| 54865 | */ | ||||
| 54866 | SQLITE_PRIVATEstatic Bitvec *sqlite3BitvecCreate(u32 iSize){ | ||||
| 54867 | Bitvec *p; | ||||
| 54868 | assert( sizeof(*p)==BITVEC_SZ )((void) (0)); | ||||
| 54869 | p = sqlite3MallocZero( sizeof(*p) ); | ||||
| 54870 | if( p ){ | ||||
| 54871 | p->iSize = iSize; | ||||
| 54872 | } | ||||
| 54873 | return p; | ||||
| 54874 | } | ||||
| 54875 | |||||
| 54876 | /* | ||||
| 54877 | ** Check to see if the i-th bit is set. Return true or false. | ||||
| 54878 | ** If p is NULL (if the bitmap has not been created) or if | ||||
| 54879 | ** i is out of range, then return false. | ||||
| 54880 | */ | ||||
| 54881 | SQLITE_PRIVATEstatic int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){ | ||||
| 54882 | assert( p!=0 )((void) (0)); | ||||
| 54883 | i--; | ||||
| 54884 | if( i>=p->iSize ) return 0; | ||||
| 54885 | while( p->iDivisor ){ | ||||
| 54886 | u32 bin = i/p->iDivisor; | ||||
| 54887 | i = i%p->iDivisor; | ||||
| 54888 | p = p->u.apSub[bin]; | ||||
| 54889 | if (!p) { | ||||
| 54890 | return 0; | ||||
| 54891 | } | ||||
| 54892 | } | ||||
| 54893 | if( p->iSize<=BITVEC_NBIT(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u8))*8) ){ | ||||
| 54894 | return (p->u.aBitmap[i/BITVEC_SZELEM8] & (1<<(i&(BITVEC_SZELEM8-1))))!=0; | ||||
| 54895 | } else{ | ||||
| 54896 | u32 h = BITVEC_HASH(i++)(((i++)*1)%((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof( Bitvec*))/sizeof(u32))); | ||||
| 54897 | while( p->u.aHash[h] ){ | ||||
| 54898 | if( p->u.aHash[h]==i ) return 1; | ||||
| 54899 | h = (h+1) % BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32)); | ||||
| 54900 | } | ||||
| 54901 | return 0; | ||||
| 54902 | } | ||||
| 54903 | } | ||||
| 54904 | SQLITE_PRIVATEstatic int sqlite3BitvecTest(Bitvec *p, u32 i){ | ||||
| 54905 | return p!=0 && sqlite3BitvecTestNotNull(p,i); | ||||
| 54906 | } | ||||
| 54907 | |||||
| 54908 | /* | ||||
| 54909 | ** Set the i-th bit. Return 0 on success and an error code if | ||||
| 54910 | ** anything goes wrong. | ||||
| 54911 | ** | ||||
| 54912 | ** This routine might cause sub-bitmaps to be allocated. Failing | ||||
| 54913 | ** to get the memory needed to hold the sub-bitmap is the only | ||||
| 54914 | ** that can go wrong with an insert, assuming p and i are valid. | ||||
| 54915 | ** | ||||
| 54916 | ** The calling function must ensure that p is a valid Bitvec object | ||||
| 54917 | ** and that the value for "i" is within range of the Bitvec object. | ||||
| 54918 | ** Otherwise the behavior is undefined. | ||||
| 54919 | */ | ||||
| 54920 | SQLITE_PRIVATEstatic int sqlite3BitvecSet(Bitvec *p, u32 i){ | ||||
| 54921 | u32 h; | ||||
| 54922 | if( p==0 ) return SQLITE_OK0; | ||||
| 54923 | assert( i>0 )((void) (0)); | ||||
| 54924 | assert( i<=p->iSize )((void) (0)); | ||||
| 54925 | i--; | ||||
| 54926 | while((p->iSize > BITVEC_NBIT(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u8))*8)) && p->iDivisor) { | ||||
| 54927 | u32 bin = i/p->iDivisor; | ||||
| 54928 | i = i%p->iDivisor; | ||||
| 54929 | if( p->u.apSub[bin]==0 ){ | ||||
| 54930 | p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor ); | ||||
| 54931 | if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 54932 | } | ||||
| 54933 | p = p->u.apSub[bin]; | ||||
| 54934 | } | ||||
| 54935 | if( p->iSize<=BITVEC_NBIT(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u8))*8) ){ | ||||
| 54936 | p->u.aBitmap[i/BITVEC_SZELEM8] |= 1 << (i&(BITVEC_SZELEM8-1)); | ||||
| 54937 | return SQLITE_OK0; | ||||
| 54938 | } | ||||
| 54939 | h = BITVEC_HASH(i++)(((i++)*1)%((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof( Bitvec*))/sizeof(u32))); | ||||
| 54940 | /* if there wasn't a hash collision, and this doesn't */ | ||||
| 54941 | /* completely fill the hash, then just add it without */ | ||||
| 54942 | /* worrying about sub-dividing and re-hashing. */ | ||||
| 54943 | if( !p->u.aHash[h] ){ | ||||
| 54944 | if (p->nSet<(BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32))-1)) { | ||||
| 54945 | goto bitvec_set_end; | ||||
| 54946 | } else { | ||||
| 54947 | goto bitvec_set_rehash; | ||||
| 54948 | } | ||||
| 54949 | } | ||||
| 54950 | /* there was a collision, check to see if it's already */ | ||||
| 54951 | /* in hash, if not, try to find a spot for it */ | ||||
| 54952 | do { | ||||
| 54953 | if( p->u.aHash[h]==i ) return SQLITE_OK0; | ||||
| 54954 | h++; | ||||
| 54955 | if( h>=BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32)) ) h = 0; | ||||
| 54956 | } while( p->u.aHash[h] ); | ||||
| 54957 | /* we didn't find it in the hash. h points to the first */ | ||||
| 54958 | /* available free spot. check to see if this is going to */ | ||||
| 54959 | /* make our hash too "full". */ | ||||
| 54960 | bitvec_set_rehash: | ||||
| 54961 | if( p->nSet>=BITVEC_MXHASH(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u32))/2) ){ | ||||
| 54962 | unsigned int j; | ||||
| 54963 | int rc; | ||||
| 54964 | u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash))sqlite3DbMallocRaw(0,sizeof(p->u.aHash)); | ||||
| 54965 | if( aiValues==0 ){ | ||||
| 54966 | return SQLITE_NOMEM_BKPT7; | ||||
| 54967 | }else{ | ||||
| 54968 | memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); | ||||
| 54969 | memset(p->u.apSub, 0, sizeof(p->u.apSub)); | ||||
| 54970 | p->iDivisor = p->iSize/BITVEC_NPTR((u32)((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec *))/sizeof(Bitvec *))); | ||||
| 54971 | if( (p->iSize%BITVEC_NPTR((u32)((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec *))/sizeof(Bitvec *))))!=0 ) p->iDivisor++; | ||||
| 54972 | if( p->iDivisor<BITVEC_NBIT(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u8))*8) ) p->iDivisor = BITVEC_NBIT(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u8))*8); | ||||
| 54973 | rc = sqlite3BitvecSet(p, i); | ||||
| 54974 | for(j=0; j<BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32)); j++){ | ||||
| 54975 | if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]); | ||||
| 54976 | } | ||||
| 54977 | sqlite3StackFree(0, aiValues)sqlite3DbFree(0,aiValues); | ||||
| 54978 | return rc; | ||||
| 54979 | } | ||||
| 54980 | } | ||||
| 54981 | bitvec_set_end: | ||||
| 54982 | p->nSet++; | ||||
| 54983 | p->u.aHash[h] = i; | ||||
| 54984 | return SQLITE_OK0; | ||||
| 54985 | } | ||||
| 54986 | |||||
| 54987 | /* | ||||
| 54988 | ** Clear the i-th bit. | ||||
| 54989 | ** | ||||
| 54990 | ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage | ||||
| 54991 | ** that BitvecClear can use to rebuilt its hash table. | ||||
| 54992 | */ | ||||
| 54993 | SQLITE_PRIVATEstatic void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ | ||||
| 54994 | if( p==0 ) return; | ||||
| 54995 | assert( i>0 )((void) (0)); | ||||
| 54996 | i--; | ||||
| 54997 | while( p->iDivisor ){ | ||||
| 54998 | u32 bin = i/p->iDivisor; | ||||
| 54999 | i = i%p->iDivisor; | ||||
| 55000 | p = p->u.apSub[bin]; | ||||
| 55001 | if (!p) { | ||||
| 55002 | return; | ||||
| 55003 | } | ||||
| 55004 | } | ||||
| 55005 | if( p->iSize<=BITVEC_NBIT(((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/ sizeof(u8))*8) ){ | ||||
| 55006 | p->u.aBitmap[i/BITVEC_SZELEM8] &= ~(BITVEC_TELEMu8)(1<<(i&(BITVEC_SZELEM8-1))); | ||||
| 55007 | }else{ | ||||
| 55008 | unsigned int j; | ||||
| 55009 | u32 *aiValues = pBuf; | ||||
| 55010 | memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); | ||||
| 55011 | memset(p->u.aHash, 0, sizeof(p->u.aHash)); | ||||
| 55012 | p->nSet = 0; | ||||
| 55013 | for(j=0; j<BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32)); j++){ | ||||
| 55014 | if( aiValues[j] && aiValues[j]!=(i+1) ){ | ||||
| 55015 | u32 h = BITVEC_HASH(aiValues[j]-1)(((aiValues[j]-1)*1)%((((512 -(3*sizeof(u32)))/sizeof(Bitvec* ))*sizeof(Bitvec*))/sizeof(u32))); | ||||
| 55016 | p->nSet++; | ||||
| 55017 | while( p->u.aHash[h] ){ | ||||
| 55018 | h++; | ||||
| 55019 | if( h>=BITVEC_NINT((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))/sizeof (u32)) ) h = 0; | ||||
| 55020 | } | ||||
| 55021 | p->u.aHash[h] = aiValues[j]; | ||||
| 55022 | } | ||||
| 55023 | } | ||||
| 55024 | } | ||||
| 55025 | } | ||||
| 55026 | |||||
| 55027 | /* | ||||
| 55028 | ** Destroy a bitmap object. Reclaim all memory used. | ||||
| 55029 | */ | ||||
| 55030 | SQLITE_PRIVATEstatic void sqlite3BitvecDestroy(Bitvec *p){ | ||||
| 55031 | if( p==0 ) return; | ||||
| 55032 | if( p->iDivisor ){ | ||||
| 55033 | unsigned int i; | ||||
| 55034 | for(i=0; i<BITVEC_NPTR((u32)((((512 -(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec *))/sizeof(Bitvec *))); i++){ | ||||
| 55035 | sqlite3BitvecDestroy(p->u.apSub[i]); | ||||
| 55036 | } | ||||
| 55037 | } | ||||
| 55038 | sqlite3_free(p); | ||||
| 55039 | } | ||||
| 55040 | |||||
| 55041 | /* | ||||
| 55042 | ** Return the value of the iSize parameter specified when Bitvec *p | ||||
| 55043 | ** was created. | ||||
| 55044 | */ | ||||
| 55045 | SQLITE_PRIVATEstatic u32 sqlite3BitvecSize(Bitvec *p){ | ||||
| 55046 | return p->iSize; | ||||
| 55047 | } | ||||
| 55048 | |||||
| 55049 | #ifndef SQLITE_UNTESTABLE | ||||
| 55050 | /* | ||||
| 55051 | ** Let V[] be an array of unsigned characters sufficient to hold | ||||
| 55052 | ** up to N bits. Let I be an integer between 0 and N. 0<=I<N. | ||||
| 55053 | ** Then the following macros can be used to set, clear, or test | ||||
| 55054 | ** individual bits within V. | ||||
| 55055 | */ | ||||
| 55056 | #define SETBIT(V,I)V[I>>3] |= (1<<(I&7)) V[I>>3] |= (1<<(I&7)) | ||||
| 55057 | #define CLEARBIT(V,I)V[I>>3] &= ~(u8)(1<<(I&7)) V[I>>3] &= ~(BITVEC_TELEMu8)(1<<(I&7)) | ||||
| 55058 | #define TESTBIT(V,I)(V[I>>3]&(1<<(I&7)))!=0 (V[I>>3]&(1<<(I&7)))!=0 | ||||
| 55059 | |||||
| 55060 | /* | ||||
| 55061 | ** This routine runs an extensive test of the Bitvec code. | ||||
| 55062 | ** | ||||
| 55063 | ** The input is an array of integers that acts as a program | ||||
| 55064 | ** to test the Bitvec. The integers are opcodes followed | ||||
| 55065 | ** by 0, 1, or 3 operands, depending on the opcode. Another | ||||
| 55066 | ** opcode follows immediately after the last operand. | ||||
| 55067 | ** | ||||
| 55068 | ** There are 6 opcodes numbered from 0 through 5. 0 is the | ||||
| 55069 | ** "halt" opcode and causes the test to end. | ||||
| 55070 | ** | ||||
| 55071 | ** 0 Halt and return the number of errors | ||||
| 55072 | ** 1 N S X Set N bits beginning with S and incrementing by X | ||||
| 55073 | ** 2 N S X Clear N bits beginning with S and incrementing by X | ||||
| 55074 | ** 3 N Set N randomly chosen bits | ||||
| 55075 | ** 4 N Clear N randomly chosen bits | ||||
| 55076 | ** 5 N S X Set N bits from S increment X in array only, not in bitvec | ||||
| 55077 | ** | ||||
| 55078 | ** The opcodes 1 through 4 perform set and clear operations are performed | ||||
| 55079 | ** on both a Bitvec object and on a linear array of bits obtained from malloc. | ||||
| 55080 | ** Opcode 5 works on the linear array only, not on the Bitvec. | ||||
| 55081 | ** Opcode 5 is used to deliberately induce a fault in order to | ||||
| 55082 | ** confirm that error detection works. | ||||
| 55083 | ** | ||||
| 55084 | ** At the conclusion of the test the linear array is compared | ||||
| 55085 | ** against the Bitvec object. If there are any differences, | ||||
| 55086 | ** an error is returned. If they are the same, zero is returned. | ||||
| 55087 | ** | ||||
| 55088 | ** If a memory allocation error occurs, return -1. | ||||
| 55089 | */ | ||||
| 55090 | SQLITE_PRIVATEstatic int sqlite3BitvecBuiltinTest(int sz, int *aOp){ | ||||
| 55091 | Bitvec *pBitvec = 0; | ||||
| 55092 | unsigned char *pV = 0; | ||||
| 55093 | int rc = -1; | ||||
| 55094 | int i, nx, pc, op; | ||||
| 55095 | void *pTmpSpace; | ||||
| 55096 | |||||
| 55097 | /* Allocate the Bitvec to be tested and a linear array of | ||||
| 55098 | ** bits to act as the reference */ | ||||
| 55099 | pBitvec = sqlite3BitvecCreate( sz ); | ||||
| 55100 | pV = sqlite3MallocZero( (7+(i64)sz)/8 + 1 ); | ||||
| 55101 | pTmpSpace = sqlite3_malloc64(BITVEC_SZ512); | ||||
| 55102 | if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end; | ||||
| 55103 | |||||
| 55104 | /* NULL pBitvec tests */ | ||||
| 55105 | sqlite3BitvecSet(0, 1); | ||||
| 55106 | sqlite3BitvecClear(0, 1, pTmpSpace); | ||||
| 55107 | |||||
| 55108 | /* Run the program */ | ||||
| 55109 | pc = i = 0; | ||||
| 55110 | while( (op = aOp[pc])!=0 ){ | ||||
| 55111 | switch( op ){ | ||||
| 55112 | case 1: | ||||
| 55113 | case 2: | ||||
| 55114 | case 5: { | ||||
| 55115 | nx = 4; | ||||
| 55116 | i = aOp[pc+2] - 1; | ||||
| 55117 | aOp[pc+2] += aOp[pc+3]; | ||||
| 55118 | break; | ||||
| 55119 | } | ||||
| 55120 | case 3: | ||||
| 55121 | case 4: | ||||
| 55122 | default: { | ||||
| 55123 | nx = 2; | ||||
| 55124 | sqlite3_randomness(sizeof(i), &i); | ||||
| 55125 | break; | ||||
| 55126 | } | ||||
| 55127 | } | ||||
| 55128 | if( (--aOp[pc+1]) > 0 ) nx = 0; | ||||
| 55129 | pc += nx; | ||||
| 55130 | i = (i & 0x7fffffff)%sz; | ||||
| 55131 | if( (op & 1)!=0 ){ | ||||
| 55132 | SETBIT(pV, (i+1))pV[(i+1)>>3] |= (1<<((i+1)&7)); | ||||
| 55133 | if( op!=5 ){ | ||||
| 55134 | if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; | ||||
| 55135 | } | ||||
| 55136 | }else{ | ||||
| 55137 | CLEARBIT(pV, (i+1))pV[(i+1)>>3] &= ~(u8)(1<<((i+1)&7)); | ||||
| 55138 | sqlite3BitvecClear(pBitvec, i+1, pTmpSpace); | ||||
| 55139 | } | ||||
| 55140 | } | ||||
| 55141 | |||||
| 55142 | /* Test to make sure the linear array exactly matches the | ||||
| 55143 | ** Bitvec object. Start with the assumption that they do | ||||
| 55144 | ** match (rc==0). Change rc to non-zero if a discrepancy | ||||
| 55145 | ** is found. | ||||
| 55146 | */ | ||||
| 55147 | rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) | ||||
| 55148 | + sqlite3BitvecTest(pBitvec, 0) | ||||
| 55149 | + (sqlite3BitvecSize(pBitvec) - sz); | ||||
| 55150 | for(i=1; i<=sz; i++){ | ||||
| 55151 | if( (TESTBIT(pV,i)(pV[i>>3]&(1<<(i&7)))!=0)!=sqlite3BitvecTest(pBitvec,i) ){ | ||||
| 55152 | rc = i; | ||||
| 55153 | break; | ||||
| 55154 | } | ||||
| 55155 | } | ||||
| 55156 | |||||
| 55157 | /* Free allocated structure */ | ||||
| 55158 | bitvec_end: | ||||
| 55159 | sqlite3_free(pTmpSpace); | ||||
| 55160 | sqlite3_free(pV); | ||||
| 55161 | sqlite3BitvecDestroy(pBitvec); | ||||
| 55162 | return rc; | ||||
| 55163 | } | ||||
| 55164 | #endif /* SQLITE_UNTESTABLE */ | ||||
| 55165 | |||||
| 55166 | /************** End of bitvec.c **********************************************/ | ||||
| 55167 | /************** Begin file pcache.c ******************************************/ | ||||
| 55168 | /* | ||||
| 55169 | ** 2008 August 05 | ||||
| 55170 | ** | ||||
| 55171 | ** The author disclaims copyright to this source code. In place of | ||||
| 55172 | ** a legal notice, here is a blessing: | ||||
| 55173 | ** | ||||
| 55174 | ** May you do good and not evil. | ||||
| 55175 | ** May you find forgiveness for yourself and forgive others. | ||||
| 55176 | ** May you share freely, never taking more than you give. | ||||
| 55177 | ** | ||||
| 55178 | ************************************************************************* | ||||
| 55179 | ** This file implements that page cache. | ||||
| 55180 | */ | ||||
| 55181 | /* #include "sqliteInt.h" */ | ||||
| 55182 | |||||
| 55183 | /* | ||||
| 55184 | ** A complete page cache is an instance of this structure. Every | ||||
| 55185 | ** entry in the cache holds a single page of the database file. The | ||||
| 55186 | ** btree layer only operates on the cached copy of the database pages. | ||||
| 55187 | ** | ||||
| 55188 | ** A page cache entry is "clean" if it exactly matches what is currently | ||||
| 55189 | ** on disk. A page is "dirty" if it has been modified and needs to be | ||||
| 55190 | ** persisted to disk. | ||||
| 55191 | ** | ||||
| 55192 | ** pDirty, pDirtyTail, pSynced: | ||||
| 55193 | ** All dirty pages are linked into the doubly linked list using | ||||
| 55194 | ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order | ||||
| 55195 | ** such that p was added to the list more recently than p->pDirtyNext. | ||||
| 55196 | ** PCache.pDirty points to the first (newest) element in the list and | ||||
| 55197 | ** pDirtyTail to the last (oldest). | ||||
| 55198 | ** | ||||
| 55199 | ** The PCache.pSynced variable is used to optimize searching for a dirty | ||||
| 55200 | ** page to eject from the cache mid-transaction. It is better to eject | ||||
| 55201 | ** a page that does not require a journal sync than one that does. | ||||
| 55202 | ** Therefore, pSynced is maintained so that it *almost* always points | ||||
| 55203 | ** to either the oldest page in the pDirty/pDirtyTail list that has a | ||||
| 55204 | ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one | ||||
| 55205 | ** (so that the right page to eject can be found by following pDirtyPrev | ||||
| 55206 | ** pointers). | ||||
| 55207 | */ | ||||
| 55208 | struct PCache { | ||||
| 55209 | PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */ | ||||
| 55210 | PgHdr *pSynced; /* Last synced page in dirty page list */ | ||||
| 55211 | i64 nRefSum; /* Sum of ref counts over all pages */ | ||||
| 55212 | int szCache; /* Configured cache size */ | ||||
| 55213 | int szSpill; /* Size before spilling occurs */ | ||||
| 55214 | int szPage; /* Size of every page in this cache */ | ||||
| 55215 | int szExtra; /* Size of extra space for each page */ | ||||
| 55216 | u8 bPurgeable; /* True if pages are on backing store */ | ||||
| 55217 | u8 eCreate; /* eCreate value for for xFetch() */ | ||||
| 55218 | int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */ | ||||
| 55219 | void *pStress; /* Argument to xStress */ | ||||
| 55220 | sqlite3_pcache *pCache; /* Pluggable cache module */ | ||||
| 55221 | }; | ||||
| 55222 | |||||
| 55223 | /********************************** Test and Debug Logic **********************/ | ||||
| 55224 | /* | ||||
| 55225 | ** Debug tracing macros. Enable by by changing the "0" to "1" and | ||||
| 55226 | ** recompiling. | ||||
| 55227 | ** | ||||
| 55228 | ** When sqlite3PcacheTrace is 1, single line trace messages are issued. | ||||
| 55229 | ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries | ||||
| 55230 | ** is displayed for many operations, resulting in a lot of output. | ||||
| 55231 | */ | ||||
| 55232 | #if defined(SQLITE_DEBUG) && 0 | ||||
| 55233 | int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */ | ||||
| 55234 | int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */ | ||||
| 55235 | # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;} | ||||
| 55236 | static void pcachePageTrace(int i, sqlite3_pcache_page *pLower){ | ||||
| 55237 | PgHdr *pPg; | ||||
| 55238 | unsigned char *a; | ||||
| 55239 | int j; | ||||
| 55240 | if( pLower==0 ){ | ||||
| 55241 | printf("%3d: NULL\n", i); | ||||
| 55242 | }else{ | ||||
| 55243 | pPg = (PgHdr*)pLower->pExtra; | ||||
| 55244 | printf("%3d: nRef %2lld flgs %02x data ", i, pPg->nRef, pPg->flags); | ||||
| 55245 | a = (unsigned char *)pLower->pBuf; | ||||
| 55246 | for(j=0; j<12; j++) printf("%02x", a[j]); | ||||
| 55247 | printf(" ptr %p\n", pPg); | ||||
| 55248 | } | ||||
| 55249 | } | ||||
| 55250 | static void pcacheDump(PCache *pCache){ | ||||
| 55251 | int N; | ||||
| 55252 | int i; | ||||
| 55253 | sqlite3_pcache_page *pLower; | ||||
| 55254 | |||||
| 55255 | if( sqlite3PcacheTrace<2 ) return; | ||||
| 55256 | if( pCache->pCache==0 ) return; | ||||
| 55257 | N = sqlite3PcachePagecount(pCache); | ||||
| 55258 | if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump; | ||||
| 55259 | for(i=1; i<=N; i++){ | ||||
| 55260 | pLower = sqlite3GlobalConfigsqlite3Config.pcache2.xFetch(pCache->pCache, i, 0); | ||||
| 55261 | pcachePageTrace(i, pLower); | ||||
| 55262 | if( pLower && ((PgHdr*)pLower)->pPage==0 ){ | ||||
| 55263 | sqlite3GlobalConfigsqlite3Config.pcache2.xUnpin(pCache->pCache, pLower, 0); | ||||
| 55264 | } | ||||
| 55265 | } | ||||
| 55266 | } | ||||
| 55267 | #else | ||||
| 55268 | # define pcacheTrace(X) | ||||
| 55269 | # define pcachePageTrace(PGNO, X) | ||||
| 55270 | # define pcacheDump(X) | ||||
| 55271 | #endif | ||||
| 55272 | |||||
| 55273 | /* | ||||
| 55274 | ** Return 1 if pPg is on the dirty list for pCache. Return 0 if not. | ||||
| 55275 | ** This routine runs inside of assert() statements only. | ||||
| 55276 | */ | ||||
| 55277 | #if defined(SQLITE_ENABLE_EXPENSIVE_ASSERT) | ||||
| 55278 | static int pageOnDirtyList(PCache *pCache, PgHdr *pPg)1{ | ||||
| 55279 | PgHdr *p; | ||||
| 55280 | for(p=pCache->pDirty; p; p=p->pDirtyNext){ | ||||
| 55281 | if( p==pPg ) return 1; | ||||
| 55282 | } | ||||
| 55283 | return 0; | ||||
| 55284 | } | ||||
| 55285 | static int pageNotOnDirtyList(PCache *pCache, PgHdr *pPg)1{ | ||||
| 55286 | PgHdr *p; | ||||
| 55287 | for(p=pCache->pDirty; p; p=p->pDirtyNext){ | ||||
| 55288 | if( p==pPg ) return 0; | ||||
| 55289 | } | ||||
| 55290 | return 1; | ||||
| 55291 | } | ||||
| 55292 | #else | ||||
| 55293 | # define pageOnDirtyList(A,B)1 1 | ||||
| 55294 | # define pageNotOnDirtyList(A,B)1 1 | ||||
| 55295 | #endif | ||||
| 55296 | |||||
| 55297 | /* | ||||
| 55298 | ** Check invariants on a PgHdr entry. Return true if everything is OK. | ||||
| 55299 | ** Return false if any invariant is violated. | ||||
| 55300 | ** | ||||
| 55301 | ** This routine is for use inside of assert() statements only. For | ||||
| 55302 | ** example: | ||||
| 55303 | ** | ||||
| 55304 | ** assert( sqlite3PcachePageSanity(pPg) ); | ||||
| 55305 | */ | ||||
| 55306 | #ifdef SQLITE_DEBUG | ||||
| 55307 | SQLITE_PRIVATEstatic int sqlite3PcachePageSanity(PgHdr *pPg){ | ||||
| 55308 | PCache *pCache; | ||||
| 55309 | assert( pPg!=0 )((void) (0)); | ||||
| 55310 | assert( pPg->pgno>0 || pPg->pPager==0 )((void) (0)); /* Page number is 1 or more */ | ||||
| 55311 | pCache = pPg->pCache; | ||||
| 55312 | assert( pCache!=0 )((void) (0)); /* Every page has an associated PCache */ | ||||
| 55313 | if( pPg->flags & PGHDR_CLEAN0x001 ){ | ||||
| 55314 | assert( (pPg->flags & PGHDR_DIRTY)==0 )((void) (0));/* Cannot be both CLEAN and DIRTY */ | ||||
| 55315 | assert( pageNotOnDirtyList(pCache, pPg) )((void) (0));/* CLEAN pages not on dirtylist */ | ||||
| 55316 | }else{ | ||||
| 55317 | assert( (pPg->flags & PGHDR_DIRTY)!=0 )((void) (0));/* If not CLEAN must be DIRTY */ | ||||
| 55318 | assert( pPg->pDirtyNext==0 || pPg->pDirtyNext->pDirtyPrev==pPg )((void) (0)); | ||||
| 55319 | assert( pPg->pDirtyPrev==0 || pPg->pDirtyPrev->pDirtyNext==pPg )((void) (0)); | ||||
| 55320 | assert( pPg->pDirtyPrev!=0 || pCache->pDirty==pPg )((void) (0)); | ||||
| 55321 | assert( pageOnDirtyList(pCache, pPg) )((void) (0)); | ||||
| 55322 | } | ||||
| 55323 | /* WRITEABLE pages must also be DIRTY */ | ||||
| 55324 | if( pPg->flags & PGHDR_WRITEABLE0x004 ){ | ||||
| 55325 | assert( pPg->flags & PGHDR_DIRTY )((void) (0)); /* WRITEABLE implies DIRTY */ | ||||
| 55326 | } | ||||
| 55327 | /* NEED_SYNC can be set independently of WRITEABLE. This can happen, | ||||
| 55328 | ** for example, when using the sqlite3PagerDontWrite() optimization: | ||||
| 55329 | ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK. | ||||
| 55330 | ** (2) Page X moved to freelist, WRITEABLE is cleared | ||||
| 55331 | ** (3) Page X reused, WRITEABLE is set again | ||||
| 55332 | ** If NEED_SYNC had been cleared in step 2, then it would not be reset | ||||
| 55333 | ** in step 3, and page might be written into the database without first | ||||
| 55334 | ** syncing the rollback journal, which might cause corruption on a power | ||||
| 55335 | ** loss. | ||||
| 55336 | ** | ||||
| 55337 | ** Another example is when the database page size is smaller than the | ||||
| 55338 | ** disk sector size. When any page of a sector is journalled, all pages | ||||
| 55339 | ** in that sector are marked NEED_SYNC even if they are still CLEAN, just | ||||
| 55340 | ** in case they are later modified, since all pages in the same sector | ||||
| 55341 | ** must be journalled and synced before any of those pages can be safely | ||||
| 55342 | ** written. | ||||
| 55343 | */ | ||||
| 55344 | return 1; | ||||
| 55345 | } | ||||
| 55346 | #endif /* SQLITE_DEBUG */ | ||||
| 55347 | |||||
| 55348 | |||||
| 55349 | /********************************** Linked List Management ********************/ | ||||
| 55350 | |||||
| 55351 | /* Allowed values for second argument to pcacheManageDirtyList() */ | ||||
| 55352 | #define PCACHE_DIRTYLIST_REMOVE1 1 /* Remove pPage from dirty list */ | ||||
| 55353 | #define PCACHE_DIRTYLIST_ADD2 2 /* Add pPage to the dirty list */ | ||||
| 55354 | #define PCACHE_DIRTYLIST_FRONT3 3 /* Move pPage to the front of the list */ | ||||
| 55355 | |||||
| 55356 | /* | ||||
| 55357 | ** Manage pPage's participation on the dirty list. Bits of the addRemove | ||||
| 55358 | ** argument determines what operation to do. The 0x01 bit means first | ||||
| 55359 | ** remove pPage from the dirty list. The 0x02 means add pPage back to | ||||
| 55360 | ** the dirty list. Doing both moves pPage to the front of the dirty list. | ||||
| 55361 | */ | ||||
| 55362 | static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){ | ||||
| 55363 | PCache *p = pPage->pCache; | ||||
| 55364 | |||||
| 55365 | pcacheTrace(("%p.DIRTYLIST.%s %d\n", p, | ||||
| 55366 | addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT", | ||||
| 55367 | pPage->pgno)); | ||||
| 55368 | if( addRemove & PCACHE_DIRTYLIST_REMOVE1 ){ | ||||
| 55369 | assert( pPage->pDirtyNext || pPage==p->pDirtyTail )((void) (0)); | ||||
| 55370 | assert( pPage->pDirtyPrev || pPage==p->pDirty )((void) (0)); | ||||
| 55371 | |||||
| 55372 | /* Update the PCache1.pSynced variable if necessary. */ | ||||
| 55373 | if( p->pSynced==pPage ){ | ||||
| 55374 | p->pSynced = pPage->pDirtyPrev; | ||||
| 55375 | } | ||||
| 55376 | |||||
| 55377 | if( pPage->pDirtyNext ){ | ||||
| 55378 | pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev; | ||||
| 55379 | }else{ | ||||
| 55380 | assert( pPage==p->pDirtyTail )((void) (0)); | ||||
| 55381 | p->pDirtyTail = pPage->pDirtyPrev; | ||||
| 55382 | } | ||||
| 55383 | if( pPage->pDirtyPrev ){ | ||||
| 55384 | pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext; | ||||
| 55385 | }else{ | ||||
| 55386 | /* If there are now no dirty pages in the cache, set eCreate to 2. | ||||
| 55387 | ** This is an optimization that allows sqlite3PcacheFetch() to skip | ||||
| 55388 | ** searching for a dirty page to eject from the cache when it might | ||||
| 55389 | ** otherwise have to. */ | ||||
| 55390 | assert( pPage==p->pDirty )((void) (0)); | ||||
| 55391 | p->pDirty = pPage->pDirtyNext; | ||||
| 55392 | assert( p->bPurgeable || p->eCreate==2 )((void) (0)); | ||||
| 55393 | if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/ | ||||
| 55394 | assert( p->bPurgeable==0 || p->eCreate==1 )((void) (0)); | ||||
| 55395 | p->eCreate = 2; | ||||
| 55396 | } | ||||
| 55397 | } | ||||
| 55398 | } | ||||
| 55399 | if( addRemove & PCACHE_DIRTYLIST_ADD2 ){ | ||||
| 55400 | pPage->pDirtyPrev = 0; | ||||
| 55401 | pPage->pDirtyNext = p->pDirty; | ||||
| 55402 | if( pPage->pDirtyNext ){ | ||||
| 55403 | assert( pPage->pDirtyNext->pDirtyPrev==0 )((void) (0)); | ||||
| 55404 | pPage->pDirtyNext->pDirtyPrev = pPage; | ||||
| 55405 | }else{ | ||||
| 55406 | p->pDirtyTail = pPage; | ||||
| 55407 | if( p->bPurgeable ){ | ||||
| 55408 | assert( p->eCreate==2 )((void) (0)); | ||||
| 55409 | p->eCreate = 1; | ||||
| 55410 | } | ||||
| 55411 | } | ||||
| 55412 | p->pDirty = pPage; | ||||
| 55413 | |||||
| 55414 | /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set | ||||
| 55415 | ** pSynced to point to it. Checking the NEED_SYNC flag is an | ||||
| 55416 | ** optimization, as if pSynced points to a page with the NEED_SYNC | ||||
| 55417 | ** flag set sqlite3PcacheFetchStress() searches through all newer | ||||
| 55418 | ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */ | ||||
| 55419 | if( !p->pSynced | ||||
| 55420 | && 0==(pPage->flags&PGHDR_NEED_SYNC0x008) /*OPTIMIZATION-IF-FALSE*/ | ||||
| 55421 | ){ | ||||
| 55422 | p->pSynced = pPage; | ||||
| 55423 | } | ||||
| 55424 | } | ||||
| 55425 | pcacheDump(p); | ||||
| 55426 | } | ||||
| 55427 | |||||
| 55428 | /* | ||||
| 55429 | ** Wrapper around the pluggable caches xUnpin method. If the cache is | ||||
| 55430 | ** being used for an in-memory database, this function is a no-op. | ||||
| 55431 | */ | ||||
| 55432 | static void pcacheUnpin(PgHdr *p){ | ||||
| 55433 | if( p->pCache->bPurgeable ){ | ||||
| 55434 | pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno)); | ||||
| 55435 | sqlite3GlobalConfigsqlite3Config.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0); | ||||
| 55436 | pcacheDump(p->pCache); | ||||
| 55437 | } | ||||
| 55438 | } | ||||
| 55439 | |||||
| 55440 | /* | ||||
| 55441 | ** Compute the number of pages of cache requested. p->szCache is the | ||||
| 55442 | ** cache size requested by the "PRAGMA cache_size" statement. | ||||
| 55443 | */ | ||||
| 55444 | static int numberOfCachePages(PCache *p){ | ||||
| 55445 | if( p->szCache>=0 ){ | ||||
| 55446 | /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the | ||||
| 55447 | ** suggested cache size is set to N. */ | ||||
| 55448 | return p->szCache; | ||||
| 55449 | }else{ | ||||
| 55450 | i64 n; | ||||
| 55451 | /* IMPLEMENTATION-OF: R-59858-46238 If the argument N is negative, then the | ||||
| 55452 | ** number of cache pages is adjusted to be a number of pages that would | ||||
| 55453 | ** use approximately abs(N*1024) bytes of memory based on the current | ||||
| 55454 | ** page size. */ | ||||
| 55455 | n = ((-1024*(i64)p->szCache)/(p->szPage+p->szExtra)); | ||||
| 55456 | if( n>1000000000 ) n = 1000000000; | ||||
| 55457 | return (int)n; | ||||
| 55458 | } | ||||
| 55459 | } | ||||
| 55460 | |||||
| 55461 | /*************************************************** General Interfaces ****** | ||||
| 55462 | ** | ||||
| 55463 | ** Initialize and shutdown the page cache subsystem. Neither of these | ||||
| 55464 | ** functions are threadsafe. | ||||
| 55465 | */ | ||||
| 55466 | SQLITE_PRIVATEstatic int sqlite3PcacheInitialize(void){ | ||||
| 55467 | if( sqlite3GlobalConfigsqlite3Config.pcache2.xInit==0 ){ | ||||
| 55468 | /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the | ||||
| 55469 | ** built-in default page cache is used instead of the application defined | ||||
| 55470 | ** page cache. */ | ||||
| 55471 | sqlite3PCacheSetDefault(); | ||||
| 55472 | assert( sqlite3GlobalConfig.pcache2.xInit!=0 )((void) (0)); | ||||
| 55473 | } | ||||
| 55474 | return sqlite3GlobalConfigsqlite3Config.pcache2.xInit(sqlite3GlobalConfigsqlite3Config.pcache2.pArg); | ||||
| 55475 | } | ||||
| 55476 | SQLITE_PRIVATEstatic void sqlite3PcacheShutdown(void){ | ||||
| 55477 | if( sqlite3GlobalConfigsqlite3Config.pcache2.xShutdown ){ | ||||
| 55478 | /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ | ||||
| 55479 | sqlite3GlobalConfigsqlite3Config.pcache2.xShutdown(sqlite3GlobalConfigsqlite3Config.pcache2.pArg); | ||||
| 55480 | } | ||||
| 55481 | } | ||||
| 55482 | |||||
| 55483 | /* | ||||
| 55484 | ** Return the size in bytes of a PCache object. | ||||
| 55485 | */ | ||||
| 55486 | SQLITE_PRIVATEstatic int sqlite3PcacheSize(void){ return sizeof(PCache); } | ||||
| 55487 | |||||
| 55488 | /* | ||||
| 55489 | ** Create a new PCache object. Storage space to hold the object | ||||
| 55490 | ** has already been allocated and is passed in as the p pointer. | ||||
| 55491 | ** The caller discovers how much space needs to be allocated by | ||||
| 55492 | ** calling sqlite3PcacheSize(). | ||||
| 55493 | ** | ||||
| 55494 | ** szExtra is some extra space allocated for each page. The first | ||||
| 55495 | ** 8 bytes of the extra space will be zeroed as the page is allocated, | ||||
| 55496 | ** but remaining content will be uninitialized. Though it is opaque | ||||
| 55497 | ** to this module, the extra space really ends up being the MemPage | ||||
| 55498 | ** structure in the pager. | ||||
| 55499 | */ | ||||
| 55500 | SQLITE_PRIVATEstatic int sqlite3PcacheOpen( | ||||
| 55501 | int szPage, /* Size of every page */ | ||||
| 55502 | int szExtra, /* Extra space associated with each page */ | ||||
| 55503 | int bPurgeable, /* True if pages are on backing store */ | ||||
| 55504 | int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */ | ||||
| 55505 | void *pStress, /* Argument to xStress */ | ||||
| 55506 | PCache *p /* Preallocated space for the PCache */ | ||||
| 55507 | ){ | ||||
| 55508 | memset(p, 0, sizeof(PCache)); | ||||
| 55509 | p->szPage = 1; | ||||
| 55510 | p->szExtra = szExtra; | ||||
| 55511 | assert( szExtra>=8 )((void) (0)); /* First 8 bytes will be zeroed */ | ||||
| 55512 | p->bPurgeable = bPurgeable; | ||||
| 55513 | p->eCreate = 2; | ||||
| 55514 | p->xStress = xStress; | ||||
| 55515 | p->pStress = pStress; | ||||
| 55516 | p->szCache = 100; | ||||
| 55517 | p->szSpill = 1; | ||||
| 55518 | pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable)); | ||||
| 55519 | return sqlite3PcacheSetPageSize(p, szPage); | ||||
| 55520 | } | ||||
| 55521 | |||||
| 55522 | /* | ||||
| 55523 | ** Change the page size for PCache object. The caller must ensure that there | ||||
| 55524 | ** are no outstanding page references when this function is called. | ||||
| 55525 | */ | ||||
| 55526 | SQLITE_PRIVATEstatic int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ | ||||
| 55527 | assert( pCache->nRefSum==0 && pCache->pDirty==0 )((void) (0)); | ||||
| 55528 | if( pCache->szPage ){ | ||||
| 55529 | sqlite3_pcache *pNew; | ||||
| 55530 | pNew = sqlite3GlobalConfigsqlite3Config.pcache2.xCreate( | ||||
| 55531 | szPage, pCache->szExtra + ROUND8(sizeof(PgHdr))(((sizeof(PgHdr))+7)&~7), | ||||
| 55532 | pCache->bPurgeable | ||||
| 55533 | ); | ||||
| 55534 | if( pNew==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 55535 | sqlite3GlobalConfigsqlite3Config.pcache2.xCachesize(pNew, numberOfCachePages(pCache)); | ||||
| 55536 | if( pCache->pCache ){ | ||||
| 55537 | sqlite3GlobalConfigsqlite3Config.pcache2.xDestroy(pCache->pCache); | ||||
| 55538 | } | ||||
| 55539 | pCache->pCache = pNew; | ||||
| 55540 | pCache->szPage = szPage; | ||||
| 55541 | pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage)); | ||||
| 55542 | } | ||||
| 55543 | return SQLITE_OK0; | ||||
| 55544 | } | ||||
| 55545 | |||||
| 55546 | /* | ||||
| 55547 | ** Try to obtain a page from the cache. | ||||
| 55548 | ** | ||||
| 55549 | ** This routine returns a pointer to an sqlite3_pcache_page object if | ||||
| 55550 | ** such an object is already in cache, or if a new one is created. | ||||
| 55551 | ** This routine returns a NULL pointer if the object was not in cache | ||||
| 55552 | ** and could not be created. | ||||
| 55553 | ** | ||||
| 55554 | ** The createFlags should be 0 to check for existing pages and should | ||||
| 55555 | ** be 3 (not 1, but 3) to try to create a new page. | ||||
| 55556 | ** | ||||
| 55557 | ** If the createFlag is 0, then NULL is always returned if the page | ||||
| 55558 | ** is not already in the cache. If createFlag is 1, then a new page | ||||
| 55559 | ** is created only if that can be done without spilling dirty pages | ||||
| 55560 | ** and without exceeding the cache size limit. | ||||
| 55561 | ** | ||||
| 55562 | ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly | ||||
| 55563 | ** initialize the sqlite3_pcache_page object and convert it into a | ||||
| 55564 | ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish() | ||||
| 55565 | ** routines are split this way for performance reasons. When separated | ||||
| 55566 | ** they can both (usually) operate without having to push values to | ||||
| 55567 | ** the stack on entry and pop them back off on exit, which saves a | ||||
| 55568 | ** lot of pushing and popping. | ||||
| 55569 | */ | ||||
| 55570 | SQLITE_PRIVATEstatic sqlite3_pcache_page *sqlite3PcacheFetch( | ||||
| 55571 | PCache *pCache, /* Obtain the page from this cache */ | ||||
| 55572 | Pgno pgno, /* Page number to obtain */ | ||||
| 55573 | int createFlag /* If true, create page if it does not exist already */ | ||||
| 55574 | ){ | ||||
| 55575 | int eCreate; | ||||
| 55576 | sqlite3_pcache_page *pRes; | ||||
| 55577 | |||||
| 55578 | assert( pCache!=0 )((void) (0)); | ||||
| 55579 | assert( pCache->pCache!=0 )((void) (0)); | ||||
| 55580 | assert( createFlag==3 || createFlag==0 )((void) (0)); | ||||
| 55581 | assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) )((void) (0)); | ||||
| 55582 | |||||
| 55583 | /* eCreate defines what to do if the page does not exist. | ||||
| 55584 | ** 0 Do not allocate a new page. (createFlag==0) | ||||
| 55585 | ** 1 Allocate a new page if doing so is inexpensive. | ||||
| 55586 | ** (createFlag==1 AND bPurgeable AND pDirty) | ||||
| 55587 | ** 2 Allocate a new page even it doing so is difficult. | ||||
| 55588 | ** (createFlag==1 AND !(bPurgeable AND pDirty) | ||||
| 55589 | */ | ||||
| 55590 | eCreate = createFlag & pCache->eCreate; | ||||
| 55591 | assert( eCreate==0 || eCreate==1 || eCreate==2 )((void) (0)); | ||||
| 55592 | assert( createFlag==0 || pCache->eCreate==eCreate )((void) (0)); | ||||
| 55593 | assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) )((void) (0)); | ||||
| 55594 | pRes = sqlite3GlobalConfigsqlite3Config.pcache2.xFetch(pCache->pCache, pgno, eCreate); | ||||
| 55595 | pcacheTrace(("%p.FETCH %d%s (result: %p) ",pCache,pgno, | ||||
| 55596 | createFlag?" create":"",pRes)); | ||||
| 55597 | pcachePageTrace(pgno, pRes); | ||||
| 55598 | return pRes; | ||||
| 55599 | } | ||||
| 55600 | |||||
| 55601 | /* | ||||
| 55602 | ** If the sqlite3PcacheFetch() routine is unable to allocate a new | ||||
| 55603 | ** page because no clean pages are available for reuse and the cache | ||||
| 55604 | ** size limit has been reached, then this routine can be invoked to | ||||
| 55605 | ** try harder to allocate a page. This routine might invoke the stress | ||||
| 55606 | ** callback to spill dirty pages to the journal. It will then try to | ||||
| 55607 | ** allocate the new page and will only fail to allocate a new page on | ||||
| 55608 | ** an OOM error. | ||||
| 55609 | ** | ||||
| 55610 | ** This routine should be invoked only after sqlite3PcacheFetch() fails. | ||||
| 55611 | */ | ||||
| 55612 | SQLITE_PRIVATEstatic int sqlite3PcacheFetchStress( | ||||
| 55613 | PCache *pCache, /* Obtain the page from this cache */ | ||||
| 55614 | Pgno pgno, /* Page number to obtain */ | ||||
| 55615 | sqlite3_pcache_page **ppPage /* Write result here */ | ||||
| 55616 | ){ | ||||
| 55617 | PgHdr *pPg; | ||||
| 55618 | if( pCache->eCreate==2 ) return 0; | ||||
| 55619 | |||||
| 55620 | if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){ | ||||
| 55621 | /* Find a dirty page to write-out and recycle. First try to find a | ||||
| 55622 | ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC | ||||
| 55623 | ** cleared), but if that is not possible settle for any other | ||||
| 55624 | ** unreferenced dirty page. | ||||
| 55625 | ** | ||||
| 55626 | ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC | ||||
| 55627 | ** flag is currently referenced, then the following may leave pSynced | ||||
| 55628 | ** set incorrectly (pointing to other than the LRU page with NEED_SYNC | ||||
| 55629 | ** cleared). This is Ok, as pSynced is just an optimization. */ | ||||
| 55630 | for(pPg=pCache->pSynced; | ||||
| 55631 | pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC0x008)); | ||||
| 55632 | pPg=pPg->pDirtyPrev | ||||
| 55633 | ); | ||||
| 55634 | pCache->pSynced = pPg; | ||||
| 55635 | if( !pPg ){ | ||||
| 55636 | for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); | ||||
| 55637 | } | ||||
| 55638 | if( pPg ){ | ||||
| 55639 | int rc; | ||||
| 55640 | #ifdef SQLITE_LOG_CACHE_SPILL | ||||
| 55641 | sqlite3_log(SQLITE_FULL13, | ||||
| 55642 | "spill page %d making room for %d - cache used: %d/%d", | ||||
| 55643 | pPg->pgno, pgno, | ||||
| 55644 | sqlite3GlobalConfigsqlite3Config.pcache2.xPagecount(pCache->pCache), | ||||
| 55645 | numberOfCachePages(pCache)); | ||||
| 55646 | #endif | ||||
| 55647 | pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno)); | ||||
| 55648 | rc = pCache->xStress(pCache->pStress, pPg); | ||||
| 55649 | pcacheDump(pCache); | ||||
| 55650 | if( rc!=SQLITE_OK0 && rc!=SQLITE_BUSY5 ){ | ||||
| 55651 | return rc; | ||||
| 55652 | } | ||||
| 55653 | } | ||||
| 55654 | } | ||||
| 55655 | *ppPage = sqlite3GlobalConfigsqlite3Config.pcache2.xFetch(pCache->pCache, pgno, 2); | ||||
| 55656 | return *ppPage==0 ? SQLITE_NOMEM_BKPT7 : SQLITE_OK0; | ||||
| 55657 | } | ||||
| 55658 | |||||
| 55659 | /* | ||||
| 55660 | ** This is a helper routine for sqlite3PcacheFetchFinish() | ||||
| 55661 | ** | ||||
| 55662 | ** In the uncommon case where the page being fetched has not been | ||||
| 55663 | ** initialized, this routine is invoked to do the initialization. | ||||
| 55664 | ** This routine is broken out into a separate function since it | ||||
| 55665 | ** requires extra stack manipulation that can be avoided in the common | ||||
| 55666 | ** case. | ||||
| 55667 | */ | ||||
| 55668 | static SQLITE_NOINLINE__attribute__((noinline)) PgHdr *pcacheFetchFinishWithInit( | ||||
| 55669 | PCache *pCache, /* Obtain the page from this cache */ | ||||
| 55670 | Pgno pgno, /* Page number obtained */ | ||||
| 55671 | sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ | ||||
| 55672 | ){ | ||||
| 55673 | PgHdr *pPgHdr; | ||||
| 55674 | assert( pPage!=0 )((void) (0)); | ||||
| 55675 | pPgHdr = (PgHdr*)pPage->pExtra; | ||||
| 55676 | assert( pPgHdr->pPage==0 )((void) (0)); | ||||
| 55677 | memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty)__builtin_offsetof(PgHdr, pDirty)); | ||||
| 55678 | pPgHdr->pPage = pPage; | ||||
| 55679 | pPgHdr->pData = pPage->pBuf; | ||||
| 55680 | pPgHdr->pExtra = (void *)&pPgHdr[1]; | ||||
| 55681 | memset(pPgHdr->pExtra, 0, 8); | ||||
| 55682 | assert( EIGHT_BYTE_ALIGNMENT( pPgHdr->pExtra ) )((void) (0)); | ||||
| 55683 | pPgHdr->pCache = pCache; | ||||
| 55684 | pPgHdr->pgno = pgno; | ||||
| 55685 | pPgHdr->flags = PGHDR_CLEAN0x001; | ||||
| 55686 | return sqlite3PcacheFetchFinish(pCache,pgno,pPage); | ||||
| 55687 | } | ||||
| 55688 | |||||
| 55689 | /* | ||||
| 55690 | ** This routine converts the sqlite3_pcache_page object returned by | ||||
| 55691 | ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine | ||||
| 55692 | ** must be called after sqlite3PcacheFetch() in order to get a usable | ||||
| 55693 | ** result. | ||||
| 55694 | */ | ||||
| 55695 | SQLITE_PRIVATEstatic PgHdr *sqlite3PcacheFetchFinish( | ||||
| 55696 | PCache *pCache, /* Obtain the page from this cache */ | ||||
| 55697 | Pgno pgno, /* Page number obtained */ | ||||
| 55698 | sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */ | ||||
| 55699 | ){ | ||||
| 55700 | PgHdr *pPgHdr; | ||||
| 55701 | |||||
| 55702 | assert( pPage!=0 )((void) (0)); | ||||
| 55703 | pPgHdr = (PgHdr *)pPage->pExtra; | ||||
| 55704 | |||||
| 55705 | if( !pPgHdr->pPage ){ | ||||
| 55706 | return pcacheFetchFinishWithInit(pCache, pgno, pPage); | ||||
| 55707 | } | ||||
| 55708 | pCache->nRefSum++; | ||||
| 55709 | pPgHdr->nRef++; | ||||
| 55710 | assert( sqlite3PcachePageSanity(pPgHdr) )((void) (0)); | ||||
| 55711 | return pPgHdr; | ||||
| 55712 | } | ||||
| 55713 | |||||
| 55714 | /* | ||||
| 55715 | ** Decrement the reference count on a page. If the page is clean and the | ||||
| 55716 | ** reference count drops to 0, then it is made eligible for recycling. | ||||
| 55717 | */ | ||||
| 55718 | SQLITE_PRIVATEstatic void SQLITE_NOINLINE__attribute__((noinline)) sqlite3PcacheRelease(PgHdr *p){ | ||||
| 55719 | assert( p->nRef>0 )((void) (0)); | ||||
| 55720 | p->pCache->nRefSum--; | ||||
| 55721 | if( (--p->nRef)==0 ){ | ||||
| 55722 | if( p->flags&PGHDR_CLEAN0x001 ){ | ||||
| 55723 | pcacheUnpin(p); | ||||
| 55724 | }else{ | ||||
| 55725 | pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT3); | ||||
| 55726 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55727 | } | ||||
| 55728 | } | ||||
| 55729 | } | ||||
| 55730 | |||||
| 55731 | /* | ||||
| 55732 | ** Increase the reference count of a supplied page by 1. | ||||
| 55733 | */ | ||||
| 55734 | SQLITE_PRIVATEstatic void sqlite3PcacheRef(PgHdr *p){ | ||||
| 55735 | assert(p->nRef>0)((void) (0)); | ||||
| 55736 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55737 | p->nRef++; | ||||
| 55738 | p->pCache->nRefSum++; | ||||
| 55739 | } | ||||
| 55740 | |||||
| 55741 | /* | ||||
| 55742 | ** Drop a page from the cache. There must be exactly one reference to the | ||||
| 55743 | ** page. This function deletes that reference, so after it returns the | ||||
| 55744 | ** page pointed to by p is invalid. | ||||
| 55745 | */ | ||||
| 55746 | SQLITE_PRIVATEstatic void sqlite3PcacheDrop(PgHdr *p){ | ||||
| 55747 | assert( p->nRef==1 )((void) (0)); | ||||
| 55748 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55749 | if( p->flags&PGHDR_DIRTY0x002 ){ | ||||
| 55750 | pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE1); | ||||
| 55751 | } | ||||
| 55752 | p->pCache->nRefSum--; | ||||
| 55753 | sqlite3GlobalConfigsqlite3Config.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1); | ||||
| 55754 | } | ||||
| 55755 | |||||
| 55756 | /* | ||||
| 55757 | ** Make sure the page is marked as dirty. If it isn't dirty already, | ||||
| 55758 | ** make it so. | ||||
| 55759 | */ | ||||
| 55760 | SQLITE_PRIVATEstatic void sqlite3PcacheMakeDirty(PgHdr *p){ | ||||
| 55761 | assert( p->nRef>0 )((void) (0)); | ||||
| 55762 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55763 | if( p->flags & (PGHDR_CLEAN0x001|PGHDR_DONT_WRITE0x010) ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 55764 | p->flags &= ~PGHDR_DONT_WRITE0x010; | ||||
| 55765 | if( p->flags & PGHDR_CLEAN0x001 ){ | ||||
| 55766 | p->flags ^= (PGHDR_DIRTY0x002|PGHDR_CLEAN0x001); | ||||
| 55767 | pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno)); | ||||
| 55768 | assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY )((void) (0)); | ||||
| 55769 | pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD2); | ||||
| 55770 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55771 | } | ||||
| 55772 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55773 | } | ||||
| 55774 | } | ||||
| 55775 | |||||
| 55776 | /* | ||||
| 55777 | ** Make sure the page is marked as clean. If it isn't clean already, | ||||
| 55778 | ** make it so. | ||||
| 55779 | */ | ||||
| 55780 | SQLITE_PRIVATEstatic void sqlite3PcacheMakeClean(PgHdr *p){ | ||||
| 55781 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55782 | assert( (p->flags & PGHDR_DIRTY)!=0 )((void) (0)); | ||||
| 55783 | assert( (p->flags & PGHDR_CLEAN)==0 )((void) (0)); | ||||
| 55784 | pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE1); | ||||
| 55785 | p->flags &= ~(PGHDR_DIRTY0x002|PGHDR_NEED_SYNC0x008|PGHDR_WRITEABLE0x004); | ||||
| 55786 | p->flags |= PGHDR_CLEAN0x001; | ||||
| 55787 | pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno)); | ||||
| 55788 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55789 | if( p->nRef==0 ){ | ||||
| 55790 | pcacheUnpin(p); | ||||
| 55791 | } | ||||
| 55792 | } | ||||
| 55793 | |||||
| 55794 | /* | ||||
| 55795 | ** Make every page in the cache clean. | ||||
| 55796 | */ | ||||
| 55797 | SQLITE_PRIVATEstatic void sqlite3PcacheCleanAll(PCache *pCache){ | ||||
| 55798 | PgHdr *p; | ||||
| 55799 | pcacheTrace(("%p.CLEAN-ALL\n",pCache)); | ||||
| 55800 | while( (p = pCache->pDirty)!=0 ){ | ||||
| 55801 | sqlite3PcacheMakeClean(p); | ||||
| 55802 | } | ||||
| 55803 | } | ||||
| 55804 | |||||
| 55805 | /* | ||||
| 55806 | ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages. | ||||
| 55807 | */ | ||||
| 55808 | SQLITE_PRIVATEstatic void sqlite3PcacheClearWritable(PCache *pCache){ | ||||
| 55809 | PgHdr *p; | ||||
| 55810 | pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache)); | ||||
| 55811 | for(p=pCache->pDirty; p; p=p->pDirtyNext){ | ||||
| 55812 | p->flags &= ~(PGHDR_NEED_SYNC0x008|PGHDR_WRITEABLE0x004); | ||||
| 55813 | } | ||||
| 55814 | pCache->pSynced = pCache->pDirtyTail; | ||||
| 55815 | } | ||||
| 55816 | |||||
| 55817 | /* | ||||
| 55818 | ** Clear the PGHDR_NEED_SYNC flag from all dirty pages. | ||||
| 55819 | */ | ||||
| 55820 | SQLITE_PRIVATEstatic void sqlite3PcacheClearSyncFlags(PCache *pCache){ | ||||
| 55821 | PgHdr *p; | ||||
| 55822 | for(p=pCache->pDirty; p; p=p->pDirtyNext){ | ||||
| 55823 | p->flags &= ~PGHDR_NEED_SYNC0x008; | ||||
| 55824 | } | ||||
| 55825 | pCache->pSynced = pCache->pDirtyTail; | ||||
| 55826 | } | ||||
| 55827 | |||||
| 55828 | /* | ||||
| 55829 | ** Change the page number of page p to newPgno. | ||||
| 55830 | */ | ||||
| 55831 | SQLITE_PRIVATEstatic void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){ | ||||
| 55832 | PCache *pCache = p->pCache; | ||||
| 55833 | sqlite3_pcache_page *pOther; | ||||
| 55834 | assert( p->nRef>0 )((void) (0)); | ||||
| 55835 | assert( newPgno>0 )((void) (0)); | ||||
| 55836 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55837 | pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno)); | ||||
| 55838 | pOther = sqlite3GlobalConfigsqlite3Config.pcache2.xFetch(pCache->pCache, newPgno, 0); | ||||
| 55839 | if( pOther ){ | ||||
| 55840 | PgHdr *pXPage = (PgHdr*)pOther->pExtra; | ||||
| 55841 | assert( pXPage->nRef==0 )((void) (0)); | ||||
| 55842 | pXPage->nRef++; | ||||
| 55843 | pCache->nRefSum++; | ||||
| 55844 | sqlite3PcacheDrop(pXPage); | ||||
| 55845 | } | ||||
| 55846 | sqlite3GlobalConfigsqlite3Config.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno); | ||||
| 55847 | p->pgno = newPgno; | ||||
| 55848 | if( (p->flags&PGHDR_DIRTY0x002) && (p->flags&PGHDR_NEED_SYNC0x008) ){ | ||||
| 55849 | pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT3); | ||||
| 55850 | assert( sqlite3PcachePageSanity(p) )((void) (0)); | ||||
| 55851 | } | ||||
| 55852 | } | ||||
| 55853 | |||||
| 55854 | /* | ||||
| 55855 | ** Drop every cache entry whose page number is greater than "pgno". The | ||||
| 55856 | ** caller must ensure that there are no outstanding references to any pages | ||||
| 55857 | ** other than page 1 with a page number greater than pgno. | ||||
| 55858 | ** | ||||
| 55859 | ** If there is a reference to page 1 and the pgno parameter passed to this | ||||
| 55860 | ** function is 0, then the data area associated with page 1 is zeroed, but | ||||
| 55861 | ** the page object is not dropped. | ||||
| 55862 | */ | ||||
| 55863 | SQLITE_PRIVATEstatic void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){ | ||||
| 55864 | if( pCache->pCache ){ | ||||
| 55865 | PgHdr *p; | ||||
| 55866 | PgHdr *pNext; | ||||
| 55867 | pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno)); | ||||
| 55868 | for(p=pCache->pDirty; p; p=pNext){ | ||||
| 55869 | pNext = p->pDirtyNext; | ||||
| 55870 | /* This routine never gets call with a positive pgno except right | ||||
| 55871 | ** after sqlite3PcacheCleanAll(). So if there are dirty pages, | ||||
| 55872 | ** it must be that pgno==0. | ||||
| 55873 | */ | ||||
| 55874 | assert( p->pgno>0 )((void) (0)); | ||||
| 55875 | if( p->pgno>pgno ){ | ||||
| 55876 | assert( p->flags&PGHDR_DIRTY )((void) (0)); | ||||
| 55877 | sqlite3PcacheMakeClean(p); | ||||
| 55878 | } | ||||
| 55879 | } | ||||
| 55880 | if( pgno==0 && pCache->nRefSum ){ | ||||
| 55881 | sqlite3_pcache_page *pPage1; | ||||
| 55882 | pPage1 = sqlite3GlobalConfigsqlite3Config.pcache2.xFetch(pCache->pCache,1,0); | ||||
| 55883 | if( ALWAYS(pPage1)(pPage1) ){ /* Page 1 is always available in cache, because | ||||
| 55884 | ** pCache->nRefSum>0 */ | ||||
| 55885 | memset(pPage1->pBuf, 0, pCache->szPage); | ||||
| 55886 | pgno = 1; | ||||
| 55887 | } | ||||
| 55888 | } | ||||
| 55889 | sqlite3GlobalConfigsqlite3Config.pcache2.xTruncate(pCache->pCache, pgno+1); | ||||
| 55890 | } | ||||
| 55891 | } | ||||
| 55892 | |||||
| 55893 | /* | ||||
| 55894 | ** Close a cache. | ||||
| 55895 | */ | ||||
| 55896 | SQLITE_PRIVATEstatic void sqlite3PcacheClose(PCache *pCache){ | ||||
| 55897 | assert( pCache->pCache!=0 )((void) (0)); | ||||
| 55898 | pcacheTrace(("%p.CLOSE\n",pCache)); | ||||
| 55899 | sqlite3GlobalConfigsqlite3Config.pcache2.xDestroy(pCache->pCache); | ||||
| 55900 | } | ||||
| 55901 | |||||
| 55902 | /* | ||||
| 55903 | ** Discard the contents of the cache. | ||||
| 55904 | */ | ||||
| 55905 | SQLITE_PRIVATEstatic void sqlite3PcacheClear(PCache *pCache){ | ||||
| 55906 | sqlite3PcacheTruncate(pCache, 0); | ||||
| 55907 | } | ||||
| 55908 | |||||
| 55909 | /* | ||||
| 55910 | ** Merge two lists of pages connected by pDirty and in pgno order. | ||||
| 55911 | ** Do not bother fixing the pDirtyPrev pointers. | ||||
| 55912 | */ | ||||
| 55913 | static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){ | ||||
| 55914 | PgHdr result, *pTail; | ||||
| 55915 | pTail = &result; | ||||
| 55916 | assert( pA!=0 && pB!=0 )((void) (0)); | ||||
| 55917 | for(;;){ | ||||
| 55918 | if( pA->pgno<pB->pgno ){ | ||||
| 55919 | pTail->pDirty = pA; | ||||
| 55920 | pTail = pA; | ||||
| 55921 | pA = pA->pDirty; | ||||
| 55922 | if( pA==0 ){ | ||||
| 55923 | pTail->pDirty = pB; | ||||
| 55924 | break; | ||||
| 55925 | } | ||||
| 55926 | }else{ | ||||
| 55927 | pTail->pDirty = pB; | ||||
| 55928 | pTail = pB; | ||||
| 55929 | pB = pB->pDirty; | ||||
| 55930 | if( pB==0 ){ | ||||
| 55931 | pTail->pDirty = pA; | ||||
| 55932 | break; | ||||
| 55933 | } | ||||
| 55934 | } | ||||
| 55935 | } | ||||
| 55936 | return result.pDirty; | ||||
| 55937 | } | ||||
| 55938 | |||||
| 55939 | /* | ||||
| 55940 | ** Sort the list of pages in ascending order by pgno. Pages are | ||||
| 55941 | ** connected by pDirty pointers. The pDirtyPrev pointers are | ||||
| 55942 | ** corrupted by this sort. | ||||
| 55943 | ** | ||||
| 55944 | ** Since there cannot be more than 2^31 distinct pages in a database, | ||||
| 55945 | ** there cannot be more than 31 buckets required by the merge sorter. | ||||
| 55946 | ** One extra bucket is added to catch overflow in case something | ||||
| 55947 | ** ever changes to make the previous sentence incorrect. | ||||
| 55948 | */ | ||||
| 55949 | #define N_SORT_BUCKET32 32 | ||||
| 55950 | static PgHdr *pcacheSortDirtyList(PgHdr *pIn){ | ||||
| 55951 | PgHdr *a[N_SORT_BUCKET32], *p; | ||||
| 55952 | int i; | ||||
| 55953 | memset(a, 0, sizeof(a)); | ||||
| 55954 | while( pIn ){ | ||||
| 55955 | p = pIn; | ||||
| 55956 | pIn = p->pDirty; | ||||
| 55957 | p->pDirty = 0; | ||||
| 55958 | for(i=0; ALWAYS(i<N_SORT_BUCKET-1)(i<32 -1); i++){ | ||||
| 55959 | if( a[i]==0 ){ | ||||
| 55960 | a[i] = p; | ||||
| 55961 | break; | ||||
| 55962 | }else{ | ||||
| 55963 | p = pcacheMergeDirtyList(a[i], p); | ||||
| 55964 | a[i] = 0; | ||||
| 55965 | } | ||||
| 55966 | } | ||||
| 55967 | if( NEVER(i==N_SORT_BUCKET-1)(i==32 -1) ){ | ||||
| 55968 | /* To get here, there need to be 2^(N_SORT_BUCKET) elements in | ||||
| 55969 | ** the input list. But that is impossible. | ||||
| 55970 | */ | ||||
| 55971 | a[i] = pcacheMergeDirtyList(a[i], p); | ||||
| 55972 | } | ||||
| 55973 | } | ||||
| 55974 | p = a[0]; | ||||
| 55975 | for(i=1; i<N_SORT_BUCKET32; i++){ | ||||
| 55976 | if( a[i]==0 ) continue; | ||||
| 55977 | p = p ? pcacheMergeDirtyList(p, a[i]) : a[i]; | ||||
| 55978 | } | ||||
| 55979 | return p; | ||||
| 55980 | } | ||||
| 55981 | |||||
| 55982 | /* | ||||
| 55983 | ** Return a list of all dirty pages in the cache, sorted by page number. | ||||
| 55984 | */ | ||||
| 55985 | SQLITE_PRIVATEstatic PgHdr *sqlite3PcacheDirtyList(PCache *pCache){ | ||||
| 55986 | PgHdr *p; | ||||
| 55987 | for(p=pCache->pDirty; p; p=p->pDirtyNext){ | ||||
| 55988 | p->pDirty = p->pDirtyNext; | ||||
| 55989 | } | ||||
| 55990 | return pcacheSortDirtyList(pCache->pDirty); | ||||
| 55991 | } | ||||
| 55992 | |||||
| 55993 | /* | ||||
| 55994 | ** Return the total number of references to all pages held by the cache. | ||||
| 55995 | ** | ||||
| 55996 | ** This is not the total number of pages referenced, but the sum of the | ||||
| 55997 | ** reference count for all pages. | ||||
| 55998 | */ | ||||
| 55999 | SQLITE_PRIVATEstatic i64 sqlite3PcacheRefCount(PCache *pCache){ | ||||
| 56000 | return pCache->nRefSum; | ||||
| 56001 | } | ||||
| 56002 | |||||
| 56003 | /* | ||||
| 56004 | ** Return the number of references to the page supplied as an argument. | ||||
| 56005 | */ | ||||
| 56006 | SQLITE_PRIVATEstatic i64 sqlite3PcachePageRefcount(PgHdr *p){ | ||||
| 56007 | return p->nRef; | ||||
| 56008 | } | ||||
| 56009 | |||||
| 56010 | /* | ||||
| 56011 | ** Return the total number of pages in the cache. | ||||
| 56012 | */ | ||||
| 56013 | SQLITE_PRIVATEstatic int sqlite3PcachePagecount(PCache *pCache){ | ||||
| 56014 | assert( pCache->pCache!=0 )((void) (0)); | ||||
| 56015 | return sqlite3GlobalConfigsqlite3Config.pcache2.xPagecount(pCache->pCache); | ||||
| 56016 | } | ||||
| 56017 | |||||
| 56018 | #ifdef SQLITE_TEST | ||||
| 56019 | /* | ||||
| 56020 | ** Get the suggested cache-size value. | ||||
| 56021 | */ | ||||
| 56022 | SQLITE_PRIVATEstatic int sqlite3PcacheGetCachesize(PCache *pCache){ | ||||
| 56023 | return numberOfCachePages(pCache); | ||||
| 56024 | } | ||||
| 56025 | #endif | ||||
| 56026 | |||||
| 56027 | /* | ||||
| 56028 | ** Set the suggested cache-size value. | ||||
| 56029 | */ | ||||
| 56030 | SQLITE_PRIVATEstatic void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){ | ||||
| 56031 | assert( pCache->pCache!=0 )((void) (0)); | ||||
| 56032 | pCache->szCache = mxPage; | ||||
| 56033 | sqlite3GlobalConfigsqlite3Config.pcache2.xCachesize(pCache->pCache, | ||||
| 56034 | numberOfCachePages(pCache)); | ||||
| 56035 | } | ||||
| 56036 | |||||
| 56037 | /* | ||||
| 56038 | ** Set the suggested cache-spill value. Make no changes if if the | ||||
| 56039 | ** argument is zero. Return the effective cache-spill size, which will | ||||
| 56040 | ** be the larger of the szSpill and szCache. | ||||
| 56041 | */ | ||||
| 56042 | SQLITE_PRIVATEstatic int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){ | ||||
| 56043 | int res; | ||||
| 56044 | assert( p->pCache!=0 )((void) (0)); | ||||
| 56045 | if( mxPage ){ | ||||
| 56046 | if( mxPage<0 ){ | ||||
| 56047 | mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra)); | ||||
| 56048 | } | ||||
| 56049 | p->szSpill = mxPage; | ||||
| 56050 | } | ||||
| 56051 | res = numberOfCachePages(p); | ||||
| 56052 | if( res<p->szSpill ) res = p->szSpill; | ||||
| 56053 | return res; | ||||
| 56054 | } | ||||
| 56055 | |||||
| 56056 | /* | ||||
| 56057 | ** Free up as much memory as possible from the page cache. | ||||
| 56058 | */ | ||||
| 56059 | SQLITE_PRIVATEstatic void sqlite3PcacheShrink(PCache *pCache){ | ||||
| 56060 | assert( pCache->pCache!=0 )((void) (0)); | ||||
| 56061 | sqlite3GlobalConfigsqlite3Config.pcache2.xShrink(pCache->pCache); | ||||
| 56062 | } | ||||
| 56063 | |||||
| 56064 | /* | ||||
| 56065 | ** Return the size of the header added by this middleware layer | ||||
| 56066 | ** in the page-cache hierarchy. | ||||
| 56067 | */ | ||||
| 56068 | SQLITE_PRIVATEstatic int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr))(((sizeof(PgHdr))+7)&~7); } | ||||
| 56069 | |||||
| 56070 | /* | ||||
| 56071 | ** Return the number of dirty pages currently in the cache, as a percentage | ||||
| 56072 | ** of the configured cache size. | ||||
| 56073 | */ | ||||
| 56074 | SQLITE_PRIVATEstatic int sqlite3PCachePercentDirty(PCache *pCache){ | ||||
| 56075 | PgHdr *pDirty; | ||||
| 56076 | int nDirty = 0; | ||||
| 56077 | int nCache = numberOfCachePages(pCache); | ||||
| 56078 | for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++; | ||||
| 56079 | return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0; | ||||
| 56080 | } | ||||
| 56081 | |||||
| 56082 | #ifdef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 56083 | /* | ||||
| 56084 | ** Return true if there are one or more dirty pages in the cache. Else false. | ||||
| 56085 | */ | ||||
| 56086 | SQLITE_PRIVATEstatic int sqlite3PCacheIsDirty(PCache *pCache){ | ||||
| 56087 | return (pCache->pDirty!=0); | ||||
| 56088 | } | ||||
| 56089 | #endif | ||||
| 56090 | |||||
| 56091 | #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) | ||||
| 56092 | /* | ||||
| 56093 | ** For all dirty pages currently in the cache, invoke the specified | ||||
| 56094 | ** callback. This is only used if the SQLITE_CHECK_PAGES macro is | ||||
| 56095 | ** defined. | ||||
| 56096 | */ | ||||
| 56097 | SQLITE_PRIVATEstatic void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){ | ||||
| 56098 | PgHdr *pDirty; | ||||
| 56099 | for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){ | ||||
| 56100 | xIter(pDirty); | ||||
| 56101 | } | ||||
| 56102 | } | ||||
| 56103 | #endif | ||||
| 56104 | |||||
| 56105 | /************** End of pcache.c **********************************************/ | ||||
| 56106 | /************** Begin file pcache1.c *****************************************/ | ||||
| 56107 | /* | ||||
| 56108 | ** 2008 November 05 | ||||
| 56109 | ** | ||||
| 56110 | ** The author disclaims copyright to this source code. In place of | ||||
| 56111 | ** a legal notice, here is a blessing: | ||||
| 56112 | ** | ||||
| 56113 | ** May you do good and not evil. | ||||
| 56114 | ** May you find forgiveness for yourself and forgive others. | ||||
| 56115 | ** May you share freely, never taking more than you give. | ||||
| 56116 | ** | ||||
| 56117 | ************************************************************************* | ||||
| 56118 | ** | ||||
| 56119 | ** This file implements the default page cache implementation (the | ||||
| 56120 | ** sqlite3_pcache interface). It also contains part of the implementation | ||||
| 56121 | ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features. | ||||
| 56122 | ** If the default page cache implementation is overridden, then neither of | ||||
| 56123 | ** these two features are available. | ||||
| 56124 | ** | ||||
| 56125 | ** A Page cache line looks like this: | ||||
| 56126 | ** | ||||
| 56127 | ** ------------------------------------------------------------- | ||||
| 56128 | ** | database page content | PgHdr1 | MemPage | PgHdr | | ||||
| 56129 | ** ------------------------------------------------------------- | ||||
| 56130 | ** | ||||
| 56131 | ** The database page content is up front (so that buffer overreads tend to | ||||
| 56132 | ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage | ||||
| 56133 | ** is the extension added by the btree.c module containing information such | ||||
| 56134 | ** as the database page number and how that database page is used. PgHdr | ||||
| 56135 | ** is added by the pcache.c layer and contains information used to keep track | ||||
| 56136 | ** of which pages are "dirty". PgHdr1 is an extension added by this | ||||
| 56137 | ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page. | ||||
| 56138 | ** PgHdr1 contains information needed to look up a page by its page number. | ||||
| 56139 | ** The superclass sqlite3_pcache_page.pBuf points to the start of the | ||||
| 56140 | ** database page content and sqlite3_pcache_page.pExtra points to PgHdr. | ||||
| 56141 | ** | ||||
| 56142 | ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at | ||||
| 56143 | ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The | ||||
| 56144 | ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this | ||||
| 56145 | ** size can vary according to architecture, compile-time options, and | ||||
| 56146 | ** SQLite library version number. | ||||
| 56147 | ** | ||||
| 56148 | ** Historical note: It used to be that if the SQLITE_PCACHE_SEPARATE_HEADER | ||||
| 56149 | ** was defined, then the page content would be held in a separate memory | ||||
| 56150 | ** allocation from the PgHdr1. This was intended to avoid clownshoe memory | ||||
| 56151 | ** allocations. However, the btree layer needs a small (16-byte) overrun | ||||
| 56152 | ** area after the page content buffer. The header serves as that overrun | ||||
| 56153 | ** area. Therefore SQLITE_PCACHE_SEPARATE_HEADER was discontinued to avoid | ||||
| 56154 | ** any possibility of a memory error. | ||||
| 56155 | ** | ||||
| 56156 | ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates | ||||
| 56157 | ** with this module. Information is passed back and forth as PgHdr1 pointers. | ||||
| 56158 | ** | ||||
| 56159 | ** The pcache.c and pager.c modules deal pointers to PgHdr objects. | ||||
| 56160 | ** The btree.c module deals with pointers to MemPage objects. | ||||
| 56161 | ** | ||||
| 56162 | ** SOURCE OF PAGE CACHE MEMORY: | ||||
| 56163 | ** | ||||
| 56164 | ** Memory for a page might come from any of three sources: | ||||
| 56165 | ** | ||||
| 56166 | ** (1) The general-purpose memory allocator - sqlite3Malloc() | ||||
| 56167 | ** (2) Global page-cache memory provided using sqlite3_config() with | ||||
| 56168 | ** SQLITE_CONFIG_PAGECACHE. | ||||
| 56169 | ** (3) PCache-local bulk allocation. | ||||
| 56170 | ** | ||||
| 56171 | ** The third case is a chunk of heap memory (defaulting to 100 pages worth) | ||||
| 56172 | ** that is allocated when the page cache is created. The size of the local | ||||
| 56173 | ** bulk allocation can be adjusted using | ||||
| 56174 | ** | ||||
| 56175 | ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N). | ||||
| 56176 | ** | ||||
| 56177 | ** If N is positive, then N pages worth of memory are allocated using a single | ||||
| 56178 | ** sqlite3Malloc() call and that memory is used for the first N pages allocated. | ||||
| 56179 | ** Or if N is negative, then -1024*N bytes of memory are allocated and used | ||||
| 56180 | ** for as many pages as can be accommodated. | ||||
| 56181 | ** | ||||
| 56182 | ** Only one of (2) or (3) can be used. Once the memory available to (2) or | ||||
| 56183 | ** (3) is exhausted, subsequent allocations fail over to the general-purpose | ||||
| 56184 | ** memory allocator (1). | ||||
| 56185 | ** | ||||
| 56186 | ** Earlier versions of SQLite used only methods (1) and (2). But experiments | ||||
| 56187 | ** show that method (3) with N==100 provides about a 5% performance boost for | ||||
| 56188 | ** common workloads. | ||||
| 56189 | */ | ||||
| 56190 | /* #include "sqliteInt.h" */ | ||||
| 56191 | |||||
| 56192 | typedef struct PCache1 PCache1; | ||||
| 56193 | typedef struct PgHdr1 PgHdr1; | ||||
| 56194 | typedef struct PgFreeslot PgFreeslot; | ||||
| 56195 | typedef struct PGroup PGroup; | ||||
| 56196 | |||||
| 56197 | /* | ||||
| 56198 | ** Each cache entry is represented by an instance of the following | ||||
| 56199 | ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated | ||||
| 56200 | ** directly before this structure and is used to cache the page content. | ||||
| 56201 | ** | ||||
| 56202 | ** When reading a corrupt database file, it is possible that SQLite might | ||||
| 56203 | ** read a few bytes (no more than 16 bytes) past the end of the page buffer. | ||||
| 56204 | ** It will only read past the end of the page buffer, never write. This | ||||
| 56205 | ** object is positioned immediately after the page buffer to serve as an | ||||
| 56206 | ** overrun area, so that overreads are harmless. | ||||
| 56207 | ** | ||||
| 56208 | ** Variables isBulkLocal and isAnchor were once type "u8". That works, | ||||
| 56209 | ** but causes a 2-byte gap in the structure for most architectures (since | ||||
| 56210 | ** pointers must be either 4 or 8-byte aligned). As this structure is located | ||||
| 56211 | ** in memory directly after the associated page data, if the database is | ||||
| 56212 | ** corrupt, code at the b-tree layer may overread the page buffer and | ||||
| 56213 | ** read part of this structure before the corruption is detected. This | ||||
| 56214 | ** can cause a valgrind error if the uninitialized gap is accessed. Using u16 | ||||
| 56215 | ** ensures there is no such gap, and therefore no bytes of uninitialized | ||||
| 56216 | ** memory in the structure. | ||||
| 56217 | ** | ||||
| 56218 | ** The pLruNext and pLruPrev pointers form a double-linked circular list | ||||
| 56219 | ** of all pages that are unpinned. The PGroup.lru element (which should be | ||||
| 56220 | ** the only element on the list with PgHdr1.isAnchor set to 1) forms the | ||||
| 56221 | ** beginning and the end of the list. | ||||
| 56222 | */ | ||||
| 56223 | struct PgHdr1 { | ||||
| 56224 | sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */ | ||||
| 56225 | unsigned int iKey; /* Key value (page number) */ | ||||
| 56226 | u16 isBulkLocal; /* This page from bulk local storage */ | ||||
| 56227 | u16 isAnchor; /* This is the PGroup.lru element */ | ||||
| 56228 | PgHdr1 *pNext; /* Next in hash table chain */ | ||||
| 56229 | PCache1 *pCache; /* Cache that currently owns this page */ | ||||
| 56230 | PgHdr1 *pLruNext; /* Next in circular LRU list of unpinned pages */ | ||||
| 56231 | PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */ | ||||
| 56232 | /* NB: pLruPrev is only valid if pLruNext!=0 */ | ||||
| 56233 | }; | ||||
| 56234 | |||||
| 56235 | /* | ||||
| 56236 | ** A page is pinned if it is not on the LRU list. To be "pinned" means | ||||
| 56237 | ** that the page is in active use and must not be deallocated. | ||||
| 56238 | */ | ||||
| 56239 | #define PAGE_IS_PINNED(p)((p)->pLruNext==0) ((p)->pLruNext==0) | ||||
| 56240 | #define PAGE_IS_UNPINNED(p)((p)->pLruNext!=0) ((p)->pLruNext!=0) | ||||
| 56241 | |||||
| 56242 | /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set | ||||
| 56243 | ** of one or more PCaches that are able to recycle each other's unpinned | ||||
| 56244 | ** pages when they are under memory pressure. A PGroup is an instance of | ||||
| 56245 | ** the following object. | ||||
| 56246 | ** | ||||
| 56247 | ** This page cache implementation works in one of two modes: | ||||
| 56248 | ** | ||||
| 56249 | ** (1) Every PCache is the sole member of its own PGroup. There is | ||||
| 56250 | ** one PGroup per PCache. | ||||
| 56251 | ** | ||||
| 56252 | ** (2) There is a single global PGroup that all PCaches are a member | ||||
| 56253 | ** of. | ||||
| 56254 | ** | ||||
| 56255 | ** Mode 1 uses more memory (since PCache instances are not able to rob | ||||
| 56256 | ** unused pages from other PCaches) but it also operates without a mutex, | ||||
| 56257 | ** and is therefore often faster. Mode 2 requires a mutex in order to be | ||||
| 56258 | ** threadsafe, but recycles pages more efficiently. | ||||
| 56259 | ** | ||||
| 56260 | ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single | ||||
| 56261 | ** PGroup which is the pcache1.grp global variable and its mutex is | ||||
| 56262 | ** SQLITE_MUTEX_STATIC_LRU. | ||||
| 56263 | */ | ||||
| 56264 | struct PGroup { | ||||
| 56265 | sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */ | ||||
| 56266 | unsigned int nMaxPage; /* Sum of nMax for purgeable caches */ | ||||
| 56267 | unsigned int nMinPage; /* Sum of nMin for purgeable caches */ | ||||
| 56268 | unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */ | ||||
| 56269 | unsigned int nPurgeable; /* Number of purgeable pages allocated */ | ||||
| 56270 | PgHdr1 lru; /* The beginning and end of the LRU list */ | ||||
| 56271 | }; | ||||
| 56272 | |||||
| 56273 | /* Each page cache is an instance of the following object. Every | ||||
| 56274 | ** open database file (including each in-memory database and each | ||||
| 56275 | ** temporary or transient database) has a single page cache which | ||||
| 56276 | ** is an instance of this object. | ||||
| 56277 | ** | ||||
| 56278 | ** Pointers to structures of this type are cast and returned as | ||||
| 56279 | ** opaque sqlite3_pcache* handles. | ||||
| 56280 | */ | ||||
| 56281 | struct PCache1 { | ||||
| 56282 | /* Cache configuration parameters. Page size (szPage) and the purgeable | ||||
| 56283 | ** flag (bPurgeable) and the pnPurgeable pointer are all set when the | ||||
| 56284 | ** cache is created and are never changed thereafter. nMax may be | ||||
| 56285 | ** modified at any time by a call to the pcache1Cachesize() method. | ||||
| 56286 | ** The PGroup mutex must be held when accessing nMax. | ||||
| 56287 | */ | ||||
| 56288 | PGroup *pGroup; /* PGroup this cache belongs to */ | ||||
| 56289 | unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */ | ||||
| 56290 | int szPage; /* Size of database content section */ | ||||
| 56291 | int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */ | ||||
| 56292 | int szAlloc; /* Total size of one pcache line */ | ||||
| 56293 | int bPurgeable; /* True if cache is purgeable */ | ||||
| 56294 | unsigned int nMin; /* Minimum number of pages reserved */ | ||||
| 56295 | unsigned int nMax; /* Configured "cache_size" value */ | ||||
| 56296 | unsigned int n90pct; /* nMax*9/10 */ | ||||
| 56297 | unsigned int iMaxKey; /* Largest key seen since xTruncate() */ | ||||
| 56298 | unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/ | ||||
| 56299 | |||||
| 56300 | /* Hash table of all pages. The following variables may only be accessed | ||||
| 56301 | ** when the accessor is holding the PGroup mutex. | ||||
| 56302 | */ | ||||
| 56303 | unsigned int nRecyclable; /* Number of pages in the LRU list */ | ||||
| 56304 | unsigned int nPage; /* Total number of pages in apHash */ | ||||
| 56305 | unsigned int nHash; /* Number of slots in apHash[] */ | ||||
| 56306 | PgHdr1 **apHash; /* Hash table for fast lookup by key */ | ||||
| 56307 | PgHdr1 *pFree; /* List of unused pcache-local pages */ | ||||
| 56308 | void *pBulk; /* Bulk memory used by pcache-local */ | ||||
| 56309 | }; | ||||
| 56310 | |||||
| 56311 | /* | ||||
| 56312 | ** Free slots in the allocator used to divide up the global page cache | ||||
| 56313 | ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism. | ||||
| 56314 | */ | ||||
| 56315 | struct PgFreeslot { | ||||
| 56316 | PgFreeslot *pNext; /* Next free slot */ | ||||
| 56317 | }; | ||||
| 56318 | |||||
| 56319 | /* | ||||
| 56320 | ** Global data used by this cache. | ||||
| 56321 | */ | ||||
| 56322 | static SQLITE_WSD struct PCacheGlobal { | ||||
| 56323 | PGroup grp; /* The global PGroup for mode (2) */ | ||||
| 56324 | |||||
| 56325 | /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The | ||||
| 56326 | ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all | ||||
| 56327 | ** fixed at sqlite3_initialize() time and do not require mutex protection. | ||||
| 56328 | ** The nFreeSlot and pFree values do require mutex protection. | ||||
| 56329 | */ | ||||
| 56330 | int isInit; /* True if initialized */ | ||||
| 56331 | int separateCache; /* Use a new PGroup for each PCache */ | ||||
| 56332 | int nInitPage; /* Initial bulk allocation size */ | ||||
| 56333 | int szSlot; /* Size of each free slot */ | ||||
| 56334 | int nSlot; /* The number of pcache slots */ | ||||
| 56335 | int nReserve; /* Try to keep nFreeSlot above this */ | ||||
| 56336 | void *pStart, *pEnd; /* Bounds of global page cache memory */ | ||||
| 56337 | /* Above requires no mutex. Use mutex below for variable that follow. */ | ||||
| 56338 | sqlite3_mutex *mutex; /* Mutex for accessing the following: */ | ||||
| 56339 | PgFreeslot *pFree; /* Free page blocks */ | ||||
| 56340 | int nFreeSlot; /* Number of unused pcache slots */ | ||||
| 56341 | int bUnderPressure; /* True if low on PAGECACHE memory */ | ||||
| 56342 | } pcache1_g; | ||||
| 56343 | |||||
| 56344 | /* | ||||
| 56345 | ** All code in this file should access the global structure above via the | ||||
| 56346 | ** alias "pcache1". This ensures that the WSD emulation is used when | ||||
| 56347 | ** compiling for systems that do not support real WSD. | ||||
| 56348 | */ | ||||
| 56349 | #define pcache1(pcache1_g) (GLOBAL(struct PCacheGlobal, pcache1_g)pcache1_g) | ||||
| 56350 | |||||
| 56351 | /* | ||||
| 56352 | ** Macros to enter and leave the PCache LRU mutex. | ||||
| 56353 | */ | ||||
| 56354 | #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE2==0 | ||||
| 56355 | # define pcache1EnterMutex(X)((void) (0)) assert((X)->mutex==0)((void) (0)) | ||||
| 56356 | # define pcache1LeaveMutex(X)((void) (0)) assert((X)->mutex==0)((void) (0)) | ||||
| 56357 | # define PCACHE1_MIGHT_USE_GROUP_MUTEX0 0 | ||||
| 56358 | #else | ||||
| 56359 | # define pcache1EnterMutex(X)((void) (0)) sqlite3_mutex_enter((X)->mutex) | ||||
| 56360 | # define pcache1LeaveMutex(X)((void) (0)) sqlite3_mutex_leave((X)->mutex) | ||||
| 56361 | # define PCACHE1_MIGHT_USE_GROUP_MUTEX0 1 | ||||
| 56362 | #endif | ||||
| 56363 | |||||
| 56364 | /******************************************************************************/ | ||||
| 56365 | /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/ | ||||
| 56366 | |||||
| 56367 | |||||
| 56368 | /* | ||||
| 56369 | ** This function is called during initialization if a static buffer is | ||||
| 56370 | ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE | ||||
| 56371 | ** verb to sqlite3_config(). Parameter pBuf points to an allocation large | ||||
| 56372 | ** enough to contain 'n' buffers of 'sz' bytes each. | ||||
| 56373 | ** | ||||
| 56374 | ** This routine is called from sqlite3_initialize() and so it is guaranteed | ||||
| 56375 | ** to be serialized already. There is no need for further mutexing. | ||||
| 56376 | */ | ||||
| 56377 | SQLITE_PRIVATEstatic void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ | ||||
| 56378 | if( pcache1(pcache1_g).isInit ){ | ||||
| 56379 | PgFreeslot *p; | ||||
| 56380 | if( pBuf==0 ) sz = n = 0; | ||||
| 56381 | if( n==0 ) sz = 0; | ||||
| 56382 | sz = ROUNDDOWN8(sz)((sz)&~7); | ||||
| 56383 | pcache1(pcache1_g).szSlot = sz; | ||||
| 56384 | pcache1(pcache1_g).nSlot = pcache1(pcache1_g).nFreeSlot = n; | ||||
| 56385 | pcache1(pcache1_g).nReserve = n>90 ? 10 : (n/10 + 1); | ||||
| 56386 | pcache1(pcache1_g).pStart = pBuf; | ||||
| 56387 | pcache1(pcache1_g).pFree = 0; | ||||
| 56388 | AtomicStore(&pcache1.bUnderPressure,0)__atomic_store_n((&(pcache1_g).bUnderPressure),(0),0); | ||||
| 56389 | while( n-- ){ | ||||
| 56390 | p = (PgFreeslot*)pBuf; | ||||
| 56391 | p->pNext = pcache1(pcache1_g).pFree; | ||||
| 56392 | pcache1(pcache1_g).pFree = p; | ||||
| 56393 | pBuf = (void*)&((char*)pBuf)[sz]; | ||||
| 56394 | } | ||||
| 56395 | pcache1(pcache1_g).pEnd = pBuf; | ||||
| 56396 | } | ||||
| 56397 | } | ||||
| 56398 | |||||
| 56399 | /* | ||||
| 56400 | ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return | ||||
| 56401 | ** true if pCache->pFree ends up containing one or more free pages. | ||||
| 56402 | */ | ||||
| 56403 | static int pcache1InitBulk(PCache1 *pCache){ | ||||
| 56404 | i64 szBulk; | ||||
| 56405 | char *zBulk; | ||||
| 56406 | if( pcache1(pcache1_g).nInitPage==0 ) return 0; | ||||
| 56407 | /* Do not bother with a bulk allocation if the cache size very small */ | ||||
| 56408 | if( pCache->nMax<3 ) return 0; | ||||
| 56409 | sqlite3BeginBenignMalloc(); | ||||
| 56410 | if( pcache1(pcache1_g).nInitPage>0 ){ | ||||
| 56411 | szBulk = pCache->szAlloc * (i64)pcache1(pcache1_g).nInitPage; | ||||
| 56412 | }else{ | ||||
| 56413 | szBulk = -1024 * (i64)pcache1(pcache1_g).nInitPage; | ||||
| 56414 | } | ||||
| 56415 | if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){ | ||||
| 56416 | szBulk = pCache->szAlloc*(i64)pCache->nMax; | ||||
| 56417 | } | ||||
| 56418 | zBulk = pCache->pBulk = sqlite3Malloc( szBulk ); | ||||
| 56419 | sqlite3EndBenignMalloc(); | ||||
| 56420 | if( zBulk ){ | ||||
| 56421 | int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc; | ||||
| 56422 | do{ | ||||
| 56423 | PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage]; | ||||
| 56424 | pX->page.pBuf = zBulk; | ||||
| 56425 | pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX))(((sizeof(*pX))+7)&~7); | ||||
| 56426 | assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) )((void) (0)); | ||||
| 56427 | pX->isBulkLocal = 1; | ||||
| 56428 | pX->isAnchor = 0; | ||||
| 56429 | pX->pNext = pCache->pFree; | ||||
| 56430 | pX->pLruPrev = 0; /* Initializing this saves a valgrind error */ | ||||
| 56431 | pCache->pFree = pX; | ||||
| 56432 | zBulk += pCache->szAlloc; | ||||
| 56433 | }while( --nBulk ); | ||||
| 56434 | } | ||||
| 56435 | return pCache->pFree!=0; | ||||
| 56436 | } | ||||
| 56437 | |||||
| 56438 | /* | ||||
| 56439 | ** Malloc function used within this file to allocate space from the buffer | ||||
| 56440 | ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no | ||||
| 56441 | ** such buffer exists or there is no space left in it, this function falls | ||||
| 56442 | ** back to sqlite3Malloc(). | ||||
| 56443 | ** | ||||
| 56444 | ** Multiple threads can run this routine at the same time. Global variables | ||||
| 56445 | ** in pcache1 need to be protected via mutex. | ||||
| 56446 | */ | ||||
| 56447 | static void *pcache1Alloc(int nByte){ | ||||
| 56448 | void *p = 0; | ||||
| 56449 | assert( sqlite3_mutex_notheld(pcache1.grp.mutex) )((void) (0)); | ||||
| 56450 | if( nByte<=pcache1(pcache1_g).szSlot ){ | ||||
| 56451 | sqlite3_mutex_enter(pcache1(pcache1_g).mutex); | ||||
| 56452 | p = (PgHdr1 *)pcache1(pcache1_g).pFree; | ||||
| 56453 | if( p ){ | ||||
| 56454 | pcache1(pcache1_g).pFree = pcache1(pcache1_g).pFree->pNext; | ||||
| 56455 | pcache1(pcache1_g).nFreeSlot--; | ||||
| 56456 | AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve)__atomic_store_n((&(pcache1_g).bUnderPressure),((pcache1_g ).nFreeSlot<(pcache1_g).nReserve),0); | ||||
| 56457 | assert( pcache1.nFreeSlot>=0 )((void) (0)); | ||||
| 56458 | sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE7, nByte); | ||||
| 56459 | sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED1, 1); | ||||
| 56460 | } | ||||
| 56461 | sqlite3_mutex_leave(pcache1(pcache1_g).mutex); | ||||
| 56462 | } | ||||
| 56463 | if( p==0 ){ | ||||
| 56464 | /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get | ||||
| 56465 | ** it from sqlite3Malloc instead. | ||||
| 56466 | */ | ||||
| 56467 | p = sqlite3Malloc(nByte); | ||||
| 56468 | #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS | ||||
| 56469 | if( p ){ | ||||
| 56470 | int sz = sqlite3MallocSize(p); | ||||
| 56471 | sqlite3_mutex_enter(pcache1(pcache1_g).mutex); | ||||
| 56472 | sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE7, nByte); | ||||
| 56473 | sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW2, sz); | ||||
| 56474 | sqlite3_mutex_leave(pcache1(pcache1_g).mutex); | ||||
| 56475 | } | ||||
| 56476 | #endif | ||||
| 56477 | sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); | ||||
| 56478 | } | ||||
| 56479 | return p; | ||||
| 56480 | } | ||||
| 56481 | |||||
| 56482 | /* | ||||
| 56483 | ** Free an allocated buffer obtained from pcache1Alloc(). | ||||
| 56484 | */ | ||||
| 56485 | static void pcache1Free(void *p){ | ||||
| 56486 | if( p==0 ) return; | ||||
| 56487 | if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd)(((uptr)(p)>=(uptr)((pcache1_g).pStart))&&((uptr)( p)<(uptr)((pcache1_g).pEnd))) ){ | ||||
| 56488 | PgFreeslot *pSlot; | ||||
| 56489 | sqlite3_mutex_enter(pcache1(pcache1_g).mutex); | ||||
| 56490 | sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED1, 1); | ||||
| 56491 | pSlot = (PgFreeslot*)p; | ||||
| 56492 | pSlot->pNext = pcache1(pcache1_g).pFree; | ||||
| 56493 | pcache1(pcache1_g).pFree = pSlot; | ||||
| 56494 | pcache1(pcache1_g).nFreeSlot++; | ||||
| 56495 | AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve)__atomic_store_n((&(pcache1_g).bUnderPressure),((pcache1_g ).nFreeSlot<(pcache1_g).nReserve),0); | ||||
| 56496 | assert( pcache1.nFreeSlot<=pcache1.nSlot )((void) (0)); | ||||
| 56497 | sqlite3_mutex_leave(pcache1(pcache1_g).mutex); | ||||
| 56498 | }else{ | ||||
| 56499 | assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) )((void) (0)); | ||||
| 56500 | sqlite3MemdebugSetType(p, MEMTYPE_HEAP); | ||||
| 56501 | #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS | ||||
| 56502 | { | ||||
| 56503 | int nFreed = 0; | ||||
| 56504 | nFreed = sqlite3MallocSize(p); | ||||
| 56505 | sqlite3_mutex_enter(pcache1(pcache1_g).mutex); | ||||
| 56506 | sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW2, nFreed); | ||||
| 56507 | sqlite3_mutex_leave(pcache1(pcache1_g).mutex); | ||||
| 56508 | } | ||||
| 56509 | #endif | ||||
| 56510 | sqlite3_free(p); | ||||
| 56511 | } | ||||
| 56512 | } | ||||
| 56513 | |||||
| 56514 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 56515 | /* | ||||
| 56516 | ** Return the size of a pcache allocation | ||||
| 56517 | */ | ||||
| 56518 | static int pcache1MemSize(void *p){ | ||||
| 56519 | if( p>=pcache1(pcache1_g).pStart && p<pcache1(pcache1_g).pEnd ){ | ||||
| 56520 | return pcache1(pcache1_g).szSlot; | ||||
| 56521 | }else{ | ||||
| 56522 | int iSize; | ||||
| 56523 | assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) )((void) (0)); | ||||
| 56524 | sqlite3MemdebugSetType(p, MEMTYPE_HEAP); | ||||
| 56525 | iSize = sqlite3MallocSize(p); | ||||
| 56526 | sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); | ||||
| 56527 | return iSize; | ||||
| 56528 | } | ||||
| 56529 | } | ||||
| 56530 | #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */ | ||||
| 56531 | |||||
| 56532 | /* | ||||
| 56533 | ** Allocate a new page object initially associated with cache pCache. | ||||
| 56534 | */ | ||||
| 56535 | static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){ | ||||
| 56536 | PgHdr1 *p = 0; | ||||
| 56537 | void *pPg; | ||||
| 56538 | |||||
| 56539 | assert( sqlite3_mutex_held(pCache->pGroup->mutex) )((void) (0)); | ||||
| 56540 | if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){ | ||||
| 56541 | assert( pCache->pFree!=0 )((void) (0)); | ||||
| 56542 | p = pCache->pFree; | ||||
| 56543 | pCache->pFree = p->pNext; | ||||
| 56544 | p->pNext = 0; | ||||
| 56545 | }else{ | ||||
| 56546 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 56547 | /* The group mutex must be released before pcache1Alloc() is called. This | ||||
| 56548 | ** is because it might call sqlite3_release_memory(), which assumes that | ||||
| 56549 | ** this mutex is not held. */ | ||||
| 56550 | assert( pcache1.separateCache==0 )((void) (0)); | ||||
| 56551 | assert( pCache->pGroup==&pcache1.grp )((void) (0)); | ||||
| 56552 | pcache1LeaveMutex(pCache->pGroup)((void) (0)); | ||||
| 56553 | #endif | ||||
| 56554 | if( benignMalloc ){ sqlite3BeginBenignMalloc(); } | ||||
| 56555 | pPg = pcache1Alloc(pCache->szAlloc); | ||||
| 56556 | if( benignMalloc ){ sqlite3EndBenignMalloc(); } | ||||
| 56557 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 56558 | pcache1EnterMutex(pCache->pGroup)((void) (0)); | ||||
| 56559 | #endif | ||||
| 56560 | if( pPg==0 ) return 0; | ||||
| 56561 | p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; | ||||
| 56562 | p->page.pBuf = pPg; | ||||
| 56563 | p->page.pExtra = (u8*)p + ROUND8(sizeof(*p))(((sizeof(*p))+7)&~7); | ||||
| 56564 | assert( EIGHT_BYTE_ALIGNMENT( p->page.pExtra ) )((void) (0)); | ||||
| 56565 | p->isBulkLocal = 0; | ||||
| 56566 | p->isAnchor = 0; | ||||
| 56567 | p->pLruPrev = 0; /* Initializing this saves a valgrind error */ | ||||
| 56568 | } | ||||
| 56569 | (*pCache->pnPurgeable)++; | ||||
| 56570 | return p; | ||||
| 56571 | } | ||||
| 56572 | |||||
| 56573 | /* | ||||
| 56574 | ** Free a page object allocated by pcache1AllocPage(). | ||||
| 56575 | */ | ||||
| 56576 | static void pcache1FreePage(PgHdr1 *p){ | ||||
| 56577 | PCache1 *pCache; | ||||
| 56578 | assert( p!=0 )((void) (0)); | ||||
| 56579 | pCache = p->pCache; | ||||
| 56580 | assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) )((void) (0)); | ||||
| 56581 | if( p->isBulkLocal ){ | ||||
| 56582 | p->pNext = pCache->pFree; | ||||
| 56583 | pCache->pFree = p; | ||||
| 56584 | }else{ | ||||
| 56585 | pcache1Free(p->page.pBuf); | ||||
| 56586 | } | ||||
| 56587 | (*pCache->pnPurgeable)--; | ||||
| 56588 | } | ||||
| 56589 | |||||
| 56590 | /* | ||||
| 56591 | ** Malloc function used by SQLite to obtain space from the buffer configured | ||||
| 56592 | ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer | ||||
| 56593 | ** exists, this function falls back to sqlite3Malloc(). | ||||
| 56594 | */ | ||||
| 56595 | SQLITE_PRIVATEstatic void *sqlite3PageMalloc(int sz){ | ||||
| 56596 | assert( sz<=65536+8 )((void) (0)); /* These allocations are never very large */ | ||||
| 56597 | return pcache1Alloc(sz); | ||||
| 56598 | } | ||||
| 56599 | |||||
| 56600 | /* | ||||
| 56601 | ** Free an allocated buffer obtained from sqlite3PageMalloc(). | ||||
| 56602 | */ | ||||
| 56603 | SQLITE_PRIVATEstatic void sqlite3PageFree(void *p){ | ||||
| 56604 | pcache1Free(p); | ||||
| 56605 | } | ||||
| 56606 | |||||
| 56607 | |||||
| 56608 | /* | ||||
| 56609 | ** Return true if it desirable to avoid allocating a new page cache | ||||
| 56610 | ** entry. | ||||
| 56611 | ** | ||||
| 56612 | ** If memory was allocated specifically to the page cache using | ||||
| 56613 | ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then | ||||
| 56614 | ** it is desirable to avoid allocating a new page cache entry because | ||||
| 56615 | ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient | ||||
| 56616 | ** for all page cache needs and we should not need to spill the | ||||
| 56617 | ** allocation onto the heap. | ||||
| 56618 | ** | ||||
| 56619 | ** Or, the heap is used for all page cache memory but the heap is | ||||
| 56620 | ** under memory pressure, then again it is desirable to avoid | ||||
| 56621 | ** allocating a new page cache entry in order to avoid stressing | ||||
| 56622 | ** the heap even further. | ||||
| 56623 | */ | ||||
| 56624 | static int pcache1UnderMemoryPressure(PCache1 *pCache){ | ||||
| 56625 | if( pcache1(pcache1_g).nSlot && (pCache->szPage+pCache->szExtra)<=pcache1(pcache1_g).szSlot ){ | ||||
| 56626 | return AtomicLoad(&pcache1.bUnderPressure)__atomic_load_n((&(pcache1_g).bUnderPressure),0); | ||||
| 56627 | }else{ | ||||
| 56628 | return sqlite3HeapNearlyFull(); | ||||
| 56629 | } | ||||
| 56630 | } | ||||
| 56631 | |||||
| 56632 | /******************************************************************************/ | ||||
| 56633 | /******** General Implementation Functions ************************************/ | ||||
| 56634 | |||||
| 56635 | /* | ||||
| 56636 | ** This function is used to resize the hash table used by the cache passed | ||||
| 56637 | ** as the first argument. | ||||
| 56638 | ** | ||||
| 56639 | ** The PCache mutex must be held when this function is called. | ||||
| 56640 | */ | ||||
| 56641 | static void pcache1ResizeHash(PCache1 *p){ | ||||
| 56642 | PgHdr1 **apNew; | ||||
| 56643 | u64 nNew; | ||||
| 56644 | u32 i; | ||||
| 56645 | |||||
| 56646 | assert( sqlite3_mutex_held(p->pGroup->mutex) )((void) (0)); | ||||
| 56647 | |||||
| 56648 | nNew = 2*(u64)p->nHash; | ||||
| 56649 | if( nNew<256 ){ | ||||
| 56650 | nNew = 256; | ||||
| 56651 | } | ||||
| 56652 | |||||
| 56653 | pcache1LeaveMutex(p->pGroup)((void) (0)); | ||||
| 56654 | if( p->nHash ){ sqlite3BeginBenignMalloc(); } | ||||
| 56655 | apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew); | ||||
| 56656 | if( p->nHash ){ sqlite3EndBenignMalloc(); } | ||||
| 56657 | pcache1EnterMutex(p->pGroup)((void) (0)); | ||||
| 56658 | if( apNew ){ | ||||
| 56659 | for(i=0; i<p->nHash; i++){ | ||||
| 56660 | PgHdr1 *pPage; | ||||
| 56661 | PgHdr1 *pNext = p->apHash[i]; | ||||
| 56662 | while( (pPage = pNext)!=0 ){ | ||||
| 56663 | unsigned int h = pPage->iKey % nNew; | ||||
| 56664 | pNext = pPage->pNext; | ||||
| 56665 | pPage->pNext = apNew[h]; | ||||
| 56666 | apNew[h] = pPage; | ||||
| 56667 | } | ||||
| 56668 | } | ||||
| 56669 | sqlite3_free(p->apHash); | ||||
| 56670 | p->apHash = apNew; | ||||
| 56671 | p->nHash = nNew; | ||||
| 56672 | } | ||||
| 56673 | } | ||||
| 56674 | |||||
| 56675 | /* | ||||
| 56676 | ** This function is used internally to remove the page pPage from the | ||||
| 56677 | ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup | ||||
| 56678 | ** LRU list, then this function is a no-op. | ||||
| 56679 | ** | ||||
| 56680 | ** The PGroup mutex must be held when this function is called. | ||||
| 56681 | */ | ||||
| 56682 | static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){ | ||||
| 56683 | assert( pPage!=0 )((void) (0)); | ||||
| 56684 | assert( PAGE_IS_UNPINNED(pPage) )((void) (0)); | ||||
| 56685 | assert( pPage->pLruNext )((void) (0)); | ||||
| 56686 | assert( pPage->pLruPrev )((void) (0)); | ||||
| 56687 | assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) )((void) (0)); | ||||
| 56688 | pPage->pLruPrev->pLruNext = pPage->pLruNext; | ||||
| 56689 | pPage->pLruNext->pLruPrev = pPage->pLruPrev; | ||||
| 56690 | pPage->pLruNext = 0; | ||||
| 56691 | /* pPage->pLruPrev = 0; | ||||
| 56692 | ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */ | ||||
| 56693 | assert( pPage->isAnchor==0 )((void) (0)); | ||||
| 56694 | assert( pPage->pCache->pGroup->lru.isAnchor==1 )((void) (0)); | ||||
| 56695 | pPage->pCache->nRecyclable--; | ||||
| 56696 | return pPage; | ||||
| 56697 | } | ||||
| 56698 | |||||
| 56699 | |||||
| 56700 | /* | ||||
| 56701 | ** Remove the page supplied as an argument from the hash table | ||||
| 56702 | ** (PCache1.apHash structure) that it is currently stored in. | ||||
| 56703 | ** Also free the page if freePage is true. | ||||
| 56704 | ** | ||||
| 56705 | ** The PGroup mutex must be held when this function is called. | ||||
| 56706 | */ | ||||
| 56707 | static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){ | ||||
| 56708 | unsigned int h; | ||||
| 56709 | PCache1 *pCache = pPage->pCache; | ||||
| 56710 | PgHdr1 **pp; | ||||
| 56711 | |||||
| 56712 | assert( sqlite3_mutex_held(pCache->pGroup->mutex) )((void) (0)); | ||||
| 56713 | h = pPage->iKey % pCache->nHash; | ||||
| 56714 | for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext); | ||||
| 56715 | *pp = (*pp)->pNext; | ||||
| 56716 | |||||
| 56717 | pCache->nPage--; | ||||
| 56718 | if( freeFlag ) pcache1FreePage(pPage); | ||||
| 56719 | } | ||||
| 56720 | |||||
| 56721 | /* | ||||
| 56722 | ** If there are currently more than nMaxPage pages allocated, try | ||||
| 56723 | ** to recycle pages to reduce the number allocated to nMaxPage. | ||||
| 56724 | */ | ||||
| 56725 | static void pcache1EnforceMaxPage(PCache1 *pCache){ | ||||
| 56726 | PGroup *pGroup = pCache->pGroup; | ||||
| 56727 | PgHdr1 *p; | ||||
| 56728 | assert( sqlite3_mutex_held(pGroup->mutex) )((void) (0)); | ||||
| 56729 | while( pGroup->nPurgeable>pGroup->nMaxPage | ||||
| 56730 | && (p=pGroup->lru.pLruPrev)->isAnchor==0 | ||||
| 56731 | ){ | ||||
| 56732 | assert( p->pCache->pGroup==pGroup )((void) (0)); | ||||
| 56733 | assert( PAGE_IS_UNPINNED(p) )((void) (0)); | ||||
| 56734 | pcache1PinPage(p); | ||||
| 56735 | pcache1RemoveFromHash(p, 1); | ||||
| 56736 | } | ||||
| 56737 | if( pCache->nPage==0 && pCache->pBulk ){ | ||||
| 56738 | sqlite3_free(pCache->pBulk); | ||||
| 56739 | pCache->pBulk = pCache->pFree = 0; | ||||
| 56740 | } | ||||
| 56741 | } | ||||
| 56742 | |||||
| 56743 | /* | ||||
| 56744 | ** Discard all pages from cache pCache with a page number (key value) | ||||
| 56745 | ** greater than or equal to iLimit. Any pinned pages that meet this | ||||
| 56746 | ** criteria are unpinned before they are discarded. | ||||
| 56747 | ** | ||||
| 56748 | ** The PCache mutex must be held when this function is called. | ||||
| 56749 | */ | ||||
| 56750 | static void pcache1TruncateUnsafe( | ||||
| 56751 | PCache1 *pCache, /* The cache to truncate */ | ||||
| 56752 | unsigned int iLimit /* Drop pages with this pgno or larger */ | ||||
| 56753 | ){ | ||||
| 56754 | TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */ | ||||
| 56755 | unsigned int h, iStop; | ||||
| 56756 | assert( sqlite3_mutex_held(pCache->pGroup->mutex) )((void) (0)); | ||||
| 56757 | assert( pCache->iMaxKey >= iLimit )((void) (0)); | ||||
| 56758 | assert( pCache->nHash > 0 )((void) (0)); | ||||
| 56759 | if( pCache->iMaxKey - iLimit < pCache->nHash ){ | ||||
| 56760 | /* If we are just shaving the last few pages off the end of the | ||||
| 56761 | ** cache, then there is no point in scanning the entire hash table. | ||||
| 56762 | ** Only scan those hash slots that might contain pages that need to | ||||
| 56763 | ** be removed. */ | ||||
| 56764 | h = iLimit % pCache->nHash; | ||||
| 56765 | iStop = pCache->iMaxKey % pCache->nHash; | ||||
| 56766 | TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */ | ||||
| 56767 | }else{ | ||||
| 56768 | /* This is the general case where many pages are being removed. | ||||
| 56769 | ** It is necessary to scan the entire hash table */ | ||||
| 56770 | h = pCache->nHash/2; | ||||
| 56771 | iStop = h - 1; | ||||
| 56772 | } | ||||
| 56773 | for(;;){ | ||||
| 56774 | PgHdr1 **pp; | ||||
| 56775 | PgHdr1 *pPage; | ||||
| 56776 | assert( h<pCache->nHash )((void) (0)); | ||||
| 56777 | pp = &pCache->apHash[h]; | ||||
| 56778 | while( (pPage = *pp)!=0 ){ | ||||
| 56779 | if( pPage->iKey>=iLimit ){ | ||||
| 56780 | pCache->nPage--; | ||||
| 56781 | *pp = pPage->pNext; | ||||
| 56782 | if( PAGE_IS_UNPINNED(pPage)((pPage)->pLruNext!=0) ) pcache1PinPage(pPage); | ||||
| 56783 | pcache1FreePage(pPage); | ||||
| 56784 | }else{ | ||||
| 56785 | pp = &pPage->pNext; | ||||
| 56786 | TESTONLY( if( nPage>=0 ) nPage++; ) | ||||
| 56787 | } | ||||
| 56788 | } | ||||
| 56789 | if( h==iStop ) break; | ||||
| 56790 | h = (h+1) % pCache->nHash; | ||||
| 56791 | } | ||||
| 56792 | assert( nPage<0 || pCache->nPage==(unsigned)nPage )((void) (0)); | ||||
| 56793 | } | ||||
| 56794 | |||||
| 56795 | /******************************************************************************/ | ||||
| 56796 | /******** sqlite3_pcache Methods **********************************************/ | ||||
| 56797 | |||||
| 56798 | /* | ||||
| 56799 | ** Implementation of the sqlite3_pcache.xInit method. | ||||
| 56800 | */ | ||||
| 56801 | static int pcache1Init(void *NotUsed){ | ||||
| 56802 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 56803 | assert( pcache1.isInit==0 )((void) (0)); | ||||
| 56804 | memset(&pcache1(pcache1_g), 0, sizeof(pcache1(pcache1_g))); | ||||
| 56805 | |||||
| 56806 | |||||
| 56807 | /* | ||||
| 56808 | ** The pcache1.separateCache variable is true if each PCache has its own | ||||
| 56809 | ** private PGroup (mode-1). pcache1.separateCache is false if the single | ||||
| 56810 | ** PGroup in pcache1.grp is used for all page caches (mode-2). | ||||
| 56811 | ** | ||||
| 56812 | ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT | ||||
| 56813 | ** | ||||
| 56814 | ** * Use a unified cache in single-threaded applications that have | ||||
| 56815 | ** configured a start-time buffer for use as page-cache memory using | ||||
| 56816 | ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL | ||||
| 56817 | ** pBuf argument. | ||||
| 56818 | ** | ||||
| 56819 | ** * Otherwise use separate caches (mode-1) | ||||
| 56820 | */ | ||||
| 56821 | #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) | ||||
| 56822 | pcache1(pcache1_g).separateCache = 0; | ||||
| 56823 | #elif SQLITE_THREADSAFE2 | ||||
| 56824 | pcache1(pcache1_g).separateCache = sqlite3GlobalConfigsqlite3Config.pPage==0 | ||||
| 56825 | || sqlite3GlobalConfigsqlite3Config.bCoreMutex>0; | ||||
| 56826 | #else | ||||
| 56827 | pcache1(pcache1_g).separateCache = sqlite3GlobalConfigsqlite3Config.pPage==0; | ||||
| 56828 | #endif | ||||
| 56829 | |||||
| 56830 | #if SQLITE_THREADSAFE2 | ||||
| 56831 | if( sqlite3GlobalConfigsqlite3Config.bCoreMutex ){ | ||||
| 56832 | pcache1(pcache1_g).grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU6); | ||||
| 56833 | pcache1(pcache1_g).mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM7); | ||||
| 56834 | } | ||||
| 56835 | #endif | ||||
| 56836 | if( pcache1(pcache1_g).separateCache | ||||
| 56837 | && sqlite3GlobalConfigsqlite3Config.nPage!=0 | ||||
| 56838 | && sqlite3GlobalConfigsqlite3Config.pPage==0 | ||||
| 56839 | ){ | ||||
| 56840 | pcache1(pcache1_g).nInitPage = sqlite3GlobalConfigsqlite3Config.nPage; | ||||
| 56841 | }else{ | ||||
| 56842 | pcache1(pcache1_g).nInitPage = 0; | ||||
| 56843 | } | ||||
| 56844 | pcache1(pcache1_g).grp.mxPinned = 10; | ||||
| 56845 | pcache1(pcache1_g).isInit = 1; | ||||
| 56846 | return SQLITE_OK0; | ||||
| 56847 | } | ||||
| 56848 | |||||
| 56849 | /* | ||||
| 56850 | ** Implementation of the sqlite3_pcache.xShutdown method. | ||||
| 56851 | ** Note that the static mutex allocated in xInit does | ||||
| 56852 | ** not need to be freed. | ||||
| 56853 | */ | ||||
| 56854 | static void pcache1Shutdown(void *NotUsed){ | ||||
| 56855 | UNUSED_PARAMETER(NotUsed)(void)(NotUsed); | ||||
| 56856 | assert( pcache1.isInit!=0 )((void) (0)); | ||||
| 56857 | memset(&pcache1(pcache1_g), 0, sizeof(pcache1(pcache1_g))); | ||||
| 56858 | } | ||||
| 56859 | |||||
| 56860 | /* forward declaration */ | ||||
| 56861 | static void pcache1Destroy(sqlite3_pcache *p); | ||||
| 56862 | |||||
| 56863 | /* | ||||
| 56864 | ** Implementation of the sqlite3_pcache.xCreate method. | ||||
| 56865 | ** | ||||
| 56866 | ** Allocate a new cache. | ||||
| 56867 | */ | ||||
| 56868 | static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ | ||||
| 56869 | PCache1 *pCache; /* The newly created page cache */ | ||||
| 56870 | PGroup *pGroup; /* The group the new page cache will belong to */ | ||||
| 56871 | i64 sz; /* Bytes of memory required to allocate the new cache */ | ||||
| 56872 | |||||
| 56873 | assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 )((void) (0)); | ||||
| 56874 | assert( szExtra < 300 )((void) (0)); | ||||
| 56875 | |||||
| 56876 | sz = sizeof(PCache1) + sizeof(PGroup)*pcache1(pcache1_g).separateCache; | ||||
| 56877 | pCache = (PCache1 *)sqlite3MallocZero(sz); | ||||
| 56878 | if( pCache ){ | ||||
| 56879 | if( pcache1(pcache1_g).separateCache ){ | ||||
| 56880 | pGroup = (PGroup*)&pCache[1]; | ||||
| 56881 | pGroup->mxPinned = 10; | ||||
| 56882 | }else{ | ||||
| 56883 | pGroup = &pcache1(pcache1_g).grp; | ||||
| 56884 | } | ||||
| 56885 | pcache1EnterMutex(pGroup)((void) (0)); | ||||
| 56886 | if( pGroup->lru.isAnchor==0 ){ | ||||
| 56887 | pGroup->lru.isAnchor = 1; | ||||
| 56888 | pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru; | ||||
| 56889 | } | ||||
| 56890 | pCache->pGroup = pGroup; | ||||
| 56891 | pCache->szPage = szPage; | ||||
| 56892 | pCache->szExtra = szExtra; | ||||
| 56893 | pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1))(((sizeof(PgHdr1))+7)&~7); | ||||
| 56894 | pCache->bPurgeable = (bPurgeable ? 1 : 0); | ||||
| 56895 | pcache1ResizeHash(pCache); | ||||
| 56896 | if( bPurgeable ){ | ||||
| 56897 | pCache->nMin = 10; | ||||
| 56898 | pGroup->nMinPage += pCache->nMin; | ||||
| 56899 | pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; | ||||
| 56900 | pCache->pnPurgeable = &pGroup->nPurgeable; | ||||
| 56901 | }else{ | ||||
| 56902 | pCache->pnPurgeable = &pCache->nPurgeableDummy; | ||||
| 56903 | } | ||||
| 56904 | pcache1LeaveMutex(pGroup)((void) (0)); | ||||
| 56905 | if( pCache->nHash==0 ){ | ||||
| 56906 | pcache1Destroy((sqlite3_pcache*)pCache); | ||||
| 56907 | pCache = 0; | ||||
| 56908 | } | ||||
| 56909 | } | ||||
| 56910 | return (sqlite3_pcache *)pCache; | ||||
| 56911 | } | ||||
| 56912 | |||||
| 56913 | /* | ||||
| 56914 | ** Implementation of the sqlite3_pcache.xCachesize method. | ||||
| 56915 | ** | ||||
| 56916 | ** Configure the cache_size limit for a cache. | ||||
| 56917 | */ | ||||
| 56918 | static void pcache1Cachesize(sqlite3_pcache *p, int nMax){ | ||||
| 56919 | PCache1 *pCache = (PCache1 *)p; | ||||
| 56920 | u32 n; | ||||
| 56921 | assert( nMax>=0 )((void) (0)); | ||||
| 56922 | if( pCache->bPurgeable ){ | ||||
| 56923 | PGroup *pGroup = pCache->pGroup; | ||||
| 56924 | pcache1EnterMutex(pGroup)((void) (0)); | ||||
| 56925 | n = (u32)nMax; | ||||
| 56926 | if( n > 0x7fff0000 - pGroup->nMaxPage + pCache->nMax ){ | ||||
| 56927 | n = 0x7fff0000 - pGroup->nMaxPage + pCache->nMax; | ||||
| 56928 | } | ||||
| 56929 | pGroup->nMaxPage += (n - pCache->nMax); | ||||
| 56930 | pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; | ||||
| 56931 | pCache->nMax = n; | ||||
| 56932 | pCache->n90pct = pCache->nMax*9/10; | ||||
| 56933 | pcache1EnforceMaxPage(pCache); | ||||
| 56934 | pcache1LeaveMutex(pGroup)((void) (0)); | ||||
| 56935 | } | ||||
| 56936 | } | ||||
| 56937 | |||||
| 56938 | /* | ||||
| 56939 | ** Implementation of the sqlite3_pcache.xShrink method. | ||||
| 56940 | ** | ||||
| 56941 | ** Free up as much memory as possible. | ||||
| 56942 | */ | ||||
| 56943 | static void pcache1Shrink(sqlite3_pcache *p){ | ||||
| 56944 | PCache1 *pCache = (PCache1*)p; | ||||
| 56945 | if( pCache->bPurgeable ){ | ||||
| 56946 | PGroup *pGroup = pCache->pGroup; | ||||
| 56947 | unsigned int savedMaxPage; | ||||
| 56948 | pcache1EnterMutex(pGroup)((void) (0)); | ||||
| 56949 | savedMaxPage = pGroup->nMaxPage; | ||||
| 56950 | pGroup->nMaxPage = 0; | ||||
| 56951 | pcache1EnforceMaxPage(pCache); | ||||
| 56952 | pGroup->nMaxPage = savedMaxPage; | ||||
| 56953 | pcache1LeaveMutex(pGroup)((void) (0)); | ||||
| 56954 | } | ||||
| 56955 | } | ||||
| 56956 | |||||
| 56957 | /* | ||||
| 56958 | ** Implementation of the sqlite3_pcache.xPagecount method. | ||||
| 56959 | */ | ||||
| 56960 | static int pcache1Pagecount(sqlite3_pcache *p){ | ||||
| 56961 | int n; | ||||
| 56962 | PCache1 *pCache = (PCache1*)p; | ||||
| 56963 | pcache1EnterMutex(pCache->pGroup)((void) (0)); | ||||
| 56964 | n = pCache->nPage; | ||||
| 56965 | pcache1LeaveMutex(pCache->pGroup)((void) (0)); | ||||
| 56966 | return n; | ||||
| 56967 | } | ||||
| 56968 | |||||
| 56969 | |||||
| 56970 | /* | ||||
| 56971 | ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described | ||||
| 56972 | ** in the header of the pcache1Fetch() procedure. | ||||
| 56973 | ** | ||||
| 56974 | ** This steps are broken out into a separate procedure because they are | ||||
| 56975 | ** usually not needed, and by avoiding the stack initialization required | ||||
| 56976 | ** for these steps, the main pcache1Fetch() procedure can run faster. | ||||
| 56977 | */ | ||||
| 56978 | static SQLITE_NOINLINE__attribute__((noinline)) PgHdr1 *pcache1FetchStage2( | ||||
| 56979 | PCache1 *pCache, | ||||
| 56980 | unsigned int iKey, | ||||
| 56981 | int createFlag | ||||
| 56982 | ){ | ||||
| 56983 | unsigned int nPinned; | ||||
| 56984 | PGroup *pGroup = pCache->pGroup; | ||||
| 56985 | PgHdr1 *pPage = 0; | ||||
| 56986 | |||||
| 56987 | /* Step 3: Abort if createFlag is 1 but the cache is nearly full */ | ||||
| 56988 | assert( pCache->nPage >= pCache->nRecyclable )((void) (0)); | ||||
| 56989 | nPinned = pCache->nPage - pCache->nRecyclable; | ||||
| 56990 | assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage )((void) (0)); | ||||
| 56991 | assert( pCache->n90pct == pCache->nMax*9/10 )((void) (0)); | ||||
| 56992 | if( createFlag==1 && ( | ||||
| 56993 | nPinned>=pGroup->mxPinned | ||||
| 56994 | || nPinned>=pCache->n90pct | ||||
| 56995 | || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned) | ||||
| 56996 | )){ | ||||
| 56997 | return 0; | ||||
| 56998 | } | ||||
| 56999 | |||||
| 57000 | if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache); | ||||
| 57001 | assert( pCache->nHash>0 && pCache->apHash )((void) (0)); | ||||
| 57002 | |||||
| 57003 | /* Step 4. Try to recycle a page. */ | ||||
| 57004 | if( pCache->bPurgeable | ||||
| 57005 | && !pGroup->lru.pLruPrev->isAnchor | ||||
| 57006 | && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache)) | ||||
| 57007 | ){ | ||||
| 57008 | PCache1 *pOther; | ||||
| 57009 | pPage = pGroup->lru.pLruPrev; | ||||
| 57010 | assert( PAGE_IS_UNPINNED(pPage) )((void) (0)); | ||||
| 57011 | pcache1RemoveFromHash(pPage, 0); | ||||
| 57012 | pcache1PinPage(pPage); | ||||
| 57013 | pOther = pPage->pCache; | ||||
| 57014 | if( pOther->szAlloc != pCache->szAlloc ){ | ||||
| 57015 | pcache1FreePage(pPage); | ||||
| 57016 | pPage = 0; | ||||
| 57017 | }else{ | ||||
| 57018 | pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable); | ||||
| 57019 | } | ||||
| 57020 | } | ||||
| 57021 | |||||
| 57022 | /* Step 5. If a usable page buffer has still not been found, | ||||
| 57023 | ** attempt to allocate a new one. | ||||
| 57024 | */ | ||||
| 57025 | if( !pPage ){ | ||||
| 57026 | pPage = pcache1AllocPage(pCache, createFlag==1); | ||||
| 57027 | } | ||||
| 57028 | |||||
| 57029 | if( pPage ){ | ||||
| 57030 | unsigned int h = iKey % pCache->nHash; | ||||
| 57031 | pCache->nPage++; | ||||
| 57032 | pPage->iKey = iKey; | ||||
| 57033 | pPage->pNext = pCache->apHash[h]; | ||||
| 57034 | pPage->pCache = pCache; | ||||
| 57035 | pPage->pLruNext = 0; | ||||
| 57036 | /* pPage->pLruPrev = 0; | ||||
| 57037 | ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */ | ||||
| 57038 | *(void **)pPage->page.pExtra = 0; | ||||
| 57039 | pCache->apHash[h] = pPage; | ||||
| 57040 | if( iKey>pCache->iMaxKey ){ | ||||
| 57041 | pCache->iMaxKey = iKey; | ||||
| 57042 | } | ||||
| 57043 | } | ||||
| 57044 | return pPage; | ||||
| 57045 | } | ||||
| 57046 | |||||
| 57047 | /* | ||||
| 57048 | ** Implementation of the sqlite3_pcache.xFetch method. | ||||
| 57049 | ** | ||||
| 57050 | ** Fetch a page by key value. | ||||
| 57051 | ** | ||||
| 57052 | ** Whether or not a new page may be allocated by this function depends on | ||||
| 57053 | ** the value of the createFlag argument. 0 means do not allocate a new | ||||
| 57054 | ** page. 1 means allocate a new page if space is easily available. 2 | ||||
| 57055 | ** means to try really hard to allocate a new page. | ||||
| 57056 | ** | ||||
| 57057 | ** For a non-purgeable cache (a cache used as the storage for an in-memory | ||||
| 57058 | ** database) there is really no difference between createFlag 1 and 2. So | ||||
| 57059 | ** the calling function (pcache.c) will never have a createFlag of 1 on | ||||
| 57060 | ** a non-purgeable cache. | ||||
| 57061 | ** | ||||
| 57062 | ** There are three different approaches to obtaining space for a page, | ||||
| 57063 | ** depending on the value of parameter createFlag (which may be 0, 1 or 2). | ||||
| 57064 | ** | ||||
| 57065 | ** 1. Regardless of the value of createFlag, the cache is searched for a | ||||
| 57066 | ** copy of the requested page. If one is found, it is returned. | ||||
| 57067 | ** | ||||
| 57068 | ** 2. If createFlag==0 and the page is not already in the cache, NULL is | ||||
| 57069 | ** returned. | ||||
| 57070 | ** | ||||
| 57071 | ** 3. If createFlag is 1, and the page is not already in the cache, then | ||||
| 57072 | ** return NULL (do not allocate a new page) if any of the following | ||||
| 57073 | ** conditions are true: | ||||
| 57074 | ** | ||||
| 57075 | ** (a) the number of pages pinned by the cache is greater than | ||||
| 57076 | ** PCache1.nMax, or | ||||
| 57077 | ** | ||||
| 57078 | ** (b) the number of pages pinned by the cache is greater than | ||||
| 57079 | ** the sum of nMax for all purgeable caches, less the sum of | ||||
| 57080 | ** nMin for all other purgeable caches, or | ||||
| 57081 | ** | ||||
| 57082 | ** 4. If none of the first three conditions apply and the cache is marked | ||||
| 57083 | ** as purgeable, and if one of the following is true: | ||||
| 57084 | ** | ||||
| 57085 | ** (a) The number of pages allocated for the cache is already | ||||
| 57086 | ** PCache1.nMax, or | ||||
| 57087 | ** | ||||
| 57088 | ** (b) The number of pages allocated for all purgeable caches is | ||||
| 57089 | ** already equal to or greater than the sum of nMax for all | ||||
| 57090 | ** purgeable caches, | ||||
| 57091 | ** | ||||
| 57092 | ** (c) The system is under memory pressure and wants to avoid | ||||
| 57093 | ** unnecessary pages cache entry allocations | ||||
| 57094 | ** | ||||
| 57095 | ** then attempt to recycle a page from the LRU list. If it is the right | ||||
| 57096 | ** size, return the recycled buffer. Otherwise, free the buffer and | ||||
| 57097 | ** proceed to step 5. | ||||
| 57098 | ** | ||||
| 57099 | ** 5. Otherwise, allocate and return a new page buffer. | ||||
| 57100 | ** | ||||
| 57101 | ** There are two versions of this routine. pcache1FetchWithMutex() is | ||||
| 57102 | ** the general case. pcache1FetchNoMutex() is a faster implementation for | ||||
| 57103 | ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper | ||||
| 57104 | ** invokes the appropriate routine. | ||||
| 57105 | */ | ||||
| 57106 | static PgHdr1 *pcache1FetchNoMutex( | ||||
| 57107 | sqlite3_pcache *p, | ||||
| 57108 | unsigned int iKey, | ||||
| 57109 | int createFlag | ||||
| 57110 | ){ | ||||
| 57111 | PCache1 *pCache = (PCache1 *)p; | ||||
| 57112 | PgHdr1 *pPage = 0; | ||||
| 57113 | |||||
| 57114 | /* Step 1: Search the hash table for an existing entry. */ | ||||
| 57115 | pPage = pCache->apHash[iKey % pCache->nHash]; | ||||
| 57116 | while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; } | ||||
| 57117 | |||||
| 57118 | /* Step 2: If the page was found in the hash table, then return it. | ||||
| 57119 | ** If the page was not in the hash table and createFlag is 0, abort. | ||||
| 57120 | ** Otherwise (page not in hash and createFlag!=0) continue with | ||||
| 57121 | ** subsequent steps to try to create the page. */ | ||||
| 57122 | if( pPage ){ | ||||
| 57123 | if( PAGE_IS_UNPINNED(pPage)((pPage)->pLruNext!=0) ){ | ||||
| 57124 | return pcache1PinPage(pPage); | ||||
| 57125 | }else{ | ||||
| 57126 | return pPage; | ||||
| 57127 | } | ||||
| 57128 | }else if( createFlag ){ | ||||
| 57129 | /* Steps 3, 4, and 5 implemented by this subroutine */ | ||||
| 57130 | return pcache1FetchStage2(pCache, iKey, createFlag); | ||||
| 57131 | }else{ | ||||
| 57132 | return 0; | ||||
| 57133 | } | ||||
| 57134 | } | ||||
| 57135 | #if PCACHE1_MIGHT_USE_GROUP_MUTEX0 | ||||
| 57136 | static PgHdr1 *pcache1FetchWithMutex( | ||||
| 57137 | sqlite3_pcache *p, | ||||
| 57138 | unsigned int iKey, | ||||
| 57139 | int createFlag | ||||
| 57140 | ){ | ||||
| 57141 | PCache1 *pCache = (PCache1 *)p; | ||||
| 57142 | PgHdr1 *pPage; | ||||
| 57143 | |||||
| 57144 | pcache1EnterMutex(pCache->pGroup)((void) (0)); | ||||
| 57145 | pPage = pcache1FetchNoMutex(p, iKey, createFlag); | ||||
| 57146 | assert( pPage==0 || pCache->iMaxKey>=iKey )((void) (0)); | ||||
| 57147 | pcache1LeaveMutex(pCache->pGroup)((void) (0)); | ||||
| 57148 | return pPage; | ||||
| 57149 | } | ||||
| 57150 | #endif | ||||
| 57151 | static sqlite3_pcache_page *pcache1Fetch( | ||||
| 57152 | sqlite3_pcache *p, | ||||
| 57153 | unsigned int iKey, | ||||
| 57154 | int createFlag | ||||
| 57155 | ){ | ||||
| 57156 | #if PCACHE1_MIGHT_USE_GROUP_MUTEX0 || defined(SQLITE_DEBUG) | ||||
| 57157 | PCache1 *pCache = (PCache1 *)p; | ||||
| 57158 | #endif | ||||
| 57159 | |||||
| 57160 | assert( offsetof(PgHdr1,page)==0 )((void) (0)); | ||||
| 57161 | assert( pCache->bPurgeable || createFlag!=1 )((void) (0)); | ||||
| 57162 | assert( pCache->bPurgeable || pCache->nMin==0 )((void) (0)); | ||||
| 57163 | assert( pCache->bPurgeable==0 || pCache->nMin==10 )((void) (0)); | ||||
| 57164 | assert( pCache->nMin==0 || pCache->bPurgeable )((void) (0)); | ||||
| 57165 | assert( pCache->nHash>0 )((void) (0)); | ||||
| 57166 | #if PCACHE1_MIGHT_USE_GROUP_MUTEX0 | ||||
| 57167 | if( pCache->pGroup->mutex ){ | ||||
| 57168 | return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag); | ||||
| 57169 | }else | ||||
| 57170 | #endif | ||||
| 57171 | { | ||||
| 57172 | return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag); | ||||
| 57173 | } | ||||
| 57174 | } | ||||
| 57175 | |||||
| 57176 | |||||
| 57177 | /* | ||||
| 57178 | ** Implementation of the sqlite3_pcache.xUnpin method. | ||||
| 57179 | ** | ||||
| 57180 | ** Mark a page as unpinned (eligible for asynchronous recycling). | ||||
| 57181 | */ | ||||
| 57182 | static void pcache1Unpin( | ||||
| 57183 | sqlite3_pcache *p, | ||||
| 57184 | sqlite3_pcache_page *pPg, | ||||
| 57185 | int reuseUnlikely | ||||
| 57186 | ){ | ||||
| 57187 | PCache1 *pCache = (PCache1 *)p; | ||||
| 57188 | PgHdr1 *pPage = (PgHdr1 *)pPg; | ||||
| 57189 | PGroup *pGroup = pCache->pGroup; | ||||
| 57190 | |||||
| 57191 | assert( pPage->pCache==pCache )((void) (0)); | ||||
| 57192 | pcache1EnterMutex(pGroup)((void) (0)); | ||||
| 57193 | |||||
| 57194 | /* It is an error to call this function if the page is already | ||||
| 57195 | ** part of the PGroup LRU list. | ||||
| 57196 | */ | ||||
| 57197 | assert( pPage->pLruNext==0 )((void) (0)); | ||||
| 57198 | assert( PAGE_IS_PINNED(pPage) )((void) (0)); | ||||
| 57199 | |||||
| 57200 | if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){ | ||||
| 57201 | pcache1RemoveFromHash(pPage, 1); | ||||
| 57202 | }else{ | ||||
| 57203 | /* Add the page to the PGroup LRU list. */ | ||||
| 57204 | PgHdr1 **ppFirst = &pGroup->lru.pLruNext; | ||||
| 57205 | pPage->pLruPrev = &pGroup->lru; | ||||
| 57206 | (pPage->pLruNext = *ppFirst)->pLruPrev = pPage; | ||||
| 57207 | *ppFirst = pPage; | ||||
| 57208 | pCache->nRecyclable++; | ||||
| 57209 | } | ||||
| 57210 | |||||
| 57211 | pcache1LeaveMutex(pCache->pGroup)((void) (0)); | ||||
| 57212 | } | ||||
| 57213 | |||||
| 57214 | /* | ||||
| 57215 | ** Implementation of the sqlite3_pcache.xRekey method. | ||||
| 57216 | */ | ||||
| 57217 | static void pcache1Rekey( | ||||
| 57218 | sqlite3_pcache *p, | ||||
| 57219 | sqlite3_pcache_page *pPg, | ||||
| 57220 | unsigned int iOld, | ||||
| 57221 | unsigned int iNew | ||||
| 57222 | ){ | ||||
| 57223 | PCache1 *pCache = (PCache1 *)p; | ||||
| 57224 | PgHdr1 *pPage = (PgHdr1 *)pPg; | ||||
| 57225 | PgHdr1 **pp; | ||||
| 57226 | unsigned int hOld, hNew; | ||||
| 57227 | assert( pPage->iKey==iOld )((void) (0)); | ||||
| 57228 | assert( pPage->pCache==pCache )((void) (0)); | ||||
| 57229 | assert( iOld!=iNew )((void) (0)); /* The page number really is changing */ | ||||
| 57230 | |||||
| 57231 | pcache1EnterMutex(pCache->pGroup)((void) (0)); | ||||
| 57232 | |||||
| 57233 | assert( pcache1FetchNoMutex(p, iOld, 0)==pPage )((void) (0)); /* pPg really is iOld */ | ||||
| 57234 | hOld = iOld%pCache->nHash; | ||||
| 57235 | pp = &pCache->apHash[hOld]; | ||||
| 57236 | while( (*pp)!=pPage ){ | ||||
| 57237 | pp = &(*pp)->pNext; | ||||
| 57238 | } | ||||
| 57239 | *pp = pPage->pNext; | ||||
| 57240 | |||||
| 57241 | assert( pcache1FetchNoMutex(p, iNew, 0)==0 )((void) (0)); /* iNew not in cache */ | ||||
| 57242 | hNew = iNew%pCache->nHash; | ||||
| 57243 | pPage->iKey = iNew; | ||||
| 57244 | pPage->pNext = pCache->apHash[hNew]; | ||||
| 57245 | pCache->apHash[hNew] = pPage; | ||||
| 57246 | if( iNew>pCache->iMaxKey ){ | ||||
| 57247 | pCache->iMaxKey = iNew; | ||||
| 57248 | } | ||||
| 57249 | |||||
| 57250 | pcache1LeaveMutex(pCache->pGroup)((void) (0)); | ||||
| 57251 | } | ||||
| 57252 | |||||
| 57253 | /* | ||||
| 57254 | ** Implementation of the sqlite3_pcache.xTruncate method. | ||||
| 57255 | ** | ||||
| 57256 | ** Discard all unpinned pages in the cache with a page number equal to | ||||
| 57257 | ** or greater than parameter iLimit. Any pinned pages with a page number | ||||
| 57258 | ** equal to or greater than iLimit are implicitly unpinned. | ||||
| 57259 | */ | ||||
| 57260 | static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){ | ||||
| 57261 | PCache1 *pCache = (PCache1 *)p; | ||||
| 57262 | pcache1EnterMutex(pCache->pGroup)((void) (0)); | ||||
| 57263 | if( iLimit<=pCache->iMaxKey ){ | ||||
| 57264 | pcache1TruncateUnsafe(pCache, iLimit); | ||||
| 57265 | pCache->iMaxKey = iLimit-1; | ||||
| 57266 | } | ||||
| 57267 | pcache1LeaveMutex(pCache->pGroup)((void) (0)); | ||||
| 57268 | } | ||||
| 57269 | |||||
| 57270 | /* | ||||
| 57271 | ** Implementation of the sqlite3_pcache.xDestroy method. | ||||
| 57272 | ** | ||||
| 57273 | ** Destroy a cache allocated using pcache1Create(). | ||||
| 57274 | */ | ||||
| 57275 | static void pcache1Destroy(sqlite3_pcache *p){ | ||||
| 57276 | PCache1 *pCache = (PCache1 *)p; | ||||
| 57277 | PGroup *pGroup = pCache->pGroup; | ||||
| 57278 | assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) )((void) (0)); | ||||
| 57279 | pcache1EnterMutex(pGroup)((void) (0)); | ||||
| 57280 | if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0); | ||||
| 57281 | assert( pGroup->nMaxPage >= pCache->nMax )((void) (0)); | ||||
| 57282 | pGroup->nMaxPage -= pCache->nMax; | ||||
| 57283 | assert( pGroup->nMinPage >= pCache->nMin )((void) (0)); | ||||
| 57284 | pGroup->nMinPage -= pCache->nMin; | ||||
| 57285 | pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; | ||||
| 57286 | pcache1EnforceMaxPage(pCache); | ||||
| 57287 | pcache1LeaveMutex(pGroup)((void) (0)); | ||||
| 57288 | sqlite3_free(pCache->pBulk); | ||||
| 57289 | sqlite3_free(pCache->apHash); | ||||
| 57290 | sqlite3_free(pCache); | ||||
| 57291 | } | ||||
| 57292 | |||||
| 57293 | /* | ||||
| 57294 | ** This function is called during initialization (sqlite3_initialize()) to | ||||
| 57295 | ** install the default pluggable cache module, assuming the user has not | ||||
| 57296 | ** already provided an alternative. | ||||
| 57297 | */ | ||||
| 57298 | SQLITE_PRIVATEstatic void sqlite3PCacheSetDefault(void){ | ||||
| 57299 | static const sqlite3_pcache_methods2 defaultMethods = { | ||||
| 57300 | 1, /* iVersion */ | ||||
| 57301 | 0, /* pArg */ | ||||
| 57302 | pcache1Init, /* xInit */ | ||||
| 57303 | pcache1Shutdown, /* xShutdown */ | ||||
| 57304 | pcache1Create, /* xCreate */ | ||||
| 57305 | pcache1Cachesize, /* xCachesize */ | ||||
| 57306 | pcache1Pagecount, /* xPagecount */ | ||||
| 57307 | pcache1Fetch, /* xFetch */ | ||||
| 57308 | pcache1Unpin, /* xUnpin */ | ||||
| 57309 | pcache1Rekey, /* xRekey */ | ||||
| 57310 | pcache1Truncate, /* xTruncate */ | ||||
| 57311 | pcache1Destroy, /* xDestroy */ | ||||
| 57312 | pcache1Shrink /* xShrink */ | ||||
| 57313 | }; | ||||
| 57314 | sqlite3_config(SQLITE_CONFIG_PCACHE218, &defaultMethods); | ||||
| 57315 | } | ||||
| 57316 | |||||
| 57317 | /* | ||||
| 57318 | ** Return the size of the header on each page of this PCACHE implementation. | ||||
| 57319 | */ | ||||
| 57320 | SQLITE_PRIVATEstatic int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1))(((sizeof(PgHdr1))+7)&~7); } | ||||
| 57321 | |||||
| 57322 | /* | ||||
| 57323 | ** Return the global mutex used by this PCACHE implementation. The | ||||
| 57324 | ** sqlite3_status() routine needs access to this mutex. | ||||
| 57325 | */ | ||||
| 57326 | SQLITE_PRIVATEstatic sqlite3_mutex *sqlite3Pcache1Mutex(void){ | ||||
| 57327 | return pcache1(pcache1_g).mutex; | ||||
| 57328 | } | ||||
| 57329 | |||||
| 57330 | #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT | ||||
| 57331 | /* | ||||
| 57332 | ** This function is called to free superfluous dynamically allocated memory | ||||
| 57333 | ** held by the pager system. Memory in use by any SQLite pager allocated | ||||
| 57334 | ** by the current thread may be sqlite3_free()ed. | ||||
| 57335 | ** | ||||
| 57336 | ** nReq is the number of bytes of memory required. Once this much has | ||||
| 57337 | ** been released, the function returns. The return value is the total number | ||||
| 57338 | ** of bytes of memory released. | ||||
| 57339 | */ | ||||
| 57340 | SQLITE_PRIVATEstatic int sqlite3PcacheReleaseMemory(int nReq){ | ||||
| 57341 | int nFree = 0; | ||||
| 57342 | assert( sqlite3_mutex_notheld(pcache1.grp.mutex) )((void) (0)); | ||||
| 57343 | assert( sqlite3_mutex_notheld(pcache1.mutex) )((void) (0)); | ||||
| 57344 | if( sqlite3GlobalConfigsqlite3Config.pPage==0 ){ | ||||
| 57345 | PgHdr1 *p; | ||||
| 57346 | pcache1EnterMutex(&pcache1.grp)((void) (0)); | ||||
| 57347 | while( (nReq<0 || nFree<nReq) | ||||
| 57348 | && (p=pcache1(pcache1_g).grp.lru.pLruPrev)!=0 | ||||
| 57349 | && p->isAnchor==0 | ||||
| 57350 | ){ | ||||
| 57351 | nFree += pcache1MemSize(p->page.pBuf); | ||||
| 57352 | assert( PAGE_IS_UNPINNED(p) )((void) (0)); | ||||
| 57353 | pcache1PinPage(p); | ||||
| 57354 | pcache1RemoveFromHash(p, 1); | ||||
| 57355 | } | ||||
| 57356 | pcache1LeaveMutex(&pcache1.grp)((void) (0)); | ||||
| 57357 | } | ||||
| 57358 | return nFree; | ||||
| 57359 | } | ||||
| 57360 | #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */ | ||||
| 57361 | |||||
| 57362 | #ifdef SQLITE_TEST | ||||
| 57363 | /* | ||||
| 57364 | ** This function is used by test procedures to inspect the internal state | ||||
| 57365 | ** of the global cache. | ||||
| 57366 | */ | ||||
| 57367 | SQLITE_PRIVATEstatic void sqlite3PcacheStats( | ||||
| 57368 | int *pnCurrent, /* OUT: Total number of pages cached */ | ||||
| 57369 | int *pnMax, /* OUT: Global maximum cache size */ | ||||
| 57370 | int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */ | ||||
| 57371 | int *pnRecyclable /* OUT: Total number of pages available for recycling */ | ||||
| 57372 | ){ | ||||
| 57373 | PgHdr1 *p; | ||||
| 57374 | int nRecyclable = 0; | ||||
| 57375 | for(p=pcache1(pcache1_g).grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){ | ||||
| 57376 | assert( PAGE_IS_UNPINNED(p) )((void) (0)); | ||||
| 57377 | nRecyclable++; | ||||
| 57378 | } | ||||
| 57379 | *pnCurrent = pcache1(pcache1_g).grp.nPurgeable; | ||||
| 57380 | *pnMax = (int)pcache1(pcache1_g).grp.nMaxPage; | ||||
| 57381 | *pnMin = (int)pcache1(pcache1_g).grp.nMinPage; | ||||
| 57382 | *pnRecyclable = nRecyclable; | ||||
| 57383 | } | ||||
| 57384 | #endif | ||||
| 57385 | |||||
| 57386 | /************** End of pcache1.c *********************************************/ | ||||
| 57387 | /************** Begin file rowset.c ******************************************/ | ||||
| 57388 | /* | ||||
| 57389 | ** 2008 December 3 | ||||
| 57390 | ** | ||||
| 57391 | ** The author disclaims copyright to this source code. In place of | ||||
| 57392 | ** a legal notice, here is a blessing: | ||||
| 57393 | ** | ||||
| 57394 | ** May you do good and not evil. | ||||
| 57395 | ** May you find forgiveness for yourself and forgive others. | ||||
| 57396 | ** May you share freely, never taking more than you give. | ||||
| 57397 | ** | ||||
| 57398 | ************************************************************************* | ||||
| 57399 | ** | ||||
| 57400 | ** This module implements an object we call a "RowSet". | ||||
| 57401 | ** | ||||
| 57402 | ** The RowSet object is a collection of rowids. Rowids | ||||
| 57403 | ** are inserted into the RowSet in an arbitrary order. Inserts | ||||
| 57404 | ** can be intermixed with tests to see if a given rowid has been | ||||
| 57405 | ** previously inserted into the RowSet. | ||||
| 57406 | ** | ||||
| 57407 | ** After all inserts are finished, it is possible to extract the | ||||
| 57408 | ** elements of the RowSet in sorted order. Once this extraction | ||||
| 57409 | ** process has started, no new elements may be inserted. | ||||
| 57410 | ** | ||||
| 57411 | ** Hence, the primitive operations for a RowSet are: | ||||
| 57412 | ** | ||||
| 57413 | ** CREATE | ||||
| 57414 | ** INSERT | ||||
| 57415 | ** TEST | ||||
| 57416 | ** SMALLEST | ||||
| 57417 | ** DESTROY | ||||
| 57418 | ** | ||||
| 57419 | ** The CREATE and DESTROY primitives are the constructor and destructor, | ||||
| 57420 | ** obviously. The INSERT primitive adds a new element to the RowSet. | ||||
| 57421 | ** TEST checks to see if an element is already in the RowSet. SMALLEST | ||||
| 57422 | ** extracts the least value from the RowSet. | ||||
| 57423 | ** | ||||
| 57424 | ** The INSERT primitive might allocate additional memory. Memory is | ||||
| 57425 | ** allocated in chunks so most INSERTs do no allocation. There is an | ||||
| 57426 | ** upper bound on the size of allocated memory. No memory is freed | ||||
| 57427 | ** until DESTROY. | ||||
| 57428 | ** | ||||
| 57429 | ** The TEST primitive includes a "batch" number. The TEST primitive | ||||
| 57430 | ** will only see elements that were inserted before the last change | ||||
| 57431 | ** in the batch number. In other words, if an INSERT occurs between | ||||
| 57432 | ** two TESTs where the TESTs have the same batch number, then the | ||||
| 57433 | ** value added by the INSERT will not be visible to the second TEST. | ||||
| 57434 | ** The initial batch number is zero, so if the very first TEST contains | ||||
| 57435 | ** a non-zero batch number, it will see all prior INSERTs. | ||||
| 57436 | ** | ||||
| 57437 | ** No INSERTs may occurs after a SMALLEST. An assertion will fail if | ||||
| 57438 | ** that is attempted. | ||||
| 57439 | ** | ||||
| 57440 | ** The cost of an INSERT is roughly constant. (Sometimes new memory | ||||
| 57441 | ** has to be allocated on an INSERT.) The cost of a TEST with a new | ||||
| 57442 | ** batch number is O(NlogN) where N is the number of elements in the RowSet. | ||||
| 57443 | ** The cost of a TEST using the same batch number is O(logN). The cost | ||||
| 57444 | ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST | ||||
| 57445 | ** primitives are constant time. The cost of DESTROY is O(N). | ||||
| 57446 | ** | ||||
| 57447 | ** TEST and SMALLEST may not be used by the same RowSet. This used to | ||||
| 57448 | ** be possible, but the feature was not used, so it was removed in order | ||||
| 57449 | ** to simplify the code. | ||||
| 57450 | */ | ||||
| 57451 | /* #include "sqliteInt.h" */ | ||||
| 57452 | |||||
| 57453 | |||||
| 57454 | /* | ||||
| 57455 | ** Target size for allocation chunks. | ||||
| 57456 | */ | ||||
| 57457 | #define ROWSET_ALLOCATION_SIZE1024 1024 | ||||
| 57458 | |||||
| 57459 | /* | ||||
| 57460 | ** The number of rowset entries per allocation chunk. | ||||
| 57461 | */ | ||||
| 57462 | #define ROWSET_ENTRY_PER_CHUNK((1024 -8)/sizeof(struct RowSetEntry)) \ | ||||
| 57463 | ((ROWSET_ALLOCATION_SIZE1024-8)/sizeof(struct RowSetEntry)) | ||||
| 57464 | |||||
| 57465 | /* | ||||
| 57466 | ** Each entry in a RowSet is an instance of the following object. | ||||
| 57467 | ** | ||||
| 57468 | ** This same object is reused to store a linked list of trees of RowSetEntry | ||||
| 57469 | ** objects. In that alternative use, pRight points to the next entry | ||||
| 57470 | ** in the list, pLeft points to the tree, and v is unused. The | ||||
| 57471 | ** RowSet.pForest value points to the head of this forest list. | ||||
| 57472 | */ | ||||
| 57473 | struct RowSetEntry { | ||||
| 57474 | i64 v; /* ROWID value for this entry */ | ||||
| 57475 | struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */ | ||||
| 57476 | struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */ | ||||
| 57477 | }; | ||||
| 57478 | |||||
| 57479 | /* | ||||
| 57480 | ** RowSetEntry objects are allocated in large chunks (instances of the | ||||
| 57481 | ** following structure) to reduce memory allocation overhead. The | ||||
| 57482 | ** chunks are kept on a linked list so that they can be deallocated | ||||
| 57483 | ** when the RowSet is destroyed. | ||||
| 57484 | */ | ||||
| 57485 | struct RowSetChunk { | ||||
| 57486 | struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */ | ||||
| 57487 | struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK((1024 -8)/sizeof(struct RowSetEntry))]; /* Allocated entries */ | ||||
| 57488 | }; | ||||
| 57489 | |||||
| 57490 | /* | ||||
| 57491 | ** A RowSet in an instance of the following structure. | ||||
| 57492 | ** | ||||
| 57493 | ** A typedef of this structure if found in sqliteInt.h. | ||||
| 57494 | */ | ||||
| 57495 | struct RowSet { | ||||
| 57496 | struct RowSetChunk *pChunk; /* List of all chunk allocations */ | ||||
| 57497 | sqlite3 *db; /* The database connection */ | ||||
| 57498 | struct RowSetEntry *pEntry; /* List of entries using pRight */ | ||||
| 57499 | struct RowSetEntry *pLast; /* Last entry on the pEntry list */ | ||||
| 57500 | struct RowSetEntry *pFresh; /* Source of new entry objects */ | ||||
| 57501 | struct RowSetEntry *pForest; /* List of binary trees of entries */ | ||||
| 57502 | u16 nFresh; /* Number of objects on pFresh */ | ||||
| 57503 | u16 rsFlags; /* Various flags */ | ||||
| 57504 | int iBatch; /* Current insert batch */ | ||||
| 57505 | }; | ||||
| 57506 | |||||
| 57507 | /* | ||||
| 57508 | ** Allowed values for RowSet.rsFlags | ||||
| 57509 | */ | ||||
| 57510 | #define ROWSET_SORTED0x01 0x01 /* True if RowSet.pEntry is sorted */ | ||||
| 57511 | #define ROWSET_NEXT0x02 0x02 /* True if sqlite3RowSetNext() has been called */ | ||||
| 57512 | |||||
| 57513 | /* | ||||
| 57514 | ** Allocate a RowSet object. Return NULL if a memory allocation | ||||
| 57515 | ** error occurs. | ||||
| 57516 | */ | ||||
| 57517 | SQLITE_PRIVATEstatic RowSet *sqlite3RowSetInit(sqlite3 *db){ | ||||
| 57518 | RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p)); | ||||
| 57519 | if( p ){ | ||||
| 57520 | int N = sqlite3DbMallocSize(db, p); | ||||
| 57521 | p->pChunk = 0; | ||||
| 57522 | p->db = db; | ||||
| 57523 | p->pEntry = 0; | ||||
| 57524 | p->pLast = 0; | ||||
| 57525 | p->pForest = 0; | ||||
| 57526 | p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p))(((sizeof(*p))+7)&~7) + (char*)p); | ||||
| 57527 | p->nFresh = (u16)((N - ROUND8(sizeof(*p))(((sizeof(*p))+7)&~7))/sizeof(struct RowSetEntry)); | ||||
| 57528 | p->rsFlags = ROWSET_SORTED0x01; | ||||
| 57529 | p->iBatch = 0; | ||||
| 57530 | } | ||||
| 57531 | return p; | ||||
| 57532 | } | ||||
| 57533 | |||||
| 57534 | /* | ||||
| 57535 | ** Deallocate all chunks from a RowSet. This frees all memory that | ||||
| 57536 | ** the RowSet has allocated over its lifetime. This routine is | ||||
| 57537 | ** the destructor for the RowSet. | ||||
| 57538 | */ | ||||
| 57539 | SQLITE_PRIVATEstatic void sqlite3RowSetClear(void *pArg){ | ||||
| 57540 | RowSet *p = (RowSet*)pArg; | ||||
| 57541 | struct RowSetChunk *pChunk, *pNextChunk; | ||||
| 57542 | for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){ | ||||
| 57543 | pNextChunk = pChunk->pNextChunk; | ||||
| 57544 | sqlite3DbFree(p->db, pChunk); | ||||
| 57545 | } | ||||
| 57546 | p->pChunk = 0; | ||||
| 57547 | p->nFresh = 0; | ||||
| 57548 | p->pEntry = 0; | ||||
| 57549 | p->pLast = 0; | ||||
| 57550 | p->pForest = 0; | ||||
| 57551 | p->rsFlags = ROWSET_SORTED0x01; | ||||
| 57552 | } | ||||
| 57553 | |||||
| 57554 | /* | ||||
| 57555 | ** Deallocate all chunks from a RowSet. This frees all memory that | ||||
| 57556 | ** the RowSet has allocated over its lifetime. This routine is | ||||
| 57557 | ** the destructor for the RowSet. | ||||
| 57558 | */ | ||||
| 57559 | SQLITE_PRIVATEstatic void sqlite3RowSetDelete(void *pArg){ | ||||
| 57560 | sqlite3RowSetClear(pArg); | ||||
| 57561 | sqlite3DbFree(((RowSet*)pArg)->db, pArg); | ||||
| 57562 | } | ||||
| 57563 | |||||
| 57564 | /* | ||||
| 57565 | ** Allocate a new RowSetEntry object that is associated with the | ||||
| 57566 | ** given RowSet. Return a pointer to the new and completely uninitialized | ||||
| 57567 | ** object. | ||||
| 57568 | ** | ||||
| 57569 | ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this | ||||
| 57570 | ** routine returns NULL. | ||||
| 57571 | */ | ||||
| 57572 | static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ | ||||
| 57573 | assert( p!=0 )((void) (0)); | ||||
| 57574 | if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 57575 | /* We could allocate a fresh RowSetEntry each time one is needed, but it | ||||
| 57576 | ** is more efficient to pull a preallocated entry from the pool */ | ||||
| 57577 | struct RowSetChunk *pNew; | ||||
| 57578 | pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew)); | ||||
| 57579 | if( pNew==0 ){ | ||||
| 57580 | return 0; | ||||
| 57581 | } | ||||
| 57582 | pNew->pNextChunk = p->pChunk; | ||||
| 57583 | p->pChunk = pNew; | ||||
| 57584 | p->pFresh = pNew->aEntry; | ||||
| 57585 | p->nFresh = ROWSET_ENTRY_PER_CHUNK((1024 -8)/sizeof(struct RowSetEntry)); | ||||
| 57586 | } | ||||
| 57587 | p->nFresh--; | ||||
| 57588 | return p->pFresh++; | ||||
| 57589 | } | ||||
| 57590 | |||||
| 57591 | /* | ||||
| 57592 | ** Insert a new value into a RowSet. | ||||
| 57593 | ** | ||||
| 57594 | ** The mallocFailed flag of the database connection is set if a | ||||
| 57595 | ** memory allocation fails. | ||||
| 57596 | */ | ||||
| 57597 | SQLITE_PRIVATEstatic void sqlite3RowSetInsert(RowSet *p, i64 rowid){ | ||||
| 57598 | struct RowSetEntry *pEntry; /* The new entry */ | ||||
| 57599 | struct RowSetEntry *pLast; /* The last prior entry */ | ||||
| 57600 | |||||
| 57601 | /* This routine is never called after sqlite3RowSetNext() */ | ||||
| 57602 | assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 )((void) (0)); | ||||
| 57603 | |||||
| 57604 | pEntry = rowSetEntryAlloc(p); | ||||
| 57605 | if( pEntry==0 ) return; | ||||
| 57606 | pEntry->v = rowid; | ||||
| 57607 | pEntry->pRight = 0; | ||||
| 57608 | pLast = p->pLast; | ||||
| 57609 | if( pLast ){ | ||||
| 57610 | if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 57611 | /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags | ||||
| 57612 | ** where possible */ | ||||
| 57613 | p->rsFlags &= ~ROWSET_SORTED0x01; | ||||
| 57614 | } | ||||
| 57615 | pLast->pRight = pEntry; | ||||
| 57616 | }else{ | ||||
| 57617 | p->pEntry = pEntry; | ||||
| 57618 | } | ||||
| 57619 | p->pLast = pEntry; | ||||
| 57620 | } | ||||
| 57621 | |||||
| 57622 | /* | ||||
| 57623 | ** Merge two lists of RowSetEntry objects. Remove duplicates. | ||||
| 57624 | ** | ||||
| 57625 | ** The input lists are connected via pRight pointers and are | ||||
| 57626 | ** assumed to each already be in sorted order. | ||||
| 57627 | */ | ||||
| 57628 | static struct RowSetEntry *rowSetEntryMerge( | ||||
| 57629 | struct RowSetEntry *pA, /* First sorted list to be merged */ | ||||
| 57630 | struct RowSetEntry *pB /* Second sorted list to be merged */ | ||||
| 57631 | ){ | ||||
| 57632 | struct RowSetEntry head; | ||||
| 57633 | struct RowSetEntry *pTail; | ||||
| 57634 | |||||
| 57635 | pTail = &head; | ||||
| 57636 | assert( pA!=0 && pB!=0 )((void) (0)); | ||||
| 57637 | for(;;){ | ||||
| 57638 | assert( pA->pRight==0 || pA->v<=pA->pRight->v )((void) (0)); | ||||
| 57639 | assert( pB->pRight==0 || pB->v<=pB->pRight->v )((void) (0)); | ||||
| 57640 | if( pA->v<=pB->v ){ | ||||
| 57641 | if( pA->v<pB->v ) pTail = pTail->pRight = pA; | ||||
| 57642 | pA = pA->pRight; | ||||
| 57643 | if( pA==0 ){ | ||||
| 57644 | pTail->pRight = pB; | ||||
| 57645 | break; | ||||
| 57646 | } | ||||
| 57647 | }else{ | ||||
| 57648 | pTail = pTail->pRight = pB; | ||||
| 57649 | pB = pB->pRight; | ||||
| 57650 | if( pB==0 ){ | ||||
| 57651 | pTail->pRight = pA; | ||||
| 57652 | break; | ||||
| 57653 | } | ||||
| 57654 | } | ||||
| 57655 | } | ||||
| 57656 | return head.pRight; | ||||
| 57657 | } | ||||
| 57658 | |||||
| 57659 | /* | ||||
| 57660 | ** Sort all elements on the list of RowSetEntry objects into order of | ||||
| 57661 | ** increasing v. | ||||
| 57662 | */ | ||||
| 57663 | static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){ | ||||
| 57664 | unsigned int i; | ||||
| 57665 | struct RowSetEntry *pNext, *aBucket[40]; | ||||
| 57666 | |||||
| 57667 | memset(aBucket, 0, sizeof(aBucket)); | ||||
| 57668 | while( pIn ){ | ||||
| 57669 | pNext = pIn->pRight; | ||||
| 57670 | pIn->pRight = 0; | ||||
| 57671 | for(i=0; aBucket[i]; i++){ | ||||
| 57672 | pIn = rowSetEntryMerge(aBucket[i], pIn); | ||||
| 57673 | aBucket[i] = 0; | ||||
| 57674 | } | ||||
| 57675 | aBucket[i] = pIn; | ||||
| 57676 | pIn = pNext; | ||||
| 57677 | } | ||||
| 57678 | pIn = aBucket[0]; | ||||
| 57679 | for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){ | ||||
| 57680 | if( aBucket[i]==0 ) continue; | ||||
| 57681 | pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i]; | ||||
| 57682 | } | ||||
| 57683 | return pIn; | ||||
| 57684 | } | ||||
| 57685 | |||||
| 57686 | |||||
| 57687 | /* | ||||
| 57688 | ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects. | ||||
| 57689 | ** Convert this tree into a linked list connected by the pRight pointers | ||||
| 57690 | ** and return pointers to the first and last elements of the new list. | ||||
| 57691 | */ | ||||
| 57692 | static void rowSetTreeToList( | ||||
| 57693 | struct RowSetEntry *pIn, /* Root of the input tree */ | ||||
| 57694 | struct RowSetEntry **ppFirst, /* Write head of the output list here */ | ||||
| 57695 | struct RowSetEntry **ppLast /* Write tail of the output list here */ | ||||
| 57696 | ){ | ||||
| 57697 | assert( pIn!=0 )((void) (0)); | ||||
| 57698 | if( pIn->pLeft ){ | ||||
| 57699 | struct RowSetEntry *p; | ||||
| 57700 | rowSetTreeToList(pIn->pLeft, ppFirst, &p); | ||||
| 57701 | p->pRight = pIn; | ||||
| 57702 | }else{ | ||||
| 57703 | *ppFirst = pIn; | ||||
| 57704 | } | ||||
| 57705 | if( pIn->pRight ){ | ||||
| 57706 | rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast); | ||||
| 57707 | }else{ | ||||
| 57708 | *ppLast = pIn; | ||||
| 57709 | } | ||||
| 57710 | assert( (*ppLast)->pRight==0 )((void) (0)); | ||||
| 57711 | } | ||||
| 57712 | |||||
| 57713 | |||||
| 57714 | /* | ||||
| 57715 | ** Convert a sorted list of elements (connected by pRight) into a binary | ||||
| 57716 | ** tree with depth of iDepth. A depth of 1 means the tree contains a single | ||||
| 57717 | ** node taken from the head of *ppList. A depth of 2 means a tree with | ||||
| 57718 | ** three nodes. And so forth. | ||||
| 57719 | ** | ||||
| 57720 | ** Use as many entries from the input list as required and update the | ||||
| 57721 | ** *ppList to point to the unused elements of the list. If the input | ||||
| 57722 | ** list contains too few elements, then construct an incomplete tree | ||||
| 57723 | ** and leave *ppList set to NULL. | ||||
| 57724 | ** | ||||
| 57725 | ** Return a pointer to the root of the constructed binary tree. | ||||
| 57726 | */ | ||||
| 57727 | static struct RowSetEntry *rowSetNDeepTree( | ||||
| 57728 | struct RowSetEntry **ppList, | ||||
| 57729 | int iDepth | ||||
| 57730 | ){ | ||||
| 57731 | struct RowSetEntry *p; /* Root of the new tree */ | ||||
| 57732 | struct RowSetEntry *pLeft; /* Left subtree */ | ||||
| 57733 | if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/ | ||||
| 57734 | /* Prevent unnecessary deep recursion when we run out of entries */ | ||||
| 57735 | return 0; | ||||
| 57736 | } | ||||
| 57737 | if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/ | ||||
| 57738 | /* This branch causes a *balanced* tree to be generated. A valid tree | ||||
| 57739 | ** is still generated without this branch, but the tree is wildly | ||||
| 57740 | ** unbalanced and inefficient. */ | ||||
| 57741 | pLeft = rowSetNDeepTree(ppList, iDepth-1); | ||||
| 57742 | p = *ppList; | ||||
| 57743 | if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 57744 | /* It is safe to always return here, but the resulting tree | ||||
| 57745 | ** would be unbalanced */ | ||||
| 57746 | return pLeft; | ||||
| 57747 | } | ||||
| 57748 | p->pLeft = pLeft; | ||||
| 57749 | *ppList = p->pRight; | ||||
| 57750 | p->pRight = rowSetNDeepTree(ppList, iDepth-1); | ||||
| 57751 | }else{ | ||||
| 57752 | p = *ppList; | ||||
| 57753 | *ppList = p->pRight; | ||||
| 57754 | p->pLeft = p->pRight = 0; | ||||
| 57755 | } | ||||
| 57756 | return p; | ||||
| 57757 | } | ||||
| 57758 | |||||
| 57759 | /* | ||||
| 57760 | ** Convert a sorted list of elements into a binary tree. Make the tree | ||||
| 57761 | ** as deep as it needs to be in order to contain the entire list. | ||||
| 57762 | */ | ||||
| 57763 | static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ | ||||
| 57764 | int iDepth; /* Depth of the tree so far */ | ||||
| 57765 | struct RowSetEntry *p; /* Current tree root */ | ||||
| 57766 | struct RowSetEntry *pLeft; /* Left subtree */ | ||||
| 57767 | |||||
| 57768 | assert( pList!=0 )((void) (0)); | ||||
| 57769 | p = pList; | ||||
| 57770 | pList = p->pRight; | ||||
| 57771 | p->pLeft = p->pRight = 0; | ||||
| 57772 | for(iDepth=1; pList; iDepth++){ | ||||
| 57773 | pLeft = p; | ||||
| 57774 | p = pList; | ||||
| 57775 | pList = p->pRight; | ||||
| 57776 | p->pLeft = pLeft; | ||||
| 57777 | p->pRight = rowSetNDeepTree(&pList, iDepth); | ||||
| 57778 | } | ||||
| 57779 | return p; | ||||
| 57780 | } | ||||
| 57781 | |||||
| 57782 | /* | ||||
| 57783 | ** Extract the smallest element from the RowSet. | ||||
| 57784 | ** Write the element into *pRowid. Return 1 on success. Return | ||||
| 57785 | ** 0 if the RowSet is already empty. | ||||
| 57786 | ** | ||||
| 57787 | ** After this routine has been called, the sqlite3RowSetInsert() | ||||
| 57788 | ** routine may not be called again. | ||||
| 57789 | ** | ||||
| 57790 | ** This routine may not be called after sqlite3RowSetTest() has | ||||
| 57791 | ** been used. Older versions of RowSet allowed that, but as the | ||||
| 57792 | ** capability was not used by the code generator, it was removed | ||||
| 57793 | ** for code economy. | ||||
| 57794 | */ | ||||
| 57795 | SQLITE_PRIVATEstatic int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ | ||||
| 57796 | assert( p!=0 )((void) (0)); | ||||
| 57797 | assert( p->pForest==0 )((void) (0)); /* Cannot be used with sqlite3RowSetText() */ | ||||
| 57798 | |||||
| 57799 | /* Merge the forest into a single sorted list on first call */ | ||||
| 57800 | if( (p->rsFlags & ROWSET_NEXT0x02)==0 ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 57801 | if( (p->rsFlags & ROWSET_SORTED0x01)==0 ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 57802 | p->pEntry = rowSetEntrySort(p->pEntry); | ||||
| 57803 | } | ||||
| 57804 | p->rsFlags |= ROWSET_SORTED0x01|ROWSET_NEXT0x02; | ||||
| 57805 | } | ||||
| 57806 | |||||
| 57807 | /* Return the next entry on the list */ | ||||
| 57808 | if( p->pEntry ){ | ||||
| 57809 | *pRowid = p->pEntry->v; | ||||
| 57810 | p->pEntry = p->pEntry->pRight; | ||||
| 57811 | if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/ | ||||
| 57812 | /* Free memory immediately, rather than waiting on sqlite3_finalize() */ | ||||
| 57813 | sqlite3RowSetClear(p); | ||||
| 57814 | } | ||||
| 57815 | return 1; | ||||
| 57816 | }else{ | ||||
| 57817 | return 0; | ||||
| 57818 | } | ||||
| 57819 | } | ||||
| 57820 | |||||
| 57821 | /* | ||||
| 57822 | ** Check to see if element iRowid was inserted into the rowset as | ||||
| 57823 | ** part of any insert batch prior to iBatch. Return 1 or 0. | ||||
| 57824 | ** | ||||
| 57825 | ** If this is the first test of a new batch and if there exist entries | ||||
| 57826 | ** on pRowSet->pEntry, then sort those entries into the forest at | ||||
| 57827 | ** pRowSet->pForest so that they can be tested. | ||||
| 57828 | */ | ||||
| 57829 | SQLITE_PRIVATEstatic int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){ | ||||
| 57830 | struct RowSetEntry *p, *pTree; | ||||
| 57831 | |||||
| 57832 | /* This routine is never called after sqlite3RowSetNext() */ | ||||
| 57833 | assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 )((void) (0)); | ||||
| 57834 | |||||
| 57835 | /* Sort entries into the forest on the first test of a new batch. | ||||
| 57836 | ** To save unnecessary work, only do this when the batch number changes. | ||||
| 57837 | */ | ||||
| 57838 | if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 57839 | p = pRowSet->pEntry; | ||||
| 57840 | if( p ){ | ||||
| 57841 | struct RowSetEntry **ppPrevTree = &pRowSet->pForest; | ||||
| 57842 | if( (pRowSet->rsFlags & ROWSET_SORTED0x01)==0 ){ /*OPTIMIZATION-IF-FALSE*/ | ||||
| 57843 | /* Only sort the current set of entries if they need it */ | ||||
| 57844 | p = rowSetEntrySort(p); | ||||
| 57845 | } | ||||
| 57846 | for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ | ||||
| 57847 | ppPrevTree = &pTree->pRight; | ||||
| 57848 | if( pTree->pLeft==0 ){ | ||||
| 57849 | pTree->pLeft = rowSetListToTree(p); | ||||
| 57850 | break; | ||||
| 57851 | }else{ | ||||
| 57852 | struct RowSetEntry *pAux, *pTail; | ||||
| 57853 | rowSetTreeToList(pTree->pLeft, &pAux, &pTail); | ||||
| 57854 | pTree->pLeft = 0; | ||||
| 57855 | p = rowSetEntryMerge(pAux, p); | ||||
| 57856 | } | ||||
| 57857 | } | ||||
| 57858 | if( pTree==0 ){ | ||||
| 57859 | *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet); | ||||
| 57860 | if( pTree ){ | ||||
| 57861 | pTree->v = 0; | ||||
| 57862 | pTree->pRight = 0; | ||||
| 57863 | pTree->pLeft = rowSetListToTree(p); | ||||
| 57864 | } | ||||
| 57865 | } | ||||
| 57866 | pRowSet->pEntry = 0; | ||||
| 57867 | pRowSet->pLast = 0; | ||||
| 57868 | pRowSet->rsFlags |= ROWSET_SORTED0x01; | ||||
| 57869 | } | ||||
| 57870 | pRowSet->iBatch = iBatch; | ||||
| 57871 | } | ||||
| 57872 | |||||
| 57873 | /* Test to see if the iRowid value appears anywhere in the forest. | ||||
| 57874 | ** Return 1 if it does and 0 if not. | ||||
| 57875 | */ | ||||
| 57876 | for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ | ||||
| 57877 | p = pTree->pLeft; | ||||
| 57878 | while( p ){ | ||||
| 57879 | if( p->v<iRowid ){ | ||||
| 57880 | p = p->pRight; | ||||
| 57881 | }else if( p->v>iRowid ){ | ||||
| 57882 | p = p->pLeft; | ||||
| 57883 | }else{ | ||||
| 57884 | return 1; | ||||
| 57885 | } | ||||
| 57886 | } | ||||
| 57887 | } | ||||
| 57888 | return 0; | ||||
| 57889 | } | ||||
| 57890 | |||||
| 57891 | /************** End of rowset.c **********************************************/ | ||||
| 57892 | /************** Begin file pager.c *******************************************/ | ||||
| 57893 | /* | ||||
| 57894 | ** 2001 September 15 | ||||
| 57895 | ** | ||||
| 57896 | ** The author disclaims copyright to this source code. In place of | ||||
| 57897 | ** a legal notice, here is a blessing: | ||||
| 57898 | ** | ||||
| 57899 | ** May you do good and not evil. | ||||
| 57900 | ** May you find forgiveness for yourself and forgive others. | ||||
| 57901 | ** May you share freely, never taking more than you give. | ||||
| 57902 | ** | ||||
| 57903 | ************************************************************************* | ||||
| 57904 | ** This is the implementation of the page cache subsystem or "pager". | ||||
| 57905 | ** | ||||
| 57906 | ** The pager is used to access a database disk file. It implements | ||||
| 57907 | ** atomic commit and rollback through the use of a journal file that | ||||
| 57908 | ** is separate from the database file. The pager also implements file | ||||
| 57909 | ** locking to prevent two processes from writing the same database | ||||
| 57910 | ** file simultaneously, or one process from reading the database while | ||||
| 57911 | ** another is writing. | ||||
| 57912 | */ | ||||
| 57913 | #ifndef SQLITE_OMIT_DISKIO | ||||
| 57914 | /* #include "sqliteInt.h" */ | ||||
| 57915 | /************** Include wal.h in the middle of pager.c ***********************/ | ||||
| 57916 | /************** Begin file wal.h *********************************************/ | ||||
| 57917 | /* | ||||
| 57918 | ** 2010 February 1 | ||||
| 57919 | ** | ||||
| 57920 | ** The author disclaims copyright to this source code. In place of | ||||
| 57921 | ** a legal notice, here is a blessing: | ||||
| 57922 | ** | ||||
| 57923 | ** May you do good and not evil. | ||||
| 57924 | ** May you find forgiveness for yourself and forgive others. | ||||
| 57925 | ** May you share freely, never taking more than you give. | ||||
| 57926 | ** | ||||
| 57927 | ************************************************************************* | ||||
| 57928 | ** This header file defines the interface to the write-ahead logging | ||||
| 57929 | ** system. Refer to the comments below and the header comment attached to | ||||
| 57930 | ** the implementation of each function in log.c for further details. | ||||
| 57931 | */ | ||||
| 57932 | |||||
| 57933 | #ifndef SQLITE_WAL_H | ||||
| 57934 | #define SQLITE_WAL_H | ||||
| 57935 | |||||
| 57936 | /* #include "sqliteInt.h" */ | ||||
| 57937 | |||||
| 57938 | /* Macros for extracting appropriate sync flags for either transaction | ||||
| 57939 | ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)): | ||||
| 57940 | */ | ||||
| 57941 | #define WAL_SYNC_FLAGS(X)((X)&0x03) ((X)&0x03) | ||||
| 57942 | #define CKPT_SYNC_FLAGS(X)(((X)>>2)&0x03) (((X)>>2)&0x03) | ||||
| 57943 | |||||
| 57944 | #ifdef SQLITE_OMIT_WAL | ||||
| 57945 | # define sqlite3WalOpen(x,y,z) 0 | ||||
| 57946 | # define sqlite3WalLimit(x,y) | ||||
| 57947 | # define sqlite3WalClose(v,w,x,y,z) 0 | ||||
| 57948 | # define sqlite3WalBeginReadTransaction(y,z) 0 | ||||
| 57949 | # define sqlite3WalEndReadTransaction(z) | ||||
| 57950 | # define sqlite3WalDbsize(y) 0 | ||||
| 57951 | # define sqlite3WalBeginWriteTransaction(y) 0 | ||||
| 57952 | # define sqlite3WalEndWriteTransaction(x) 0 | ||||
| 57953 | # define sqlite3WalUndo(x,y,z) 0 | ||||
| 57954 | # define sqlite3WalSavepoint(y,z) | ||||
| 57955 | # define sqlite3WalSavepointUndo(y,z) 0 | ||||
| 57956 | # define sqlite3WalFrames(u,v,w,x,y,z) 0 | ||||
| 57957 | # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0 | ||||
| 57958 | # define sqlite3WalCallback(z) 0 | ||||
| 57959 | # define sqlite3WalExclusiveMode(y,z) 0 | ||||
| 57960 | # define sqlite3WalHeapMemory(z) 0 | ||||
| 57961 | # define sqlite3WalFramesize(z) 0 | ||||
| 57962 | # define sqlite3WalFindFrame(x,y,z) 0 | ||||
| 57963 | # define sqlite3WalFile(x) 0 | ||||
| 57964 | # undef SQLITE_USE_SEH | ||||
| 57965 | #else | ||||
| 57966 | |||||
| 57967 | #define WAL_SAVEPOINT_NDATA4 4 | ||||
| 57968 | |||||
| 57969 | /* Connection to a write-ahead log (WAL) file. | ||||
| 57970 | ** There is one object of this type for each pager. | ||||
| 57971 | */ | ||||
| 57972 | typedef struct Wal Wal; | ||||
| 57973 | |||||
| 57974 | /* Open and close a connection to a write-ahead log. */ | ||||
| 57975 | SQLITE_PRIVATEstatic int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**); | ||||
| 57976 | SQLITE_PRIVATEstatic int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *); | ||||
| 57977 | |||||
| 57978 | /* Set the limiting size of a WAL file. */ | ||||
| 57979 | SQLITE_PRIVATEstatic void sqlite3WalLimit(Wal*, i64); | ||||
| 57980 | |||||
| 57981 | /* Used by readers to open (lock) and close (unlock) a snapshot. A | ||||
| 57982 | ** snapshot is like a read-transaction. It is the state of the database | ||||
| 57983 | ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and | ||||
| 57984 | ** preserves the current state even if the other threads or processes | ||||
| 57985 | ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the | ||||
| 57986 | ** transaction and releases the lock. | ||||
| 57987 | */ | ||||
| 57988 | SQLITE_PRIVATEstatic int sqlite3WalBeginReadTransaction(Wal *pWal, int *); | ||||
| 57989 | SQLITE_PRIVATEstatic void sqlite3WalEndReadTransaction(Wal *pWal); | ||||
| 57990 | |||||
| 57991 | /* Read a page from the write-ahead log, if it is present. */ | ||||
| 57992 | SQLITE_PRIVATEstatic int sqlite3WalFindFrame(Wal *, Pgno, u32 *); | ||||
| 57993 | SQLITE_PRIVATEstatic int sqlite3WalReadFrame(Wal *, u32, int, u8 *); | ||||
| 57994 | |||||
| 57995 | /* If the WAL is not empty, return the size of the database. */ | ||||
| 57996 | SQLITE_PRIVATEstatic Pgno sqlite3WalDbsize(Wal *pWal); | ||||
| 57997 | |||||
| 57998 | /* Obtain or release the WRITER lock. */ | ||||
| 57999 | SQLITE_PRIVATEstatic int sqlite3WalBeginWriteTransaction(Wal *pWal); | ||||
| 58000 | SQLITE_PRIVATEstatic int sqlite3WalEndWriteTransaction(Wal *pWal); | ||||
| 58001 | |||||
| 58002 | /* Undo any frames written (but not committed) to the log */ | ||||
| 58003 | SQLITE_PRIVATEstatic int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); | ||||
| 58004 | |||||
| 58005 | /* Return an integer that records the current (uncommitted) write | ||||
| 58006 | ** position in the WAL */ | ||||
| 58007 | SQLITE_PRIVATEstatic void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData); | ||||
| 58008 | |||||
| 58009 | /* Move the write position of the WAL back to iFrame. Called in | ||||
| 58010 | ** response to a ROLLBACK TO command. */ | ||||
| 58011 | SQLITE_PRIVATEstatic int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); | ||||
| 58012 | |||||
| 58013 | /* Write a frame or frames to the log. */ | ||||
| 58014 | SQLITE_PRIVATEstatic int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); | ||||
| 58015 | |||||
| 58016 | /* Copy pages from the log to the database file */ | ||||
| 58017 | SQLITE_PRIVATEstatic int sqlite3WalCheckpoint( | ||||
| 58018 | Wal *pWal, /* Write-ahead log connection */ | ||||
| 58019 | sqlite3 *db, /* Check this handle's interrupt flag */ | ||||
| 58020 | int eMode, /* One of PASSIVE, FULL and RESTART */ | ||||
| 58021 | int (*xBusy)(void*), /* Function to call when busy */ | ||||
| 58022 | void *pBusyArg, /* Context argument for xBusyHandler */ | ||||
| 58023 | int sync_flags, /* Flags to sync db file with (or 0) */ | ||||
| 58024 | int nBuf, /* Size of buffer nBuf */ | ||||
| 58025 | u8 *zBuf, /* Temporary buffer to use */ | ||||
| 58026 | int *pnLog, /* OUT: Number of frames in WAL */ | ||||
| 58027 | int *pnCkpt /* OUT: Number of backfilled frames in WAL */ | ||||
| 58028 | ); | ||||
| 58029 | |||||
| 58030 | /* Return the value to pass to a sqlite3_wal_hook callback, the | ||||
| 58031 | ** number of frames in the WAL at the point of the last commit since | ||||
| 58032 | ** sqlite3WalCallback() was called. If no commits have occurred since | ||||
| 58033 | ** the last call, then return 0. | ||||
| 58034 | */ | ||||
| 58035 | SQLITE_PRIVATEstatic int sqlite3WalCallback(Wal *pWal); | ||||
| 58036 | |||||
| 58037 | /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released) | ||||
| 58038 | ** by the pager layer on the database file. | ||||
| 58039 | */ | ||||
| 58040 | SQLITE_PRIVATEstatic int sqlite3WalExclusiveMode(Wal *pWal, int op); | ||||
| 58041 | |||||
| 58042 | /* Return true if the argument is non-NULL and the WAL module is using | ||||
| 58043 | ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the | ||||
| 58044 | ** WAL module is using shared-memory, return false. | ||||
| 58045 | */ | ||||
| 58046 | SQLITE_PRIVATEstatic int sqlite3WalHeapMemory(Wal *pWal); | ||||
| 58047 | |||||
| 58048 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 58049 | SQLITE_PRIVATEstatic int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot); | ||||
| 58050 | SQLITE_PRIVATEstatic void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot); | ||||
| 58051 | SQLITE_PRIVATEstatic int sqlite3WalSnapshotRecover(Wal *pWal); | ||||
| 58052 | SQLITE_PRIVATEstatic int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot); | ||||
| 58053 | SQLITE_PRIVATEstatic void sqlite3WalSnapshotUnlock(Wal *pWal); | ||||
| 58054 | #endif | ||||
| 58055 | |||||
| 58056 | #ifdef SQLITE_ENABLE_ZIPVFS | ||||
| 58057 | /* If the WAL file is not empty, return the number of bytes of content | ||||
| 58058 | ** stored in each frame (i.e. the db page-size when the WAL was created). | ||||
| 58059 | */ | ||||
| 58060 | SQLITE_PRIVATEstatic int sqlite3WalFramesize(Wal *pWal); | ||||
| 58061 | #endif | ||||
| 58062 | |||||
| 58063 | /* Return the sqlite3_file object for the WAL file */ | ||||
| 58064 | SQLITE_PRIVATEstatic sqlite3_file *sqlite3WalFile(Wal *pWal); | ||||
| 58065 | |||||
| 58066 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 58067 | SQLITE_PRIVATEstatic int sqlite3WalWriteLock(Wal *pWal, int bLock); | ||||
| 58068 | SQLITE_PRIVATEstatic void sqlite3WalDb(Wal *pWal, sqlite3 *db); | ||||
| 58069 | #endif | ||||
| 58070 | |||||
| 58071 | #ifdef SQLITE_USE_SEH | ||||
| 58072 | SQLITE_PRIVATEstatic int sqlite3WalSystemErrno(Wal*); | ||||
| 58073 | #endif | ||||
| 58074 | |||||
| 58075 | #endif /* ifndef SQLITE_OMIT_WAL */ | ||||
| 58076 | #endif /* SQLITE_WAL_H */ | ||||
| 58077 | |||||
| 58078 | /************** End of wal.h *************************************************/ | ||||
| 58079 | /************** Continuing where we left off in pager.c **********************/ | ||||
| 58080 | |||||
| 58081 | |||||
| 58082 | /******************* NOTES ON THE DESIGN OF THE PAGER ************************ | ||||
| 58083 | ** | ||||
| 58084 | ** This comment block describes invariants that hold when using a rollback | ||||
| 58085 | ** journal. These invariants do not apply for journal_mode=WAL, | ||||
| 58086 | ** journal_mode=MEMORY, or journal_mode=OFF. | ||||
| 58087 | ** | ||||
| 58088 | ** Within this comment block, a page is deemed to have been synced | ||||
| 58089 | ** automatically as soon as it is written when PRAGMA synchronous=OFF. | ||||
| 58090 | ** Otherwise, the page is not synced until the xSync method of the VFS | ||||
| 58091 | ** is called successfully on the file containing the page. | ||||
| 58092 | ** | ||||
| 58093 | ** Definition: A page of the database file is said to be "overwriteable" if | ||||
| 58094 | ** one or more of the following are true about the page: | ||||
| 58095 | ** | ||||
| 58096 | ** (a) The original content of the page as it was at the beginning of | ||||
| 58097 | ** the transaction has been written into the rollback journal and | ||||
| 58098 | ** synced. | ||||
| 58099 | ** | ||||
| 58100 | ** (b) The page was a freelist leaf page at the start of the transaction. | ||||
| 58101 | ** | ||||
| 58102 | ** (c) The page number is greater than the largest page that existed in | ||||
| 58103 | ** the database file at the start of the transaction. | ||||
| 58104 | ** | ||||
| 58105 | ** (1) A page of the database file is never overwritten unless one of the | ||||
| 58106 | ** following are true: | ||||
| 58107 | ** | ||||
| 58108 | ** (a) The page and all other pages on the same sector are overwriteable. | ||||
| 58109 | ** | ||||
| 58110 | ** (b) The atomic page write optimization is enabled, and the entire | ||||
| 58111 | ** transaction other than the update of the transaction sequence | ||||
| 58112 | ** number consists of a single page change. | ||||
| 58113 | ** | ||||
| 58114 | ** (2) The content of a page written into the rollback journal exactly matches | ||||
| 58115 | ** both the content in the database when the rollback journal was written | ||||
| 58116 | ** and the content in the database at the beginning of the current | ||||
| 58117 | ** transaction. | ||||
| 58118 | ** | ||||
| 58119 | ** (3) Writes to the database file are an integer multiple of the page size | ||||
| 58120 | ** in length and are aligned on a page boundary. | ||||
| 58121 | ** | ||||
| 58122 | ** (4) Reads from the database file are either aligned on a page boundary and | ||||
| 58123 | ** an integer multiple of the page size in length or are taken from the | ||||
| 58124 | ** first 100 bytes of the database file. | ||||
| 58125 | ** | ||||
| 58126 | ** (5) All writes to the database file are synced prior to the rollback journal | ||||
| 58127 | ** being deleted, truncated, or zeroed. | ||||
| 58128 | ** | ||||
| 58129 | ** (6) If a super-journal file is used, then all writes to the database file | ||||
| 58130 | ** are synced prior to the super-journal being deleted. | ||||
| 58131 | ** | ||||
| 58132 | ** Definition: Two databases (or the same database at two points it time) | ||||
| 58133 | ** are said to be "logically equivalent" if they give the same answer to | ||||
| 58134 | ** all queries. Note in particular the content of freelist leaf | ||||
| 58135 | ** pages can be changed arbitrarily without affecting the logical equivalence | ||||
| 58136 | ** of the database. | ||||
| 58137 | ** | ||||
| 58138 | ** (7) At any time, if any subset, including the empty set and the total set, | ||||
| 58139 | ** of the unsynced changes to a rollback journal are removed and the | ||||
| 58140 | ** journal is rolled back, the resulting database file will be logically | ||||
| 58141 | ** equivalent to the database file at the beginning of the transaction. | ||||
| 58142 | ** | ||||
| 58143 | ** (8) When a transaction is rolled back, the xTruncate method of the VFS | ||||
| 58144 | ** is called to restore the database file to the same size it was at | ||||
| 58145 | ** the beginning of the transaction. (In some VFSes, the xTruncate | ||||
| 58146 | ** method is a no-op, but that does not change the fact the SQLite will | ||||
| 58147 | ** invoke it.) | ||||
| 58148 | ** | ||||
| 58149 | ** (9) Whenever the database file is modified, at least one bit in the range | ||||
| 58150 | ** of bytes from 24 through 39 inclusive will be changed prior to releasing | ||||
| 58151 | ** the EXCLUSIVE lock, thus signaling other connections on the same | ||||
| 58152 | ** database to flush their caches. | ||||
| 58153 | ** | ||||
| 58154 | ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less | ||||
| 58155 | ** than one billion transactions. | ||||
| 58156 | ** | ||||
| 58157 | ** (11) A database file is well-formed at the beginning and at the conclusion | ||||
| 58158 | ** of every transaction. | ||||
| 58159 | ** | ||||
| 58160 | ** (12) An EXCLUSIVE lock is held on the database file when writing to | ||||
| 58161 | ** the database file. | ||||
| 58162 | ** | ||||
| 58163 | ** (13) A SHARED lock is held on the database file while reading any | ||||
| 58164 | ** content out of the database file. | ||||
| 58165 | ** | ||||
| 58166 | ******************************************************************************/ | ||||
| 58167 | |||||
| 58168 | /* | ||||
| 58169 | ** Macros for troubleshooting. Normally turned off | ||||
| 58170 | */ | ||||
| 58171 | #if 0 | ||||
| 58172 | int sqlite3PagerTrace=1; /* True to enable tracing */ | ||||
| 58173 | #define sqlite3DebugPrintf printf | ||||
| 58174 | #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } | ||||
| 58175 | #else | ||||
| 58176 | #define PAGERTRACE(X) | ||||
| 58177 | #endif | ||||
| 58178 | |||||
| 58179 | /* | ||||
| 58180 | ** The following two macros are used within the PAGERTRACE() macros above | ||||
| 58181 | ** to print out file-descriptors. | ||||
| 58182 | ** | ||||
| 58183 | ** PAGERID() takes a pointer to a Pager struct as its argument. The | ||||
| 58184 | ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file | ||||
| 58185 | ** struct as its argument. | ||||
| 58186 | */ | ||||
| 58187 | #define PAGERID(p)(((int)(long int)(p->fd))) (SQLITE_PTR_TO_INT(p->fd)((int)(long int)(p->fd))) | ||||
| 58188 | #define FILEHANDLEID(fd)(((int)(long int)(fd))) (SQLITE_PTR_TO_INT(fd)((int)(long int)(fd))) | ||||
| 58189 | |||||
| 58190 | /* | ||||
| 58191 | ** The Pager.eState variable stores the current 'state' of a pager. A | ||||
| 58192 | ** pager may be in any one of the seven states shown in the following | ||||
| 58193 | ** state diagram. | ||||
| 58194 | ** | ||||
| 58195 | ** OPEN <------+------+ | ||||
| 58196 | ** | | | | ||||
| 58197 | ** V | | | ||||
| 58198 | ** +---------> READER-------+ | | ||||
| 58199 | ** | | | | ||||
| 58200 | ** | V | | ||||
| 58201 | ** |<-------WRITER_LOCKED------> ERROR | ||||
| 58202 | ** | | ^ | ||||
| 58203 | ** | V | | ||||
| 58204 | ** |<------WRITER_CACHEMOD-------->| | ||||
| 58205 | ** | | | | ||||
| 58206 | ** | V | | ||||
| 58207 | ** |<-------WRITER_DBMOD---------->| | ||||
| 58208 | ** | | | | ||||
| 58209 | ** | V | | ||||
| 58210 | ** +<------WRITER_FINISHED-------->+ | ||||
| 58211 | ** | ||||
| 58212 | ** | ||||
| 58213 | ** List of state transitions and the C [function] that performs each: | ||||
| 58214 | ** | ||||
| 58215 | ** OPEN -> READER [sqlite3PagerSharedLock] | ||||
| 58216 | ** READER -> OPEN [pager_unlock] | ||||
| 58217 | ** | ||||
| 58218 | ** READER -> WRITER_LOCKED [sqlite3PagerBegin] | ||||
| 58219 | ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] | ||||
| 58220 | ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] | ||||
| 58221 | ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] | ||||
| 58222 | ** WRITER_*** -> READER [pager_end_transaction] | ||||
| 58223 | ** | ||||
| 58224 | ** WRITER_*** -> ERROR [pager_error] | ||||
| 58225 | ** ERROR -> OPEN [pager_unlock] | ||||
| 58226 | ** | ||||
| 58227 | ** | ||||
| 58228 | ** OPEN: | ||||
| 58229 | ** | ||||
| 58230 | ** The pager starts up in this state. Nothing is guaranteed in this | ||||
| 58231 | ** state - the file may or may not be locked and the database size is | ||||
| 58232 | ** unknown. The database may not be read or written. | ||||
| 58233 | ** | ||||
| 58234 | ** * No read or write transaction is active. | ||||
| 58235 | ** * Any lock, or no lock at all, may be held on the database file. | ||||
| 58236 | ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted. | ||||
| 58237 | ** | ||||
| 58238 | ** READER: | ||||
| 58239 | ** | ||||
| 58240 | ** In this state all the requirements for reading the database in | ||||
| 58241 | ** rollback (non-WAL) mode are met. Unless the pager is (or recently | ||||
| 58242 | ** was) in exclusive-locking mode, a user-level read transaction is | ||||
| 58243 | ** open. The database size is known in this state. | ||||
| 58244 | ** | ||||
| 58245 | ** A connection running with locking_mode=normal enters this state when | ||||
| 58246 | ** it opens a read-transaction on the database and returns to state | ||||
| 58247 | ** OPEN after the read-transaction is completed. However a connection | ||||
| 58248 | ** running in locking_mode=exclusive (including temp databases) remains in | ||||
| 58249 | ** this state even after the read-transaction is closed. The only way | ||||
| 58250 | ** a locking_mode=exclusive connection can transition from READER to OPEN | ||||
| 58251 | ** is via the ERROR state (see below). | ||||
| 58252 | ** | ||||
| 58253 | ** * A read transaction may be active (but a write-transaction cannot). | ||||
| 58254 | ** * A SHARED or greater lock is held on the database file. | ||||
| 58255 | ** * The dbSize variable may be trusted (even if a user-level read | ||||
| 58256 | ** transaction is not active). The dbOrigSize and dbFileSize variables | ||||
| 58257 | ** may not be trusted at this point. | ||||
| 58258 | ** * If the database is a WAL database, then the WAL connection is open. | ||||
| 58259 | ** * Even if a read-transaction is not open, it is guaranteed that | ||||
| 58260 | ** there is no hot-journal in the file-system. | ||||
| 58261 | ** | ||||
| 58262 | ** WRITER_LOCKED: | ||||
| 58263 | ** | ||||
| 58264 | ** The pager moves to this state from READER when a write-transaction | ||||
| 58265 | ** is first opened on the database. In WRITER_LOCKED state, all locks | ||||
| 58266 | ** required to start a write-transaction are held, but no actual | ||||
| 58267 | ** modifications to the cache or database have taken place. | ||||
| 58268 | ** | ||||
| 58269 | ** In rollback mode, a RESERVED or (if the transaction was opened with | ||||
| 58270 | ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when | ||||
| 58271 | ** moving to this state, but the journal file is not written to or opened | ||||
| 58272 | ** to in this state. If the transaction is committed or rolled back while | ||||
| 58273 | ** in WRITER_LOCKED state, all that is required is to unlock the database | ||||
| 58274 | ** file. | ||||
| 58275 | ** | ||||
| 58276 | ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file. | ||||
| 58277 | ** If the connection is running with locking_mode=exclusive, an attempt | ||||
| 58278 | ** is made to obtain an EXCLUSIVE lock on the database file. | ||||
| 58279 | ** | ||||
| 58280 | ** * A write transaction is active. | ||||
| 58281 | ** * If the connection is open in rollback-mode, a RESERVED or greater | ||||
| 58282 | ** lock is held on the database file. | ||||
| 58283 | ** * If the connection is open in WAL-mode, a WAL write transaction | ||||
| 58284 | ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully | ||||
| 58285 | ** called). | ||||
| 58286 | ** * The dbSize, dbOrigSize and dbFileSize variables are all valid. | ||||
| 58287 | ** * The contents of the pager cache have not been modified. | ||||
| 58288 | ** * The journal file may or may not be open. | ||||
| 58289 | ** * Nothing (not even the first header) has been written to the journal. | ||||
| 58290 | ** | ||||
| 58291 | ** WRITER_CACHEMOD: | ||||
| 58292 | ** | ||||
| 58293 | ** A pager moves from WRITER_LOCKED state to this state when a page is | ||||
| 58294 | ** first modified by the upper layer. In rollback mode the journal file | ||||
| 58295 | ** is opened (if it is not already open) and a header written to the | ||||
| 58296 | ** start of it. The database file on disk has not been modified. | ||||
| 58297 | ** | ||||
| 58298 | ** * A write transaction is active. | ||||
| 58299 | ** * A RESERVED or greater lock is held on the database file. | ||||
| 58300 | ** * The journal file is open and the first header has been written | ||||
| 58301 | ** to it, but the header has not been synced to disk. | ||||
| 58302 | ** * The contents of the page cache have been modified. | ||||
| 58303 | ** | ||||
| 58304 | ** WRITER_DBMOD: | ||||
| 58305 | ** | ||||
| 58306 | ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state | ||||
| 58307 | ** when it modifies the contents of the database file. WAL connections | ||||
| 58308 | ** never enter this state (since they do not modify the database file, | ||||
| 58309 | ** just the log file). | ||||
| 58310 | ** | ||||
| 58311 | ** * A write transaction is active. | ||||
| 58312 | ** * An EXCLUSIVE or greater lock is held on the database file. | ||||
| 58313 | ** * The journal file is open and the first header has been written | ||||
| 58314 | ** and synced to disk. | ||||
| 58315 | ** * The contents of the page cache have been modified (and possibly | ||||
| 58316 | ** written to disk). | ||||
| 58317 | ** | ||||
| 58318 | ** WRITER_FINISHED: | ||||
| 58319 | ** | ||||
| 58320 | ** It is not possible for a WAL connection to enter this state. | ||||
| 58321 | ** | ||||
| 58322 | ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD | ||||
| 58323 | ** state after the entire transaction has been successfully written into the | ||||
| 58324 | ** database file. In this state the transaction may be committed simply | ||||
| 58325 | ** by finalizing the journal file. Once in WRITER_FINISHED state, it is | ||||
| 58326 | ** not possible to modify the database further. At this point, the upper | ||||
| 58327 | ** layer must either commit or rollback the transaction. | ||||
| 58328 | ** | ||||
| 58329 | ** * A write transaction is active. | ||||
| 58330 | ** * An EXCLUSIVE or greater lock is held on the database file. | ||||
| 58331 | ** * All writing and syncing of journal and database data has finished. | ||||
| 58332 | ** If no error occurred, all that remains is to finalize the journal to | ||||
| 58333 | ** commit the transaction. If an error did occur, the caller will need | ||||
| 58334 | ** to rollback the transaction. | ||||
| 58335 | ** | ||||
| 58336 | ** ERROR: | ||||
| 58337 | ** | ||||
| 58338 | ** The ERROR state is entered when an IO or disk-full error (including | ||||
| 58339 | ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it | ||||
| 58340 | ** difficult to be sure that the in-memory pager state (cache contents, | ||||
| 58341 | ** db size etc.) are consistent with the contents of the file-system. | ||||
| 58342 | ** | ||||
| 58343 | ** Temporary pager files may enter the ERROR state, but in-memory pagers | ||||
| 58344 | ** cannot. | ||||
| 58345 | ** | ||||
| 58346 | ** For example, if an IO error occurs while performing a rollback, | ||||
| 58347 | ** the contents of the page-cache may be left in an inconsistent state. | ||||
| 58348 | ** At this point it would be dangerous to change back to READER state | ||||
| 58349 | ** (as usually happens after a rollback). Any subsequent readers might | ||||
| 58350 | ** report database corruption (due to the inconsistent cache), and if | ||||
| 58351 | ** they upgrade to writers, they may inadvertently corrupt the database | ||||
| 58352 | ** file. To avoid this hazard, the pager switches into the ERROR state | ||||
| 58353 | ** instead of READER following such an error. | ||||
| 58354 | ** | ||||
| 58355 | ** Once it has entered the ERROR state, any attempt to use the pager | ||||
| 58356 | ** to read or write data returns an error. Eventually, once all | ||||
| 58357 | ** outstanding transactions have been abandoned, the pager is able to | ||||
| 58358 | ** transition back to OPEN state, discarding the contents of the | ||||
| 58359 | ** page-cache and any other in-memory state at the same time. Everything | ||||
| 58360 | ** is reloaded from disk (and, if necessary, hot-journal rollback performed) | ||||
| 58361 | ** when a read-transaction is next opened on the pager (transitioning | ||||
| 58362 | ** the pager into READER state). At that point the system has recovered | ||||
| 58363 | ** from the error. | ||||
| 58364 | ** | ||||
| 58365 | ** Specifically, the pager jumps into the ERROR state if: | ||||
| 58366 | ** | ||||
| 58367 | ** 1. An error occurs while attempting a rollback. This happens in | ||||
| 58368 | ** function sqlite3PagerRollback(). | ||||
| 58369 | ** | ||||
| 58370 | ** 2. An error occurs while attempting to finalize a journal file | ||||
| 58371 | ** following a commit in function sqlite3PagerCommitPhaseTwo(). | ||||
| 58372 | ** | ||||
| 58373 | ** 3. An error occurs while attempting to write to the journal or | ||||
| 58374 | ** database file in function pagerStress() in order to free up | ||||
| 58375 | ** memory. | ||||
| 58376 | ** | ||||
| 58377 | ** In other cases, the error is returned to the b-tree layer. The b-tree | ||||
| 58378 | ** layer then attempts a rollback operation. If the error condition | ||||
| 58379 | ** persists, the pager enters the ERROR state via condition (1) above. | ||||
| 58380 | ** | ||||
| 58381 | ** Condition (3) is necessary because it can be triggered by a read-only | ||||
| 58382 | ** statement executed within a transaction. In this case, if the error | ||||
| 58383 | ** code were simply returned to the user, the b-tree layer would not | ||||
| 58384 | ** automatically attempt a rollback, as it assumes that an error in a | ||||
| 58385 | ** read-only statement cannot leave the pager in an internally inconsistent | ||||
| 58386 | ** state. | ||||
| 58387 | ** | ||||
| 58388 | ** * The Pager.errCode variable is set to something other than SQLITE_OK. | ||||
| 58389 | ** * There are one or more outstanding references to pages (after the | ||||
| 58390 | ** last reference is dropped the pager should move back to OPEN state). | ||||
| 58391 | ** * The pager is not an in-memory pager. | ||||
| 58392 | ** | ||||
| 58393 | ** | ||||
| 58394 | ** Notes: | ||||
| 58395 | ** | ||||
| 58396 | ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the | ||||
| 58397 | ** connection is open in WAL mode. A WAL connection is always in one | ||||
| 58398 | ** of the first four states. | ||||
| 58399 | ** | ||||
| 58400 | ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN | ||||
| 58401 | ** state. There are two exceptions: immediately after exclusive-mode has | ||||
| 58402 | ** been turned on (and before any read or write transactions are | ||||
| 58403 | ** executed), and when the pager is leaving the "error state". | ||||
| 58404 | ** | ||||
| 58405 | ** * See also: assert_pager_state(). | ||||
| 58406 | */ | ||||
| 58407 | #define PAGER_OPEN0 0 | ||||
| 58408 | #define PAGER_READER1 1 | ||||
| 58409 | #define PAGER_WRITER_LOCKED2 2 | ||||
| 58410 | #define PAGER_WRITER_CACHEMOD3 3 | ||||
| 58411 | #define PAGER_WRITER_DBMOD4 4 | ||||
| 58412 | #define PAGER_WRITER_FINISHED5 5 | ||||
| 58413 | #define PAGER_ERROR6 6 | ||||
| 58414 | |||||
| 58415 | /* | ||||
| 58416 | ** The Pager.eLock variable is almost always set to one of the | ||||
| 58417 | ** following locking-states, according to the lock currently held on | ||||
| 58418 | ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. | ||||
| 58419 | ** This variable is kept up to date as locks are taken and released by | ||||
| 58420 | ** the pagerLockDb() and pagerUnlockDb() wrappers. | ||||
| 58421 | ** | ||||
| 58422 | ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY | ||||
| 58423 | ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not | ||||
| 58424 | ** the operation was successful. In these circumstances pagerLockDb() and | ||||
| 58425 | ** pagerUnlockDb() take a conservative approach - eLock is always updated | ||||
| 58426 | ** when unlocking the file, and only updated when locking the file if the | ||||
| 58427 | ** VFS call is successful. This way, the Pager.eLock variable may be set | ||||
| 58428 | ** to a less exclusive (lower) value than the lock that is actually held | ||||
| 58429 | ** at the system level, but it is never set to a more exclusive value. | ||||
| 58430 | ** | ||||
| 58431 | ** This is usually safe. If an xUnlock fails or appears to fail, there may | ||||
| 58432 | ** be a few redundant xLock() calls or a lock may be held for longer than | ||||
| 58433 | ** required, but nothing really goes wrong. | ||||
| 58434 | ** | ||||
| 58435 | ** The exception is when the database file is unlocked as the pager moves | ||||
| 58436 | ** from ERROR to OPEN state. At this point there may be a hot-journal file | ||||
| 58437 | ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED | ||||
| 58438 | ** transition, by the same pager or any other). If the call to xUnlock() | ||||
| 58439 | ** fails at this point and the pager is left holding an EXCLUSIVE lock, this | ||||
| 58440 | ** can confuse the call to xCheckReservedLock() call made later as part | ||||
| 58441 | ** of hot-journal detection. | ||||
| 58442 | ** | ||||
| 58443 | ** xCheckReservedLock() is defined as returning true "if there is a RESERVED | ||||
| 58444 | ** lock held by this process or any others". So xCheckReservedLock may | ||||
| 58445 | ** return true because the caller itself is holding an EXCLUSIVE lock (but | ||||
| 58446 | ** doesn't know it because of a previous error in xUnlock). If this happens | ||||
| 58447 | ** a hot-journal may be mistaken for a journal being created by an active | ||||
| 58448 | ** transaction in another process, causing SQLite to read from the database | ||||
| 58449 | ** without rolling it back. | ||||
| 58450 | ** | ||||
| 58451 | ** To work around this, if a call to xUnlock() fails when unlocking the | ||||
| 58452 | ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It | ||||
| 58453 | ** is only changed back to a real locking state after a successful call | ||||
| 58454 | ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition | ||||
| 58455 | ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK | ||||
| 58456 | ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE | ||||
| 58457 | ** lock on the database file before attempting to roll it back. See function | ||||
| 58458 | ** PagerSharedLock() for more detail. | ||||
| 58459 | ** | ||||
| 58460 | ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in | ||||
| 58461 | ** PAGER_OPEN state. | ||||
| 58462 | */ | ||||
| 58463 | #define UNKNOWN_LOCK(4 +1) (EXCLUSIVE_LOCK4+1) | ||||
| 58464 | |||||
| 58465 | /* | ||||
| 58466 | ** The maximum allowed sector size. 64KiB. If the xSectorsize() method | ||||
| 58467 | ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. | ||||
| 58468 | ** This could conceivably cause corruption following a power failure on | ||||
| 58469 | ** such a system. This is currently an undocumented limit. | ||||
| 58470 | */ | ||||
| 58471 | #define MAX_SECTOR_SIZE0x10000 0x10000 | ||||
| 58472 | |||||
| 58473 | |||||
| 58474 | /* | ||||
| 58475 | ** An instance of the following structure is allocated for each active | ||||
| 58476 | ** savepoint and statement transaction in the system. All such structures | ||||
| 58477 | ** are stored in the Pager.aSavepoint[] array, which is allocated and | ||||
| 58478 | ** resized using sqlite3Realloc(). | ||||
| 58479 | ** | ||||
| 58480 | ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is | ||||
| 58481 | ** set to 0. If a journal-header is written into the main journal while | ||||
| 58482 | ** the savepoint is active, then iHdrOffset is set to the byte offset | ||||
| 58483 | ** immediately following the last journal record written into the main | ||||
| 58484 | ** journal before the journal-header. This is required during savepoint | ||||
| 58485 | ** rollback (see pagerPlaybackSavepoint()). | ||||
| 58486 | */ | ||||
| 58487 | typedef struct PagerSavepoint PagerSavepoint; | ||||
| 58488 | struct PagerSavepoint { | ||||
| 58489 | i64 iOffset; /* Starting offset in main journal */ | ||||
| 58490 | i64 iHdrOffset; /* See above */ | ||||
| 58491 | Bitvec *pInSavepoint; /* Set of pages in this savepoint */ | ||||
| 58492 | Pgno nOrig; /* Original number of pages in file */ | ||||
| 58493 | Pgno iSubRec; /* Index of first record in sub-journal */ | ||||
| 58494 | int bTruncateOnRelease; /* If stmt journal may be truncated on RELEASE */ | ||||
| 58495 | #ifndef SQLITE_OMIT_WAL | ||||
| 58496 | u32 aWalData[WAL_SAVEPOINT_NDATA4]; /* WAL savepoint context */ | ||||
| 58497 | #endif | ||||
| 58498 | }; | ||||
| 58499 | |||||
| 58500 | /* | ||||
| 58501 | ** Bits of the Pager.doNotSpill flag. See further description below. | ||||
| 58502 | */ | ||||
| 58503 | #define SPILLFLAG_OFF0x01 0x01 /* Never spill cache. Set via pragma */ | ||||
| 58504 | #define SPILLFLAG_ROLLBACK0x02 0x02 /* Current rolling back, so do not spill */ | ||||
| 58505 | #define SPILLFLAG_NOSYNC0x04 0x04 /* Spill is ok, but do not sync */ | ||||
| 58506 | |||||
| 58507 | /* | ||||
| 58508 | ** An open page cache is an instance of struct Pager. A description of | ||||
| 58509 | ** some of the more important member variables follows: | ||||
| 58510 | ** | ||||
| 58511 | ** eState | ||||
| 58512 | ** | ||||
| 58513 | ** The current 'state' of the pager object. See the comment and state | ||||
| 58514 | ** diagram above for a description of the pager state. | ||||
| 58515 | ** | ||||
| 58516 | ** eLock | ||||
| 58517 | ** | ||||
| 58518 | ** For a real on-disk database, the current lock held on the database file - | ||||
| 58519 | ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. | ||||
| 58520 | ** | ||||
| 58521 | ** For a temporary or in-memory database (neither of which require any | ||||
| 58522 | ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such | ||||
| 58523 | ** databases always have Pager.exclusiveMode==1, this tricks the pager | ||||
| 58524 | ** logic into thinking that it already has all the locks it will ever | ||||
| 58525 | ** need (and no reason to release them). | ||||
| 58526 | ** | ||||
| 58527 | ** In some (obscure) circumstances, this variable may also be set to | ||||
| 58528 | ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for | ||||
| 58529 | ** details. | ||||
| 58530 | ** | ||||
| 58531 | ** changeCountDone | ||||
| 58532 | ** | ||||
| 58533 | ** This boolean variable is used to make sure that the change-counter | ||||
| 58534 | ** (the 4-byte header field at byte offset 24 of the database file) is | ||||
| 58535 | ** not updated more often than necessary. | ||||
| 58536 | ** | ||||
| 58537 | ** It is set to true when the change-counter field is updated, which | ||||
| 58538 | ** can only happen if an exclusive lock is held on the database file. | ||||
| 58539 | ** It is cleared (set to false) whenever an exclusive lock is | ||||
| 58540 | ** relinquished on the database file. Each time a transaction is committed, | ||||
| 58541 | ** The changeCountDone flag is inspected. If it is true, the work of | ||||
| 58542 | ** updating the change-counter is omitted for the current transaction. | ||||
| 58543 | ** | ||||
| 58544 | ** This mechanism means that when running in exclusive mode, a connection | ||||
| 58545 | ** need only update the change-counter once, for the first transaction | ||||
| 58546 | ** committed. | ||||
| 58547 | ** | ||||
| 58548 | ** setSuper | ||||
| 58549 | ** | ||||
| 58550 | ** When PagerCommitPhaseOne() is called to commit a transaction, it may | ||||
| 58551 | ** (or may not) specify a super-journal name to be written into the | ||||
| 58552 | ** journal file before it is synced to disk. | ||||
| 58553 | ** | ||||
| 58554 | ** Whether or not a journal file contains a super-journal pointer affects | ||||
| 58555 | ** the way in which the journal file is finalized after the transaction is | ||||
| 58556 | ** committed or rolled back when running in "journal_mode=PERSIST" mode. | ||||
| 58557 | ** If a journal file does not contain a super-journal pointer, it is | ||||
| 58558 | ** finalized by overwriting the first journal header with zeroes. If | ||||
| 58559 | ** it does contain a super-journal pointer the journal file is finalized | ||||
| 58560 | ** by truncating it to zero bytes, just as if the connection were | ||||
| 58561 | ** running in "journal_mode=truncate" mode. | ||||
| 58562 | ** | ||||
| 58563 | ** Journal files that contain super-journal pointers cannot be finalized | ||||
| 58564 | ** simply by overwriting the first journal-header with zeroes, as the | ||||
| 58565 | ** super-journal pointer could interfere with hot-journal rollback of any | ||||
| 58566 | ** subsequently interrupted transaction that reuses the journal file. | ||||
| 58567 | ** | ||||
| 58568 | ** The flag is cleared as soon as the journal file is finalized (either | ||||
| 58569 | ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the | ||||
| 58570 | ** journal file from being successfully finalized, the setSuper flag | ||||
| 58571 | ** is cleared anyway (and the pager will move to ERROR state). | ||||
| 58572 | ** | ||||
| 58573 | ** doNotSpill | ||||
| 58574 | ** | ||||
| 58575 | ** This variables control the behavior of cache-spills (calls made by | ||||
| 58576 | ** the pcache module to the pagerStress() routine to write cached data | ||||
| 58577 | ** to the file-system in order to free up memory). | ||||
| 58578 | ** | ||||
| 58579 | ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set, | ||||
| 58580 | ** writing to the database from pagerStress() is disabled altogether. | ||||
| 58581 | ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that | ||||
| 58582 | ** comes up during savepoint rollback that requires the pcache module | ||||
| 58583 | ** to allocate a new page to prevent the journal file from being written | ||||
| 58584 | ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF | ||||
| 58585 | ** case is a user preference. | ||||
| 58586 | ** | ||||
| 58587 | ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from | ||||
| 58588 | ** pagerStress() is permitted, but syncing the journal file is not. | ||||
| 58589 | ** This flag is set by sqlite3PagerWrite() when the file-system sector-size | ||||
| 58590 | ** is larger than the database page-size in order to prevent a journal sync | ||||
| 58591 | ** from happening in between the journalling of two pages on the same sector. | ||||
| 58592 | ** | ||||
| 58593 | ** subjInMemory | ||||
| 58594 | ** | ||||
| 58595 | ** This is a boolean variable. If true, then any required sub-journal | ||||
| 58596 | ** is opened as an in-memory journal file. If false, then in-memory | ||||
| 58597 | ** sub-journals are only used for in-memory pager files. | ||||
| 58598 | ** | ||||
| 58599 | ** This variable is updated by the upper layer each time a new | ||||
| 58600 | ** write-transaction is opened. | ||||
| 58601 | ** | ||||
| 58602 | ** dbSize, dbOrigSize, dbFileSize | ||||
| 58603 | ** | ||||
| 58604 | ** Variable dbSize is set to the number of pages in the database file. | ||||
| 58605 | ** It is valid in PAGER_READER and higher states (all states except for | ||||
| 58606 | ** OPEN and ERROR). | ||||
| 58607 | ** | ||||
| 58608 | ** dbSize is set based on the size of the database file, which may be | ||||
| 58609 | ** larger than the size of the database (the value stored at offset | ||||
| 58610 | ** 28 of the database header by the btree). If the size of the file | ||||
| 58611 | ** is not an integer multiple of the page-size, the value stored in | ||||
| 58612 | ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2). | ||||
| 58613 | ** Except, any file that is greater than 0 bytes in size is considered | ||||
| 58614 | ** to have at least one page. (i.e. a 1KB file with 2K page-size leads | ||||
| 58615 | ** to dbSize==1). | ||||
| 58616 | ** | ||||
| 58617 | ** During a write-transaction, if pages with page-numbers greater than | ||||
| 58618 | ** dbSize are modified in the cache, dbSize is updated accordingly. | ||||
| 58619 | ** Similarly, if the database is truncated using PagerTruncateImage(), | ||||
| 58620 | ** dbSize is updated. | ||||
| 58621 | ** | ||||
| 58622 | ** Variables dbOrigSize and dbFileSize are valid in states | ||||
| 58623 | ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize | ||||
| 58624 | ** variable at the start of the transaction. It is used during rollback, | ||||
| 58625 | ** and to determine whether or not pages need to be journalled before | ||||
| 58626 | ** being modified. | ||||
| 58627 | ** | ||||
| 58628 | ** Throughout a write-transaction, dbFileSize contains the size of | ||||
| 58629 | ** the file on disk in pages. It is set to a copy of dbSize when the | ||||
| 58630 | ** write-transaction is first opened, and updated when VFS calls are made | ||||
| 58631 | ** to write or truncate the database file on disk. | ||||
| 58632 | ** | ||||
| 58633 | ** The only reason the dbFileSize variable is required is to suppress | ||||
| 58634 | ** unnecessary calls to xTruncate() after committing a transaction. If, | ||||
| 58635 | ** when a transaction is committed, the dbFileSize variable indicates | ||||
| 58636 | ** that the database file is larger than the database image (Pager.dbSize), | ||||
| 58637 | ** pager_truncate() is called. The pager_truncate() call uses xFilesize() | ||||
| 58638 | ** to measure the database file on disk, and then truncates it if required. | ||||
| 58639 | ** dbFileSize is not used when rolling back a transaction. In this case | ||||
| 58640 | ** pager_truncate() is called unconditionally (which means there may be | ||||
| 58641 | ** a call to xFilesize() that is not strictly required). In either case, | ||||
| 58642 | ** pager_truncate() may cause the file to become smaller or larger. | ||||
| 58643 | ** | ||||
| 58644 | ** dbHintSize | ||||
| 58645 | ** | ||||
| 58646 | ** The dbHintSize variable is used to limit the number of calls made to | ||||
| 58647 | ** the VFS xFileControl(FCNTL_SIZE_HINT) method. | ||||
| 58648 | ** | ||||
| 58649 | ** dbHintSize is set to a copy of the dbSize variable when a | ||||
| 58650 | ** write-transaction is opened (at the same time as dbFileSize and | ||||
| 58651 | ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called, | ||||
| 58652 | ** dbHintSize is increased to the number of pages that correspond to the | ||||
| 58653 | ** size-hint passed to the method call. See pager_write_pagelist() for | ||||
| 58654 | ** details. | ||||
| 58655 | ** | ||||
| 58656 | ** errCode | ||||
| 58657 | ** | ||||
| 58658 | ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It | ||||
| 58659 | ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode | ||||
| 58660 | ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX | ||||
| 58661 | ** sub-codes. | ||||
| 58662 | ** | ||||
| 58663 | ** syncFlags, walSyncFlags | ||||
| 58664 | ** | ||||
| 58665 | ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03). | ||||
| 58666 | ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode | ||||
| 58667 | ** and contains the flags used to sync the checkpoint operations in the | ||||
| 58668 | ** lower two bits, and sync flags used for transaction commits in the WAL | ||||
| 58669 | ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags | ||||
| 58670 | ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct | ||||
| 58671 | ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note | ||||
| 58672 | ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced | ||||
| 58673 | ** meaning that the 0x04 and 0x08 bits are both zero. | ||||
| 58674 | */ | ||||
| 58675 | struct Pager { | ||||
| 58676 | sqlite3_vfs *pVfs; /* OS functions to use for IO */ | ||||
| 58677 | u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ | ||||
| 58678 | u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */ | ||||
| 58679 | u8 useJournal; /* Use a rollback journal on this file */ | ||||
| 58680 | u8 noSync; /* Do not sync the journal if true */ | ||||
| 58681 | u8 fullSync; /* Do extra syncs of the journal for robustness */ | ||||
| 58682 | u8 extraSync; /* sync directory after journal delete */ | ||||
| 58683 | u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ | ||||
| 58684 | u8 walSyncFlags; /* See description above */ | ||||
| 58685 | u8 tempFile; /* zFilename is a temporary or immutable file */ | ||||
| 58686 | u8 noLock; /* Do not lock (except in WAL mode) */ | ||||
| 58687 | u8 readOnly; /* True for a read-only database */ | ||||
| 58688 | u8 memDb; /* True to inhibit all file I/O */ | ||||
| 58689 | u8 memVfs; /* VFS-implemented memory database */ | ||||
| 58690 | |||||
| 58691 | /************************************************************************** | ||||
| 58692 | ** The following block contains those class members that change during | ||||
| 58693 | ** routine operation. Class members not in this block are either fixed | ||||
| 58694 | ** when the pager is first created or else only change when there is a | ||||
| 58695 | ** significant mode change (such as changing the page_size, locking_mode, | ||||
| 58696 | ** or the journal_mode). From another view, these class members describe | ||||
| 58697 | ** the "state" of the pager, while other class members describe the | ||||
| 58698 | ** "configuration" of the pager. | ||||
| 58699 | */ | ||||
| 58700 | u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */ | ||||
| 58701 | u8 eLock; /* Current lock held on database file */ | ||||
| 58702 | u8 changeCountDone; /* Set after incrementing the change-counter */ | ||||
| 58703 | u8 setSuper; /* Super-jrnl name is written into jrnl */ | ||||
| 58704 | u8 doNotSpill; /* Do not spill the cache when non-zero */ | ||||
| 58705 | u8 subjInMemory; /* True to use in-memory sub-journals */ | ||||
| 58706 | u8 bUseFetch; /* True to use xFetch() */ | ||||
| 58707 | u8 hasHeldSharedLock; /* True if a shared lock has ever been held */ | ||||
| 58708 | Pgno dbSize; /* Number of pages in the database */ | ||||
| 58709 | Pgno dbOrigSize; /* dbSize before the current transaction */ | ||||
| 58710 | Pgno dbFileSize; /* Number of pages in the database file */ | ||||
| 58711 | Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */ | ||||
| 58712 | int errCode; /* One of several kinds of errors */ | ||||
| 58713 | int nRec; /* Pages journalled since last j-header written */ | ||||
| 58714 | u32 cksumInit; /* Quasi-random value added to every checksum */ | ||||
| 58715 | u32 nSubRec; /* Number of records written to sub-journal */ | ||||
| 58716 | Bitvec *pInJournal; /* One bit for each page in the database file */ | ||||
| 58717 | sqlite3_file *fd; /* File descriptor for database */ | ||||
| 58718 | sqlite3_file *jfd; /* File descriptor for main journal */ | ||||
| 58719 | sqlite3_file *sjfd; /* File descriptor for sub-journal */ | ||||
| 58720 | i64 journalOff; /* Current write offset in the journal file */ | ||||
| 58721 | i64 journalHdr; /* Byte offset to previous journal header */ | ||||
| 58722 | sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ | ||||
| 58723 | PagerSavepoint *aSavepoint; /* Array of active savepoints */ | ||||
| 58724 | int nSavepoint; /* Number of elements in aSavepoint[] */ | ||||
| 58725 | u32 iDataVersion; /* Changes whenever database content changes */ | ||||
| 58726 | char dbFileVers[16]; /* Changes whenever database file changes */ | ||||
| 58727 | |||||
| 58728 | int nMmapOut; /* Number of mmap pages currently outstanding */ | ||||
| 58729 | sqlite3_int64 szMmap; /* Desired maximum mmap size */ | ||||
| 58730 | PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */ | ||||
| 58731 | /* | ||||
| 58732 | ** End of the routinely-changing class members | ||||
| 58733 | ***************************************************************************/ | ||||
| 58734 | |||||
| 58735 | u16 nExtra; /* Add this many bytes to each in-memory page */ | ||||
| 58736 | i16 nReserve; /* Number of unused bytes at end of each page */ | ||||
| 58737 | u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ | ||||
| 58738 | u32 sectorSize; /* Assumed sector size during rollback */ | ||||
| 58739 | Pgno mxPgno; /* Maximum allowed size of the database */ | ||||
| 58740 | Pgno lckPgno; /* Page number for the locking page */ | ||||
| 58741 | i64 pageSize; /* Number of bytes in a page */ | ||||
| 58742 | i64 journalSizeLimit; /* Size limit for persistent journal files */ | ||||
| 58743 | char *zFilename; /* Name of the database file */ | ||||
| 58744 | char *zJournal; /* Name of the journal file */ | ||||
| 58745 | int (*xBusyHandler)(void*); /* Function to call when busy */ | ||||
| 58746 | void *pBusyHandlerArg; /* Context argument for xBusyHandler */ | ||||
| 58747 | u32 aStat[4]; /* Total cache hits, misses, writes, spills */ | ||||
| 58748 | #ifdef SQLITE_TEST | ||||
| 58749 | int nRead; /* Database pages read */ | ||||
| 58750 | #endif | ||||
| 58751 | void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */ | ||||
| 58752 | int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */ | ||||
| 58753 | char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ | ||||
| 58754 | PCache *pPCache; /* Pointer to page cache object */ | ||||
| 58755 | #ifndef SQLITE_OMIT_WAL | ||||
| 58756 | Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */ | ||||
| 58757 | char *zWal; /* File name for write-ahead log */ | ||||
| 58758 | #endif | ||||
| 58759 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 58760 | sqlite3 *dbWal; | ||||
| 58761 | #endif | ||||
| 58762 | }; | ||||
| 58763 | |||||
| 58764 | /* | ||||
| 58765 | ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains | ||||
| 58766 | ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS | ||||
| 58767 | ** or CACHE_WRITE to sqlite3_db_status(). | ||||
| 58768 | */ | ||||
| 58769 | #define PAGER_STAT_HIT0 0 | ||||
| 58770 | #define PAGER_STAT_MISS1 1 | ||||
| 58771 | #define PAGER_STAT_WRITE2 2 | ||||
| 58772 | #define PAGER_STAT_SPILL3 3 | ||||
| 58773 | |||||
| 58774 | /* | ||||
| 58775 | ** The following global variables hold counters used for | ||||
| 58776 | ** testing purposes only. These variables do not exist in | ||||
| 58777 | ** a non-testing build. These variables are not thread-safe. | ||||
| 58778 | */ | ||||
| 58779 | #ifdef SQLITE_TEST | ||||
| 58780 | SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ | ||||
| 58781 | SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ | ||||
| 58782 | SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ | ||||
| 58783 | # define PAGER_INCR(v) v++ | ||||
| 58784 | #else | ||||
| 58785 | # define PAGER_INCR(v) | ||||
| 58786 | #endif | ||||
| 58787 | |||||
| 58788 | |||||
| 58789 | |||||
| 58790 | /* | ||||
| 58791 | ** Journal files begin with the following magic string. The data | ||||
| 58792 | ** was obtained from /dev/random. It is used only as a sanity check. | ||||
| 58793 | ** | ||||
| 58794 | ** Since version 2.8.0, the journal format contains additional sanity | ||||
| 58795 | ** checking information. If the power fails while the journal is being | ||||
| 58796 | ** written, semi-random garbage data might appear in the journal | ||||
| 58797 | ** file after power is restored. If an attempt is then made | ||||
| 58798 | ** to roll the journal back, the database could be corrupted. The additional | ||||
| 58799 | ** sanity checking data is an attempt to discover the garbage in the | ||||
| 58800 | ** journal and ignore it. | ||||
| 58801 | ** | ||||
| 58802 | ** The sanity checking information for the new journal format consists | ||||
| 58803 | ** of a 32-bit checksum on each page of data. The checksum covers both | ||||
| 58804 | ** the page number and the pPager->pageSize bytes of data for the page. | ||||
| 58805 | ** This cksum is initialized to a 32-bit random value that appears in the | ||||
| 58806 | ** journal file right after the header. The random initializer is important, | ||||
| 58807 | ** because garbage data that appears at the end of a journal is likely | ||||
| 58808 | ** data that was once in other files that have now been deleted. If the | ||||
| 58809 | ** garbage data came from an obsolete journal file, the checksums might | ||||
| 58810 | ** be correct. But by initializing the checksum to random value which | ||||
| 58811 | ** is different for every journal, we minimize that risk. | ||||
| 58812 | */ | ||||
| 58813 | static const unsigned char aJournalMagic[] = { | ||||
| 58814 | 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, | ||||
| 58815 | }; | ||||
| 58816 | |||||
| 58817 | /* | ||||
| 58818 | ** The size of the of each page record in the journal is given by | ||||
| 58819 | ** the following macro. | ||||
| 58820 | */ | ||||
| 58821 | #define JOURNAL_PG_SZ(pPager)((pPager->pageSize) + 8) ((pPager->pageSize) + 8) | ||||
| 58822 | |||||
| 58823 | /* | ||||
| 58824 | ** The journal header size for this pager. This is usually the same | ||||
| 58825 | ** size as a single disk sector. See also setSectorSize(). | ||||
| 58826 | */ | ||||
| 58827 | #define JOURNAL_HDR_SZ(pPager)(pPager->sectorSize) (pPager->sectorSize) | ||||
| 58828 | |||||
| 58829 | /* | ||||
| 58830 | ** The macro MEMDB is true if we are dealing with an in-memory database. | ||||
| 58831 | ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, | ||||
| 58832 | ** the value of MEMDB will be a constant and the compiler will optimize | ||||
| 58833 | ** out code that would never execute. | ||||
| 58834 | */ | ||||
| 58835 | #ifdef SQLITE_OMIT_MEMORYDB | ||||
| 58836 | # define MEMDBpPager->memDb 0 | ||||
| 58837 | #else | ||||
| 58838 | # define MEMDBpPager->memDb pPager->memDb | ||||
| 58839 | #endif | ||||
| 58840 | |||||
| 58841 | /* | ||||
| 58842 | ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch | ||||
| 58843 | ** interfaces to access the database using memory-mapped I/O. | ||||
| 58844 | */ | ||||
| 58845 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 58846 | # define USEFETCH(x)((x)->bUseFetch) ((x)->bUseFetch) | ||||
| 58847 | #else | ||||
| 58848 | # define USEFETCH(x)((x)->bUseFetch) 0 | ||||
| 58849 | #endif | ||||
| 58850 | |||||
| 58851 | #ifdef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 58852 | /* | ||||
| 58853 | ** Return true if page pgno can be read directly from the database file | ||||
| 58854 | ** by the b-tree layer. This is the case if: | ||||
| 58855 | ** | ||||
| 58856 | ** (1) the database file is open | ||||
| 58857 | ** (2) the VFS for the database is able to do unaligned sub-page reads | ||||
| 58858 | ** (3) there are no dirty pages in the cache, and | ||||
| 58859 | ** (4) the desired page is not currently in the wal file. | ||||
| 58860 | */ | ||||
| 58861 | SQLITE_PRIVATEstatic int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){ | ||||
| 58862 | assert( pPager!=0 )((void) (0)); | ||||
| 58863 | assert( pPager->fd!=0 )((void) (0)); | ||||
| 58864 | if( pPager->fd->pMethods==0 ) return 0; /* Case (1) */ | ||||
| 58865 | if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0; /* Failed (3) */ | ||||
| 58866 | #ifndef SQLITE_OMIT_WAL | ||||
| 58867 | if( pPager->pWal ){ | ||||
| 58868 | u32 iRead = 0; | ||||
| 58869 | (void)sqlite3WalFindFrame(pPager->pWal, pgno, &iRead); | ||||
| 58870 | if( iRead ) return 0; /* Case (4) */ | ||||
| 58871 | } | ||||
| 58872 | #endif | ||||
| 58873 | assert( pPager->fd->pMethods->xDeviceCharacteristics!=0 )((void) (0)); | ||||
| 58874 | if( (pPager->fd->pMethods->xDeviceCharacteristics(pPager->fd) | ||||
| 58875 | & SQLITE_IOCAP_SUBPAGE_READ0x00008000)==0 ){ | ||||
| 58876 | return 0; /* Case (2) */ | ||||
| 58877 | } | ||||
| 58878 | return 1; | ||||
| 58879 | } | ||||
| 58880 | #endif | ||||
| 58881 | |||||
| 58882 | #ifndef SQLITE_OMIT_WAL | ||||
| 58883 | # define pagerUseWal(x)((x)->pWal!=0) ((x)->pWal!=0) | ||||
| 58884 | #else | ||||
| 58885 | # define pagerUseWal(x)((x)->pWal!=0) 0 | ||||
| 58886 | # define pagerRollbackWal(x) 0 | ||||
| 58887 | # define pagerWalFrames(v,w,x,y) 0 | ||||
| 58888 | # define pagerOpenWalIfPresent(z) SQLITE_OK0 | ||||
| 58889 | # define pagerBeginReadTransaction(z) SQLITE_OK0 | ||||
| 58890 | #endif | ||||
| 58891 | |||||
| 58892 | #ifndef NDEBUG1 | ||||
| 58893 | /* | ||||
| 58894 | ** Usage: | ||||
| 58895 | ** | ||||
| 58896 | ** assert( assert_pager_state(pPager) ); | ||||
| 58897 | ** | ||||
| 58898 | ** This function runs many asserts to try to find inconsistencies in | ||||
| 58899 | ** the internal state of the Pager object. | ||||
| 58900 | */ | ||||
| 58901 | static int assert_pager_state(Pager *p){ | ||||
| 58902 | Pager *pPager = p; | ||||
| 58903 | |||||
| 58904 | /* State must be valid. */ | ||||
| 58905 | assert( p->eState==PAGER_OPEN((void) (0)) | ||||
| 58906 | || p->eState==PAGER_READER((void) (0)) | ||||
| 58907 | || p->eState==PAGER_WRITER_LOCKED((void) (0)) | ||||
| 58908 | || p->eState==PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 58909 | || p->eState==PAGER_WRITER_DBMOD((void) (0)) | ||||
| 58910 | || p->eState==PAGER_WRITER_FINISHED((void) (0)) | ||||
| 58911 | || p->eState==PAGER_ERROR((void) (0)) | ||||
| 58912 | )((void) (0)); | ||||
| 58913 | |||||
| 58914 | /* Regardless of the current state, a temp-file connection always behaves | ||||
| 58915 | ** as if it has an exclusive lock on the database file. It never updates | ||||
| 58916 | ** the change-counter field, so the changeCountDone flag is always set. | ||||
| 58917 | */ | ||||
| 58918 | assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 58919 | assert( p->tempFile==0 || pPager->changeCountDone )((void) (0)); | ||||
| 58920 | |||||
| 58921 | /* If the useJournal flag is clear, the journal-mode must be "OFF". | ||||
| 58922 | ** And if the journal-mode is "OFF", the journal file must not be open. | ||||
| 58923 | */ | ||||
| 58924 | assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal )((void) (0)); | ||||
| 58925 | assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) )((void) (0)); | ||||
| 58926 | |||||
| 58927 | /* Check that MEMDB implies noSync. And an in-memory journal. Since | ||||
| 58928 | ** this means an in-memory pager performs no IO at all, it cannot encounter | ||||
| 58929 | ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing | ||||
| 58930 | ** a journal file. (although the in-memory journal implementation may | ||||
| 58931 | ** return SQLITE_IOERR_NOMEM while the journal file is being written). It | ||||
| 58932 | ** is therefore not possible for an in-memory pager to enter the ERROR | ||||
| 58933 | ** state. | ||||
| 58934 | */ | ||||
| 58935 | if( MEMDBpPager->memDb ){ | ||||
| 58936 | assert( !isOpen(p->fd) )((void) (0)); | ||||
| 58937 | assert( p->noSync )((void) (0)); | ||||
| 58938 | assert( p->journalMode==PAGER_JOURNALMODE_OFF((void) (0)) | ||||
| 58939 | || p->journalMode==PAGER_JOURNALMODE_MEMORY((void) (0)) | ||||
| 58940 | )((void) (0)); | ||||
| 58941 | assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN )((void) (0)); | ||||
| 58942 | assert( pagerUseWal(p)==0 )((void) (0)); | ||||
| 58943 | } | ||||
| 58944 | |||||
| 58945 | /* If changeCountDone is set, a RESERVED lock or greater must be held | ||||
| 58946 | ** on the file. | ||||
| 58947 | */ | ||||
| 58948 | assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK )((void) (0)); | ||||
| 58949 | assert( p->eLock!=PENDING_LOCK )((void) (0)); | ||||
| 58950 | |||||
| 58951 | switch( p->eState ){ | ||||
| 58952 | case PAGER_OPEN0: | ||||
| 58953 | assert( !MEMDB )((void) (0)); | ||||
| 58954 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 58955 | assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile )((void) (0)); | ||||
| 58956 | break; | ||||
| 58957 | |||||
| 58958 | case PAGER_READER1: | ||||
| 58959 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 58960 | assert( p->eLock!=UNKNOWN_LOCK )((void) (0)); | ||||
| 58961 | assert( p->eLock>=SHARED_LOCK )((void) (0)); | ||||
| 58962 | break; | ||||
| 58963 | |||||
| 58964 | case PAGER_WRITER_LOCKED2: | ||||
| 58965 | assert( p->eLock!=UNKNOWN_LOCK )((void) (0)); | ||||
| 58966 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 58967 | if( !pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 58968 | assert( p->eLock>=RESERVED_LOCK )((void) (0)); | ||||
| 58969 | } | ||||
| 58970 | assert( pPager->dbSize==pPager->dbOrigSize )((void) (0)); | ||||
| 58971 | assert( pPager->dbOrigSize==pPager->dbFileSize )((void) (0)); | ||||
| 58972 | assert( pPager->dbOrigSize==pPager->dbHintSize )((void) (0)); | ||||
| 58973 | assert( pPager->setSuper==0 )((void) (0)); | ||||
| 58974 | break; | ||||
| 58975 | |||||
| 58976 | case PAGER_WRITER_CACHEMOD3: | ||||
| 58977 | assert( p->eLock!=UNKNOWN_LOCK )((void) (0)); | ||||
| 58978 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 58979 | if( !pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 58980 | /* It is possible that if journal_mode=wal here that neither the | ||||
| 58981 | ** journal file nor the WAL file are open. This happens during | ||||
| 58982 | ** a rollback transaction that switches from journal_mode=off | ||||
| 58983 | ** to journal_mode=wal. | ||||
| 58984 | */ | ||||
| 58985 | assert( p->eLock>=RESERVED_LOCK )((void) (0)); | ||||
| 58986 | assert( isOpen(p->jfd)((void) (0)) | ||||
| 58987 | || p->journalMode==PAGER_JOURNALMODE_OFF((void) (0)) | ||||
| 58988 | || p->journalMode==PAGER_JOURNALMODE_WAL((void) (0)) | ||||
| 58989 | )((void) (0)); | ||||
| 58990 | } | ||||
| 58991 | assert( pPager->dbOrigSize==pPager->dbFileSize )((void) (0)); | ||||
| 58992 | assert( pPager->dbOrigSize==pPager->dbHintSize )((void) (0)); | ||||
| 58993 | break; | ||||
| 58994 | |||||
| 58995 | case PAGER_WRITER_DBMOD4: | ||||
| 58996 | assert( p->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 58997 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 58998 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 58999 | assert( p->eLock>=EXCLUSIVE_LOCK )((void) (0)); | ||||
| 59000 | assert( isOpen(p->jfd)((void) (0)) | ||||
| 59001 | || p->journalMode==PAGER_JOURNALMODE_OFF((void) (0)) | ||||
| 59002 | || p->journalMode==PAGER_JOURNALMODE_WAL((void) (0)) | ||||
| 59003 | || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)((void) (0)) | ||||
| 59004 | )((void) (0)); | ||||
| 59005 | assert( pPager->dbOrigSize<=pPager->dbHintSize )((void) (0)); | ||||
| 59006 | break; | ||||
| 59007 | |||||
| 59008 | case PAGER_WRITER_FINISHED5: | ||||
| 59009 | assert( p->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 59010 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 59011 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 59012 | assert( isOpen(p->jfd)((void) (0)) | ||||
| 59013 | || p->journalMode==PAGER_JOURNALMODE_OFF((void) (0)) | ||||
| 59014 | || p->journalMode==PAGER_JOURNALMODE_WAL((void) (0)) | ||||
| 59015 | || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)((void) (0)) | ||||
| 59016 | )((void) (0)); | ||||
| 59017 | break; | ||||
| 59018 | |||||
| 59019 | case PAGER_ERROR6: | ||||
| 59020 | /* There must be at least one outstanding reference to the pager if | ||||
| 59021 | ** in ERROR state. Otherwise the pager should have already dropped | ||||
| 59022 | ** back to OPEN state. | ||||
| 59023 | */ | ||||
| 59024 | assert( pPager->errCode!=SQLITE_OK )((void) (0)); | ||||
| 59025 | assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile )((void) (0)); | ||||
| 59026 | break; | ||||
| 59027 | } | ||||
| 59028 | |||||
| 59029 | return 1; | ||||
| 59030 | } | ||||
| 59031 | #endif /* ifndef NDEBUG */ | ||||
| 59032 | |||||
| 59033 | #ifdef SQLITE_DEBUG | ||||
| 59034 | /* | ||||
| 59035 | ** Return a pointer to a human readable string in a static buffer | ||||
| 59036 | ** containing the state of the Pager object passed as an argument. This | ||||
| 59037 | ** is intended to be used within debuggers. For example, as an alternative | ||||
| 59038 | ** to "print *pPager" in gdb: | ||||
| 59039 | ** | ||||
| 59040 | ** (gdb) printf "%s", print_pager_state(pPager) | ||||
| 59041 | ** | ||||
| 59042 | ** This routine has external linkage in order to suppress compiler warnings | ||||
| 59043 | ** about an unused function. It is enclosed within SQLITE_DEBUG and so does | ||||
| 59044 | ** not appear in normal builds. | ||||
| 59045 | */ | ||||
| 59046 | char *print_pager_state(Pager *p){ | ||||
| 59047 | static char zRet[1024]; | ||||
| 59048 | |||||
| 59049 | sqlite3_snprintf(1024, zRet, | ||||
| 59050 | "Filename: %s\n" | ||||
| 59051 | "State: %s errCode=%d\n" | ||||
| 59052 | "Lock: %s\n" | ||||
| 59053 | "Locking mode: locking_mode=%s\n" | ||||
| 59054 | "Journal mode: journal_mode=%s\n" | ||||
| 59055 | "Backing store: tempFile=%d memDb=%d useJournal=%d\n" | ||||
| 59056 | "Journal: journalOff=%lld journalHdr=%lld\n" | ||||
| 59057 | "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n" | ||||
| 59058 | , p->zFilename | ||||
| 59059 | , p->eState==PAGER_OPEN0 ? "OPEN" : | ||||
| 59060 | p->eState==PAGER_READER1 ? "READER" : | ||||
| 59061 | p->eState==PAGER_WRITER_LOCKED2 ? "WRITER_LOCKED" : | ||||
| 59062 | p->eState==PAGER_WRITER_CACHEMOD3 ? "WRITER_CACHEMOD" : | ||||
| 59063 | p->eState==PAGER_WRITER_DBMOD4 ? "WRITER_DBMOD" : | ||||
| 59064 | p->eState==PAGER_WRITER_FINISHED5 ? "WRITER_FINISHED" : | ||||
| 59065 | p->eState==PAGER_ERROR6 ? "ERROR" : "?error?" | ||||
| 59066 | , (int)p->errCode | ||||
| 59067 | , p->eLock==NO_LOCK0 ? "NO_LOCK" : | ||||
| 59068 | p->eLock==RESERVED_LOCK2 ? "RESERVED" : | ||||
| 59069 | p->eLock==EXCLUSIVE_LOCK4 ? "EXCLUSIVE" : | ||||
| 59070 | p->eLock==SHARED_LOCK1 ? "SHARED" : | ||||
| 59071 | p->eLock==UNKNOWN_LOCK(4 +1) ? "UNKNOWN" : "?error?" | ||||
| 59072 | , p->exclusiveMode ? "exclusive" : "normal" | ||||
| 59073 | , p->journalMode==PAGER_JOURNALMODE_MEMORY4 ? "memory" : | ||||
| 59074 | p->journalMode==PAGER_JOURNALMODE_OFF2 ? "off" : | ||||
| 59075 | p->journalMode==PAGER_JOURNALMODE_DELETE0 ? "delete" : | ||||
| 59076 | p->journalMode==PAGER_JOURNALMODE_PERSIST1 ? "persist" : | ||||
| 59077 | p->journalMode==PAGER_JOURNALMODE_TRUNCATE3 ? "truncate" : | ||||
| 59078 | p->journalMode==PAGER_JOURNALMODE_WAL5 ? "wal" : "?error?" | ||||
| 59079 | , (int)p->tempFile, (int)p->memDb, (int)p->useJournal | ||||
| 59080 | , p->journalOff, p->journalHdr | ||||
| 59081 | , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize | ||||
| 59082 | ); | ||||
| 59083 | |||||
| 59084 | return zRet; | ||||
| 59085 | } | ||||
| 59086 | #endif | ||||
| 59087 | |||||
| 59088 | /* Forward references to the various page getters */ | ||||
| 59089 | static int getPageNormal(Pager*,Pgno,DbPage**,int); | ||||
| 59090 | static int getPageError(Pager*,Pgno,DbPage**,int); | ||||
| 59091 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 59092 | static int getPageMMap(Pager*,Pgno,DbPage**,int); | ||||
| 59093 | #endif | ||||
| 59094 | |||||
| 59095 | /* | ||||
| 59096 | ** Set the Pager.xGet method for the appropriate routine used to fetch | ||||
| 59097 | ** content from the pager. | ||||
| 59098 | */ | ||||
| 59099 | static void setGetterMethod(Pager *pPager){ | ||||
| 59100 | if( pPager->errCode ){ | ||||
| 59101 | pPager->xGet = getPageError; | ||||
| 59102 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 59103 | }else if( USEFETCH(pPager)((pPager)->bUseFetch) ){ | ||||
| 59104 | pPager->xGet = getPageMMap; | ||||
| 59105 | #endif /* SQLITE_MAX_MMAP_SIZE>0 */ | ||||
| 59106 | }else{ | ||||
| 59107 | pPager->xGet = getPageNormal; | ||||
| 59108 | } | ||||
| 59109 | } | ||||
| 59110 | |||||
| 59111 | /* | ||||
| 59112 | ** Return true if it is necessary to write page *pPg into the sub-journal. | ||||
| 59113 | ** A page needs to be written into the sub-journal if there exists one | ||||
| 59114 | ** or more open savepoints for which: | ||||
| 59115 | ** | ||||
| 59116 | ** * The page-number is less than or equal to PagerSavepoint.nOrig, and | ||||
| 59117 | ** * The bit corresponding to the page-number is not set in | ||||
| 59118 | ** PagerSavepoint.pInSavepoint. | ||||
| 59119 | */ | ||||
| 59120 | static int subjRequiresPage(PgHdr *pPg){ | ||||
| 59121 | Pager *pPager = pPg->pPager; | ||||
| 59122 | PagerSavepoint *p; | ||||
| 59123 | Pgno pgno = pPg->pgno; | ||||
| 59124 | int i; | ||||
| 59125 | for(i=0; i<pPager->nSavepoint; i++){ | ||||
| 59126 | p = &pPager->aSavepoint[i]; | ||||
| 59127 | if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){ | ||||
| 59128 | for(i=i+1; i<pPager->nSavepoint; i++){ | ||||
| 59129 | pPager->aSavepoint[i].bTruncateOnRelease = 0; | ||||
| 59130 | } | ||||
| 59131 | return 1; | ||||
| 59132 | } | ||||
| 59133 | } | ||||
| 59134 | return 0; | ||||
| 59135 | } | ||||
| 59136 | |||||
| 59137 | #ifdef SQLITE_DEBUG | ||||
| 59138 | /* | ||||
| 59139 | ** Return true if the page is already in the journal file. | ||||
| 59140 | */ | ||||
| 59141 | static int pageInJournal(Pager *pPager, PgHdr *pPg){ | ||||
| 59142 | return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno); | ||||
| 59143 | } | ||||
| 59144 | #endif | ||||
| 59145 | |||||
| 59146 | /* | ||||
| 59147 | ** Read a 32-bit integer from the given file descriptor. Store the integer | ||||
| 59148 | ** that is read in *pRes. Return SQLITE_OK if everything worked, or an | ||||
| 59149 | ** error code is something goes wrong. | ||||
| 59150 | ** | ||||
| 59151 | ** All values are stored on disk as big-endian. | ||||
| 59152 | */ | ||||
| 59153 | static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ | ||||
| 59154 | unsigned char ac[4]; | ||||
| 59155 | int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset); | ||||
| 59156 | if( rc==SQLITE_OK0 ){ | ||||
| 59157 | *pRes = sqlite3Get4byte(ac); | ||||
| 59158 | } | ||||
| 59159 | return rc; | ||||
| 59160 | } | ||||
| 59161 | |||||
| 59162 | /* | ||||
| 59163 | ** Write a 32-bit integer into a string buffer in big-endian byte order. | ||||
| 59164 | */ | ||||
| 59165 | #define put32bits(A,B)sqlite3Put4byte((u8*)A,B) sqlite3Put4byte((u8*)A,B) | ||||
| 59166 | |||||
| 59167 | |||||
| 59168 | /* | ||||
| 59169 | ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK | ||||
| 59170 | ** on success or an error code is something goes wrong. | ||||
| 59171 | */ | ||||
| 59172 | static int write32bits(sqlite3_file *fd, i64 offset, u32 val){ | ||||
| 59173 | char ac[4]; | ||||
| 59174 | put32bits(ac, val)sqlite3Put4byte((u8*)ac,val); | ||||
| 59175 | return sqlite3OsWrite(fd, ac, 4, offset); | ||||
| 59176 | } | ||||
| 59177 | |||||
| 59178 | /* | ||||
| 59179 | ** Unlock the database file to level eLock, which must be either NO_LOCK | ||||
| 59180 | ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock() | ||||
| 59181 | ** succeeds, set the Pager.eLock variable to match the (attempted) new lock. | ||||
| 59182 | ** | ||||
| 59183 | ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is | ||||
| 59184 | ** called, do not modify it. See the comment above the #define of | ||||
| 59185 | ** UNKNOWN_LOCK for an explanation of this. | ||||
| 59186 | */ | ||||
| 59187 | static int pagerUnlockDb(Pager *pPager, int eLock){ | ||||
| 59188 | int rc = SQLITE_OK0; | ||||
| 59189 | |||||
| 59190 | assert( !pPager->exclusiveMode || pPager->eLock==eLock )((void) (0)); | ||||
| 59191 | assert( eLock==NO_LOCK || eLock==SHARED_LOCK )((void) (0)); | ||||
| 59192 | assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 )((void) (0)); | ||||
| 59193 | if( isOpen(pPager->fd)((pPager->fd)->pMethods!=0) ){ | ||||
| 59194 | assert( pPager->eLock>=eLock )((void) (0)); | ||||
| 59195 | rc = pPager->noLock ? SQLITE_OK0 : sqlite3OsUnlock(pPager->fd, eLock); | ||||
| 59196 | if( pPager->eLock!=UNKNOWN_LOCK(4 +1) ){ | ||||
| 59197 | pPager->eLock = (u8)eLock; | ||||
| 59198 | } | ||||
| 59199 | IOTRACE(("UNLOCK %p %d\n", pPager, eLock)) | ||||
| 59200 | } | ||||
| 59201 | pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */ | ||||
| 59202 | return rc; | ||||
| 59203 | } | ||||
| 59204 | |||||
| 59205 | /* | ||||
| 59206 | ** Lock the database file to level eLock, which must be either SHARED_LOCK, | ||||
| 59207 | ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the | ||||
| 59208 | ** Pager.eLock variable to the new locking state. | ||||
| 59209 | ** | ||||
| 59210 | ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is | ||||
| 59211 | ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. | ||||
| 59212 | ** See the comment above the #define of UNKNOWN_LOCK for an explanation | ||||
| 59213 | ** of this. | ||||
| 59214 | */ | ||||
| 59215 | static int pagerLockDb(Pager *pPager, int eLock){ | ||||
| 59216 | int rc = SQLITE_OK0; | ||||
| 59217 | |||||
| 59218 | assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 59219 | if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK(4 +1) ){ | ||||
| 59220 | rc = pPager->noLock ? SQLITE_OK0 : sqlite3OsLock(pPager->fd, eLock); | ||||
| 59221 | if( rc==SQLITE_OK0 && (pPager->eLock!=UNKNOWN_LOCK(4 +1)||eLock==EXCLUSIVE_LOCK4) ){ | ||||
| 59222 | pPager->eLock = (u8)eLock; | ||||
| 59223 | IOTRACE(("LOCK %p %d\n", pPager, eLock)) | ||||
| 59224 | } | ||||
| 59225 | } | ||||
| 59226 | return rc; | ||||
| 59227 | } | ||||
| 59228 | |||||
| 59229 | /* | ||||
| 59230 | ** This function determines whether or not the atomic-write or | ||||
| 59231 | ** atomic-batch-write optimizations can be used with this pager. The | ||||
| 59232 | ** atomic-write optimization can be used if: | ||||
| 59233 | ** | ||||
| 59234 | ** (a) the value returned by OsDeviceCharacteristics() indicates that | ||||
| 59235 | ** a database page may be written atomically, and | ||||
| 59236 | ** (b) the value returned by OsSectorSize() is less than or equal | ||||
| 59237 | ** to the page size. | ||||
| 59238 | ** | ||||
| 59239 | ** If it can be used, then the value returned is the size of the journal | ||||
| 59240 | ** file when it contains rollback data for exactly one page. | ||||
| 59241 | ** | ||||
| 59242 | ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics() | ||||
| 59243 | ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is | ||||
| 59244 | ** returned in this case. | ||||
| 59245 | ** | ||||
| 59246 | ** If neither optimization can be used, 0 is returned. | ||||
| 59247 | */ | ||||
| 59248 | static int jrnlBufferSize(Pager *pPager){ | ||||
| 59249 | assert( !MEMDB )((void) (0)); | ||||
| 59250 | |||||
| 59251 | #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ | ||||
| 59252 | || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) | ||||
| 59253 | int dc; /* Device characteristics */ | ||||
| 59254 | |||||
| 59255 | assert( isOpen(pPager->fd) )((void) (0)); | ||||
| 59256 | dc = sqlite3OsDeviceCharacteristics(pPager->fd); | ||||
| 59257 | #else | ||||
| 59258 | UNUSED_PARAMETER(pPager)(void)(pPager); | ||||
| 59259 | #endif | ||||
| 59260 | |||||
| 59261 | #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE | ||||
| 59262 | if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC0x00004000) ){ | ||||
| 59263 | return -1; | ||||
| 59264 | } | ||||
| 59265 | #endif | ||||
| 59266 | |||||
| 59267 | #ifdef SQLITE_ENABLE_ATOMIC_WRITE | ||||
| 59268 | { | ||||
| 59269 | int nSector = pPager->sectorSize; | ||||
| 59270 | int szPage = pPager->pageSize; | ||||
| 59271 | |||||
| 59272 | assert(SQLITE_IOCAP_ATOMIC512==(512>>8))((void) (0)); | ||||
| 59273 | assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8))((void) (0)); | ||||
| 59274 | if( 0==(dc&(SQLITE_IOCAP_ATOMIC0x00000001|(szPage>>8)) || nSector>szPage) ){ | ||||
| 59275 | return 0; | ||||
| 59276 | } | ||||
| 59277 | } | ||||
| 59278 | |||||
| 59279 | return JOURNAL_HDR_SZ(pPager)(pPager->sectorSize) + JOURNAL_PG_SZ(pPager)((pPager->pageSize) + 8); | ||||
| 59280 | #endif | ||||
| 59281 | |||||
| 59282 | return 0; | ||||
| 59283 | } | ||||
| 59284 | |||||
| 59285 | /* | ||||
| 59286 | ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking | ||||
| 59287 | ** on the cache using a hash function. This is used for testing | ||||
| 59288 | ** and debugging only. | ||||
| 59289 | */ | ||||
| 59290 | #ifdef SQLITE_CHECK_PAGES | ||||
| 59291 | /* | ||||
| 59292 | ** Return a 32-bit hash of the page data for pPage. | ||||
| 59293 | */ | ||||
| 59294 | static u32 pager_datahash(int nByte, unsigned char *pData)0{ | ||||
| 59295 | u32 hash = 0; | ||||
| 59296 | int i; | ||||
| 59297 | for(i=0; i<nByte; i++){ | ||||
| 59298 | hash = (hash*1039) + pData[i]; | ||||
| 59299 | } | ||||
| 59300 | return hash; | ||||
| 59301 | } | ||||
| 59302 | static u32 pager_pagehash(PgHdr *pPage)0{ | ||||
| 59303 | return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData)0; | ||||
| 59304 | } | ||||
| 59305 | static void pager_set_pagehash(PgHdr *pPage){ | ||||
| 59306 | pPage->pageHash = pager_pagehash(pPage)0; | ||||
| 59307 | } | ||||
| 59308 | |||||
| 59309 | /* | ||||
| 59310 | ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES | ||||
| 59311 | ** is defined, and NDEBUG is not defined, an assert() statement checks | ||||
| 59312 | ** that the page is either dirty or still matches the calculated page-hash. | ||||
| 59313 | */ | ||||
| 59314 | #define CHECK_PAGE(x) checkPage(x) | ||||
| 59315 | static void checkPage(PgHdr *pPg){ | ||||
| 59316 | Pager *pPager = pPg->pPager; | ||||
| 59317 | assert( pPager->eState!=PAGER_ERROR )((void) (0)); | ||||
| 59318 | assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) )((void) (0)); | ||||
| 59319 | } | ||||
| 59320 | |||||
| 59321 | #else | ||||
| 59322 | #define pager_datahash(X,Y)0 0 | ||||
| 59323 | #define pager_pagehash(X)0 0 | ||||
| 59324 | #define pager_set_pagehash(X) | ||||
| 59325 | #define CHECK_PAGE(x) | ||||
| 59326 | #endif /* SQLITE_CHECK_PAGES */ | ||||
| 59327 | |||||
| 59328 | /* | ||||
| 59329 | ** When this is called the journal file for pager pPager must be open. | ||||
| 59330 | ** This function attempts to read a super-journal file name from the | ||||
| 59331 | ** end of the file and, if successful, copies it into memory supplied | ||||
| 59332 | ** by the caller. See comments above writeSuperJournal() for the format | ||||
| 59333 | ** used to store a super-journal file name at the end of a journal file. | ||||
| 59334 | ** | ||||
| 59335 | ** zSuper must point to a buffer of at least nSuper bytes allocated by | ||||
| 59336 | ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is | ||||
| 59337 | ** enough space to write the super-journal name). If the super-journal | ||||
| 59338 | ** name in the journal is longer than nSuper bytes (including a | ||||
| 59339 | ** nul-terminator), then this is handled as if no super-journal name | ||||
| 59340 | ** were present in the journal. | ||||
| 59341 | ** | ||||
| 59342 | ** If a super-journal file name is present at the end of the journal | ||||
| 59343 | ** file, then it is copied into the buffer pointed to by zSuper. A | ||||
| 59344 | ** nul-terminator byte is appended to the buffer following the | ||||
| 59345 | ** super-journal file name. | ||||
| 59346 | ** | ||||
| 59347 | ** If it is determined that no super-journal file name is present | ||||
| 59348 | ** zSuper[0] is set to 0 and SQLITE_OK returned. | ||||
| 59349 | ** | ||||
| 59350 | ** If an error occurs while reading from the journal file, an SQLite | ||||
| 59351 | ** error code is returned. | ||||
| 59352 | */ | ||||
| 59353 | static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u64 nSuper){ | ||||
| 59354 | int rc; /* Return code */ | ||||
| 59355 | u32 len; /* Length in bytes of super-journal name */ | ||||
| 59356 | i64 szJ; /* Total size in bytes of journal file pJrnl */ | ||||
| 59357 | u32 cksum; /* MJ checksum value read from journal */ | ||||
| 59358 | u32 u; /* Unsigned loop counter */ | ||||
| 59359 | unsigned char aMagic[8]; /* A buffer to hold the magic header */ | ||||
| 59360 | zSuper[0] = '\0'; | ||||
| 59361 | |||||
| 59362 | if( SQLITE_OK0!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) | ||||
| 59363 | || szJ<16 | ||||
| 59364 | || SQLITE_OK0!=(rc = read32bits(pJrnl, szJ-16, &len)) | ||||
| 59365 | || len>=nSuper | ||||
| 59366 | || len>szJ-16 | ||||
| 59367 | || len==0 | ||||
| 59368 | || SQLITE_OK0!=(rc = read32bits(pJrnl, szJ-12, &cksum)) | ||||
| 59369 | || SQLITE_OK0!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) | ||||
| 59370 | || memcmp(aMagic, aJournalMagic, 8) | ||||
| 59371 | || SQLITE_OK0!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len)) | ||||
| 59372 | ){ | ||||
| 59373 | return rc; | ||||
| 59374 | } | ||||
| 59375 | |||||
| 59376 | /* See if the checksum matches the super-journal name */ | ||||
| 59377 | for(u=0; u<len; u++){ | ||||
| 59378 | cksum -= zSuper[u]; | ||||
| 59379 | } | ||||
| 59380 | if( cksum ){ | ||||
| 59381 | /* If the checksum doesn't add up, then one or more of the disk sectors | ||||
| 59382 | ** containing the super-journal filename is corrupted. This means | ||||
| 59383 | ** definitely roll back, so just return SQLITE_OK and report a (nul) | ||||
| 59384 | ** super-journal filename. | ||||
| 59385 | */ | ||||
| 59386 | len = 0; | ||||
| 59387 | } | ||||
| 59388 | zSuper[len] = '\0'; | ||||
| 59389 | zSuper[len+1] = '\0'; | ||||
| 59390 | |||||
| 59391 | return SQLITE_OK0; | ||||
| 59392 | } | ||||
| 59393 | |||||
| 59394 | /* | ||||
| 59395 | ** Return the offset of the sector boundary at or immediately | ||||
| 59396 | ** following the value in pPager->journalOff, assuming a sector | ||||
| 59397 | ** size of pPager->sectorSize bytes. | ||||
| 59398 | ** | ||||
| 59399 | ** i.e for a sector size of 512: | ||||
| 59400 | ** | ||||
| 59401 | ** Pager.journalOff Return value | ||||
| 59402 | ** --------------------------------------- | ||||
| 59403 | ** 0 0 | ||||
| 59404 | ** 512 512 | ||||
| 59405 | ** 100 512 | ||||
| 59406 | ** 2000 2048 | ||||
| 59407 | ** | ||||
| 59408 | */ | ||||
| 59409 | static i64 journalHdrOffset(Pager *pPager){ | ||||
| 59410 | i64 offset = 0; | ||||
| 59411 | i64 c = pPager->journalOff; | ||||
| 59412 | if( c ){ | ||||
| 59413 | offset = ((c-1)/JOURNAL_HDR_SZ(pPager)(pPager->sectorSize) + 1) * JOURNAL_HDR_SZ(pPager)(pPager->sectorSize); | ||||
| 59414 | } | ||||
| 59415 | assert( offset%JOURNAL_HDR_SZ(pPager)==0 )((void) (0)); | ||||
| 59416 | assert( offset>=c )((void) (0)); | ||||
| 59417 | assert( (offset-c)<JOURNAL_HDR_SZ(pPager) )((void) (0)); | ||||
| 59418 | return offset; | ||||
| 59419 | } | ||||
| 59420 | |||||
| 59421 | /* | ||||
| 59422 | ** The journal file must be open when this function is called. | ||||
| 59423 | ** | ||||
| 59424 | ** This function is a no-op if the journal file has not been written to | ||||
| 59425 | ** within the current transaction (i.e. if Pager.journalOff==0). | ||||
| 59426 | ** | ||||
| 59427 | ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is | ||||
| 59428 | ** set to 0, then truncate the journal file to zero bytes in size. Otherwise, | ||||
| 59429 | ** zero the 28-byte header at the start of the journal file. In either case, | ||||
| 59430 | ** if the pager is not in no-sync mode, sync the journal file immediately | ||||
| 59431 | ** after writing or truncating it. | ||||
| 59432 | ** | ||||
| 59433 | ** If Pager.journalSizeLimit is set to a positive, non-zero value, and | ||||
| 59434 | ** following the truncation or zeroing described above the size of the | ||||
| 59435 | ** journal file in bytes is larger than this value, then truncate the | ||||
| 59436 | ** journal file to Pager.journalSizeLimit bytes. The journal file does | ||||
| 59437 | ** not need to be synced following this operation. | ||||
| 59438 | ** | ||||
| 59439 | ** If an IO error occurs, abandon processing and return the IO error code. | ||||
| 59440 | ** Otherwise, return SQLITE_OK. | ||||
| 59441 | */ | ||||
| 59442 | static int zeroJournalHdr(Pager *pPager, int doTruncate){ | ||||
| 59443 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 59444 | assert( isOpen(pPager->jfd) )((void) (0)); | ||||
| 59445 | assert( !sqlite3JournalIsInMemory(pPager->jfd) )((void) (0)); | ||||
| 59446 | if( pPager->journalOff ){ | ||||
| 59447 | const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */ | ||||
| 59448 | |||||
| 59449 | IOTRACE(("JZEROHDR %p\n", pPager)) | ||||
| 59450 | if( doTruncate || iLimit==0 ){ | ||||
| 59451 | rc = sqlite3OsTruncate(pPager->jfd, 0); | ||||
| 59452 | }else{ | ||||
| 59453 | static const char zeroHdr[28] = {0}; | ||||
| 59454 | rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); | ||||
| 59455 | } | ||||
| 59456 | if( rc==SQLITE_OK0 && !pPager->noSync ){ | ||||
| 59457 | rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY0x00010|pPager->syncFlags); | ||||
| 59458 | } | ||||
| 59459 | |||||
| 59460 | /* At this point the transaction is committed but the write lock | ||||
| 59461 | ** is still held on the file. If there is a size limit configured for | ||||
| 59462 | ** the persistent journal and the journal file currently consumes more | ||||
| 59463 | ** space than that limit allows for, truncate it now. There is no need | ||||
| 59464 | ** to sync the file following this operation. | ||||
| 59465 | */ | ||||
| 59466 | if( rc==SQLITE_OK0 && iLimit>0 ){ | ||||
| 59467 | i64 sz; | ||||
| 59468 | rc = sqlite3OsFileSize(pPager->jfd, &sz); | ||||
| 59469 | if( rc==SQLITE_OK0 && sz>iLimit ){ | ||||
| 59470 | rc = sqlite3OsTruncate(pPager->jfd, iLimit); | ||||
| 59471 | } | ||||
| 59472 | } | ||||
| 59473 | } | ||||
| 59474 | return rc; | ||||
| 59475 | } | ||||
| 59476 | |||||
| 59477 | /* | ||||
| 59478 | ** The journal file must be open when this routine is called. A journal | ||||
| 59479 | ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the | ||||
| 59480 | ** current location. | ||||
| 59481 | ** | ||||
| 59482 | ** The format for the journal header is as follows: | ||||
| 59483 | ** - 8 bytes: Magic identifying journal format. | ||||
| 59484 | ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. | ||||
| 59485 | ** - 4 bytes: Random number used for page hash. | ||||
| 59486 | ** - 4 bytes: Initial database page count. | ||||
| 59487 | ** - 4 bytes: Sector size used by the process that wrote this journal. | ||||
| 59488 | ** - 4 bytes: Database page size. | ||||
| 59489 | ** | ||||
| 59490 | ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. | ||||
| 59491 | */ | ||||
| 59492 | static int writeJournalHdr(Pager *pPager){ | ||||
| 59493 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 59494 | char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */ | ||||
| 59495 | u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */ | ||||
| 59496 | u32 nWrite; /* Bytes of header sector written */ | ||||
| 59497 | int ii; /* Loop counter */ | ||||
| 59498 | |||||
| 59499 | assert( isOpen(pPager->jfd) )((void) (0)); /* Journal file must be open. */ | ||||
| 59500 | |||||
| 59501 | if( nHeader>JOURNAL_HDR_SZ(pPager)(pPager->sectorSize) ){ | ||||
| 59502 | nHeader = JOURNAL_HDR_SZ(pPager)(pPager->sectorSize); | ||||
| 59503 | } | ||||
| 59504 | |||||
| 59505 | /* If there are active savepoints and any of them were created | ||||
| 59506 | ** since the most recent journal header was written, update the | ||||
| 59507 | ** PagerSavepoint.iHdrOffset fields now. | ||||
| 59508 | */ | ||||
| 59509 | for(ii=0; ii<pPager->nSavepoint; ii++){ | ||||
| 59510 | if( pPager->aSavepoint[ii].iHdrOffset==0 ){ | ||||
| 59511 | pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff; | ||||
| 59512 | } | ||||
| 59513 | } | ||||
| 59514 | |||||
| 59515 | pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager); | ||||
| 59516 | |||||
| 59517 | /* | ||||
| 59518 | ** Write the nRec Field - the number of page records that follow this | ||||
| 59519 | ** journal header. Normally, zero is written to this value at this time. | ||||
| 59520 | ** After the records are added to the journal (and the journal synced, | ||||
| 59521 | ** if in full-sync mode), the zero is overwritten with the true number | ||||
| 59522 | ** of records (see syncJournal()). | ||||
| 59523 | ** | ||||
| 59524 | ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When | ||||
| 59525 | ** reading the journal this value tells SQLite to assume that the | ||||
| 59526 | ** rest of the journal file contains valid page records. This assumption | ||||
| 59527 | ** is dangerous, as if a failure occurred whilst writing to the journal | ||||
| 59528 | ** file it may contain some garbage data. There are two scenarios | ||||
| 59529 | ** where this risk can be ignored: | ||||
| 59530 | ** | ||||
| 59531 | ** * When the pager is in no-sync mode. Corruption can follow a | ||||
| 59532 | ** power failure in this case anyway. | ||||
| 59533 | ** | ||||
| 59534 | ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees | ||||
| 59535 | ** that garbage data is never appended to the journal file. | ||||
| 59536 | */ | ||||
| 59537 | assert( isOpen(pPager->fd) || pPager->noSync )((void) (0)); | ||||
| 59538 | if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY4) | ||||
| 59539 | || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND0x00000200) | ||||
| 59540 | ){ | ||||
| 59541 | memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); | ||||
| 59542 | put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff)sqlite3Put4byte((u8*)&zHeader[sizeof(aJournalMagic)],0xffffffff ); | ||||
| 59543 | }else{ | ||||
| 59544 | memset(zHeader, 0, sizeof(aJournalMagic)+4); | ||||
| 59545 | } | ||||
| 59546 | |||||
| 59547 | |||||
| 59548 | |||||
| 59549 | /* The random check-hash initializer */ | ||||
| 59550 | if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY4 ){ | ||||
| 59551 | sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); | ||||
| 59552 | } | ||||
| 59553 | #ifdef SQLITE_DEBUG | ||||
| 59554 | else{ | ||||
| 59555 | /* The Pager.cksumInit variable is usually randomized above to protect | ||||
| 59556 | ** against there being existing records in the journal file. This is | ||||
| 59557 | ** dangerous, as following a crash they may be mistaken for records | ||||
| 59558 | ** written by the current transaction and rolled back into the database | ||||
| 59559 | ** file, causing corruption. The following assert statements verify | ||||
| 59560 | ** that this is not required in "journal_mode=memory" mode, as in that | ||||
| 59561 | ** case the journal file is always 0 bytes in size at this point. | ||||
| 59562 | ** It is advantageous to avoid the sqlite3_randomness() call if possible | ||||
| 59563 | ** as it takes the global PRNG mutex. */ | ||||
| 59564 | i64 sz = 0; | ||||
| 59565 | sqlite3OsFileSize(pPager->jfd, &sz); | ||||
| 59566 | assert( sz==0 )((void) (0)); | ||||
| 59567 | assert( pPager->journalOff==journalHdrOffset(pPager) )((void) (0)); | ||||
| 59568 | assert( sqlite3JournalIsInMemory(pPager->jfd) )((void) (0)); | ||||
| 59569 | } | ||||
| 59570 | #endif | ||||
| 59571 | put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit)sqlite3Put4byte((u8*)&zHeader[sizeof(aJournalMagic)+4],pPager ->cksumInit); | ||||
| 59572 | |||||
| 59573 | /* The initial database size */ | ||||
| 59574 | put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize)sqlite3Put4byte((u8*)&zHeader[sizeof(aJournalMagic)+8],pPager ->dbOrigSize); | ||||
| 59575 | /* The assumed sector size for this process */ | ||||
| 59576 | put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize)sqlite3Put4byte((u8*)&zHeader[sizeof(aJournalMagic)+12],pPager ->sectorSize); | ||||
| 59577 | |||||
| 59578 | /* The page size */ | ||||
| 59579 | put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize)sqlite3Put4byte((u8*)&zHeader[sizeof(aJournalMagic)+16],pPager ->pageSize); | ||||
| 59580 | |||||
| 59581 | /* Initializing the tail of the buffer is not necessary. Everything | ||||
| 59582 | ** works find if the following memset() is omitted. But initializing | ||||
| 59583 | ** the memory prevents valgrind from complaining, so we are willing to | ||||
| 59584 | ** take the performance hit. | ||||
| 59585 | */ | ||||
| 59586 | memset(&zHeader[sizeof(aJournalMagic)+20], 0, | ||||
| 59587 | nHeader-(sizeof(aJournalMagic)+20)); | ||||
| 59588 | |||||
| 59589 | /* In theory, it is only necessary to write the 28 bytes that the | ||||
| 59590 | ** journal header consumes to the journal file here. Then increment the | ||||
| 59591 | ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next | ||||
| 59592 | ** record is written to the following sector (leaving a gap in the file | ||||
| 59593 | ** that will be implicitly filled in by the OS). | ||||
| 59594 | ** | ||||
| 59595 | ** However it has been discovered that on some systems this pattern can | ||||
| 59596 | ** be significantly slower than contiguously writing data to the file, | ||||
| 59597 | ** even if that means explicitly writing data to the block of | ||||
| 59598 | ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what | ||||
| 59599 | ** is done. | ||||
| 59600 | ** | ||||
| 59601 | ** The loop is required here in case the sector-size is larger than the | ||||
| 59602 | ** database page size. Since the zHeader buffer is only Pager.pageSize | ||||
| 59603 | ** bytes in size, more than one call to sqlite3OsWrite() may be required | ||||
| 59604 | ** to populate the entire journal header sector. | ||||
| 59605 | */ | ||||
| 59606 | for(nWrite=0; rc==SQLITE_OK0&&nWrite<JOURNAL_HDR_SZ(pPager)(pPager->sectorSize); nWrite+=nHeader){ | ||||
| 59607 | IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader)) | ||||
| 59608 | rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); | ||||
| 59609 | assert( pPager->journalHdr <= pPager->journalOff )((void) (0)); | ||||
| 59610 | pPager->journalOff += nHeader; | ||||
| 59611 | } | ||||
| 59612 | |||||
| 59613 | return rc; | ||||
| 59614 | } | ||||
| 59615 | |||||
| 59616 | /* | ||||
| 59617 | ** The journal file must be open when this is called. A journal header file | ||||
| 59618 | ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal | ||||
| 59619 | ** file. The current location in the journal file is given by | ||||
| 59620 | ** pPager->journalOff. See comments above function writeJournalHdr() for | ||||
| 59621 | ** a description of the journal header format. | ||||
| 59622 | ** | ||||
| 59623 | ** If the header is read successfully, *pNRec is set to the number of | ||||
| 59624 | ** page records following this header and *pDbSize is set to the size of the | ||||
| 59625 | ** database before the transaction began, in pages. Also, pPager->cksumInit | ||||
| 59626 | ** is set to the value read from the journal header. SQLITE_OK is returned | ||||
| 59627 | ** in this case. | ||||
| 59628 | ** | ||||
| 59629 | ** If the journal header file appears to be corrupted, SQLITE_DONE is | ||||
| 59630 | ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes | ||||
| 59631 | ** cannot be read from the journal file an error code is returned. | ||||
| 59632 | */ | ||||
| 59633 | static int readJournalHdr( | ||||
| 59634 | Pager *pPager, /* Pager object */ | ||||
| 59635 | int isHot, | ||||
| 59636 | i64 journalSize, /* Size of the open journal file in bytes */ | ||||
| 59637 | u32 *pNRec, /* OUT: Value read from the nRec field */ | ||||
| 59638 | u32 *pDbSize /* OUT: Value of original database size field */ | ||||
| 59639 | ){ | ||||
| 59640 | int rc; /* Return code */ | ||||
| 59641 | unsigned char aMagic[8]; /* A buffer to hold the magic header */ | ||||
| 59642 | i64 iHdrOff; /* Offset of journal header being read */ | ||||
| 59643 | |||||
| 59644 | assert( isOpen(pPager->jfd) )((void) (0)); /* Journal file must be open. */ | ||||
| 59645 | |||||
| 59646 | /* Advance Pager.journalOff to the start of the next sector. If the | ||||
| 59647 | ** journal file is too small for there to be a header stored at this | ||||
| 59648 | ** point, return SQLITE_DONE. | ||||
| 59649 | */ | ||||
| 59650 | pPager->journalOff = journalHdrOffset(pPager); | ||||
| 59651 | if( pPager->journalOff+JOURNAL_HDR_SZ(pPager)(pPager->sectorSize) > journalSize ){ | ||||
| 59652 | return SQLITE_DONE101; | ||||
| 59653 | } | ||||
| 59654 | iHdrOff = pPager->journalOff; | ||||
| 59655 | |||||
| 59656 | /* Read in the first 8 bytes of the journal header. If they do not match | ||||
| 59657 | ** the magic string found at the start of each journal header, return | ||||
| 59658 | ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, | ||||
| 59659 | ** proceed. | ||||
| 59660 | */ | ||||
| 59661 | if( isHot || iHdrOff!=pPager->journalHdr ){ | ||||
| 59662 | rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); | ||||
| 59663 | if( rc ){ | ||||
| 59664 | return rc; | ||||
| 59665 | } | ||||
| 59666 | if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){ | ||||
| 59667 | return SQLITE_DONE101; | ||||
| 59668 | } | ||||
| 59669 | } | ||||
| 59670 | |||||
| 59671 | /* Read the first three 32-bit fields of the journal header: The nRec | ||||
| 59672 | ** field, the checksum-initializer and the database size at the start | ||||
| 59673 | ** of the transaction. Return an error code if anything goes wrong. | ||||
| 59674 | */ | ||||
| 59675 | if( SQLITE_OK0!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec)) | ||||
| 59676 | || SQLITE_OK0!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit)) | ||||
| 59677 | || SQLITE_OK0!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize)) | ||||
| 59678 | ){ | ||||
| 59679 | return rc; | ||||
| 59680 | } | ||||
| 59681 | |||||
| 59682 | if( pPager->journalOff==0 ){ | ||||
| 59683 | u32 iPageSize; /* Page-size field of journal header */ | ||||
| 59684 | u32 iSectorSize; /* Sector-size field of journal header */ | ||||
| 59685 | |||||
| 59686 | /* Read the page-size and sector-size journal header fields. */ | ||||
| 59687 | if( SQLITE_OK0!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize)) | ||||
| 59688 | || SQLITE_OK0!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize)) | ||||
| 59689 | ){ | ||||
| 59690 | return rc; | ||||
| 59691 | } | ||||
| 59692 | |||||
| 59693 | /* Versions of SQLite prior to 3.5.8 set the page-size field of the | ||||
| 59694 | ** journal header to zero. In this case, assume that the Pager.pageSize | ||||
| 59695 | ** variable is already set to the correct page size. | ||||
| 59696 | */ | ||||
| 59697 | if( iPageSize==0 ){ | ||||
| 59698 | iPageSize = pPager->pageSize; | ||||
| 59699 | } | ||||
| 59700 | |||||
| 59701 | /* Check that the values read from the page-size and sector-size fields | ||||
| 59702 | ** are within range. To be 'in range', both values need to be a power | ||||
| 59703 | ** of two greater than or equal to 512 or 32, and not greater than their | ||||
| 59704 | ** respective compile time maximum limits. | ||||
| 59705 | */ | ||||
| 59706 | if( iPageSize<512 || iSectorSize<32 | ||||
| 59707 | || iPageSize>SQLITE_MAX_PAGE_SIZE65536 || iSectorSize>MAX_SECTOR_SIZE0x10000 | ||||
| 59708 | || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0 | ||||
| 59709 | ){ | ||||
| 59710 | /* If the either the page-size or sector-size in the journal-header is | ||||
| 59711 | ** invalid, then the process that wrote the journal-header must have | ||||
| 59712 | ** crashed before the header was synced. In this case stop reading | ||||
| 59713 | ** the journal file here. | ||||
| 59714 | */ | ||||
| 59715 | return SQLITE_DONE101; | ||||
| 59716 | } | ||||
| 59717 | |||||
| 59718 | /* Update the page-size to match the value read from the journal. | ||||
| 59719 | ** Use a testcase() macro to make sure that malloc failure within | ||||
| 59720 | ** PagerSetPagesize() is tested. | ||||
| 59721 | */ | ||||
| 59722 | rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1); | ||||
| 59723 | testcase( rc!=SQLITE_OK ); | ||||
| 59724 | |||||
| 59725 | /* Update the assumed sector-size to match the value used by | ||||
| 59726 | ** the process that created this journal. If this journal was | ||||
| 59727 | ** created by a process other than this one, then this routine | ||||
| 59728 | ** is being called from within pager_playback(). The local value | ||||
| 59729 | ** of Pager.sectorSize is restored at the end of that routine. | ||||
| 59730 | */ | ||||
| 59731 | pPager->sectorSize = iSectorSize; | ||||
| 59732 | } | ||||
| 59733 | |||||
| 59734 | pPager->journalOff += JOURNAL_HDR_SZ(pPager)(pPager->sectorSize); | ||||
| 59735 | return rc; | ||||
| 59736 | } | ||||
| 59737 | |||||
| 59738 | |||||
| 59739 | /* | ||||
| 59740 | ** Write the supplied super-journal name into the journal file for pager | ||||
| 59741 | ** pPager at the current location. The super-journal name must be the last | ||||
| 59742 | ** thing written to a journal file. If the pager is in full-sync mode, the | ||||
| 59743 | ** journal file descriptor is advanced to the next sector boundary before | ||||
| 59744 | ** anything is written. The format is: | ||||
| 59745 | ** | ||||
| 59746 | ** + 4 bytes: PAGER_SJ_PGNO. | ||||
| 59747 | ** + N bytes: super-journal filename in utf-8. | ||||
| 59748 | ** + 4 bytes: N (length of super-journal name in bytes, no nul-terminator). | ||||
| 59749 | ** + 4 bytes: super-journal name checksum. | ||||
| 59750 | ** + 8 bytes: aJournalMagic[]. | ||||
| 59751 | ** | ||||
| 59752 | ** The super-journal page checksum is the sum of the bytes in the super-journal | ||||
| 59753 | ** name, where each byte is interpreted as a signed 8-bit integer. | ||||
| 59754 | ** | ||||
| 59755 | ** If zSuper is a NULL pointer (occurs for a single database transaction), | ||||
| 59756 | ** this call is a no-op. | ||||
| 59757 | */ | ||||
| 59758 | static int writeSuperJournal(Pager *pPager, const char *zSuper){ | ||||
| 59759 | int rc; /* Return code */ | ||||
| 59760 | int nSuper; /* Length of string zSuper */ | ||||
| 59761 | i64 iHdrOff; /* Offset of header in journal file */ | ||||
| 59762 | i64 jrnlSize; /* Size of journal file on disk */ | ||||
| 59763 | u32 cksum = 0; /* Checksum of string zSuper */ | ||||
| 59764 | |||||
| 59765 | assert( pPager->setSuper==0 )((void) (0)); | ||||
| 59766 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 59767 | |||||
| 59768 | if( !zSuper | ||||
| 59769 | || pPager->journalMode==PAGER_JOURNALMODE_MEMORY4 | ||||
| 59770 | || !isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) | ||||
| 59771 | ){ | ||||
| 59772 | return SQLITE_OK0; | ||||
| 59773 | } | ||||
| 59774 | pPager->setSuper = 1; | ||||
| 59775 | assert( pPager->journalHdr <= pPager->journalOff )((void) (0)); | ||||
| 59776 | |||||
| 59777 | /* Calculate the length in bytes and the checksum of zSuper */ | ||||
| 59778 | for(nSuper=0; zSuper[nSuper]; nSuper++){ | ||||
| 59779 | cksum += zSuper[nSuper]; | ||||
| 59780 | } | ||||
| 59781 | |||||
| 59782 | /* If in full-sync mode, advance to the next disk sector before writing | ||||
| 59783 | ** the super-journal name. This is in case the previous page written to | ||||
| 59784 | ** the journal has already been synced. | ||||
| 59785 | */ | ||||
| 59786 | if( pPager->fullSync ){ | ||||
| 59787 | pPager->journalOff = journalHdrOffset(pPager); | ||||
| 59788 | } | ||||
| 59789 | iHdrOff = pPager->journalOff; | ||||
| 59790 | |||||
| 59791 | /* Write the super-journal data to the end of the journal file. If | ||||
| 59792 | ** an error occurs, return the error code to the caller. | ||||
| 59793 | */ | ||||
| 59794 | if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_SJ_PGNO(pPager)((pPager)->lckPgno)))) | ||||
| 59795 | || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4))) | ||||
| 59796 | || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper))) | ||||
| 59797 | || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum))) | ||||
| 59798 | || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, | ||||
| 59799 | iHdrOff+4+nSuper+8))) | ||||
| 59800 | ){ | ||||
| 59801 | return rc; | ||||
| 59802 | } | ||||
| 59803 | pPager->journalOff += (nSuper+20); | ||||
| 59804 | |||||
| 59805 | /* If the pager is in persistent-journal mode, then the physical | ||||
| 59806 | ** journal-file may extend past the end of the super-journal name | ||||
| 59807 | ** and 8 bytes of magic data just written to the file. This is | ||||
| 59808 | ** dangerous because the code to rollback a hot-journal file | ||||
| 59809 | ** will not be able to find the super-journal name to determine | ||||
| 59810 | ** whether or not the journal is hot. | ||||
| 59811 | ** | ||||
| 59812 | ** Easiest thing to do in this scenario is to truncate the journal | ||||
| 59813 | ** file to the required size. | ||||
| 59814 | */ | ||||
| 59815 | if( SQLITE_OK0==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize)) | ||||
| 59816 | && jrnlSize>pPager->journalOff | ||||
| 59817 | ){ | ||||
| 59818 | rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff); | ||||
| 59819 | } | ||||
| 59820 | return rc; | ||||
| 59821 | } | ||||
| 59822 | |||||
| 59823 | /* | ||||
| 59824 | ** Discard the entire contents of the in-memory page-cache. | ||||
| 59825 | */ | ||||
| 59826 | static void pager_reset(Pager *pPager){ | ||||
| 59827 | pPager->iDataVersion++; | ||||
| 59828 | sqlite3BackupRestart(pPager->pBackup); | ||||
| 59829 | sqlite3PcacheClear(pPager->pPCache); | ||||
| 59830 | } | ||||
| 59831 | |||||
| 59832 | /* | ||||
| 59833 | ** Return the pPager->iDataVersion value | ||||
| 59834 | */ | ||||
| 59835 | SQLITE_PRIVATEstatic u32 sqlite3PagerDataVersion(Pager *pPager){ | ||||
| 59836 | return pPager->iDataVersion; | ||||
| 59837 | } | ||||
| 59838 | |||||
| 59839 | /* | ||||
| 59840 | ** Free all structures in the Pager.aSavepoint[] array and set both | ||||
| 59841 | ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal | ||||
| 59842 | ** if it is open and the pager is not in exclusive mode. | ||||
| 59843 | */ | ||||
| 59844 | static void releaseAllSavepoints(Pager *pPager){ | ||||
| 59845 | int ii; /* Iterator for looping through Pager.aSavepoint */ | ||||
| 59846 | for(ii=0; ii<pPager->nSavepoint; ii++){ | ||||
| 59847 | sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); | ||||
| 59848 | } | ||||
| 59849 | if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){ | ||||
| 59850 | sqlite3OsClose(pPager->sjfd); | ||||
| 59851 | } | ||||
| 59852 | sqlite3_free(pPager->aSavepoint); | ||||
| 59853 | pPager->aSavepoint = 0; | ||||
| 59854 | pPager->nSavepoint = 0; | ||||
| 59855 | pPager->nSubRec = 0; | ||||
| 59856 | } | ||||
| 59857 | |||||
| 59858 | /* | ||||
| 59859 | ** Set the bit number pgno in the PagerSavepoint.pInSavepoint | ||||
| 59860 | ** bitvecs of all open savepoints. Return SQLITE_OK if successful | ||||
| 59861 | ** or SQLITE_NOMEM if a malloc failure occurs. | ||||
| 59862 | */ | ||||
| 59863 | static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){ | ||||
| 59864 | int ii; /* Loop counter */ | ||||
| 59865 | int rc = SQLITE_OK0; /* Result code */ | ||||
| 59866 | |||||
| 59867 | for(ii=0; ii<pPager->nSavepoint; ii++){ | ||||
| 59868 | PagerSavepoint *p = &pPager->aSavepoint[ii]; | ||||
| 59869 | if( pgno<=p->nOrig ){ | ||||
| 59870 | rc |= sqlite3BitvecSet(p->pInSavepoint, pgno); | ||||
| 59871 | testcase( rc==SQLITE_NOMEM ); | ||||
| 59872 | assert( rc==SQLITE_OK || rc==SQLITE_NOMEM )((void) (0)); | ||||
| 59873 | } | ||||
| 59874 | } | ||||
| 59875 | return rc; | ||||
| 59876 | } | ||||
| 59877 | |||||
| 59878 | /* | ||||
| 59879 | ** This function is a no-op if the pager is in exclusive mode and not | ||||
| 59880 | ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN | ||||
| 59881 | ** state. | ||||
| 59882 | ** | ||||
| 59883 | ** If the pager is not in exclusive-access mode, the database file is | ||||
| 59884 | ** completely unlocked. If the file is unlocked and the file-system does | ||||
| 59885 | ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is | ||||
| 59886 | ** closed (if it is open). | ||||
| 59887 | ** | ||||
| 59888 | ** If the pager is in ERROR state when this function is called, the | ||||
| 59889 | ** contents of the pager cache are discarded before switching back to | ||||
| 59890 | ** the OPEN state. Regardless of whether the pager is in exclusive-mode | ||||
| 59891 | ** or not, any journal file left in the file-system will be treated | ||||
| 59892 | ** as a hot-journal and rolled back the next time a read-transaction | ||||
| 59893 | ** is opened (by this or by any other connection). | ||||
| 59894 | */ | ||||
| 59895 | static void pager_unlock(Pager *pPager){ | ||||
| 59896 | |||||
| 59897 | assert( pPager->eState==PAGER_READER((void) (0)) | ||||
| 59898 | || pPager->eState==PAGER_OPEN((void) (0)) | ||||
| 59899 | || pPager->eState==PAGER_ERROR((void) (0)) | ||||
| 59900 | )((void) (0)); | ||||
| 59901 | |||||
| 59902 | sqlite3BitvecDestroy(pPager->pInJournal); | ||||
| 59903 | pPager->pInJournal = 0; | ||||
| 59904 | releaseAllSavepoints(pPager); | ||||
| 59905 | |||||
| 59906 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 59907 | assert( !isOpen(pPager->jfd) )((void) (0)); | ||||
| 59908 | if( pPager->eState==PAGER_ERROR6 ){ | ||||
| 59909 | /* If an IO error occurs in wal.c while attempting to wrap the wal file, | ||||
| 59910 | ** then the Wal object may be holding a write-lock but no read-lock. | ||||
| 59911 | ** This call ensures that the write-lock is dropped as well. We cannot | ||||
| 59912 | ** have sqlite3WalEndReadTransaction() drop the write-lock, as it once | ||||
| 59913 | ** did, because this would break "BEGIN EXCLUSIVE" handling for | ||||
| 59914 | ** SQLITE_ENABLE_SETLK_TIMEOUT builds. */ | ||||
| 59915 | sqlite3WalEndWriteTransaction(pPager->pWal); | ||||
| 59916 | } | ||||
| 59917 | sqlite3WalEndReadTransaction(pPager->pWal); | ||||
| 59918 | pPager->eState = PAGER_OPEN0; | ||||
| 59919 | }else if( !pPager->exclusiveMode ){ | ||||
| 59920 | int rc; /* Error code returned by pagerUnlockDb() */ | ||||
| 59921 | int iDc = isOpen(pPager->fd)((pPager->fd)->pMethods!=0)?sqlite3OsDeviceCharacteristics(pPager->fd):0; | ||||
| 59922 | |||||
| 59923 | /* If the operating system support deletion of open files, then | ||||
| 59924 | ** close the journal file when dropping the database lock. Otherwise | ||||
| 59925 | ** another connection with journal_mode=delete might delete the file | ||||
| 59926 | ** out from under us. | ||||
| 59927 | */ | ||||
| 59928 | assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 )((void) (0)); | ||||
| 59929 | assert( (PAGER_JOURNALMODE_OFF & 5)!=1 )((void) (0)); | ||||
| 59930 | assert( (PAGER_JOURNALMODE_WAL & 5)!=1 )((void) (0)); | ||||
| 59931 | assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 )((void) (0)); | ||||
| 59932 | assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 )((void) (0)); | ||||
| 59933 | assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 )((void) (0)); | ||||
| 59934 | if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN0x00000800) | ||||
| 59935 | || 1!=(pPager->journalMode & 5) | ||||
| 59936 | ){ | ||||
| 59937 | sqlite3OsClose(pPager->jfd); | ||||
| 59938 | } | ||||
| 59939 | |||||
| 59940 | /* If the pager is in the ERROR state and the call to unlock the database | ||||
| 59941 | ** file fails, set the current lock to UNKNOWN_LOCK. See the comment | ||||
| 59942 | ** above the #define for UNKNOWN_LOCK for an explanation of why this | ||||
| 59943 | ** is necessary. | ||||
| 59944 | */ | ||||
| 59945 | rc = pagerUnlockDb(pPager, NO_LOCK0); | ||||
| 59946 | if( rc!=SQLITE_OK0 && pPager->eState==PAGER_ERROR6 ){ | ||||
| 59947 | pPager->eLock = UNKNOWN_LOCK(4 +1); | ||||
| 59948 | } | ||||
| 59949 | |||||
| 59950 | /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here | ||||
| 59951 | ** without clearing the error code. This is intentional - the error | ||||
| 59952 | ** code is cleared and the cache reset in the block below. | ||||
| 59953 | */ | ||||
| 59954 | assert( pPager->errCode || pPager->eState!=PAGER_ERROR )((void) (0)); | ||||
| 59955 | pPager->eState = PAGER_OPEN0; | ||||
| 59956 | } | ||||
| 59957 | |||||
| 59958 | /* If Pager.errCode is set, the contents of the pager cache cannot be | ||||
| 59959 | ** trusted. Now that there are no outstanding references to the pager, | ||||
| 59960 | ** it can safely move back to PAGER_OPEN state. This happens in both | ||||
| 59961 | ** normal and exclusive-locking mode. | ||||
| 59962 | */ | ||||
| 59963 | assert( pPager->errCode==SQLITE_OK || !MEMDB )((void) (0)); | ||||
| 59964 | if( pPager->errCode ){ | ||||
| 59965 | if( pPager->tempFile==0 ){ | ||||
| 59966 | pager_reset(pPager); | ||||
| 59967 | pPager->changeCountDone = 0; | ||||
| 59968 | pPager->eState = PAGER_OPEN0; | ||||
| 59969 | }else{ | ||||
| 59970 | pPager->eState = (isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) ? PAGER_OPEN0 : PAGER_READER1); | ||||
| 59971 | } | ||||
| 59972 | if( USEFETCH(pPager)((pPager)->bUseFetch) ) sqlite3OsUnfetch(pPager->fd, 0, 0); | ||||
| 59973 | pPager->errCode = SQLITE_OK0; | ||||
| 59974 | setGetterMethod(pPager); | ||||
| 59975 | } | ||||
| 59976 | |||||
| 59977 | pPager->journalOff = 0; | ||||
| 59978 | pPager->journalHdr = 0; | ||||
| 59979 | pPager->setSuper = 0; | ||||
| 59980 | } | ||||
| 59981 | |||||
| 59982 | /* | ||||
| 59983 | ** This function is called whenever an IOERR or FULL error that requires | ||||
| 59984 | ** the pager to transition into the ERROR state may have occurred. | ||||
| 59985 | ** The first argument is a pointer to the pager structure, the second | ||||
| 59986 | ** the error-code about to be returned by a pager API function. The | ||||
| 59987 | ** value returned is a copy of the second argument to this function. | ||||
| 59988 | ** | ||||
| 59989 | ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the | ||||
| 59990 | ** IOERR sub-codes, the pager enters the ERROR state and the error code | ||||
| 59991 | ** is stored in Pager.errCode. While the pager remains in the ERROR state, | ||||
| 59992 | ** all major API calls on the Pager will immediately return Pager.errCode. | ||||
| 59993 | ** | ||||
| 59994 | ** The ERROR state indicates that the contents of the pager-cache | ||||
| 59995 | ** cannot be trusted. This state can be cleared by completely discarding | ||||
| 59996 | ** the contents of the pager-cache. If a transaction was active when | ||||
| 59997 | ** the persistent error occurred, then the rollback journal may need | ||||
| 59998 | ** to be replayed to restore the contents of the database file (as if | ||||
| 59999 | ** it were a hot-journal). | ||||
| 60000 | */ | ||||
| 60001 | static int pager_error(Pager *pPager, int rc){ | ||||
| 60002 | int rc2 = rc & 0xff; | ||||
| 60003 | assert( rc==SQLITE_OK || !MEMDB )((void) (0)); | ||||
| 60004 | assert(((void) (0)) | ||||
| 60005 | pPager->errCode==SQLITE_FULL ||((void) (0)) | ||||
| 60006 | pPager->errCode==SQLITE_OK ||((void) (0)) | ||||
| 60007 | (pPager->errCode & 0xff)==SQLITE_IOERR((void) (0)) | ||||
| 60008 | )((void) (0)); | ||||
| 60009 | if( rc2==SQLITE_FULL13 || rc2==SQLITE_IOERR10 ){ | ||||
| 60010 | pPager->errCode = rc; | ||||
| 60011 | pPager->eState = PAGER_ERROR6; | ||||
| 60012 | setGetterMethod(pPager); | ||||
| 60013 | } | ||||
| 60014 | return rc; | ||||
| 60015 | } | ||||
| 60016 | |||||
| 60017 | static int pager_truncate(Pager *pPager, Pgno nPage); | ||||
| 60018 | |||||
| 60019 | /* | ||||
| 60020 | ** The write transaction open on pPager is being committed (bCommit==1) | ||||
| 60021 | ** or rolled back (bCommit==0). | ||||
| 60022 | ** | ||||
| 60023 | ** Return TRUE if and only if all dirty pages should be flushed to disk. | ||||
| 60024 | ** | ||||
| 60025 | ** Rules: | ||||
| 60026 | ** | ||||
| 60027 | ** * For non-TEMP databases, always sync to disk. This is necessary | ||||
| 60028 | ** for transactions to be durable. | ||||
| 60029 | ** | ||||
| 60030 | ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing | ||||
| 60031 | ** file has been created already (via a spill on pagerStress()) and | ||||
| 60032 | ** when the number of dirty pages in memory exceeds 25% of the total | ||||
| 60033 | ** cache size. | ||||
| 60034 | */ | ||||
| 60035 | static int pagerFlushOnCommit(Pager *pPager, int bCommit){ | ||||
| 60036 | if( pPager->tempFile==0 ) return 1; | ||||
| 60037 | if( !bCommit ) return 0; | ||||
| 60038 | if( !isOpen(pPager->fd)((pPager->fd)->pMethods!=0) ) return 0; | ||||
| 60039 | return (sqlite3PCachePercentDirty(pPager->pPCache)>=25); | ||||
| 60040 | } | ||||
| 60041 | |||||
| 60042 | /* | ||||
| 60043 | ** This routine ends a transaction. A transaction is usually ended by | ||||
| 60044 | ** either a COMMIT or a ROLLBACK operation. This routine may be called | ||||
| 60045 | ** after rollback of a hot-journal, or if an error occurs while opening | ||||
| 60046 | ** the journal file or writing the very first journal-header of a | ||||
| 60047 | ** database transaction. | ||||
| 60048 | ** | ||||
| 60049 | ** This routine is never called in PAGER_ERROR state. If it is called | ||||
| 60050 | ** in PAGER_NONE or PAGER_SHARED state and the lock held is less | ||||
| 60051 | ** exclusive than a RESERVED lock, it is a no-op. | ||||
| 60052 | ** | ||||
| 60053 | ** Otherwise, any active savepoints are released. | ||||
| 60054 | ** | ||||
| 60055 | ** If the journal file is open, then it is "finalized". Once a journal | ||||
| 60056 | ** file has been finalized it is not possible to use it to roll back a | ||||
| 60057 | ** transaction. Nor will it be considered to be a hot-journal by this | ||||
| 60058 | ** or any other database connection. Exactly how a journal is finalized | ||||
| 60059 | ** depends on whether or not the pager is running in exclusive mode and | ||||
| 60060 | ** the current journal-mode (Pager.journalMode value), as follows: | ||||
| 60061 | ** | ||||
| 60062 | ** journalMode==MEMORY | ||||
| 60063 | ** Journal file descriptor is simply closed. This destroys an | ||||
| 60064 | ** in-memory journal. | ||||
| 60065 | ** | ||||
| 60066 | ** journalMode==TRUNCATE | ||||
| 60067 | ** Journal file is truncated to zero bytes in size. | ||||
| 60068 | ** | ||||
| 60069 | ** journalMode==PERSIST | ||||
| 60070 | ** The first 28 bytes of the journal file are zeroed. This invalidates | ||||
| 60071 | ** the first journal header in the file, and hence the entire journal | ||||
| 60072 | ** file. An invalid journal file cannot be rolled back. | ||||
| 60073 | ** | ||||
| 60074 | ** journalMode==DELETE | ||||
| 60075 | ** The journal file is closed and deleted using sqlite3OsDelete(). | ||||
| 60076 | ** | ||||
| 60077 | ** If the pager is running in exclusive mode, this method of finalizing | ||||
| 60078 | ** the journal file is never used. Instead, if the journalMode is | ||||
| 60079 | ** DELETE and the pager is in exclusive mode, the method described under | ||||
| 60080 | ** journalMode==PERSIST is used instead. | ||||
| 60081 | ** | ||||
| 60082 | ** After the journal is finalized, the pager moves to PAGER_READER state. | ||||
| 60083 | ** If running in non-exclusive rollback mode, the lock on the file is | ||||
| 60084 | ** downgraded to a SHARED_LOCK. | ||||
| 60085 | ** | ||||
| 60086 | ** SQLITE_OK is returned if no error occurs. If an error occurs during | ||||
| 60087 | ** any of the IO operations to finalize the journal file or unlock the | ||||
| 60088 | ** database then the IO error code is returned to the user. If the | ||||
| 60089 | ** operation to finalize the journal file fails, then the code still | ||||
| 60090 | ** tries to unlock the database file if not in exclusive mode. If the | ||||
| 60091 | ** unlock operation fails as well, then the first error code related | ||||
| 60092 | ** to the first error encountered (the journal finalization one) is | ||||
| 60093 | ** returned. | ||||
| 60094 | */ | ||||
| 60095 | static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){ | ||||
| 60096 | int rc = SQLITE_OK0; /* Error code from journal finalization operation */ | ||||
| 60097 | int rc2 = SQLITE_OK0; /* Error code from db file unlock operation */ | ||||
| 60098 | |||||
| 60099 | /* Do nothing if the pager does not have an open write transaction | ||||
| 60100 | ** or at least a RESERVED lock. This function may be called when there | ||||
| 60101 | ** is no write-transaction active but a RESERVED or greater lock is | ||||
| 60102 | ** held under two circumstances: | ||||
| 60103 | ** | ||||
| 60104 | ** 1. After a successful hot-journal rollback, it is called with | ||||
| 60105 | ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK. | ||||
| 60106 | ** | ||||
| 60107 | ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE | ||||
| 60108 | ** lock switches back to locking_mode=normal and then executes a | ||||
| 60109 | ** read-transaction, this function is called with eState==PAGER_READER | ||||
| 60110 | ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed. | ||||
| 60111 | */ | ||||
| 60112 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 60113 | assert( pPager->eState!=PAGER_ERROR )((void) (0)); | ||||
| 60114 | if( pPager->eState<PAGER_WRITER_LOCKED2 && pPager->eLock<RESERVED_LOCK2 ){ | ||||
| 60115 | return SQLITE_OK0; | ||||
| 60116 | } | ||||
| 60117 | |||||
| 60118 | releaseAllSavepoints(pPager); | ||||
| 60119 | assert( isOpen(pPager->jfd) || pPager->pInJournal==0((void) (0)) | ||||
| 60120 | || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)((void) (0)) | ||||
| 60121 | )((void) (0)); | ||||
| 60122 | if( isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) ){ | ||||
| 60123 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 60124 | |||||
| 60125 | /* Finalize the journal file. */ | ||||
| 60126 | if( sqlite3JournalIsInMemory(pPager->jfd) ){ | ||||
| 60127 | /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */ | ||||
| 60128 | sqlite3OsClose(pPager->jfd); | ||||
| 60129 | }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE3 ){ | ||||
| 60130 | if( pPager->journalOff==0 ){ | ||||
| 60131 | rc = SQLITE_OK0; | ||||
| 60132 | }else{ | ||||
| 60133 | rc = sqlite3OsTruncate(pPager->jfd, 0); | ||||
| 60134 | if( rc==SQLITE_OK0 && pPager->fullSync ){ | ||||
| 60135 | /* Make sure the new file size is written into the inode right away. | ||||
| 60136 | ** Otherwise the journal might resurrect following a power loss and | ||||
| 60137 | ** cause the last transaction to roll back. See | ||||
| 60138 | ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773 | ||||
| 60139 | */ | ||||
| 60140 | rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); | ||||
| 60141 | } | ||||
| 60142 | } | ||||
| 60143 | pPager->journalOff = 0; | ||||
| 60144 | }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST1 | ||||
| 60145 | || (pPager->exclusiveMode && pPager->journalMode<PAGER_JOURNALMODE_WAL5) | ||||
| 60146 | ){ | ||||
| 60147 | rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile); | ||||
| 60148 | pPager->journalOff = 0; | ||||
| 60149 | }else{ | ||||
| 60150 | /* This branch may be executed with Pager.journalMode==MEMORY if | ||||
| 60151 | ** a hot-journal was just rolled back. In this case the journal | ||||
| 60152 | ** file should be closed and deleted. If this connection writes to | ||||
| 60153 | ** the database file, it will do so using an in-memory journal. | ||||
| 60154 | */ | ||||
| 60155 | int bDelete = !pPager->tempFile; | ||||
| 60156 | assert( sqlite3JournalIsInMemory(pPager->jfd)==0 )((void) (0)); | ||||
| 60157 | assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE((void) (0)) | ||||
| 60158 | || pPager->journalMode==PAGER_JOURNALMODE_MEMORY((void) (0)) | ||||
| 60159 | || pPager->journalMode==PAGER_JOURNALMODE_WAL((void) (0)) | ||||
| 60160 | )((void) (0)); | ||||
| 60161 | sqlite3OsClose(pPager->jfd); | ||||
| 60162 | if( bDelete ){ | ||||
| 60163 | rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync); | ||||
| 60164 | } | ||||
| 60165 | } | ||||
| 60166 | } | ||||
| 60167 | |||||
| 60168 | #ifdef SQLITE_CHECK_PAGES | ||||
| 60169 | sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); | ||||
| 60170 | if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){ | ||||
| 60171 | PgHdr *p = sqlite3PagerLookup(pPager, 1); | ||||
| 60172 | if( p ){ | ||||
| 60173 | p->pageHash = 0; | ||||
| 60174 | sqlite3PagerUnrefNotNull(p); | ||||
| 60175 | } | ||||
| 60176 | } | ||||
| 60177 | #endif | ||||
| 60178 | |||||
| 60179 | sqlite3BitvecDestroy(pPager->pInJournal); | ||||
| 60180 | pPager->pInJournal = 0; | ||||
| 60181 | pPager->nRec = 0; | ||||
| 60182 | if( rc==SQLITE_OK0 ){ | ||||
| 60183 | if( MEMDBpPager->memDb || pagerFlushOnCommit(pPager, bCommit) ){ | ||||
| 60184 | sqlite3PcacheCleanAll(pPager->pPCache); | ||||
| 60185 | }else{ | ||||
| 60186 | sqlite3PcacheClearWritable(pPager->pPCache); | ||||
| 60187 | } | ||||
| 60188 | sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); | ||||
| 60189 | } | ||||
| 60190 | |||||
| 60191 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 60192 | /* Drop the WAL write-lock, if any. Also, if the connection was in | ||||
| 60193 | ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE | ||||
| 60194 | ** lock held on the database file. | ||||
| 60195 | */ | ||||
| 60196 | rc2 = sqlite3WalEndWriteTransaction(pPager->pWal); | ||||
| 60197 | assert( rc2==SQLITE_OK )((void) (0)); | ||||
| 60198 | }else if( rc==SQLITE_OK0 && bCommit && pPager->dbFileSize>pPager->dbSize ){ | ||||
| 60199 | /* This branch is taken when committing a transaction in rollback-journal | ||||
| 60200 | ** mode if the database file on disk is larger than the database image. | ||||
| 60201 | ** At this point the journal has been finalized and the transaction | ||||
| 60202 | ** successfully committed, but the EXCLUSIVE lock is still held on the | ||||
| 60203 | ** file. So it is safe to truncate the database file to its minimum | ||||
| 60204 | ** required size. */ | ||||
| 60205 | assert( pPager->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 60206 | rc = pager_truncate(pPager, pPager->dbSize); | ||||
| 60207 | } | ||||
| 60208 | |||||
| 60209 | if( rc==SQLITE_OK0 && bCommit ){ | ||||
| 60210 | rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO22, 0); | ||||
| 60211 | if( rc==SQLITE_NOTFOUND12 ) rc = SQLITE_OK0; | ||||
| 60212 | } | ||||
| 60213 | |||||
| 60214 | if( !pPager->exclusiveMode | ||||
| 60215 | && (!pagerUseWal(pPager)((pPager)->pWal!=0) || sqlite3WalExclusiveMode(pPager->pWal, 0)) | ||||
| 60216 | ){ | ||||
| 60217 | rc2 = pagerUnlockDb(pPager, SHARED_LOCK1); | ||||
| 60218 | } | ||||
| 60219 | pPager->eState = PAGER_READER1; | ||||
| 60220 | pPager->setSuper = 0; | ||||
| 60221 | |||||
| 60222 | return (rc==SQLITE_OK0?rc2:rc); | ||||
| 60223 | } | ||||
| 60224 | |||||
| 60225 | /* Forward reference */ | ||||
| 60226 | static int pager_playback(Pager *pPager, int isHot); | ||||
| 60227 | |||||
| 60228 | /* | ||||
| 60229 | ** Execute a rollback if a transaction is active and unlock the | ||||
| 60230 | ** database file. | ||||
| 60231 | ** | ||||
| 60232 | ** If the pager has already entered the ERROR state, do not attempt | ||||
| 60233 | ** the rollback at this time. Instead, pager_unlock() is called. The | ||||
| 60234 | ** call to pager_unlock() will discard all in-memory pages, unlock | ||||
| 60235 | ** the database file and move the pager back to OPEN state. If this | ||||
| 60236 | ** means that there is a hot-journal left in the file-system, the next | ||||
| 60237 | ** connection to obtain a shared lock on the pager (which may be this one) | ||||
| 60238 | ** will roll it back. | ||||
| 60239 | ** | ||||
| 60240 | ** If the pager has not already entered the ERROR state, but an IO or | ||||
| 60241 | ** malloc error occurs during a rollback, then this will itself cause | ||||
| 60242 | ** the pager to enter the ERROR state. Which will be cleared by the | ||||
| 60243 | ** call to pager_unlock(), as described above. | ||||
| 60244 | */ | ||||
| 60245 | static void pagerUnlockAndRollback(Pager *pPager){ | ||||
| 60246 | if( pPager->eState!=PAGER_ERROR6 && pPager->eState!=PAGER_OPEN0 ){ | ||||
| 60247 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 60248 | if( pPager->eState>=PAGER_WRITER_LOCKED2 ){ | ||||
| 60249 | sqlite3BeginBenignMalloc(); | ||||
| 60250 | sqlite3PagerRollback(pPager); | ||||
| 60251 | sqlite3EndBenignMalloc(); | ||||
| 60252 | }else if( !pPager->exclusiveMode ){ | ||||
| 60253 | assert( pPager->eState==PAGER_READER )((void) (0)); | ||||
| 60254 | pager_end_transaction(pPager, 0, 0); | ||||
| 60255 | } | ||||
| 60256 | }else if( pPager->eState==PAGER_ERROR6 | ||||
| 60257 | && pPager->journalMode==PAGER_JOURNALMODE_MEMORY4 | ||||
| 60258 | && isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) | ||||
| 60259 | ){ | ||||
| 60260 | /* Special case for a ROLLBACK due to I/O error with an in-memory | ||||
| 60261 | ** journal: We have to rollback immediately, before the journal is | ||||
| 60262 | ** closed, because once it is closed, all content is forgotten. */ | ||||
| 60263 | int errCode = pPager->errCode; | ||||
| 60264 | u8 eLock = pPager->eLock; | ||||
| 60265 | pPager->eState = PAGER_OPEN0; | ||||
| 60266 | pPager->errCode = SQLITE_OK0; | ||||
| 60267 | pPager->eLock = EXCLUSIVE_LOCK4; | ||||
| 60268 | pager_playback(pPager, 1); | ||||
| 60269 | pPager->errCode = errCode; | ||||
| 60270 | pPager->eLock = eLock; | ||||
| 60271 | } | ||||
| 60272 | pager_unlock(pPager); | ||||
| 60273 | } | ||||
| 60274 | |||||
| 60275 | /* | ||||
| 60276 | ** Parameter aData must point to a buffer of pPager->pageSize bytes | ||||
| 60277 | ** of data. Compute and return a checksum based on the contents of the | ||||
| 60278 | ** page of data and the current value of pPager->cksumInit. | ||||
| 60279 | ** | ||||
| 60280 | ** This is not a real checksum. It is really just the sum of the | ||||
| 60281 | ** random initial value (pPager->cksumInit) and every 200th byte | ||||
| 60282 | ** of the page data, starting with byte offset (pPager->pageSize%200). | ||||
| 60283 | ** Each byte is interpreted as an 8-bit unsigned integer. | ||||
| 60284 | ** | ||||
| 60285 | ** Changing the formula used to compute this checksum results in an | ||||
| 60286 | ** incompatible journal file format. | ||||
| 60287 | ** | ||||
| 60288 | ** If journal corruption occurs due to a power failure, the most likely | ||||
| 60289 | ** scenario is that one end or the other of the record will be changed. | ||||
| 60290 | ** It is much less likely that the two ends of the journal record will be | ||||
| 60291 | ** correct and the middle be corrupt. Thus, this "checksum" scheme, | ||||
| 60292 | ** though fast and simple, catches the mostly likely kind of corruption. | ||||
| 60293 | */ | ||||
| 60294 | static u32 pager_cksum(Pager *pPager, const u8 *aData){ | ||||
| 60295 | u32 cksum = pPager->cksumInit; /* Checksum value to return */ | ||||
| 60296 | int i = pPager->pageSize-200; /* Loop counter */ | ||||
| 60297 | while( i>0 ){ | ||||
| 60298 | cksum += aData[i]; | ||||
| 60299 | i -= 200; | ||||
| 60300 | } | ||||
| 60301 | return cksum; | ||||
| 60302 | } | ||||
| 60303 | |||||
| 60304 | /* | ||||
| 60305 | ** Read a single page from either the journal file (if isMainJrnl==1) or | ||||
| 60306 | ** from the sub-journal (if isMainJrnl==0) and playback that page. | ||||
| 60307 | ** The page begins at offset *pOffset into the file. The *pOffset | ||||
| 60308 | ** value is increased to the start of the next page in the journal. | ||||
| 60309 | ** | ||||
| 60310 | ** The main rollback journal uses checksums - the statement journal does | ||||
| 60311 | ** not. | ||||
| 60312 | ** | ||||
| 60313 | ** If the page number of the page record read from the (sub-)journal file | ||||
| 60314 | ** is greater than the current value of Pager.dbSize, then playback is | ||||
| 60315 | ** skipped and SQLITE_OK is returned. | ||||
| 60316 | ** | ||||
| 60317 | ** If pDone is not NULL, then it is a record of pages that have already | ||||
| 60318 | ** been played back. If the page at *pOffset has already been played back | ||||
| 60319 | ** (if the corresponding pDone bit is set) then skip the playback. | ||||
| 60320 | ** Make sure the pDone bit corresponding to the *pOffset page is set | ||||
| 60321 | ** prior to returning. | ||||
| 60322 | ** | ||||
| 60323 | ** If the page record is successfully read from the (sub-)journal file | ||||
| 60324 | ** and played back, then SQLITE_OK is returned. If an IO error occurs | ||||
| 60325 | ** while reading the record from the (sub-)journal file or while writing | ||||
| 60326 | ** to the database file, then the IO error code is returned. If data | ||||
| 60327 | ** is successfully read from the (sub-)journal file but appears to be | ||||
| 60328 | ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in | ||||
| 60329 | ** two circumstances: | ||||
| 60330 | ** | ||||
| 60331 | ** * If the record page-number is illegal (0 or PAGER_SJ_PGNO), or | ||||
| 60332 | ** * If the record is being rolled back from the main journal file | ||||
| 60333 | ** and the checksum field does not match the record content. | ||||
| 60334 | ** | ||||
| 60335 | ** Neither of these two scenarios are possible during a savepoint rollback. | ||||
| 60336 | ** | ||||
| 60337 | ** If this is a savepoint rollback, then memory may have to be dynamically | ||||
| 60338 | ** allocated by this function. If this is the case and an allocation fails, | ||||
| 60339 | ** SQLITE_NOMEM is returned. | ||||
| 60340 | */ | ||||
| 60341 | static int pager_playback_one_page( | ||||
| 60342 | Pager *pPager, /* The pager being played back */ | ||||
| 60343 | i64 *pOffset, /* Offset of record to playback */ | ||||
| 60344 | Bitvec *pDone, /* Bitvec of pages already played back */ | ||||
| 60345 | int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */ | ||||
| 60346 | int isSavepnt /* True for a savepoint rollback */ | ||||
| 60347 | ){ | ||||
| 60348 | int rc; | ||||
| 60349 | PgHdr *pPg; /* An existing page in the cache */ | ||||
| 60350 | Pgno pgno; /* The page number of a page in journal */ | ||||
| 60351 | u32 cksum; /* Checksum used for sanity checking */ | ||||
| 60352 | char *aData; /* Temporary storage for the page */ | ||||
| 60353 | sqlite3_file *jfd; /* The file descriptor for the journal file */ | ||||
| 60354 | int isSynced; /* True if journal page is synced */ | ||||
| 60355 | |||||
| 60356 | assert( (isMainJrnl&~1)==0 )((void) (0)); /* isMainJrnl is 0 or 1 */ | ||||
| 60357 | assert( (isSavepnt&~1)==0 )((void) (0)); /* isSavepnt is 0 or 1 */ | ||||
| 60358 | assert( isMainJrnl || pDone )((void) (0)); /* pDone always used on sub-journals */ | ||||
| 60359 | assert( isSavepnt || pDone==0 )((void) (0)); /* pDone never used on non-savepoint */ | ||||
| 60360 | |||||
| 60361 | aData = pPager->pTmpSpace; | ||||
| 60362 | assert( aData )((void) (0)); /* Temp storage must have already been allocated */ | ||||
| 60363 | assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) )((void) (0)); | ||||
| 60364 | |||||
| 60365 | /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction | ||||
| 60366 | ** or savepoint rollback done at the request of the caller) or this is | ||||
| 60367 | ** a hot-journal rollback. If it is a hot-journal rollback, the pager | ||||
| 60368 | ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback | ||||
| 60369 | ** only reads from the main journal, not the sub-journal. | ||||
| 60370 | */ | ||||
| 60371 | assert( pPager->eState>=PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 60372 | || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)((void) (0)) | ||||
| 60373 | )((void) (0)); | ||||
| 60374 | assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl )((void) (0)); | ||||
| 60375 | |||||
| 60376 | /* Read the page number and page data from the journal or sub-journal | ||||
| 60377 | ** file. Return an error code to the caller if an IO error occurs. | ||||
| 60378 | */ | ||||
| 60379 | jfd = isMainJrnl ? pPager->jfd : pPager->sjfd; | ||||
| 60380 | rc = read32bits(jfd, *pOffset, &pgno); | ||||
| 60381 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 60382 | rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); | ||||
| 60383 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 60384 | *pOffset += pPager->pageSize + 4 + isMainJrnl*4; | ||||
| 60385 | |||||
| 60386 | /* Sanity checking on the page. This is more important that I originally | ||||
| 60387 | ** thought. If a power failure occurs while the journal is being written, | ||||
| 60388 | ** it could cause invalid data to be written into the journal. We need to | ||||
| 60389 | ** detect this invalid data (with high probability) and ignore it. | ||||
| 60390 | */ | ||||
| 60391 | if( pgno==0 || pgno==PAGER_SJ_PGNO(pPager)((pPager)->lckPgno) ){ | ||||
| 60392 | assert( !isSavepnt )((void) (0)); | ||||
| 60393 | return SQLITE_DONE101; | ||||
| 60394 | } | ||||
| 60395 | if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){ | ||||
| 60396 | return SQLITE_OK0; | ||||
| 60397 | } | ||||
| 60398 | if( isMainJrnl ){ | ||||
| 60399 | rc = read32bits(jfd, (*pOffset)-4, &cksum); | ||||
| 60400 | if( rc ) return rc; | ||||
| 60401 | if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){ | ||||
| 60402 | return SQLITE_DONE101; | ||||
| 60403 | } | ||||
| 60404 | } | ||||
| 60405 | |||||
| 60406 | /* If this page has already been played back before during the current | ||||
| 60407 | ** rollback, then don't bother to play it back again. | ||||
| 60408 | */ | ||||
| 60409 | if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK0 ){ | ||||
| 60410 | return rc; | ||||
| 60411 | } | ||||
| 60412 | |||||
| 60413 | /* When playing back page 1, restore the nReserve setting | ||||
| 60414 | */ | ||||
| 60415 | if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){ | ||||
| 60416 | pPager->nReserve = ((u8*)aData)[20]; | ||||
| 60417 | } | ||||
| 60418 | |||||
| 60419 | /* If the pager is in CACHEMOD state, then there must be a copy of this | ||||
| 60420 | ** page in the pager cache. In this case just update the pager cache, | ||||
| 60421 | ** not the database file. The page is left marked dirty in this case. | ||||
| 60422 | ** | ||||
| 60423 | ** An exception to the above rule: If the database is in no-sync mode | ||||
| 60424 | ** and a page is moved during an incremental vacuum then the page may | ||||
| 60425 | ** not be in the pager cache. Later: if a malloc() or IO error occurs | ||||
| 60426 | ** during a Movepage() call, then the page may not be in the cache | ||||
| 60427 | ** either. So the condition described in the above paragraph is not | ||||
| 60428 | ** assert()able. | ||||
| 60429 | ** | ||||
| 60430 | ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the | ||||
| 60431 | ** pager cache if it exists and the main file. The page is then marked | ||||
| 60432 | ** not dirty. Since this code is only executed in PAGER_OPEN state for | ||||
| 60433 | ** a hot-journal rollback, it is guaranteed that the page-cache is empty | ||||
| 60434 | ** if the pager is in OPEN state. | ||||
| 60435 | ** | ||||
| 60436 | ** Ticket #1171: The statement journal might contain page content that is | ||||
| 60437 | ** different from the page content at the start of the transaction. | ||||
| 60438 | ** This occurs when a page is changed prior to the start of a statement | ||||
| 60439 | ** then changed again within the statement. When rolling back such a | ||||
| 60440 | ** statement we must not write to the original database unless we know | ||||
| 60441 | ** for certain that original page contents are synced into the main rollback | ||||
| 60442 | ** journal. Otherwise, a power loss might leave modified data in the | ||||
| 60443 | ** database file without an entry in the rollback journal that can | ||||
| 60444 | ** restore the database to its original form. Two conditions must be | ||||
| 60445 | ** met before writing to the database files. (1) the database must be | ||||
| 60446 | ** locked. (2) we know that the original page content is fully synced | ||||
| 60447 | ** in the main journal either because the page is not in cache or else | ||||
| 60448 | ** the page is marked as needSync==0. | ||||
| 60449 | ** | ||||
| 60450 | ** 2008-04-14: When attempting to vacuum a corrupt database file, it | ||||
| 60451 | ** is possible to fail a statement on a database that does not yet exist. | ||||
| 60452 | ** Do not attempt to write if database file has never been opened. | ||||
| 60453 | */ | ||||
| 60454 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 60455 | pPg = 0; | ||||
| 60456 | }else{ | ||||
| 60457 | pPg = sqlite3PagerLookup(pPager, pgno); | ||||
| 60458 | } | ||||
| 60459 | assert( pPg || !MEMDB )((void) (0)); | ||||
| 60460 | assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile )((void) (0)); | ||||
| 60461 | PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n", | ||||
| 60462 | PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData), | ||||
| 60463 | (isMainJrnl?"main-journal":"sub-journal") | ||||
| 60464 | )); | ||||
| 60465 | if( isMainJrnl ){ | ||||
| 60466 | isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr); | ||||
| 60467 | }else{ | ||||
| 60468 | isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC0x008)); | ||||
| 60469 | } | ||||
| 60470 | if( isOpen(pPager->fd)((pPager->fd)->pMethods!=0) | ||||
| 60471 | && (pPager->eState>=PAGER_WRITER_DBMOD4 || pPager->eState==PAGER_OPEN0) | ||||
| 60472 | && isSynced | ||||
| 60473 | ){ | ||||
| 60474 | i64 ofst = (pgno-1)*(i64)pPager->pageSize; | ||||
| 60475 | testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 ); | ||||
| 60476 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 60477 | |||||
| 60478 | /* Write the data read from the journal back into the database file. | ||||
| 60479 | ** This is usually safe even for an encrypted database - as the data | ||||
| 60480 | ** was encrypted before it was written to the journal file. The exception | ||||
| 60481 | ** is if the data was just read from an in-memory sub-journal. In that | ||||
| 60482 | ** case it must be encrypted here before it is copied into the database | ||||
| 60483 | ** file. */ | ||||
| 60484 | rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); | ||||
| 60485 | |||||
| 60486 | if( pgno>pPager->dbFileSize ){ | ||||
| 60487 | pPager->dbFileSize = pgno; | ||||
| 60488 | } | ||||
| 60489 | if( pPager->pBackup ){ | ||||
| 60490 | sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); | ||||
| 60491 | } | ||||
| 60492 | }else if( !isMainJrnl && pPg==0 ){ | ||||
| 60493 | /* If this is a rollback of a savepoint and data was not written to | ||||
| 60494 | ** the database and the page is not in-memory, there is a potential | ||||
| 60495 | ** problem. When the page is next fetched by the b-tree layer, it | ||||
| 60496 | ** will be read from the database file, which may or may not be | ||||
| 60497 | ** current. | ||||
| 60498 | ** | ||||
| 60499 | ** There are a couple of different ways this can happen. All are quite | ||||
| 60500 | ** obscure. When running in synchronous mode, this can only happen | ||||
| 60501 | ** if the page is on the free-list at the start of the transaction, then | ||||
| 60502 | ** populated, then moved using sqlite3PagerMovepage(). | ||||
| 60503 | ** | ||||
| 60504 | ** The solution is to add an in-memory page to the cache containing | ||||
| 60505 | ** the data just read from the sub-journal. Mark the page as dirty | ||||
| 60506 | ** and if the pager requires a journal-sync, then mark the page as | ||||
| 60507 | ** requiring a journal-sync before it is written. | ||||
| 60508 | */ | ||||
| 60509 | assert( isSavepnt )((void) (0)); | ||||
| 60510 | assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 )((void) (0)); | ||||
| 60511 | pPager->doNotSpill |= SPILLFLAG_ROLLBACK0x02; | ||||
| 60512 | rc = sqlite3PagerGet(pPager, pgno, &pPg, 1); | ||||
| 60513 | assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 )((void) (0)); | ||||
| 60514 | pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK0x02; | ||||
| 60515 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 60516 | sqlite3PcacheMakeDirty(pPg); | ||||
| 60517 | } | ||||
| 60518 | if( pPg ){ | ||||
| 60519 | /* No page should ever be explicitly rolled back that is in use, except | ||||
| 60520 | ** for page 1 which is held in use in order to keep the lock on the | ||||
| 60521 | ** database active. However such a page may be rolled back as a result | ||||
| 60522 | ** of an internal error resulting in an automatic call to | ||||
| 60523 | ** sqlite3PagerRollback(). | ||||
| 60524 | */ | ||||
| 60525 | void *pData; | ||||
| 60526 | pData = pPg->pData; | ||||
| 60527 | memcpy(pData, (u8*)aData, pPager->pageSize); | ||||
| 60528 | pPager->xReiniter(pPg); | ||||
| 60529 | /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But | ||||
| 60530 | ** that call was dangerous and had no detectable benefit since the cache | ||||
| 60531 | ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so | ||||
| 60532 | ** has been removed. */ | ||||
| 60533 | pager_set_pagehash(pPg); | ||||
| 60534 | |||||
| 60535 | /* If this was page 1, then restore the value of Pager.dbFileVers. | ||||
| 60536 | ** Do this before any decoding. */ | ||||
| 60537 | if( pgno==1 ){ | ||||
| 60538 | memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); | ||||
| 60539 | } | ||||
| 60540 | sqlite3PcacheRelease(pPg); | ||||
| 60541 | } | ||||
| 60542 | return rc; | ||||
| 60543 | } | ||||
| 60544 | |||||
| 60545 | /* | ||||
| 60546 | ** Parameter zSuper is the name of a super-journal file. A single journal | ||||
| 60547 | ** file that referred to the super-journal file has just been rolled back. | ||||
| 60548 | ** This routine checks if it is possible to delete the super-journal file, | ||||
| 60549 | ** and does so if it is. | ||||
| 60550 | ** | ||||
| 60551 | ** Argument zSuper may point to Pager.pTmpSpace. So that buffer is not | ||||
| 60552 | ** available for use within this function. | ||||
| 60553 | ** | ||||
| 60554 | ** When a super-journal file is created, it is populated with the names | ||||
| 60555 | ** of all of its child journals, one after another, formatted as utf-8 | ||||
| 60556 | ** encoded text. The end of each child journal file is marked with a | ||||
| 60557 | ** nul-terminator byte (0x00). i.e. the entire contents of a super-journal | ||||
| 60558 | ** file for a transaction involving two databases might be: | ||||
| 60559 | ** | ||||
| 60560 | ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" | ||||
| 60561 | ** | ||||
| 60562 | ** A super-journal file may only be deleted once all of its child | ||||
| 60563 | ** journals have been rolled back. | ||||
| 60564 | ** | ||||
| 60565 | ** This function reads the contents of the super-journal file into | ||||
| 60566 | ** memory and loops through each of the child journal names. For | ||||
| 60567 | ** each child journal, it checks if: | ||||
| 60568 | ** | ||||
| 60569 | ** * if the child journal exists, and if so | ||||
| 60570 | ** * if the child journal contains a reference to super-journal | ||||
| 60571 | ** file zSuper | ||||
| 60572 | ** | ||||
| 60573 | ** If a child journal can be found that matches both of the criteria | ||||
| 60574 | ** above, this function returns without doing anything. Otherwise, if | ||||
| 60575 | ** no such child journal can be found, file zSuper is deleted from | ||||
| 60576 | ** the file-system using sqlite3OsDelete(). | ||||
| 60577 | ** | ||||
| 60578 | ** If an IO error within this function, an error code is returned. This | ||||
| 60579 | ** function allocates memory by calling sqlite3Malloc(). If an allocation | ||||
| 60580 | ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors | ||||
| 60581 | ** occur, SQLITE_OK is returned. | ||||
| 60582 | ** | ||||
| 60583 | ** TODO: This function allocates a single block of memory to load | ||||
| 60584 | ** the entire contents of the super-journal file. This could be | ||||
| 60585 | ** a couple of kilobytes or so - potentially larger than the page | ||||
| 60586 | ** size. | ||||
| 60587 | */ | ||||
| 60588 | static int pager_delsuper(Pager *pPager, const char *zSuper){ | ||||
| 60589 | sqlite3_vfs *pVfs = pPager->pVfs; | ||||
| 60590 | int rc; /* Return code */ | ||||
| 60591 | sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */ | ||||
| 60592 | sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ | ||||
| 60593 | char *zSuperJournal = 0; /* Contents of super-journal file */ | ||||
| 60594 | i64 nSuperJournal; /* Size of super-journal file */ | ||||
| 60595 | char *zJournal; /* Pointer to one journal within MJ file */ | ||||
| 60596 | char *zSuperPtr; /* Space to hold super-journal filename */ | ||||
| 60597 | char *zFree = 0; /* Free this buffer */ | ||||
| 60598 | i64 nSuperPtr; /* Amount of space allocated to zSuperPtr[] */ | ||||
| 60599 | |||||
| 60600 | /* Allocate space for both the pJournal and pSuper file descriptors. | ||||
| 60601 | ** If successful, open the super-journal file for reading. | ||||
| 60602 | */ | ||||
| 60603 | pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile); | ||||
| 60604 | if( !pSuper ){ | ||||
| 60605 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 60606 | pJournal = 0; | ||||
| 60607 | }else{ | ||||
| 60608 | const int flags = (SQLITE_OPEN_READONLY0x00000001|SQLITE_OPEN_SUPER_JOURNAL0x00004000); | ||||
| 60609 | rc = sqlite3OsOpen(pVfs, zSuper, pSuper, flags, 0); | ||||
| 60610 | pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile); | ||||
| 60611 | } | ||||
| 60612 | if( rc!=SQLITE_OK0 ) goto delsuper_out; | ||||
| 60613 | |||||
| 60614 | /* Load the entire super-journal file into space obtained from | ||||
| 60615 | ** sqlite3_malloc() and pointed to by zSuperJournal. Also obtain | ||||
| 60616 | ** sufficient space (in zSuperPtr) to hold the names of super-journal | ||||
| 60617 | ** files extracted from regular rollback-journals. | ||||
| 60618 | */ | ||||
| 60619 | rc = sqlite3OsFileSize(pSuper, &nSuperJournal); | ||||
| 60620 | if( rc!=SQLITE_OK0 ) goto delsuper_out; | ||||
| 60621 | nSuperPtr = 1 + (i64)pVfs->mxPathname; | ||||
| 60622 | assert( nSuperJournal>=0 && nSuperPtr>0 )((void) (0)); | ||||
| 60623 | zFree = sqlite3Malloc(4 + nSuperJournal + nSuperPtr + 2); | ||||
| 60624 | if( !zFree ){ | ||||
| 60625 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 60626 | goto delsuper_out; | ||||
| 60627 | }else{ | ||||
| 60628 | assert( nSuperJournal<=0x7fffffff )((void) (0)); | ||||
| 60629 | } | ||||
| 60630 | zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0; | ||||
| 60631 | zSuperJournal = &zFree[4]; | ||||
| 60632 | zSuperPtr = &zSuperJournal[nSuperJournal+2]; | ||||
| 60633 | rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0); | ||||
| 60634 | if( rc!=SQLITE_OK0 ) goto delsuper_out; | ||||
| 60635 | zSuperJournal[nSuperJournal] = 0; | ||||
| 60636 | zSuperJournal[nSuperJournal+1] = 0; | ||||
| 60637 | |||||
| 60638 | zJournal = zSuperJournal; | ||||
| 60639 | while( (zJournal-zSuperJournal)<nSuperJournal ){ | ||||
| 60640 | int exists; | ||||
| 60641 | rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS0, &exists); | ||||
| 60642 | if( rc!=SQLITE_OK0 ){ | ||||
| 60643 | goto delsuper_out; | ||||
| 60644 | } | ||||
| 60645 | if( exists ){ | ||||
| 60646 | /* One of the journals pointed to by the super-journal exists. | ||||
| 60647 | ** Open it and check if it points at the super-journal. If | ||||
| 60648 | ** so, return without deleting the super-journal file. | ||||
| 60649 | ** NB: zJournal is really a MAIN_JOURNAL. But call it a | ||||
| 60650 | ** SUPER_JOURNAL here so that the VFS will not send the zJournal | ||||
| 60651 | ** name into sqlite3_database_file_object(). | ||||
| 60652 | */ | ||||
| 60653 | int c; | ||||
| 60654 | int flags = (SQLITE_OPEN_READONLY0x00000001|SQLITE_OPEN_SUPER_JOURNAL0x00004000); | ||||
| 60655 | rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0); | ||||
| 60656 | if( rc!=SQLITE_OK0 ){ | ||||
| 60657 | goto delsuper_out; | ||||
| 60658 | } | ||||
| 60659 | |||||
| 60660 | rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr); | ||||
| 60661 | sqlite3OsClose(pJournal); | ||||
| 60662 | if( rc!=SQLITE_OK0 ){ | ||||
| 60663 | goto delsuper_out; | ||||
| 60664 | } | ||||
| 60665 | |||||
| 60666 | c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0; | ||||
| 60667 | if( c ){ | ||||
| 60668 | /* We have a match. Do not delete the super-journal file. */ | ||||
| 60669 | goto delsuper_out; | ||||
| 60670 | } | ||||
| 60671 | } | ||||
| 60672 | zJournal += (sqlite3Strlen30(zJournal)+1); | ||||
| 60673 | } | ||||
| 60674 | |||||
| 60675 | sqlite3OsClose(pSuper); | ||||
| 60676 | rc = sqlite3OsDelete(pVfs, zSuper, 0); | ||||
| 60677 | |||||
| 60678 | delsuper_out: | ||||
| 60679 | sqlite3_free(zFree); | ||||
| 60680 | if( pSuper ){ | ||||
| 60681 | sqlite3OsClose(pSuper); | ||||
| 60682 | assert( !isOpen(pJournal) )((void) (0)); | ||||
| 60683 | sqlite3_free(pSuper); | ||||
| 60684 | } | ||||
| 60685 | return rc; | ||||
| 60686 | } | ||||
| 60687 | |||||
| 60688 | |||||
| 60689 | /* | ||||
| 60690 | ** This function is used to change the actual size of the database | ||||
| 60691 | ** file in the file-system. This only happens when committing a transaction, | ||||
| 60692 | ** or rolling back a transaction (including rolling back a hot-journal). | ||||
| 60693 | ** | ||||
| 60694 | ** If the main database file is not open, or the pager is not in either | ||||
| 60695 | ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size | ||||
| 60696 | ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). | ||||
| 60697 | ** If the file on disk is currently larger than nPage pages, then use the VFS | ||||
| 60698 | ** xTruncate() method to truncate it. | ||||
| 60699 | ** | ||||
| 60700 | ** Or, it might be the case that the file on disk is smaller than | ||||
| 60701 | ** nPage pages. Some operating system implementations can get confused if | ||||
| 60702 | ** you try to truncate a file to some size that is larger than it | ||||
| 60703 | ** currently is, so detect this case and write a single zero byte to | ||||
| 60704 | ** the end of the new file instead. | ||||
| 60705 | ** | ||||
| 60706 | ** If successful, return SQLITE_OK. If an IO error occurs while modifying | ||||
| 60707 | ** the database file, return the error code to the caller. | ||||
| 60708 | */ | ||||
| 60709 | static int pager_truncate(Pager *pPager, Pgno nPage){ | ||||
| 60710 | int rc = SQLITE_OK0; | ||||
| 60711 | assert( pPager->eState!=PAGER_ERROR )((void) (0)); | ||||
| 60712 | assert( pPager->eState!=PAGER_READER )((void) (0)); | ||||
| 60713 | PAGERTRACE(("Truncate %d npage %u\n", PAGERID(pPager), nPage)); | ||||
| 60714 | |||||
| 60715 | |||||
| 60716 | if( isOpen(pPager->fd)((pPager->fd)->pMethods!=0) | ||||
| 60717 | && (pPager->eState>=PAGER_WRITER_DBMOD4 || pPager->eState==PAGER_OPEN0) | ||||
| 60718 | ){ | ||||
| 60719 | i64 currentSize, newSize; | ||||
| 60720 | int szPage = pPager->pageSize; | ||||
| 60721 | assert( pPager->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 60722 | /* TODO: Is it safe to use Pager.dbFileSize here? */ | ||||
| 60723 | rc = sqlite3OsFileSize(pPager->fd, ¤tSize); | ||||
| 60724 | newSize = szPage*(i64)nPage; | ||||
| 60725 | if( rc==SQLITE_OK0 && currentSize!=newSize ){ | ||||
| 60726 | if( currentSize>newSize ){ | ||||
| 60727 | rc = sqlite3OsTruncate(pPager->fd, newSize); | ||||
| 60728 | }else if( (currentSize+szPage)<=newSize ){ | ||||
| 60729 | char *pTmp = pPager->pTmpSpace; | ||||
| 60730 | memset(pTmp, 0, szPage); | ||||
| 60731 | testcase( (newSize-szPage) == currentSize ); | ||||
| 60732 | testcase( (newSize-szPage) > currentSize ); | ||||
| 60733 | sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT5, &newSize); | ||||
| 60734 | rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); | ||||
| 60735 | } | ||||
| 60736 | if( rc==SQLITE_OK0 ){ | ||||
| 60737 | pPager->dbFileSize = nPage; | ||||
| 60738 | } | ||||
| 60739 | } | ||||
| 60740 | } | ||||
| 60741 | return rc; | ||||
| 60742 | } | ||||
| 60743 | |||||
| 60744 | /* | ||||
| 60745 | ** Return a sanitized version of the sector-size of OS file pFile. The | ||||
| 60746 | ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE. | ||||
| 60747 | */ | ||||
| 60748 | SQLITE_PRIVATEstatic int sqlite3SectorSize(sqlite3_file *pFile){ | ||||
| 60749 | int iRet = sqlite3OsSectorSize(pFile); | ||||
| 60750 | if( iRet<32 ){ | ||||
| 60751 | iRet = 512; | ||||
| 60752 | }else if( iRet>MAX_SECTOR_SIZE0x10000 ){ | ||||
| 60753 | assert( MAX_SECTOR_SIZE>=512 )((void) (0)); | ||||
| 60754 | iRet = MAX_SECTOR_SIZE0x10000; | ||||
| 60755 | } | ||||
| 60756 | return iRet; | ||||
| 60757 | } | ||||
| 60758 | |||||
| 60759 | /* | ||||
| 60760 | ** Set the value of the Pager.sectorSize variable for the given | ||||
| 60761 | ** pager based on the value returned by the xSectorSize method | ||||
| 60762 | ** of the open database file. The sector size will be used | ||||
| 60763 | ** to determine the size and alignment of journal header and | ||||
| 60764 | ** super-journal pointers within created journal files. | ||||
| 60765 | ** | ||||
| 60766 | ** For temporary files the effective sector size is always 512 bytes. | ||||
| 60767 | ** | ||||
| 60768 | ** Otherwise, for non-temporary files, the effective sector size is | ||||
| 60769 | ** the value returned by the xSectorSize() method rounded up to 32 if | ||||
| 60770 | ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it | ||||
| 60771 | ** is greater than MAX_SECTOR_SIZE. | ||||
| 60772 | ** | ||||
| 60773 | ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set | ||||
| 60774 | ** the effective sector size to its minimum value (512). The purpose of | ||||
| 60775 | ** pPager->sectorSize is to define the "blast radius" of bytes that | ||||
| 60776 | ** might change if a crash occurs while writing to a single byte in | ||||
| 60777 | ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero | ||||
| 60778 | ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector | ||||
| 60779 | ** size. For backwards compatibility of the rollback journal file format, | ||||
| 60780 | ** we cannot reduce the effective sector size below 512. | ||||
| 60781 | */ | ||||
| 60782 | static void setSectorSize(Pager *pPager){ | ||||
| 60783 | assert( isOpen(pPager->fd) || pPager->tempFile )((void) (0)); | ||||
| 60784 | |||||
| 60785 | if( pPager->tempFile | ||||
| 60786 | || (sqlite3OsDeviceCharacteristics(pPager->fd) & | ||||
| 60787 | SQLITE_IOCAP_POWERSAFE_OVERWRITE0x00001000)!=0 | ||||
| 60788 | ){ | ||||
| 60789 | /* Sector size doesn't matter for temporary files. Also, the file | ||||
| 60790 | ** may not have been opened yet, in which case the OsSectorSize() | ||||
| 60791 | ** call will segfault. */ | ||||
| 60792 | pPager->sectorSize = 512; | ||||
| 60793 | }else{ | ||||
| 60794 | pPager->sectorSize = sqlite3SectorSize(pPager->fd); | ||||
| 60795 | } | ||||
| 60796 | } | ||||
| 60797 | |||||
| 60798 | /* | ||||
| 60799 | ** Playback the journal and thus restore the database file to | ||||
| 60800 | ** the state it was in before we started making changes. | ||||
| 60801 | ** | ||||
| 60802 | ** The journal file format is as follows: | ||||
| 60803 | ** | ||||
| 60804 | ** (1) 8 byte prefix. A copy of aJournalMagic[]. | ||||
| 60805 | ** (2) 4 byte big-endian integer which is the number of valid page records | ||||
| 60806 | ** in the journal. If this value is 0xffffffff, then compute the | ||||
| 60807 | ** number of page records from the journal size. | ||||
| 60808 | ** (3) 4 byte big-endian integer which is the initial value for the | ||||
| 60809 | ** sanity checksum. | ||||
| 60810 | ** (4) 4 byte integer which is the number of pages to truncate the | ||||
| 60811 | ** database to during a rollback. | ||||
| 60812 | ** (5) 4 byte big-endian integer which is the sector size. The header | ||||
| 60813 | ** is this many bytes in size. | ||||
| 60814 | ** (6) 4 byte big-endian integer which is the page size. | ||||
| 60815 | ** (7) zero padding out to the next sector size. | ||||
| 60816 | ** (8) Zero or more pages instances, each as follows: | ||||
| 60817 | ** + 4 byte page number. | ||||
| 60818 | ** + pPager->pageSize bytes of data. | ||||
| 60819 | ** + 4 byte checksum | ||||
| 60820 | ** | ||||
| 60821 | ** When we speak of the journal header, we mean the first 7 items above. | ||||
| 60822 | ** Each entry in the journal is an instance of the 8th item. | ||||
| 60823 | ** | ||||
| 60824 | ** Call the value from the second bullet "nRec". nRec is the number of | ||||
| 60825 | ** valid page entries in the journal. In most cases, you can compute the | ||||
| 60826 | ** value of nRec from the size of the journal file. But if a power | ||||
| 60827 | ** failure occurred while the journal was being written, it could be the | ||||
| 60828 | ** case that the size of the journal file had already been increased but | ||||
| 60829 | ** the extra entries had not yet made it safely to disk. In such a case, | ||||
| 60830 | ** the value of nRec computed from the file size would be too large. For | ||||
| 60831 | ** that reason, we always use the nRec value in the header. | ||||
| 60832 | ** | ||||
| 60833 | ** If the nRec value is 0xffffffff it means that nRec should be computed | ||||
| 60834 | ** from the file size. This value is used when the user selects the | ||||
| 60835 | ** no-sync option for the journal. A power failure could lead to corruption | ||||
| 60836 | ** in this case. But for things like temporary table (which will be | ||||
| 60837 | ** deleted when the power is restored) we don't care. | ||||
| 60838 | ** | ||||
| 60839 | ** If the file opened as the journal file is not a well-formed | ||||
| 60840 | ** journal file then all pages up to the first corrupted page are rolled | ||||
| 60841 | ** back (or no pages if the journal header is corrupted). The journal file | ||||
| 60842 | ** is then deleted and SQLITE_OK returned, just as if no corruption had | ||||
| 60843 | ** been encountered. | ||||
| 60844 | ** | ||||
| 60845 | ** If an I/O or malloc() error occurs, the journal-file is not deleted | ||||
| 60846 | ** and an error code is returned. | ||||
| 60847 | ** | ||||
| 60848 | ** The isHot parameter indicates that we are trying to rollback a journal | ||||
| 60849 | ** that might be a hot journal. Or, it could be that the journal is | ||||
| 60850 | ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. | ||||
| 60851 | ** If the journal really is hot, reset the pager cache prior rolling | ||||
| 60852 | ** back any content. If the journal is merely persistent, no reset is | ||||
| 60853 | ** needed. | ||||
| 60854 | */ | ||||
| 60855 | static int pager_playback(Pager *pPager, int isHot){ | ||||
| 60856 | sqlite3_vfs *pVfs = pPager->pVfs; | ||||
| 60857 | i64 szJ; /* Size of the journal file in bytes */ | ||||
| 60858 | u32 nRec; /* Number of Records in the journal */ | ||||
| 60859 | u32 u; /* Unsigned loop counter */ | ||||
| 60860 | Pgno mxPg = 0; /* Size of the original file in pages */ | ||||
| 60861 | int rc; /* Result code of a subroutine */ | ||||
| 60862 | int res = 1; /* Value returned by sqlite3OsAccess() */ | ||||
| 60863 | char *zSuper = 0; /* Name of super-journal file if any */ | ||||
| 60864 | int needPagerReset; /* True to reset page prior to first page rollback */ | ||||
| 60865 | int nPlayback = 0; /* Total number of pages restored from journal */ | ||||
| 60866 | u32 savedPageSize = pPager->pageSize; | ||||
| 60867 | |||||
| 60868 | /* Figure out how many records are in the journal. Abort early if | ||||
| 60869 | ** the journal is empty. | ||||
| 60870 | */ | ||||
| 60871 | assert( isOpen(pPager->jfd) )((void) (0)); | ||||
| 60872 | rc = sqlite3OsFileSize(pPager->jfd, &szJ); | ||||
| 60873 | if( rc!=SQLITE_OK0 ){ | ||||
| 60874 | goto end_playback; | ||||
| 60875 | } | ||||
| 60876 | |||||
| 60877 | /* Read the super-journal name from the journal, if it is present. | ||||
| 60878 | ** If a super-journal file name is specified, but the file is not | ||||
| 60879 | ** present on disk, then the journal is not hot and does not need to be | ||||
| 60880 | ** played back. | ||||
| 60881 | ** | ||||
| 60882 | ** TODO: Technically the following is an error because it assumes that | ||||
| 60883 | ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that | ||||
| 60884 | ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, | ||||
| 60885 | ** mxPathname is 512, which is the same as the minimum allowable value | ||||
| 60886 | ** for pageSize. | ||||
| 60887 | */ | ||||
| 60888 | zSuper = pPager->pTmpSpace; | ||||
| 60889 | rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname); | ||||
| 60890 | if( rc==SQLITE_OK0 && zSuper[0] ){ | ||||
| 60891 | rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS0, &res); | ||||
| 60892 | } | ||||
| 60893 | zSuper = 0; | ||||
| 60894 | if( rc!=SQLITE_OK0 || !res ){ | ||||
| 60895 | goto end_playback; | ||||
| 60896 | } | ||||
| 60897 | pPager->journalOff = 0; | ||||
| 60898 | needPagerReset = isHot; | ||||
| 60899 | |||||
| 60900 | /* This loop terminates either when a readJournalHdr() or | ||||
| 60901 | ** pager_playback_one_page() call returns SQLITE_DONE or an IO error | ||||
| 60902 | ** occurs. | ||||
| 60903 | */ | ||||
| 60904 | while( 1 ){ | ||||
| 60905 | /* Read the next journal header from the journal file. If there are | ||||
| 60906 | ** not enough bytes left in the journal file for a complete header, or | ||||
| 60907 | ** it is corrupted, then a process must have failed while writing it. | ||||
| 60908 | ** This indicates nothing more needs to be rolled back. | ||||
| 60909 | */ | ||||
| 60910 | rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg); | ||||
| 60911 | if( rc!=SQLITE_OK0 ){ | ||||
| 60912 | if( rc==SQLITE_DONE101 ){ | ||||
| 60913 | rc = SQLITE_OK0; | ||||
| 60914 | } | ||||
| 60915 | goto end_playback; | ||||
| 60916 | } | ||||
| 60917 | |||||
| 60918 | /* If nRec is 0xffffffff, then this journal was created by a process | ||||
| 60919 | ** working in no-sync mode. This means that the rest of the journal | ||||
| 60920 | ** file consists of pages, there are no more journal headers. Compute | ||||
| 60921 | ** the value of nRec based on this assumption. | ||||
| 60922 | */ | ||||
| 60923 | if( nRec==0xffffffff ){ | ||||
| 60924 | assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) )((void) (0)); | ||||
| 60925 | nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager)(pPager->sectorSize))/JOURNAL_PG_SZ(pPager)((pPager->pageSize) + 8)); | ||||
| 60926 | } | ||||
| 60927 | |||||
| 60928 | /* If nRec is 0 and this rollback is of a transaction created by this | ||||
| 60929 | ** process and if this is the final header in the journal, then it means | ||||
| 60930 | ** that this part of the journal was being filled but has not yet been | ||||
| 60931 | ** synced to disk. Compute the number of pages based on the remaining | ||||
| 60932 | ** size of the file. | ||||
| 60933 | ** | ||||
| 60934 | ** The third term of the test was added to fix ticket #2565. | ||||
| 60935 | ** When rolling back a hot journal, nRec==0 always means that the next | ||||
| 60936 | ** chunk of the journal contains zero pages to be rolled back. But | ||||
| 60937 | ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in | ||||
| 60938 | ** the journal, it means that the journal might contain additional | ||||
| 60939 | ** pages that need to be rolled back and that the number of pages | ||||
| 60940 | ** should be computed based on the journal file size. | ||||
| 60941 | */ | ||||
| 60942 | if( nRec==0 && !isHot && | ||||
| 60943 | pPager->journalHdr+JOURNAL_HDR_SZ(pPager)(pPager->sectorSize)==pPager->journalOff ){ | ||||
| 60944 | nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager)((pPager->pageSize) + 8)); | ||||
| 60945 | } | ||||
| 60946 | |||||
| 60947 | /* If this is the first header read from the journal, truncate the | ||||
| 60948 | ** database file back to its original size. | ||||
| 60949 | */ | ||||
| 60950 | if( pPager->journalOff==JOURNAL_HDR_SZ(pPager)(pPager->sectorSize) ){ | ||||
| 60951 | rc = pager_truncate(pPager, mxPg); | ||||
| 60952 | if( rc!=SQLITE_OK0 ){ | ||||
| 60953 | goto end_playback; | ||||
| 60954 | } | ||||
| 60955 | pPager->dbSize = mxPg; | ||||
| 60956 | if( pPager->mxPgno<mxPg ){ | ||||
| 60957 | pPager->mxPgno = mxPg; | ||||
| 60958 | } | ||||
| 60959 | } | ||||
| 60960 | |||||
| 60961 | /* Copy original pages out of the journal and back into the | ||||
| 60962 | ** database file and/or page cache. | ||||
| 60963 | */ | ||||
| 60964 | for(u=0; u<nRec; u++){ | ||||
| 60965 | if( needPagerReset ){ | ||||
| 60966 | pager_reset(pPager); | ||||
| 60967 | needPagerReset = 0; | ||||
| 60968 | } | ||||
| 60969 | rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0); | ||||
| 60970 | if( rc==SQLITE_OK0 ){ | ||||
| 60971 | nPlayback++; | ||||
| 60972 | }else{ | ||||
| 60973 | if( rc==SQLITE_DONE101 ){ | ||||
| 60974 | pPager->journalOff = szJ; | ||||
| 60975 | break; | ||||
| 60976 | }else if( rc==SQLITE_IOERR_SHORT_READ(10 | (2<<8)) ){ | ||||
| 60977 | /* If the journal has been truncated, simply stop reading and | ||||
| 60978 | ** processing the journal. This might happen if the journal was | ||||
| 60979 | ** not completely written and synced prior to a crash. In that | ||||
| 60980 | ** case, the database should have never been written in the | ||||
| 60981 | ** first place so it is OK to simply abandon the rollback. */ | ||||
| 60982 | rc = SQLITE_OK0; | ||||
| 60983 | goto end_playback; | ||||
| 60984 | }else{ | ||||
| 60985 | /* If we are unable to rollback, quit and return the error | ||||
| 60986 | ** code. This will cause the pager to enter the error state | ||||
| 60987 | ** so that no further harm will be done. Perhaps the next | ||||
| 60988 | ** process to come along will be able to rollback the database. | ||||
| 60989 | */ | ||||
| 60990 | goto end_playback; | ||||
| 60991 | } | ||||
| 60992 | } | ||||
| 60993 | } | ||||
| 60994 | } | ||||
| 60995 | /*NOTREACHED*/ | ||||
| 60996 | assert( 0 )((void) (0)); | ||||
| 60997 | |||||
| 60998 | end_playback: | ||||
| 60999 | if( rc==SQLITE_OK0 ){ | ||||
| 61000 | rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1); | ||||
| 61001 | } | ||||
| 61002 | /* Following a rollback, the database file should be back in its original | ||||
| 61003 | ** state prior to the start of the transaction, so invoke the | ||||
| 61004 | ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the | ||||
| 61005 | ** assertion that the transaction counter was modified. | ||||
| 61006 | */ | ||||
| 61007 | #ifdef SQLITE_DEBUG | ||||
| 61008 | sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED0xca093fa0,0); | ||||
| 61009 | #endif | ||||
| 61010 | |||||
| 61011 | /* If this playback is happening automatically as a result of an IO or | ||||
| 61012 | ** malloc error that occurred after the change-counter was updated but | ||||
| 61013 | ** before the transaction was committed, then the change-counter | ||||
| 61014 | ** modification may just have been reverted. If this happens in exclusive | ||||
| 61015 | ** mode, then subsequent transactions performed by the connection will not | ||||
| 61016 | ** update the change-counter at all. This may lead to cache inconsistency | ||||
| 61017 | ** problems for other processes at some point in the future. So, just | ||||
| 61018 | ** in case this has happened, clear the changeCountDone flag now. | ||||
| 61019 | */ | ||||
| 61020 | pPager->changeCountDone = pPager->tempFile; | ||||
| 61021 | |||||
| 61022 | if( rc==SQLITE_OK0 ){ | ||||
| 61023 | /* Leave 4 bytes of space before the super-journal filename in memory. | ||||
| 61024 | ** This is because it may end up being passed to sqlite3OsOpen(), in | ||||
| 61025 | ** which case it requires 4 0x00 bytes in memory immediately before | ||||
| 61026 | ** the filename. */ | ||||
| 61027 | zSuper = &pPager->pTmpSpace[4]; | ||||
| 61028 | rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname); | ||||
| 61029 | testcase( rc!=SQLITE_OK ); | ||||
| 61030 | } | ||||
| 61031 | if( rc==SQLITE_OK0 | ||||
| 61032 | && (pPager->eState>=PAGER_WRITER_DBMOD4 || pPager->eState==PAGER_OPEN0) | ||||
| 61033 | ){ | ||||
| 61034 | rc = sqlite3PagerSync(pPager, 0); | ||||
| 61035 | } | ||||
| 61036 | if( rc==SQLITE_OK0 ){ | ||||
| 61037 | rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0); | ||||
| 61038 | testcase( rc!=SQLITE_OK ); | ||||
| 61039 | } | ||||
| 61040 | if( rc==SQLITE_OK0 && zSuper[0] && res ){ | ||||
| 61041 | /* If there was a super-journal and this routine will return success, | ||||
| 61042 | ** see if it is possible to delete the super-journal. | ||||
| 61043 | */ | ||||
| 61044 | assert( zSuper==&pPager->pTmpSpace[4] )((void) (0)); | ||||
| 61045 | memset(pPager->pTmpSpace, 0, 4); | ||||
| 61046 | rc = pager_delsuper(pPager, zSuper); | ||||
| 61047 | testcase( rc!=SQLITE_OK ); | ||||
| 61048 | } | ||||
| 61049 | if( isHot && nPlayback ){ | ||||
| 61050 | sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK(27 | (2<<8)), "recovered %d pages from %s", | ||||
| 61051 | nPlayback, pPager->zJournal); | ||||
| 61052 | } | ||||
| 61053 | |||||
| 61054 | /* The Pager.sectorSize variable may have been updated while rolling | ||||
| 61055 | ** back a journal created by a process with a different sector size | ||||
| 61056 | ** value. Reset it to the correct value for this process. | ||||
| 61057 | */ | ||||
| 61058 | setSectorSize(pPager); | ||||
| 61059 | return rc; | ||||
| 61060 | } | ||||
| 61061 | |||||
| 61062 | |||||
| 61063 | /* | ||||
| 61064 | ** Read the content for page pPg out of the database file (or out of | ||||
| 61065 | ** the WAL if that is where the most recent copy if found) into | ||||
| 61066 | ** pPg->pData. A shared lock or greater must be held on the database | ||||
| 61067 | ** file before this function is called. | ||||
| 61068 | ** | ||||
| 61069 | ** If page 1 is read, then the value of Pager.dbFileVers[] is set to | ||||
| 61070 | ** the value read from the database file. | ||||
| 61071 | ** | ||||
| 61072 | ** If an IO error occurs, then the IO error is returned to the caller. | ||||
| 61073 | ** Otherwise, SQLITE_OK is returned. | ||||
| 61074 | */ | ||||
| 61075 | static int readDbPage(PgHdr *pPg){ | ||||
| 61076 | Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */ | ||||
| 61077 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 61078 | |||||
| 61079 | #ifndef SQLITE_OMIT_WAL | ||||
| 61080 | u32 iFrame = 0; /* Frame of WAL containing pgno */ | ||||
| 61081 | |||||
| 61082 | assert( pPager->eState>=PAGER_READER && !MEMDB )((void) (0)); | ||||
| 61083 | assert( isOpen(pPager->fd) )((void) (0)); | ||||
| 61084 | |||||
| 61085 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 61086 | rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); | ||||
| 61087 | if( rc ) return rc; | ||||
| 61088 | } | ||||
| 61089 | if( iFrame ){ | ||||
| 61090 | rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData); | ||||
| 61091 | }else | ||||
| 61092 | #endif | ||||
| 61093 | { | ||||
| 61094 | i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize; | ||||
| 61095 | rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset); | ||||
| 61096 | if( rc==SQLITE_IOERR_SHORT_READ(10 | (2<<8)) ){ | ||||
| 61097 | rc = SQLITE_OK0; | ||||
| 61098 | } | ||||
| 61099 | } | ||||
| 61100 | |||||
| 61101 | if( pPg->pgno==1 ){ | ||||
| 61102 | if( rc ){ | ||||
| 61103 | /* If the read is unsuccessful, set the dbFileVers[] to something | ||||
| 61104 | ** that will never be a valid file version. dbFileVers[] is a copy | ||||
| 61105 | ** of bytes 24..39 of the database. Bytes 28..31 should always be | ||||
| 61106 | ** zero or the size of the database in page. Bytes 32..35 and 35..39 | ||||
| 61107 | ** should be page numbers which are never 0xffffffff. So filling | ||||
| 61108 | ** pPager->dbFileVers[] with all 0xff bytes should suffice. | ||||
| 61109 | ** | ||||
| 61110 | ** For an encrypted database, the situation is more complex: bytes | ||||
| 61111 | ** 24..39 of the database are white noise. But the probability of | ||||
| 61112 | ** white noise equaling 16 bytes of 0xff is vanishingly small so | ||||
| 61113 | ** we should still be ok. | ||||
| 61114 | */ | ||||
| 61115 | memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); | ||||
| 61116 | }else{ | ||||
| 61117 | u8 *dbFileVers = &((u8*)pPg->pData)[24]; | ||||
| 61118 | memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); | ||||
| 61119 | } | ||||
| 61120 | } | ||||
| 61121 | PAGER_INCR(sqlite3_pager_readdb_count); | ||||
| 61122 | PAGER_INCR(pPager->nRead); | ||||
| 61123 | IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno)); | ||||
| 61124 | PAGERTRACE(("FETCH %d page %d hash(%08x)\n", | ||||
| 61125 | PAGERID(pPager), pPg->pgno, pager_pagehash(pPg))); | ||||
| 61126 | |||||
| 61127 | return rc; | ||||
| 61128 | } | ||||
| 61129 | |||||
| 61130 | /* | ||||
| 61131 | ** Update the value of the change-counter at offsets 24 and 92 in | ||||
| 61132 | ** the header and the sqlite version number at offset 96. | ||||
| 61133 | ** | ||||
| 61134 | ** This is an unconditional update. See also the pager_incr_changecounter() | ||||
| 61135 | ** routine which only updates the change-counter if the update is actually | ||||
| 61136 | ** needed, as determined by the pPager->changeCountDone state variable. | ||||
| 61137 | */ | ||||
| 61138 | static void pager_write_changecounter(PgHdr *pPg){ | ||||
| 61139 | u32 change_counter; | ||||
| 61140 | if( NEVER(pPg==0)(pPg==0) ) return; | ||||
| 61141 | |||||
| 61142 | /* Increment the value just read and write it back to byte 24. */ | ||||
| 61143 | change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; | ||||
| 61144 | put32bits(((char*)pPg->pData)+24, change_counter)sqlite3Put4byte((u8*)((char*)pPg->pData)+24,change_counter ); | ||||
| 61145 | |||||
| 61146 | /* Also store the SQLite version number in bytes 96..99 and in | ||||
| 61147 | ** bytes 92..95 store the change counter for which the version number | ||||
| 61148 | ** is valid. */ | ||||
| 61149 | put32bits(((char*)pPg->pData)+92, change_counter)sqlite3Put4byte((u8*)((char*)pPg->pData)+92,change_counter ); | ||||
| 61150 | put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER)sqlite3Put4byte((u8*)((char*)pPg->pData)+96,3050003); | ||||
| 61151 | } | ||||
| 61152 | |||||
| 61153 | #ifndef SQLITE_OMIT_WAL | ||||
| 61154 | /* | ||||
| 61155 | ** This function is invoked once for each page that has already been | ||||
| 61156 | ** written into the log file when a WAL transaction is rolled back. | ||||
| 61157 | ** Parameter iPg is the page number of said page. The pCtx argument | ||||
| 61158 | ** is actually a pointer to the Pager structure. | ||||
| 61159 | ** | ||||
| 61160 | ** If page iPg is present in the cache, and has no outstanding references, | ||||
| 61161 | ** it is discarded. Otherwise, if there are one or more outstanding | ||||
| 61162 | ** references, the page content is reloaded from the database. If the | ||||
| 61163 | ** attempt to reload content from the database is required and fails, | ||||
| 61164 | ** return an SQLite error code. Otherwise, SQLITE_OK. | ||||
| 61165 | */ | ||||
| 61166 | static int pagerUndoCallback(void *pCtx, Pgno iPg){ | ||||
| 61167 | int rc = SQLITE_OK0; | ||||
| 61168 | Pager *pPager = (Pager *)pCtx; | ||||
| 61169 | PgHdr *pPg; | ||||
| 61170 | |||||
| 61171 | assert( pagerUseWal(pPager) )((void) (0)); | ||||
| 61172 | pPg = sqlite3PagerLookup(pPager, iPg); | ||||
| 61173 | if( pPg ){ | ||||
| 61174 | if( sqlite3PcachePageRefcount(pPg)==1 ){ | ||||
| 61175 | sqlite3PcacheDrop(pPg); | ||||
| 61176 | }else{ | ||||
| 61177 | rc = readDbPage(pPg); | ||||
| 61178 | if( rc==SQLITE_OK0 ){ | ||||
| 61179 | pPager->xReiniter(pPg); | ||||
| 61180 | } | ||||
| 61181 | sqlite3PagerUnrefNotNull(pPg); | ||||
| 61182 | } | ||||
| 61183 | } | ||||
| 61184 | |||||
| 61185 | /* Normally, if a transaction is rolled back, any backup processes are | ||||
| 61186 | ** updated as data is copied out of the rollback journal and into the | ||||
| 61187 | ** database. This is not generally possible with a WAL database, as | ||||
| 61188 | ** rollback involves simply truncating the log file. Therefore, if one | ||||
| 61189 | ** or more frames have already been written to the log (and therefore | ||||
| 61190 | ** also copied into the backup databases) as part of this transaction, | ||||
| 61191 | ** the backups must be restarted. | ||||
| 61192 | */ | ||||
| 61193 | sqlite3BackupRestart(pPager->pBackup); | ||||
| 61194 | |||||
| 61195 | return rc; | ||||
| 61196 | } | ||||
| 61197 | |||||
| 61198 | /* | ||||
| 61199 | ** This function is called to rollback a transaction on a WAL database. | ||||
| 61200 | */ | ||||
| 61201 | static int pagerRollbackWal(Pager *pPager){ | ||||
| 61202 | int rc; /* Return Code */ | ||||
| 61203 | PgHdr *pList; /* List of dirty pages to revert */ | ||||
| 61204 | |||||
| 61205 | /* For all pages in the cache that are currently dirty or have already | ||||
| 61206 | ** been written (but not committed) to the log file, do one of the | ||||
| 61207 | ** following: | ||||
| 61208 | ** | ||||
| 61209 | ** + Discard the cached page (if refcount==0), or | ||||
| 61210 | ** + Reload page content from the database (if refcount>0). | ||||
| 61211 | */ | ||||
| 61212 | pPager->dbSize = pPager->dbOrigSize; | ||||
| 61213 | rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); | ||||
| 61214 | pList = sqlite3PcacheDirtyList(pPager->pPCache); | ||||
| 61215 | while( pList && rc==SQLITE_OK0 ){ | ||||
| 61216 | PgHdr *pNext = pList->pDirty; | ||||
| 61217 | rc = pagerUndoCallback((void *)pPager, pList->pgno); | ||||
| 61218 | pList = pNext; | ||||
| 61219 | } | ||||
| 61220 | |||||
| 61221 | return rc; | ||||
| 61222 | } | ||||
| 61223 | |||||
| 61224 | /* | ||||
| 61225 | ** This function is a wrapper around sqlite3WalFrames(). As well as logging | ||||
| 61226 | ** the contents of the list of pages headed by pList (connected by pDirty), | ||||
| 61227 | ** this function notifies any active backup processes that the pages have | ||||
| 61228 | ** changed. | ||||
| 61229 | ** | ||||
| 61230 | ** The list of pages passed into this routine is always sorted by page number. | ||||
| 61231 | ** Hence, if page 1 appears anywhere on the list, it will be the first page. | ||||
| 61232 | */ | ||||
| 61233 | static int pagerWalFrames( | ||||
| 61234 | Pager *pPager, /* Pager object */ | ||||
| 61235 | PgHdr *pList, /* List of frames to log */ | ||||
| 61236 | Pgno nTruncate, /* Database size after this commit */ | ||||
| 61237 | int isCommit /* True if this is a commit */ | ||||
| 61238 | ){ | ||||
| 61239 | int rc; /* Return code */ | ||||
| 61240 | int nList; /* Number of pages in pList */ | ||||
| 61241 | PgHdr *p; /* For looping over pages */ | ||||
| 61242 | |||||
| 61243 | assert( pPager->pWal )((void) (0)); | ||||
| 61244 | assert( pList )((void) (0)); | ||||
| 61245 | #ifdef SQLITE_DEBUG | ||||
| 61246 | /* Verify that the page list is in ascending order */ | ||||
| 61247 | for(p=pList; p && p->pDirty; p=p->pDirty){ | ||||
| 61248 | assert( p->pgno < p->pDirty->pgno )((void) (0)); | ||||
| 61249 | } | ||||
| 61250 | #endif | ||||
| 61251 | |||||
| 61252 | assert( pList->pDirty==0 || isCommit )((void) (0)); | ||||
| 61253 | if( isCommit ){ | ||||
| 61254 | /* If a WAL transaction is being committed, there is no point in writing | ||||
| 61255 | ** any pages with page numbers greater than nTruncate into the WAL file. | ||||
| 61256 | ** They will never be read by any client. So remove them from the pDirty | ||||
| 61257 | ** list here. */ | ||||
| 61258 | PgHdr **ppNext = &pList; | ||||
| 61259 | nList = 0; | ||||
| 61260 | for(p=pList; (*ppNext = p)!=0; p=p->pDirty){ | ||||
| 61261 | if( p->pgno<=nTruncate ){ | ||||
| 61262 | ppNext = &p->pDirty; | ||||
| 61263 | nList++; | ||||
| 61264 | } | ||||
| 61265 | } | ||||
| 61266 | assert( pList )((void) (0)); | ||||
| 61267 | }else{ | ||||
| 61268 | nList = 1; | ||||
| 61269 | } | ||||
| 61270 | pPager->aStat[PAGER_STAT_WRITE2] += nList; | ||||
| 61271 | |||||
| 61272 | if( pList->pgno==1 ) pager_write_changecounter(pList); | ||||
| 61273 | rc = sqlite3WalFrames(pPager->pWal, | ||||
| 61274 | pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags | ||||
| 61275 | ); | ||||
| 61276 | if( rc==SQLITE_OK0 && pPager->pBackup ){ | ||||
| 61277 | for(p=pList; p; p=p->pDirty){ | ||||
| 61278 | sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); | ||||
| 61279 | } | ||||
| 61280 | } | ||||
| 61281 | |||||
| 61282 | #ifdef SQLITE_CHECK_PAGES | ||||
| 61283 | pList = sqlite3PcacheDirtyList(pPager->pPCache); | ||||
| 61284 | for(p=pList; p; p=p->pDirty){ | ||||
| 61285 | pager_set_pagehash(p); | ||||
| 61286 | } | ||||
| 61287 | #endif | ||||
| 61288 | |||||
| 61289 | return rc; | ||||
| 61290 | } | ||||
| 61291 | |||||
| 61292 | /* | ||||
| 61293 | ** Begin a read transaction on the WAL. | ||||
| 61294 | ** | ||||
| 61295 | ** This routine used to be called "pagerOpenSnapshot()" because it essentially | ||||
| 61296 | ** makes a snapshot of the database at the current point in time and preserves | ||||
| 61297 | ** that snapshot for use by the reader in spite of concurrently changes by | ||||
| 61298 | ** other writers or checkpointers. | ||||
| 61299 | */ | ||||
| 61300 | static int pagerBeginReadTransaction(Pager *pPager){ | ||||
| 61301 | int rc; /* Return code */ | ||||
| 61302 | int changed = 0; /* True if cache must be reset */ | ||||
| 61303 | |||||
| 61304 | assert( pagerUseWal(pPager) )((void) (0)); | ||||
| 61305 | assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER )((void) (0)); | ||||
| 61306 | |||||
| 61307 | /* sqlite3WalEndReadTransaction() was not called for the previous | ||||
| 61308 | ** transaction in locking_mode=EXCLUSIVE. So call it now. If we | ||||
| 61309 | ** are in locking_mode=NORMAL and EndRead() was previously called, | ||||
| 61310 | ** the duplicate call is harmless. | ||||
| 61311 | */ | ||||
| 61312 | sqlite3WalEndReadTransaction(pPager->pWal); | ||||
| 61313 | |||||
| 61314 | rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed); | ||||
| 61315 | if( rc!=SQLITE_OK0 || changed ){ | ||||
| 61316 | pager_reset(pPager); | ||||
| 61317 | if( USEFETCH(pPager)((pPager)->bUseFetch) ) sqlite3OsUnfetch(pPager->fd, 0, 0); | ||||
| 61318 | } | ||||
| 61319 | |||||
| 61320 | return rc; | ||||
| 61321 | } | ||||
| 61322 | #endif | ||||
| 61323 | |||||
| 61324 | /* | ||||
| 61325 | ** This function is called as part of the transition from PAGER_OPEN | ||||
| 61326 | ** to PAGER_READER state to determine the size of the database file | ||||
| 61327 | ** in pages (assuming the page size currently stored in Pager.pageSize). | ||||
| 61328 | ** | ||||
| 61329 | ** If no error occurs, SQLITE_OK is returned and the size of the database | ||||
| 61330 | ** in pages is stored in *pnPage. Otherwise, an error code (perhaps | ||||
| 61331 | ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified. | ||||
| 61332 | */ | ||||
| 61333 | static int pagerPagecount(Pager *pPager, Pgno *pnPage){ | ||||
| 61334 | Pgno nPage; /* Value to return via *pnPage */ | ||||
| 61335 | |||||
| 61336 | /* Query the WAL sub-system for the database size. The WalDbsize() | ||||
| 61337 | ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or | ||||
| 61338 | ** if the database size is not available. The database size is not | ||||
| 61339 | ** available from the WAL sub-system if the log file is empty or | ||||
| 61340 | ** contains no valid committed transactions. | ||||
| 61341 | */ | ||||
| 61342 | assert( pPager->eState==PAGER_OPEN )((void) (0)); | ||||
| 61343 | assert( pPager->eLock>=SHARED_LOCK )((void) (0)); | ||||
| 61344 | assert( isOpen(pPager->fd) )((void) (0)); | ||||
| 61345 | assert( pPager->tempFile==0 )((void) (0)); | ||||
| 61346 | nPage = sqlite3WalDbsize(pPager->pWal); | ||||
| 61347 | |||||
| 61348 | /* If the number of pages in the database is not available from the | ||||
| 61349 | ** WAL sub-system, determine the page count based on the size of | ||||
| 61350 | ** the database file. If the size of the database file is not an | ||||
| 61351 | ** integer multiple of the page-size, round up the result. | ||||
| 61352 | */ | ||||
| 61353 | if( nPage==0 && ALWAYS(isOpen(pPager->fd))(((pPager->fd)->pMethods!=0)) ){ | ||||
| 61354 | i64 n = 0; /* Size of db file in bytes */ | ||||
| 61355 | int rc = sqlite3OsFileSize(pPager->fd, &n); | ||||
| 61356 | if( rc!=SQLITE_OK0 ){ | ||||
| 61357 | return rc; | ||||
| 61358 | } | ||||
| 61359 | nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize); | ||||
| 61360 | } | ||||
| 61361 | |||||
| 61362 | /* If the current number of pages in the file is greater than the | ||||
| 61363 | ** configured maximum pager number, increase the allowed limit so | ||||
| 61364 | ** that the file can be read. | ||||
| 61365 | */ | ||||
| 61366 | if( nPage>pPager->mxPgno ){ | ||||
| 61367 | pPager->mxPgno = (Pgno)nPage; | ||||
| 61368 | } | ||||
| 61369 | |||||
| 61370 | *pnPage = nPage; | ||||
| 61371 | return SQLITE_OK0; | ||||
| 61372 | } | ||||
| 61373 | |||||
| 61374 | #ifndef SQLITE_OMIT_WAL | ||||
| 61375 | /* | ||||
| 61376 | ** Check if the *-wal file that corresponds to the database opened by pPager | ||||
| 61377 | ** exists if the database is not empty, or verify that the *-wal file does | ||||
| 61378 | ** not exist (by deleting it) if the database file is empty. | ||||
| 61379 | ** | ||||
| 61380 | ** If the database is not empty and the *-wal file exists, open the pager | ||||
| 61381 | ** in WAL mode. If the database is empty or if no *-wal file exists and | ||||
| 61382 | ** if no error occurs, make sure Pager.journalMode is not set to | ||||
| 61383 | ** PAGER_JOURNALMODE_WAL. | ||||
| 61384 | ** | ||||
| 61385 | ** Return SQLITE_OK or an error code. | ||||
| 61386 | ** | ||||
| 61387 | ** The caller must hold a SHARED lock on the database file to call this | ||||
| 61388 | ** function. Because an EXCLUSIVE lock on the db file is required to delete | ||||
| 61389 | ** a WAL on a none-empty database, this ensures there is no race condition | ||||
| 61390 | ** between the xAccess() below and an xDelete() being executed by some | ||||
| 61391 | ** other connection. | ||||
| 61392 | */ | ||||
| 61393 | static int pagerOpenWalIfPresent(Pager *pPager){ | ||||
| 61394 | int rc = SQLITE_OK0; | ||||
| 61395 | assert( pPager->eState==PAGER_OPEN )((void) (0)); | ||||
| 61396 | assert( pPager->eLock>=SHARED_LOCK )((void) (0)); | ||||
| 61397 | |||||
| 61398 | if( !pPager->tempFile ){ | ||||
| 61399 | int isWal; /* True if WAL file exists */ | ||||
| 61400 | rc = sqlite3OsAccess( | ||||
| 61401 | pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS0, &isWal | ||||
| 61402 | ); | ||||
| 61403 | if( rc==SQLITE_OK0 ){ | ||||
| 61404 | if( isWal ){ | ||||
| 61405 | Pgno nPage; /* Size of the database file */ | ||||
| 61406 | |||||
| 61407 | rc = pagerPagecount(pPager, &nPage); | ||||
| 61408 | if( rc ) return rc; | ||||
| 61409 | if( nPage==0 ){ | ||||
| 61410 | rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); | ||||
| 61411 | }else{ | ||||
| 61412 | testcase( sqlite3PcachePagecount(pPager->pPCache)==0 ); | ||||
| 61413 | rc = sqlite3PagerOpenWal(pPager, 0); | ||||
| 61414 | } | ||||
| 61415 | }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL5 ){ | ||||
| 61416 | pPager->journalMode = PAGER_JOURNALMODE_DELETE0; | ||||
| 61417 | } | ||||
| 61418 | } | ||||
| 61419 | } | ||||
| 61420 | return rc; | ||||
| 61421 | } | ||||
| 61422 | #endif | ||||
| 61423 | |||||
| 61424 | /* | ||||
| 61425 | ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback | ||||
| 61426 | ** the entire super-journal file. The case pSavepoint==NULL occurs when | ||||
| 61427 | ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction | ||||
| 61428 | ** savepoint. | ||||
| 61429 | ** | ||||
| 61430 | ** When pSavepoint is not NULL (meaning a non-transaction savepoint is | ||||
| 61431 | ** being rolled back), then the rollback consists of up to three stages, | ||||
| 61432 | ** performed in the order specified: | ||||
| 61433 | ** | ||||
| 61434 | ** * Pages are played back from the main journal starting at byte | ||||
| 61435 | ** offset PagerSavepoint.iOffset and continuing to | ||||
| 61436 | ** PagerSavepoint.iHdrOffset, or to the end of the main journal | ||||
| 61437 | ** file if PagerSavepoint.iHdrOffset is zero. | ||||
| 61438 | ** | ||||
| 61439 | ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played | ||||
| 61440 | ** back starting from the journal header immediately following | ||||
| 61441 | ** PagerSavepoint.iHdrOffset to the end of the main journal file. | ||||
| 61442 | ** | ||||
| 61443 | ** * Pages are then played back from the sub-journal file, starting | ||||
| 61444 | ** with the PagerSavepoint.iSubRec and continuing to the end of | ||||
| 61445 | ** the journal file. | ||||
| 61446 | ** | ||||
| 61447 | ** Throughout the rollback process, each time a page is rolled back, the | ||||
| 61448 | ** corresponding bit is set in a bitvec structure (variable pDone in the | ||||
| 61449 | ** implementation below). This is used to ensure that a page is only | ||||
| 61450 | ** rolled back the first time it is encountered in either journal. | ||||
| 61451 | ** | ||||
| 61452 | ** If pSavepoint is NULL, then pages are only played back from the main | ||||
| 61453 | ** journal file. There is no need for a bitvec in this case. | ||||
| 61454 | ** | ||||
| 61455 | ** In either case, before playback commences the Pager.dbSize variable | ||||
| 61456 | ** is reset to the value that it held at the start of the savepoint | ||||
| 61457 | ** (or transaction). No page with a page-number greater than this value | ||||
| 61458 | ** is played back. If one is encountered it is simply skipped. | ||||
| 61459 | */ | ||||
| 61460 | static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ | ||||
| 61461 | i64 szJ; /* Effective size of the main journal */ | ||||
| 61462 | i64 iHdrOff; /* End of first segment of main-journal records */ | ||||
| 61463 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 61464 | Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */ | ||||
| 61465 | |||||
| 61466 | assert( pPager->eState!=PAGER_ERROR )((void) (0)); | ||||
| 61467 | assert( pPager->eState>=PAGER_WRITER_LOCKED )((void) (0)); | ||||
| 61468 | |||||
| 61469 | /* Allocate a bitvec to use to store the set of pages rolled back */ | ||||
| 61470 | if( pSavepoint ){ | ||||
| 61471 | pDone = sqlite3BitvecCreate(pSavepoint->nOrig); | ||||
| 61472 | if( !pDone ){ | ||||
| 61473 | return SQLITE_NOMEM_BKPT7; | ||||
| 61474 | } | ||||
| 61475 | } | ||||
| 61476 | |||||
| 61477 | /* Set the database size back to the value it was before the savepoint | ||||
| 61478 | ** being reverted was opened. | ||||
| 61479 | */ | ||||
| 61480 | pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize; | ||||
| 61481 | pPager->changeCountDone = pPager->tempFile; | ||||
| 61482 | |||||
| 61483 | if( !pSavepoint && pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 61484 | return pagerRollbackWal(pPager); | ||||
| 61485 | } | ||||
| 61486 | |||||
| 61487 | /* Use pPager->journalOff as the effective size of the main rollback | ||||
| 61488 | ** journal. The actual file might be larger than this in | ||||
| 61489 | ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything | ||||
| 61490 | ** past pPager->journalOff is off-limits to us. | ||||
| 61491 | */ | ||||
| 61492 | szJ = pPager->journalOff; | ||||
| 61493 | assert( pagerUseWal(pPager)==0 || szJ==0 )((void) (0)); | ||||
| 61494 | |||||
| 61495 | /* Begin by rolling back records from the main journal starting at | ||||
| 61496 | ** PagerSavepoint.iOffset and continuing to the next journal header. | ||||
| 61497 | ** There might be records in the main journal that have a page number | ||||
| 61498 | ** greater than the current database size (pPager->dbSize) but those | ||||
| 61499 | ** will be skipped automatically. Pages are added to pDone as they | ||||
| 61500 | ** are played back. | ||||
| 61501 | */ | ||||
| 61502 | if( pSavepoint && !pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 61503 | iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ; | ||||
| 61504 | pPager->journalOff = pSavepoint->iOffset; | ||||
| 61505 | while( rc==SQLITE_OK0 && pPager->journalOff<iHdrOff ){ | ||||
| 61506 | rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1); | ||||
| 61507 | } | ||||
| 61508 | assert( rc!=SQLITE_DONE )((void) (0)); | ||||
| 61509 | }else{ | ||||
| 61510 | pPager->journalOff = 0; | ||||
| 61511 | } | ||||
| 61512 | |||||
| 61513 | /* Continue rolling back records out of the main journal starting at | ||||
| 61514 | ** the first journal header seen and continuing until the effective end | ||||
| 61515 | ** of the main journal file. Continue to skip out-of-range pages and | ||||
| 61516 | ** continue adding pages rolled back to pDone. | ||||
| 61517 | */ | ||||
| 61518 | while( rc==SQLITE_OK0 && pPager->journalOff<szJ ){ | ||||
| 61519 | u32 ii; /* Loop counter */ | ||||
| 61520 | u32 nJRec = 0; /* Number of Journal Records */ | ||||
| 61521 | u32 dummy; | ||||
| 61522 | rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy); | ||||
| 61523 | assert( rc!=SQLITE_DONE )((void) (0)); | ||||
| 61524 | |||||
| 61525 | /* | ||||
| 61526 | ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff" | ||||
| 61527 | ** test is related to ticket #2565. See the discussion in the | ||||
| 61528 | ** pager_playback() function for additional information. | ||||
| 61529 | */ | ||||
| 61530 | if( nJRec==0 | ||||
| 61531 | && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)(pPager->sectorSize)==pPager->journalOff | ||||
| 61532 | ){ | ||||
| 61533 | nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager)((pPager->pageSize) + 8)); | ||||
| 61534 | } | ||||
| 61535 | for(ii=0; rc==SQLITE_OK0 && ii<nJRec && pPager->journalOff<szJ; ii++){ | ||||
| 61536 | rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1); | ||||
| 61537 | } | ||||
| 61538 | assert( rc!=SQLITE_DONE )((void) (0)); | ||||
| 61539 | } | ||||
| 61540 | assert( rc!=SQLITE_OK || pPager->journalOff>=szJ )((void) (0)); | ||||
| 61541 | |||||
| 61542 | /* Finally, rollback pages from the sub-journal. Page that were | ||||
| 61543 | ** previously rolled back out of the main journal (and are hence in pDone) | ||||
| 61544 | ** will be skipped. Out-of-range pages are also skipped. | ||||
| 61545 | */ | ||||
| 61546 | if( pSavepoint ){ | ||||
| 61547 | u32 ii; /* Loop counter */ | ||||
| 61548 | i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize); | ||||
| 61549 | |||||
| 61550 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 61551 | rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); | ||||
| 61552 | } | ||||
| 61553 | for(ii=pSavepoint->iSubRec; rc==SQLITE_OK0 && ii<pPager->nSubRec; ii++){ | ||||
| 61554 | assert( offset==(i64)ii*(4+pPager->pageSize) )((void) (0)); | ||||
| 61555 | rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1); | ||||
| 61556 | } | ||||
| 61557 | assert( rc!=SQLITE_DONE )((void) (0)); | ||||
| 61558 | } | ||||
| 61559 | |||||
| 61560 | sqlite3BitvecDestroy(pDone); | ||||
| 61561 | if( rc==SQLITE_OK0 ){ | ||||
| 61562 | pPager->journalOff = szJ; | ||||
| 61563 | } | ||||
| 61564 | |||||
| 61565 | return rc; | ||||
| 61566 | } | ||||
| 61567 | |||||
| 61568 | /* | ||||
| 61569 | ** Change the maximum number of in-memory pages that are allowed | ||||
| 61570 | ** before attempting to recycle clean and unused pages. | ||||
| 61571 | */ | ||||
| 61572 | SQLITE_PRIVATEstatic void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){ | ||||
| 61573 | sqlite3PcacheSetCachesize(pPager->pPCache, mxPage); | ||||
| 61574 | } | ||||
| 61575 | |||||
| 61576 | /* | ||||
| 61577 | ** Change the maximum number of in-memory pages that are allowed | ||||
| 61578 | ** before attempting to spill pages to journal. | ||||
| 61579 | */ | ||||
| 61580 | SQLITE_PRIVATEstatic int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){ | ||||
| 61581 | return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage); | ||||
| 61582 | } | ||||
| 61583 | |||||
| 61584 | /* | ||||
| 61585 | ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap. | ||||
| 61586 | */ | ||||
| 61587 | static void pagerFixMaplimit(Pager *pPager){ | ||||
| 61588 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 61589 | sqlite3_file *fd = pPager->fd; | ||||
| 61590 | if( isOpen(fd)((fd)->pMethods!=0) && fd->pMethods->iVersion>=3 ){ | ||||
| 61591 | sqlite3_int64 sz; | ||||
| 61592 | sz = pPager->szMmap; | ||||
| 61593 | pPager->bUseFetch = (sz>0); | ||||
| 61594 | setGetterMethod(pPager); | ||||
| 61595 | sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE18, &sz); | ||||
| 61596 | } | ||||
| 61597 | #endif | ||||
| 61598 | } | ||||
| 61599 | |||||
| 61600 | /* | ||||
| 61601 | ** Change the maximum size of any memory mapping made of the database file. | ||||
| 61602 | */ | ||||
| 61603 | SQLITE_PRIVATEstatic void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){ | ||||
| 61604 | pPager->szMmap = szMmap; | ||||
| 61605 | pagerFixMaplimit(pPager); | ||||
| 61606 | } | ||||
| 61607 | |||||
| 61608 | /* | ||||
| 61609 | ** Free as much memory as possible from the pager. | ||||
| 61610 | */ | ||||
| 61611 | SQLITE_PRIVATEstatic void sqlite3PagerShrink(Pager *pPager){ | ||||
| 61612 | sqlite3PcacheShrink(pPager->pPCache); | ||||
| 61613 | } | ||||
| 61614 | |||||
| 61615 | /* | ||||
| 61616 | ** Adjust settings of the pager to those specified in the pgFlags parameter. | ||||
| 61617 | ** | ||||
| 61618 | ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness | ||||
| 61619 | ** of the database to damage due to OS crashes or power failures by | ||||
| 61620 | ** changing the number of syncs()s when writing the journals. | ||||
| 61621 | ** There are four levels: | ||||
| 61622 | ** | ||||
| 61623 | ** OFF sqlite3OsSync() is never called. This is the default | ||||
| 61624 | ** for temporary and transient files. | ||||
| 61625 | ** | ||||
| 61626 | ** NORMAL The journal is synced once before writes begin on the | ||||
| 61627 | ** database. This is normally adequate protection, but | ||||
| 61628 | ** it is theoretically possible, though very unlikely, | ||||
| 61629 | ** that an inopertune power failure could leave the journal | ||||
| 61630 | ** in a state which would cause damage to the database | ||||
| 61631 | ** when it is rolled back. | ||||
| 61632 | ** | ||||
| 61633 | ** FULL The journal is synced twice before writes begin on the | ||||
| 61634 | ** database (with some additional information - the nRec field | ||||
| 61635 | ** of the journal header - being written in between the two | ||||
| 61636 | ** syncs). If we assume that writing a | ||||
| 61637 | ** single disk sector is atomic, then this mode provides | ||||
| 61638 | ** assurance that the journal will not be corrupted to the | ||||
| 61639 | ** point of causing damage to the database during rollback. | ||||
| 61640 | ** | ||||
| 61641 | ** EXTRA This is like FULL except that is also syncs the directory | ||||
| 61642 | ** that contains the rollback journal after the rollback | ||||
| 61643 | ** journal is unlinked. | ||||
| 61644 | ** | ||||
| 61645 | ** The above is for a rollback-journal mode. For WAL mode, OFF continues | ||||
| 61646 | ** to mean that no syncs ever occur. NORMAL means that the WAL is synced | ||||
| 61647 | ** prior to the start of checkpoint and that the database file is synced | ||||
| 61648 | ** at the conclusion of the checkpoint if the entire content of the WAL | ||||
| 61649 | ** was written back into the database. But no sync operations occur for | ||||
| 61650 | ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL | ||||
| 61651 | ** file is synced following each commit operation, in addition to the | ||||
| 61652 | ** syncs associated with NORMAL. There is no difference between FULL | ||||
| 61653 | ** and EXTRA for WAL mode. | ||||
| 61654 | ** | ||||
| 61655 | ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The | ||||
| 61656 | ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync | ||||
| 61657 | ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an | ||||
| 61658 | ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL | ||||
| 61659 | ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the | ||||
| 61660 | ** synchronous=FULL versus synchronous=NORMAL setting determines when | ||||
| 61661 | ** the xSync primitive is called and is relevant to all platforms. | ||||
| 61662 | ** | ||||
| 61663 | ** Numeric values associated with these states are OFF==1, NORMAL=2, | ||||
| 61664 | ** and FULL=3. | ||||
| 61665 | */ | ||||
| 61666 | SQLITE_PRIVATEstatic void sqlite3PagerSetFlags( | ||||
| 61667 | Pager *pPager, /* The pager to set safety level for */ | ||||
| 61668 | unsigned pgFlags /* Various flags */ | ||||
| 61669 | ){ | ||||
| 61670 | unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK0x07; | ||||
| 61671 | if( pPager->tempFile ){ | ||||
| 61672 | pPager->noSync = 1; | ||||
| 61673 | pPager->fullSync = 0; | ||||
| 61674 | pPager->extraSync = 0; | ||||
| 61675 | }else{ | ||||
| 61676 | pPager->noSync = level==PAGER_SYNCHRONOUS_OFF0x01 ?1:0; | ||||
| 61677 | pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL0x03 ?1:0; | ||||
| 61678 | pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA0x04 ?1:0; | ||||
| 61679 | } | ||||
| 61680 | if( pPager->noSync ){ | ||||
| 61681 | pPager->syncFlags = 0; | ||||
| 61682 | }else if( pgFlags & PAGER_FULLFSYNC0x08 ){ | ||||
| 61683 | pPager->syncFlags = SQLITE_SYNC_FULL0x00003; | ||||
| 61684 | }else{ | ||||
| 61685 | pPager->syncFlags = SQLITE_SYNC_NORMAL0x00002; | ||||
| 61686 | } | ||||
| 61687 | pPager->walSyncFlags = (pPager->syncFlags<<2); | ||||
| 61688 | if( pPager->fullSync ){ | ||||
| 61689 | pPager->walSyncFlags |= pPager->syncFlags; | ||||
| 61690 | } | ||||
| 61691 | if( (pgFlags & PAGER_CKPT_FULLFSYNC0x10) && !pPager->noSync ){ | ||||
| 61692 | pPager->walSyncFlags |= (SQLITE_SYNC_FULL0x00003<<2); | ||||
| 61693 | } | ||||
| 61694 | if( pgFlags & PAGER_CACHESPILL0x20 ){ | ||||
| 61695 | pPager->doNotSpill &= ~SPILLFLAG_OFF0x01; | ||||
| 61696 | }else{ | ||||
| 61697 | pPager->doNotSpill |= SPILLFLAG_OFF0x01; | ||||
| 61698 | } | ||||
| 61699 | } | ||||
| 61700 | |||||
| 61701 | /* | ||||
| 61702 | ** The following global variable is incremented whenever the library | ||||
| 61703 | ** attempts to open a temporary file. This information is used for | ||||
| 61704 | ** testing and analysis only. | ||||
| 61705 | */ | ||||
| 61706 | #ifdef SQLITE_TEST | ||||
| 61707 | SQLITE_API int sqlite3_opentemp_count = 0; | ||||
| 61708 | #endif | ||||
| 61709 | |||||
| 61710 | /* | ||||
| 61711 | ** Open a temporary file. | ||||
| 61712 | ** | ||||
| 61713 | ** Write the file descriptor into *pFile. Return SQLITE_OK on success | ||||
| 61714 | ** or some other error code if we fail. The OS will automatically | ||||
| 61715 | ** delete the temporary file when it is closed. | ||||
| 61716 | ** | ||||
| 61717 | ** The flags passed to the VFS layer xOpen() call are those specified | ||||
| 61718 | ** by parameter vfsFlags ORed with the following: | ||||
| 61719 | ** | ||||
| 61720 | ** SQLITE_OPEN_READWRITE | ||||
| 61721 | ** SQLITE_OPEN_CREATE | ||||
| 61722 | ** SQLITE_OPEN_EXCLUSIVE | ||||
| 61723 | ** SQLITE_OPEN_DELETEONCLOSE | ||||
| 61724 | */ | ||||
| 61725 | static int pagerOpentemp( | ||||
| 61726 | Pager *pPager, /* The pager object */ | ||||
| 61727 | sqlite3_file *pFile, /* Write the file descriptor here */ | ||||
| 61728 | int vfsFlags /* Flags passed through to the VFS */ | ||||
| 61729 | ){ | ||||
| 61730 | int rc; /* Return code */ | ||||
| 61731 | |||||
| 61732 | #ifdef SQLITE_TEST | ||||
| 61733 | sqlite3_opentemp_count++; /* Used for testing and analysis only */ | ||||
| 61734 | #endif | ||||
| 61735 | |||||
| 61736 | vfsFlags |= SQLITE_OPEN_READWRITE0x00000002 | SQLITE_OPEN_CREATE0x00000004 | | ||||
| 61737 | SQLITE_OPEN_EXCLUSIVE0x00000010 | SQLITE_OPEN_DELETEONCLOSE0x00000008; | ||||
| 61738 | rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); | ||||
| 61739 | assert( rc!=SQLITE_OK || isOpen(pFile) )((void) (0)); | ||||
| 61740 | return rc; | ||||
| 61741 | } | ||||
| 61742 | |||||
| 61743 | /* | ||||
| 61744 | ** Set the busy handler function. | ||||
| 61745 | ** | ||||
| 61746 | ** The pager invokes the busy-handler if sqlite3OsLock() returns | ||||
| 61747 | ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, | ||||
| 61748 | ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE | ||||
| 61749 | ** lock. It does *not* invoke the busy handler when upgrading from | ||||
| 61750 | ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE | ||||
| 61751 | ** (which occurs during hot-journal rollback). Summary: | ||||
| 61752 | ** | ||||
| 61753 | ** Transition | Invokes xBusyHandler | ||||
| 61754 | ** -------------------------------------------------------- | ||||
| 61755 | ** NO_LOCK -> SHARED_LOCK | Yes | ||||
| 61756 | ** SHARED_LOCK -> RESERVED_LOCK | No | ||||
| 61757 | ** SHARED_LOCK -> EXCLUSIVE_LOCK | No | ||||
| 61758 | ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes | ||||
| 61759 | ** | ||||
| 61760 | ** If the busy-handler callback returns non-zero, the lock is | ||||
| 61761 | ** retried. If it returns zero, then the SQLITE_BUSY error is | ||||
| 61762 | ** returned to the caller of the pager API function. | ||||
| 61763 | */ | ||||
| 61764 | SQLITE_PRIVATEstatic void sqlite3PagerSetBusyHandler( | ||||
| 61765 | Pager *pPager, /* Pager object */ | ||||
| 61766 | int (*xBusyHandler)(void *), /* Pointer to busy-handler function */ | ||||
| 61767 | void *pBusyHandlerArg /* Argument to pass to xBusyHandler */ | ||||
| 61768 | ){ | ||||
| 61769 | void **ap; | ||||
| 61770 | pPager->xBusyHandler = xBusyHandler; | ||||
| 61771 | pPager->pBusyHandlerArg = pBusyHandlerArg; | ||||
| 61772 | ap = (void **)&pPager->xBusyHandler; | ||||
| 61773 | assert( ((int(*)(void *))(ap[0]))==xBusyHandler )((void) (0)); | ||||
| 61774 | assert( ap[1]==pBusyHandlerArg )((void) (0)); | ||||
| 61775 | sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER15, (void *)ap); | ||||
| 61776 | } | ||||
| 61777 | |||||
| 61778 | /* | ||||
| 61779 | ** Change the page size used by the Pager object. The new page size | ||||
| 61780 | ** is passed in *pPageSize. | ||||
| 61781 | ** | ||||
| 61782 | ** If the pager is in the error state when this function is called, it | ||||
| 61783 | ** is a no-op. The value returned is the error state error code (i.e. | ||||
| 61784 | ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL). | ||||
| 61785 | ** | ||||
| 61786 | ** Otherwise, if all of the following are true: | ||||
| 61787 | ** | ||||
| 61788 | ** * the new page size (value of *pPageSize) is valid (a power | ||||
| 61789 | ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and | ||||
| 61790 | ** | ||||
| 61791 | ** * there are no outstanding page references, and | ||||
| 61792 | ** | ||||
| 61793 | ** * the database is either not an in-memory database or it is | ||||
| 61794 | ** an in-memory database that currently consists of zero pages. | ||||
| 61795 | ** | ||||
| 61796 | ** then the pager object page size is set to *pPageSize. | ||||
| 61797 | ** | ||||
| 61798 | ** If the page size is changed, then this function uses sqlite3PagerMalloc() | ||||
| 61799 | ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt | ||||
| 61800 | ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. | ||||
| 61801 | ** In all other cases, SQLITE_OK is returned. | ||||
| 61802 | ** | ||||
| 61803 | ** If the page size is not changed, either because one of the enumerated | ||||
| 61804 | ** conditions above is not true, the pager was in error state when this | ||||
| 61805 | ** function was called, or because the memory allocation attempt failed, | ||||
| 61806 | ** then *pPageSize is set to the old, retained page size before returning. | ||||
| 61807 | */ | ||||
| 61808 | SQLITE_PRIVATEstatic int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ | ||||
| 61809 | int rc = SQLITE_OK0; | ||||
| 61810 | |||||
| 61811 | /* It is not possible to do a full assert_pager_state() here, as this | ||||
| 61812 | ** function may be called from within PagerOpen(), before the state | ||||
| 61813 | ** of the Pager object is internally consistent. | ||||
| 61814 | ** | ||||
| 61815 | ** At one point this function returned an error if the pager was in | ||||
| 61816 | ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that | ||||
| 61817 | ** there is at least one outstanding page reference, this function | ||||
| 61818 | ** is a no-op for that case anyhow. | ||||
| 61819 | */ | ||||
| 61820 | |||||
| 61821 | u32 pageSize = *pPageSize; | ||||
| 61822 | assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) )((void) (0)); | ||||
| 61823 | if( (pPager->memDb==0 || pPager->dbSize==0) | ||||
| 61824 | && sqlite3PcacheRefCount(pPager->pPCache)==0 | ||||
| 61825 | && pageSize && pageSize!=(u32)pPager->pageSize | ||||
| 61826 | ){ | ||||
| 61827 | char *pNew = NULL((void*)0); /* New temp space */ | ||||
| 61828 | i64 nByte = 0; | ||||
| 61829 | |||||
| 61830 | if( pPager->eState>PAGER_OPEN0 && isOpen(pPager->fd)((pPager->fd)->pMethods!=0) ){ | ||||
| 61831 | rc = sqlite3OsFileSize(pPager->fd, &nByte); | ||||
| 61832 | } | ||||
| 61833 | if( rc==SQLITE_OK0 ){ | ||||
| 61834 | /* 8 bytes of zeroed overrun space is sufficient so that the b-tree | ||||
| 61835 | * cell header parser will never run off the end of the allocation */ | ||||
| 61836 | pNew = (char *)sqlite3PageMalloc(pageSize+8); | ||||
| 61837 | if( !pNew ){ | ||||
| 61838 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 61839 | }else{ | ||||
| 61840 | memset(pNew+pageSize, 0, 8); | ||||
| 61841 | } | ||||
| 61842 | } | ||||
| 61843 | |||||
| 61844 | if( rc==SQLITE_OK0 ){ | ||||
| 61845 | pager_reset(pPager); | ||||
| 61846 | rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize); | ||||
| 61847 | } | ||||
| 61848 | if( rc==SQLITE_OK0 ){ | ||||
| 61849 | sqlite3PageFree(pPager->pTmpSpace); | ||||
| 61850 | pPager->pTmpSpace = pNew; | ||||
| 61851 | pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize); | ||||
| 61852 | pPager->pageSize = pageSize; | ||||
| 61853 | pPager->lckPgno = (Pgno)(PENDING_BYTEsqlite3PendingByte/pageSize) + 1; | ||||
| 61854 | }else{ | ||||
| 61855 | sqlite3PageFree(pNew); | ||||
| 61856 | } | ||||
| 61857 | } | ||||
| 61858 | |||||
| 61859 | *pPageSize = pPager->pageSize; | ||||
| 61860 | if( rc==SQLITE_OK0 ){ | ||||
| 61861 | if( nReserve<0 ) nReserve = pPager->nReserve; | ||||
| 61862 | assert( nReserve>=0 && nReserve<1000 )((void) (0)); | ||||
| 61863 | pPager->nReserve = (i16)nReserve; | ||||
| 61864 | pagerFixMaplimit(pPager); | ||||
| 61865 | } | ||||
| 61866 | return rc; | ||||
| 61867 | } | ||||
| 61868 | |||||
| 61869 | /* | ||||
| 61870 | ** Return a pointer to the "temporary page" buffer held internally | ||||
| 61871 | ** by the pager. This is a buffer that is big enough to hold the | ||||
| 61872 | ** entire content of a database page. This buffer is used internally | ||||
| 61873 | ** during rollback and will be overwritten whenever a rollback | ||||
| 61874 | ** occurs. But other modules are free to use it too, as long as | ||||
| 61875 | ** no rollbacks are happening. | ||||
| 61876 | */ | ||||
| 61877 | SQLITE_PRIVATEstatic void *sqlite3PagerTempSpace(Pager *pPager){ | ||||
| 61878 | return pPager->pTmpSpace; | ||||
| 61879 | } | ||||
| 61880 | |||||
| 61881 | /* | ||||
| 61882 | ** Attempt to set the maximum database page count if mxPage is positive. | ||||
| 61883 | ** Make no changes if mxPage is zero or negative. And never reduce the | ||||
| 61884 | ** maximum page count below the current size of the database. | ||||
| 61885 | ** | ||||
| 61886 | ** Regardless of mxPage, return the current maximum page count. | ||||
| 61887 | */ | ||||
| 61888 | SQLITE_PRIVATEstatic Pgno sqlite3PagerMaxPageCount(Pager *pPager, Pgno mxPage){ | ||||
| 61889 | if( mxPage>0 ){ | ||||
| 61890 | pPager->mxPgno = mxPage; | ||||
| 61891 | } | ||||
| 61892 | assert( pPager->eState!=PAGER_OPEN )((void) (0)); /* Called only by OP_MaxPgcnt */ | ||||
| 61893 | /* assert( pPager->mxPgno>=pPager->dbSize ); */ | ||||
| 61894 | /* OP_MaxPgcnt ensures that the parameter passed to this function is not | ||||
| 61895 | ** less than the total number of valid pages in the database. But this | ||||
| 61896 | ** may be less than Pager.dbSize, and so the assert() above is not valid */ | ||||
| 61897 | return pPager->mxPgno; | ||||
| 61898 | } | ||||
| 61899 | |||||
| 61900 | /* | ||||
| 61901 | ** The following set of routines are used to disable the simulated | ||||
| 61902 | ** I/O error mechanism. These routines are used to avoid simulated | ||||
| 61903 | ** errors in places where we do not care about errors. | ||||
| 61904 | ** | ||||
| 61905 | ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops | ||||
| 61906 | ** and generate no code. | ||||
| 61907 | */ | ||||
| 61908 | #ifdef SQLITE_TEST | ||||
| 61909 | SQLITE_API extern int sqlite3_io_error_pending; | ||||
| 61910 | SQLITE_API extern int sqlite3_io_error_hit; | ||||
| 61911 | static int saved_cnt; | ||||
| 61912 | void disable_simulated_io_errors(void){ | ||||
| 61913 | saved_cnt = sqlite3_io_error_pending; | ||||
| 61914 | sqlite3_io_error_pending = -1; | ||||
| 61915 | } | ||||
| 61916 | void enable_simulated_io_errors(void){ | ||||
| 61917 | sqlite3_io_error_pending = saved_cnt; | ||||
| 61918 | } | ||||
| 61919 | #else | ||||
| 61920 | # define disable_simulated_io_errors() | ||||
| 61921 | # define enable_simulated_io_errors() | ||||
| 61922 | #endif | ||||
| 61923 | |||||
| 61924 | /* | ||||
| 61925 | ** Read the first N bytes from the beginning of the file into memory | ||||
| 61926 | ** that pDest points to. | ||||
| 61927 | ** | ||||
| 61928 | ** If the pager was opened on a transient file (zFilename==""), or | ||||
| 61929 | ** opened on a file less than N bytes in size, the output buffer is | ||||
| 61930 | ** zeroed and SQLITE_OK returned. The rationale for this is that this | ||||
| 61931 | ** function is used to read database headers, and a new transient or | ||||
| 61932 | ** zero sized database has a header than consists entirely of zeroes. | ||||
| 61933 | ** | ||||
| 61934 | ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, | ||||
| 61935 | ** the error code is returned to the caller and the contents of the | ||||
| 61936 | ** output buffer undefined. | ||||
| 61937 | */ | ||||
| 61938 | SQLITE_PRIVATEstatic int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ | ||||
| 61939 | int rc = SQLITE_OK0; | ||||
| 61940 | memset(pDest, 0, N); | ||||
| 61941 | assert( isOpen(pPager->fd) || pPager->tempFile )((void) (0)); | ||||
| 61942 | |||||
| 61943 | /* This routine is only called by btree immediately after creating | ||||
| 61944 | ** the Pager object. There has not been an opportunity to transition | ||||
| 61945 | ** to WAL mode yet. | ||||
| 61946 | */ | ||||
| 61947 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 61948 | |||||
| 61949 | if( isOpen(pPager->fd)((pPager->fd)->pMethods!=0) ){ | ||||
| 61950 | IOTRACE(("DBHDR %p 0 %d\n", pPager, N)) | ||||
| 61951 | rc = sqlite3OsRead(pPager->fd, pDest, N, 0); | ||||
| 61952 | if( rc==SQLITE_IOERR_SHORT_READ(10 | (2<<8)) ){ | ||||
| 61953 | rc = SQLITE_OK0; | ||||
| 61954 | } | ||||
| 61955 | } | ||||
| 61956 | return rc; | ||||
| 61957 | } | ||||
| 61958 | |||||
| 61959 | /* | ||||
| 61960 | ** This function may only be called when a read-transaction is open on | ||||
| 61961 | ** the pager. It returns the total number of pages in the database. | ||||
| 61962 | ** | ||||
| 61963 | ** However, if the file is between 1 and <page-size> bytes in size, then | ||||
| 61964 | ** this is considered a 1 page file. | ||||
| 61965 | */ | ||||
| 61966 | SQLITE_PRIVATEstatic void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ | ||||
| 61967 | assert( pPager->eState>=PAGER_READER )((void) (0)); | ||||
| 61968 | assert( pPager->eState!=PAGER_WRITER_FINISHED )((void) (0)); | ||||
| 61969 | *pnPage = (int)pPager->dbSize; | ||||
| 61970 | } | ||||
| 61971 | |||||
| 61972 | |||||
| 61973 | /* | ||||
| 61974 | ** Try to obtain a lock of type locktype on the database file. If | ||||
| 61975 | ** a similar or greater lock is already held, this function is a no-op | ||||
| 61976 | ** (returning SQLITE_OK immediately). | ||||
| 61977 | ** | ||||
| 61978 | ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke | ||||
| 61979 | ** the busy callback if the lock is currently not available. Repeat | ||||
| 61980 | ** until the busy callback returns false or until the attempt to | ||||
| 61981 | ** obtain the lock succeeds. | ||||
| 61982 | ** | ||||
| 61983 | ** Return SQLITE_OK on success and an error code if we cannot obtain | ||||
| 61984 | ** the lock. If the lock is obtained successfully, set the Pager.state | ||||
| 61985 | ** variable to locktype before returning. | ||||
| 61986 | */ | ||||
| 61987 | static int pager_wait_on_lock(Pager *pPager, int locktype){ | ||||
| 61988 | int rc; /* Return code */ | ||||
| 61989 | |||||
| 61990 | /* Check that this is either a no-op (because the requested lock is | ||||
| 61991 | ** already held), or one of the transitions that the busy-handler | ||||
| 61992 | ** may be invoked during, according to the comment above | ||||
| 61993 | ** sqlite3PagerSetBusyhandler(). | ||||
| 61994 | */ | ||||
| 61995 | assert( (pPager->eLock>=locktype)((void) (0)) | ||||
| 61996 | || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)((void) (0)) | ||||
| 61997 | || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)((void) (0)) | ||||
| 61998 | )((void) (0)); | ||||
| 61999 | |||||
| 62000 | do { | ||||
| 62001 | rc = pagerLockDb(pPager, locktype); | ||||
| 62002 | }while( rc==SQLITE_BUSY5 && pPager->xBusyHandler(pPager->pBusyHandlerArg) ); | ||||
| 62003 | return rc; | ||||
| 62004 | } | ||||
| 62005 | |||||
| 62006 | /* | ||||
| 62007 | ** Function assertTruncateConstraint(pPager) checks that one of the | ||||
| 62008 | ** following is true for all dirty pages currently in the page-cache: | ||||
| 62009 | ** | ||||
| 62010 | ** a) The page number is less than or equal to the size of the | ||||
| 62011 | ** current database image, in pages, OR | ||||
| 62012 | ** | ||||
| 62013 | ** b) if the page content were written at this time, it would not | ||||
| 62014 | ** be necessary to write the current content out to the sub-journal. | ||||
| 62015 | ** | ||||
| 62016 | ** If the condition asserted by this function were not true, and the | ||||
| 62017 | ** dirty page were to be discarded from the cache via the pagerStress() | ||||
| 62018 | ** routine, pagerStress() would not write the current page content to | ||||
| 62019 | ** the database file. If a savepoint transaction were rolled back after | ||||
| 62020 | ** this happened, the correct behavior would be to restore the current | ||||
| 62021 | ** content of the page. However, since this content is not present in either | ||||
| 62022 | ** the database file or the portion of the rollback journal and | ||||
| 62023 | ** sub-journal rolled back the content could not be restored and the | ||||
| 62024 | ** database image would become corrupt. It is therefore fortunate that | ||||
| 62025 | ** this circumstance cannot arise. | ||||
| 62026 | */ | ||||
| 62027 | #if defined(SQLITE_DEBUG) | ||||
| 62028 | static void assertTruncateConstraintCb(PgHdr *pPg){ | ||||
| 62029 | Pager *pPager = pPg->pPager; | ||||
| 62030 | assert( pPg->flags&PGHDR_DIRTY )((void) (0)); | ||||
| 62031 | if( pPg->pgno>pPager->dbSize ){ /* if (a) is false */ | ||||
| 62032 | Pgno pgno = pPg->pgno; | ||||
| 62033 | int i; | ||||
| 62034 | for(i=0; i<pPg->pPager->nSavepoint; i++){ | ||||
| 62035 | PagerSavepoint *p = &pPager->aSavepoint[i]; | ||||
| 62036 | assert( p->nOrig<pgno || sqlite3BitvecTestNotNull(p->pInSavepoint,pgno) )((void) (0)); | ||||
| 62037 | } | ||||
| 62038 | } | ||||
| 62039 | } | ||||
| 62040 | static void assertTruncateConstraint(Pager *pPager){ | ||||
| 62041 | sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); | ||||
| 62042 | } | ||||
| 62043 | #else | ||||
| 62044 | # define assertTruncateConstraint(pPager) | ||||
| 62045 | #endif | ||||
| 62046 | |||||
| 62047 | /* | ||||
| 62048 | ** Truncate the in-memory database file image to nPage pages. This | ||||
| 62049 | ** function does not actually modify the database file on disk. It | ||||
| 62050 | ** just sets the internal state of the pager object so that the | ||||
| 62051 | ** truncation will be done when the current transaction is committed. | ||||
| 62052 | ** | ||||
| 62053 | ** This function is only called right before committing a transaction. | ||||
| 62054 | ** Once this function has been called, the transaction must either be | ||||
| 62055 | ** rolled back or committed. It is not safe to call this function and | ||||
| 62056 | ** then continue writing to the database. | ||||
| 62057 | */ | ||||
| 62058 | SQLITE_PRIVATEstatic void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ | ||||
| 62059 | assert( pPager->dbSize>=nPage || CORRUPT_DB )((void) (0)); | ||||
| 62060 | assert( pPager->eState>=PAGER_WRITER_CACHEMOD )((void) (0)); | ||||
| 62061 | pPager->dbSize = nPage; | ||||
| 62062 | |||||
| 62063 | /* At one point the code here called assertTruncateConstraint() to | ||||
| 62064 | ** ensure that all pages being truncated away by this operation are, | ||||
| 62065 | ** if one or more savepoints are open, present in the savepoint | ||||
| 62066 | ** journal so that they can be restored if the savepoint is rolled | ||||
| 62067 | ** back. This is no longer necessary as this function is now only | ||||
| 62068 | ** called right before committing a transaction. So although the | ||||
| 62069 | ** Pager object may still have open savepoints (Pager.nSavepoint!=0), | ||||
| 62070 | ** they cannot be rolled back. So the assertTruncateConstraint() call | ||||
| 62071 | ** is no longer correct. */ | ||||
| 62072 | } | ||||
| 62073 | |||||
| 62074 | |||||
| 62075 | /* | ||||
| 62076 | ** This function is called before attempting a hot-journal rollback. It | ||||
| 62077 | ** syncs the journal file to disk, then sets pPager->journalHdr to the | ||||
| 62078 | ** size of the journal file so that the pager_playback() routine knows | ||||
| 62079 | ** that the entire journal file has been synced. | ||||
| 62080 | ** | ||||
| 62081 | ** Syncing a hot-journal to disk before attempting to roll it back ensures | ||||
| 62082 | ** that if a power-failure occurs during the rollback, the process that | ||||
| 62083 | ** attempts rollback following system recovery sees the same journal | ||||
| 62084 | ** content as this process. | ||||
| 62085 | ** | ||||
| 62086 | ** If everything goes as planned, SQLITE_OK is returned. Otherwise, | ||||
| 62087 | ** an SQLite error code. | ||||
| 62088 | */ | ||||
| 62089 | static int pagerSyncHotJournal(Pager *pPager){ | ||||
| 62090 | int rc = SQLITE_OK0; | ||||
| 62091 | if( !pPager->noSync ){ | ||||
| 62092 | rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL0x00002); | ||||
| 62093 | } | ||||
| 62094 | if( rc==SQLITE_OK0 ){ | ||||
| 62095 | rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); | ||||
| 62096 | } | ||||
| 62097 | return rc; | ||||
| 62098 | } | ||||
| 62099 | |||||
| 62100 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 62101 | /* | ||||
| 62102 | ** Obtain a reference to a memory mapped page object for page number pgno. | ||||
| 62103 | ** The new object will use the pointer pData, obtained from xFetch(). | ||||
| 62104 | ** If successful, set *ppPage to point to the new page reference | ||||
| 62105 | ** and return SQLITE_OK. Otherwise, return an SQLite error code and set | ||||
| 62106 | ** *ppPage to zero. | ||||
| 62107 | ** | ||||
| 62108 | ** Page references obtained by calling this function should be released | ||||
| 62109 | ** by calling pagerReleaseMapPage(). | ||||
| 62110 | */ | ||||
| 62111 | static int pagerAcquireMapPage( | ||||
| 62112 | Pager *pPager, /* Pager object */ | ||||
| 62113 | Pgno pgno, /* Page number */ | ||||
| 62114 | void *pData, /* xFetch()'d data for this page */ | ||||
| 62115 | PgHdr **ppPage /* OUT: Acquired page object */ | ||||
| 62116 | ){ | ||||
| 62117 | PgHdr *p; /* Memory mapped page to return */ | ||||
| 62118 | |||||
| 62119 | if( pPager->pMmapFreelist ){ | ||||
| 62120 | *ppPage = p = pPager->pMmapFreelist; | ||||
| 62121 | pPager->pMmapFreelist = p->pDirty; | ||||
| 62122 | p->pDirty = 0; | ||||
| 62123 | assert( pPager->nExtra>=8 )((void) (0)); | ||||
| 62124 | memset(p->pExtra, 0, 8); | ||||
| 62125 | }else{ | ||||
| 62126 | *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); | ||||
| 62127 | if( p==0 ){ | ||||
| 62128 | sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); | ||||
| 62129 | return SQLITE_NOMEM_BKPT7; | ||||
| 62130 | } | ||||
| 62131 | p->pExtra = (void *)&p[1]; | ||||
| 62132 | assert( EIGHT_BYTE_ALIGNMENT( p->pExtra ) )((void) (0)); | ||||
| 62133 | p->flags = PGHDR_MMAP0x020; | ||||
| 62134 | p->nRef = 1; | ||||
| 62135 | p->pPager = pPager; | ||||
| 62136 | } | ||||
| 62137 | |||||
| 62138 | assert( p->pExtra==(void *)&p[1] )((void) (0)); | ||||
| 62139 | assert( p->pPage==0 )((void) (0)); | ||||
| 62140 | assert( p->flags==PGHDR_MMAP )((void) (0)); | ||||
| 62141 | assert( p->pPager==pPager )((void) (0)); | ||||
| 62142 | assert( p->nRef==1 )((void) (0)); | ||||
| 62143 | |||||
| 62144 | p->pgno = pgno; | ||||
| 62145 | p->pData = pData; | ||||
| 62146 | pPager->nMmapOut++; | ||||
| 62147 | |||||
| 62148 | return SQLITE_OK0; | ||||
| 62149 | } | ||||
| 62150 | #endif | ||||
| 62151 | |||||
| 62152 | /* | ||||
| 62153 | ** Release a reference to page pPg. pPg must have been returned by an | ||||
| 62154 | ** earlier call to pagerAcquireMapPage(). | ||||
| 62155 | */ | ||||
| 62156 | static void pagerReleaseMapPage(PgHdr *pPg){ | ||||
| 62157 | Pager *pPager = pPg->pPager; | ||||
| 62158 | pPager->nMmapOut--; | ||||
| 62159 | pPg->pDirty = pPager->pMmapFreelist; | ||||
| 62160 | pPager->pMmapFreelist = pPg; | ||||
| 62161 | |||||
| 62162 | assert( pPager->fd->pMethods->iVersion>=3 )((void) (0)); | ||||
| 62163 | sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); | ||||
| 62164 | } | ||||
| 62165 | |||||
| 62166 | /* | ||||
| 62167 | ** Free all PgHdr objects stored in the Pager.pMmapFreelist list. | ||||
| 62168 | */ | ||||
| 62169 | static void pagerFreeMapHdrs(Pager *pPager){ | ||||
| 62170 | PgHdr *p; | ||||
| 62171 | PgHdr *pNext; | ||||
| 62172 | for(p=pPager->pMmapFreelist; p; p=pNext){ | ||||
| 62173 | pNext = p->pDirty; | ||||
| 62174 | sqlite3_free(p); | ||||
| 62175 | } | ||||
| 62176 | } | ||||
| 62177 | |||||
| 62178 | /* Verify that the database file has not be deleted or renamed out from | ||||
| 62179 | ** under the pager. Return SQLITE_OK if the database is still where it ought | ||||
| 62180 | ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error | ||||
| 62181 | ** code from sqlite3OsAccess()) if the database has gone missing. | ||||
| 62182 | */ | ||||
| 62183 | static int databaseIsUnmoved(Pager *pPager){ | ||||
| 62184 | int bHasMoved = 0; | ||||
| 62185 | int rc; | ||||
| 62186 | |||||
| 62187 | if( pPager->tempFile ) return SQLITE_OK0; | ||||
| 62188 | if( pPager->dbSize==0 ) return SQLITE_OK0; | ||||
| 62189 | assert( pPager->zFilename && pPager->zFilename[0] )((void) (0)); | ||||
| 62190 | rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED20, &bHasMoved); | ||||
| 62191 | if( rc==SQLITE_NOTFOUND12 ){ | ||||
| 62192 | /* If the HAS_MOVED file-control is unimplemented, assume that the file | ||||
| 62193 | ** has not been moved. That is the historical behavior of SQLite: prior to | ||||
| 62194 | ** version 3.8.3, it never checked */ | ||||
| 62195 | rc = SQLITE_OK0; | ||||
| 62196 | }else if( rc==SQLITE_OK0 && bHasMoved ){ | ||||
| 62197 | rc = SQLITE_READONLY_DBMOVED(8 | (4<<8)); | ||||
| 62198 | } | ||||
| 62199 | return rc; | ||||
| 62200 | } | ||||
| 62201 | |||||
| 62202 | |||||
| 62203 | /* | ||||
| 62204 | ** Shutdown the page cache. Free all memory and close all files. | ||||
| 62205 | ** | ||||
| 62206 | ** If a transaction was in progress when this routine is called, that | ||||
| 62207 | ** transaction is rolled back. All outstanding pages are invalidated | ||||
| 62208 | ** and their memory is freed. Any attempt to use a page associated | ||||
| 62209 | ** with this page cache after this function returns will likely | ||||
| 62210 | ** result in a coredump. | ||||
| 62211 | ** | ||||
| 62212 | ** This function always succeeds. If a transaction is active an attempt | ||||
| 62213 | ** is made to roll it back. If an error occurs during the rollback | ||||
| 62214 | ** a hot journal may be left in the filesystem but no error is returned | ||||
| 62215 | ** to the caller. | ||||
| 62216 | */ | ||||
| 62217 | SQLITE_PRIVATEstatic int sqlite3PagerClose(Pager *pPager, sqlite3 *db){ | ||||
| 62218 | u8 *pTmp = (u8*)pPager->pTmpSpace; | ||||
| 62219 | assert( db || pagerUseWal(pPager)==0 )((void) (0)); | ||||
| 62220 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 62221 | disable_simulated_io_errors(); | ||||
| 62222 | sqlite3BeginBenignMalloc(); | ||||
| 62223 | pagerFreeMapHdrs(pPager); | ||||
| 62224 | /* pPager->errCode = 0; */ | ||||
| 62225 | pPager->exclusiveMode = 0; | ||||
| 62226 | #ifndef SQLITE_OMIT_WAL | ||||
| 62227 | { | ||||
| 62228 | u8 *a = 0; | ||||
| 62229 | assert( db || pPager->pWal==0 )((void) (0)); | ||||
| 62230 | if( db && 0==(db->flags & SQLITE_NoCkptOnClose0x00000800) | ||||
| 62231 | && SQLITE_OK0==databaseIsUnmoved(pPager) | ||||
| 62232 | ){ | ||||
| 62233 | a = pTmp; | ||||
| 62234 | } | ||||
| 62235 | sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a); | ||||
| 62236 | pPager->pWal = 0; | ||||
| 62237 | } | ||||
| 62238 | #endif | ||||
| 62239 | pager_reset(pPager); | ||||
| 62240 | if( MEMDBpPager->memDb ){ | ||||
| 62241 | pager_unlock(pPager); | ||||
| 62242 | }else{ | ||||
| 62243 | /* If it is open, sync the journal file before calling UnlockAndRollback. | ||||
| 62244 | ** If this is not done, then an unsynced portion of the open journal | ||||
| 62245 | ** file may be played back into the database. If a power failure occurs | ||||
| 62246 | ** while this is happening, the database could become corrupt. | ||||
| 62247 | ** | ||||
| 62248 | ** If an error occurs while trying to sync the journal, shift the pager | ||||
| 62249 | ** into the ERROR state. This causes UnlockAndRollback to unlock the | ||||
| 62250 | ** database and close the journal file without attempting to roll it | ||||
| 62251 | ** back or finalize it. The next database user will have to do hot-journal | ||||
| 62252 | ** rollback before accessing the database file. | ||||
| 62253 | */ | ||||
| 62254 | if( isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) ){ | ||||
| 62255 | pager_error(pPager, pagerSyncHotJournal(pPager)); | ||||
| 62256 | } | ||||
| 62257 | pagerUnlockAndRollback(pPager); | ||||
| 62258 | } | ||||
| 62259 | sqlite3EndBenignMalloc(); | ||||
| 62260 | enable_simulated_io_errors(); | ||||
| 62261 | PAGERTRACE(("CLOSE %d\n", PAGERID(pPager))); | ||||
| 62262 | IOTRACE(("CLOSE %p\n", pPager)) | ||||
| 62263 | sqlite3OsClose(pPager->jfd); | ||||
| 62264 | sqlite3OsClose(pPager->fd); | ||||
| 62265 | sqlite3PageFree(pTmp); | ||||
| 62266 | sqlite3PcacheClose(pPager->pPCache); | ||||
| 62267 | assert( !pPager->aSavepoint && !pPager->pInJournal )((void) (0)); | ||||
| 62268 | assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) )((void) (0)); | ||||
| 62269 | |||||
| 62270 | sqlite3_free(pPager); | ||||
| 62271 | return SQLITE_OK0; | ||||
| 62272 | } | ||||
| 62273 | |||||
| 62274 | #if !defined(NDEBUG1) || defined(SQLITE_TEST) | ||||
| 62275 | /* | ||||
| 62276 | ** Return the page number for page pPg. | ||||
| 62277 | */ | ||||
| 62278 | SQLITE_PRIVATEstatic Pgno sqlite3PagerPagenumber(DbPage *pPg){ | ||||
| 62279 | return pPg->pgno; | ||||
| 62280 | } | ||||
| 62281 | #endif | ||||
| 62282 | |||||
| 62283 | /* | ||||
| 62284 | ** Increment the reference count for page pPg. | ||||
| 62285 | */ | ||||
| 62286 | SQLITE_PRIVATEstatic void sqlite3PagerRef(DbPage *pPg){ | ||||
| 62287 | sqlite3PcacheRef(pPg); | ||||
| 62288 | } | ||||
| 62289 | |||||
| 62290 | /* | ||||
| 62291 | ** Sync the journal. In other words, make sure all the pages that have | ||||
| 62292 | ** been written to the journal have actually reached the surface of the | ||||
| 62293 | ** disk and can be restored in the event of a hot-journal rollback. | ||||
| 62294 | ** | ||||
| 62295 | ** If the Pager.noSync flag is set, then this function is a no-op. | ||||
| 62296 | ** Otherwise, the actions required depend on the journal-mode and the | ||||
| 62297 | ** device characteristics of the file-system, as follows: | ||||
| 62298 | ** | ||||
| 62299 | ** * If the journal file is an in-memory journal file, no action need | ||||
| 62300 | ** be taken. | ||||
| 62301 | ** | ||||
| 62302 | ** * Otherwise, if the device does not support the SAFE_APPEND property, | ||||
| 62303 | ** then the nRec field of the most recently written journal header | ||||
| 62304 | ** is updated to contain the number of journal records that have | ||||
| 62305 | ** been written following it. If the pager is operating in full-sync | ||||
| 62306 | ** mode, then the journal file is synced before this field is updated. | ||||
| 62307 | ** | ||||
| 62308 | ** * If the device does not support the SEQUENTIAL property, then | ||||
| 62309 | ** journal file is synced. | ||||
| 62310 | ** | ||||
| 62311 | ** Or, in pseudo-code: | ||||
| 62312 | ** | ||||
| 62313 | ** if( NOT <in-memory journal> ){ | ||||
| 62314 | ** if( NOT SAFE_APPEND ){ | ||||
| 62315 | ** if( <full-sync mode> ) xSync(<journal file>); | ||||
| 62316 | ** <update nRec field> | ||||
| 62317 | ** } | ||||
| 62318 | ** if( NOT SEQUENTIAL ) xSync(<journal file>); | ||||
| 62319 | ** } | ||||
| 62320 | ** | ||||
| 62321 | ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every | ||||
| 62322 | ** page currently held in memory before returning SQLITE_OK. If an IO | ||||
| 62323 | ** error is encountered, then the IO error code is returned to the caller. | ||||
| 62324 | */ | ||||
| 62325 | static int syncJournal(Pager *pPager, int newHdr){ | ||||
| 62326 | int rc; /* Return code */ | ||||
| 62327 | |||||
| 62328 | assert( pPager->eState==PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 62329 | || pPager->eState==PAGER_WRITER_DBMOD((void) (0)) | ||||
| 62330 | )((void) (0)); | ||||
| 62331 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 62332 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 62333 | |||||
| 62334 | rc = sqlite3PagerExclusiveLock(pPager); | ||||
| 62335 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 62336 | |||||
| 62337 | if( !pPager->noSync ){ | ||||
| 62338 | assert( !pPager->tempFile )((void) (0)); | ||||
| 62339 | if( isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY4 ){ | ||||
| 62340 | const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); | ||||
| 62341 | assert( isOpen(pPager->jfd) )((void) (0)); | ||||
| 62342 | |||||
| 62343 | if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND0x00000200) ){ | ||||
| 62344 | /* This block deals with an obscure problem. If the last connection | ||||
| 62345 | ** that wrote to this database was operating in persistent-journal | ||||
| 62346 | ** mode, then the journal file may at this point actually be larger | ||||
| 62347 | ** than Pager.journalOff bytes. If the next thing in the journal | ||||
| 62348 | ** file happens to be a journal-header (written as part of the | ||||
| 62349 | ** previous connection's transaction), and a crash or power-failure | ||||
| 62350 | ** occurs after nRec is updated but before this connection writes | ||||
| 62351 | ** anything else to the journal file (or commits/rolls back its | ||||
| 62352 | ** transaction), then SQLite may become confused when doing the | ||||
| 62353 | ** hot-journal rollback following recovery. It may roll back all | ||||
| 62354 | ** of this connections data, then proceed to rolling back the old, | ||||
| 62355 | ** out-of-date data that follows it. Database corruption. | ||||
| 62356 | ** | ||||
| 62357 | ** To work around this, if the journal file does appear to contain | ||||
| 62358 | ** a valid header following Pager.journalOff, then write a 0x00 | ||||
| 62359 | ** byte to the start of it to prevent it from being recognized. | ||||
| 62360 | ** | ||||
| 62361 | ** Variable iNextHdrOffset is set to the offset at which this | ||||
| 62362 | ** problematic header will occur, if it exists. aMagic is used | ||||
| 62363 | ** as a temporary buffer to inspect the first couple of bytes of | ||||
| 62364 | ** the potential journal header. | ||||
| 62365 | */ | ||||
| 62366 | i64 iNextHdrOffset; | ||||
| 62367 | u8 aMagic[8]; | ||||
| 62368 | u8 zHeader[sizeof(aJournalMagic)+4]; | ||||
| 62369 | |||||
| 62370 | memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); | ||||
| 62371 | put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec)sqlite3Put4byte((u8*)&zHeader[sizeof(aJournalMagic)],pPager ->nRec); | ||||
| 62372 | |||||
| 62373 | iNextHdrOffset = journalHdrOffset(pPager); | ||||
| 62374 | rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); | ||||
| 62375 | if( rc==SQLITE_OK0 && 0==memcmp(aMagic, aJournalMagic, 8) ){ | ||||
| 62376 | static const u8 zerobyte = 0; | ||||
| 62377 | rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); | ||||
| 62378 | } | ||||
| 62379 | if( rc!=SQLITE_OK0 && rc!=SQLITE_IOERR_SHORT_READ(10 | (2<<8)) ){ | ||||
| 62380 | return rc; | ||||
| 62381 | } | ||||
| 62382 | |||||
| 62383 | /* Write the nRec value into the journal file header. If in | ||||
| 62384 | ** full-synchronous mode, sync the journal first. This ensures that | ||||
| 62385 | ** all data has really hit the disk before nRec is updated to mark | ||||
| 62386 | ** it as a candidate for rollback. | ||||
| 62387 | ** | ||||
| 62388 | ** This is not required if the persistent media supports the | ||||
| 62389 | ** SAFE_APPEND property. Because in this case it is not possible | ||||
| 62390 | ** for garbage data to be appended to the file, the nRec field | ||||
| 62391 | ** is populated with 0xFFFFFFFF when the journal header is written | ||||
| 62392 | ** and never needs to be updated. | ||||
| 62393 | */ | ||||
| 62394 | if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL0x00000400) ){ | ||||
| 62395 | PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); | ||||
| 62396 | IOTRACE(("JSYNC %p\n", pPager)) | ||||
| 62397 | rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); | ||||
| 62398 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 62399 | } | ||||
| 62400 | IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr)); | ||||
| 62401 | rc = sqlite3OsWrite( | ||||
| 62402 | pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr | ||||
| 62403 | ); | ||||
| 62404 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 62405 | } | ||||
| 62406 | if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL0x00000400) ){ | ||||
| 62407 | PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); | ||||
| 62408 | IOTRACE(("JSYNC %p\n", pPager)) | ||||
| 62409 | rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| | ||||
| 62410 | (pPager->syncFlags==SQLITE_SYNC_FULL0x00003?SQLITE_SYNC_DATAONLY0x00010:0) | ||||
| 62411 | ); | ||||
| 62412 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 62413 | } | ||||
| 62414 | |||||
| 62415 | pPager->journalHdr = pPager->journalOff; | ||||
| 62416 | if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND0x00000200) ){ | ||||
| 62417 | pPager->nRec = 0; | ||||
| 62418 | rc = writeJournalHdr(pPager); | ||||
| 62419 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 62420 | } | ||||
| 62421 | }else{ | ||||
| 62422 | pPager->journalHdr = pPager->journalOff; | ||||
| 62423 | } | ||||
| 62424 | } | ||||
| 62425 | |||||
| 62426 | /* Unless the pager is in noSync mode, the journal file was just | ||||
| 62427 | ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on | ||||
| 62428 | ** all pages. | ||||
| 62429 | */ | ||||
| 62430 | sqlite3PcacheClearSyncFlags(pPager->pPCache); | ||||
| 62431 | pPager->eState = PAGER_WRITER_DBMOD4; | ||||
| 62432 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 62433 | return SQLITE_OK0; | ||||
| 62434 | } | ||||
| 62435 | |||||
| 62436 | /* | ||||
| 62437 | ** The argument is the first in a linked list of dirty pages connected | ||||
| 62438 | ** by the PgHdr.pDirty pointer. This function writes each one of the | ||||
| 62439 | ** in-memory pages in the list to the database file. The argument may | ||||
| 62440 | ** be NULL, representing an empty list. In this case this function is | ||||
| 62441 | ** a no-op. | ||||
| 62442 | ** | ||||
| 62443 | ** The pager must hold at least a RESERVED lock when this function | ||||
| 62444 | ** is called. Before writing anything to the database file, this lock | ||||
| 62445 | ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, | ||||
| 62446 | ** SQLITE_BUSY is returned and no data is written to the database file. | ||||
| 62447 | ** | ||||
| 62448 | ** If the pager is a temp-file pager and the actual file-system file | ||||
| 62449 | ** is not yet open, it is created and opened before any data is | ||||
| 62450 | ** written out. | ||||
| 62451 | ** | ||||
| 62452 | ** Once the lock has been upgraded and, if necessary, the file opened, | ||||
| 62453 | ** the pages are written out to the database file in list order. Writing | ||||
| 62454 | ** a page is skipped if it meets either of the following criteria: | ||||
| 62455 | ** | ||||
| 62456 | ** * The page number is greater than Pager.dbSize, or | ||||
| 62457 | ** * The PGHDR_DONT_WRITE flag is set on the page. | ||||
| 62458 | ** | ||||
| 62459 | ** If writing out a page causes the database file to grow, Pager.dbFileSize | ||||
| 62460 | ** is updated accordingly. If page 1 is written out, then the value cached | ||||
| 62461 | ** in Pager.dbFileVers[] is updated to match the new value stored in | ||||
| 62462 | ** the database file. | ||||
| 62463 | ** | ||||
| 62464 | ** If everything is successful, SQLITE_OK is returned. If an IO error | ||||
| 62465 | ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot | ||||
| 62466 | ** be obtained, SQLITE_BUSY is returned. | ||||
| 62467 | */ | ||||
| 62468 | static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ | ||||
| 62469 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 62470 | |||||
| 62471 | /* This function is only called for rollback pagers in WRITER_DBMOD state. */ | ||||
| 62472 | assert( !pagerUseWal(pPager) )((void) (0)); | ||||
| 62473 | assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD )((void) (0)); | ||||
| 62474 | assert( pPager->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 62475 | assert( isOpen(pPager->fd) || pList->pDirty==0 )((void) (0)); | ||||
| 62476 | |||||
| 62477 | /* If the file is a temp-file has not yet been opened, open it now. It | ||||
| 62478 | ** is not possible for rc to be other than SQLITE_OK if this branch | ||||
| 62479 | ** is taken, as pager_wait_on_lock() is a no-op for temp-files. | ||||
| 62480 | */ | ||||
| 62481 | if( !isOpen(pPager->fd)((pPager->fd)->pMethods!=0) ){ | ||||
| 62482 | assert( pPager->tempFile && rc==SQLITE_OK )((void) (0)); | ||||
| 62483 | rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags); | ||||
| 62484 | } | ||||
| 62485 | |||||
| 62486 | /* Before the first write, give the VFS a hint of what the final | ||||
| 62487 | ** file size will be. | ||||
| 62488 | */ | ||||
| 62489 | assert( rc!=SQLITE_OK || isOpen(pPager->fd) )((void) (0)); | ||||
| 62490 | if( rc==SQLITE_OK0 | ||||
| 62491 | && pPager->dbHintSize<pPager->dbSize | ||||
| 62492 | && (pList->pDirty || pList->pgno>pPager->dbHintSize) | ||||
| 62493 | ){ | ||||
| 62494 | sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize; | ||||
| 62495 | sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT5, &szFile); | ||||
| 62496 | pPager->dbHintSize = pPager->dbSize; | ||||
| 62497 | } | ||||
| 62498 | |||||
| 62499 | while( rc==SQLITE_OK0 && pList ){ | ||||
| 62500 | Pgno pgno = pList->pgno; | ||||
| 62501 | |||||
| 62502 | /* If there are dirty pages in the page cache with page numbers greater | ||||
| 62503 | ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to | ||||
| 62504 | ** make the file smaller (presumably by auto-vacuum code). Do not write | ||||
| 62505 | ** any such pages to the file. | ||||
| 62506 | ** | ||||
| 62507 | ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag | ||||
| 62508 | ** set (set by sqlite3PagerDontWrite()). | ||||
| 62509 | */ | ||||
| 62510 | if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE0x010) ){ | ||||
| 62511 | i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ | ||||
| 62512 | char *pData; /* Data to write */ | ||||
| 62513 | |||||
| 62514 | assert( (pList->flags&PGHDR_NEED_SYNC)==0 )((void) (0)); | ||||
| 62515 | if( pList->pgno==1 ) pager_write_changecounter(pList); | ||||
| 62516 | |||||
| 62517 | pData = pList->pData; | ||||
| 62518 | |||||
| 62519 | /* Write out the page data. */ | ||||
| 62520 | rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); | ||||
| 62521 | |||||
| 62522 | /* If page 1 was just written, update Pager.dbFileVers to match | ||||
| 62523 | ** the value now stored in the database file. If writing this | ||||
| 62524 | ** page caused the database file to grow, update dbFileSize. | ||||
| 62525 | */ | ||||
| 62526 | if( pgno==1 ){ | ||||
| 62527 | memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); | ||||
| 62528 | } | ||||
| 62529 | if( pgno>pPager->dbFileSize ){ | ||||
| 62530 | pPager->dbFileSize = pgno; | ||||
| 62531 | } | ||||
| 62532 | pPager->aStat[PAGER_STAT_WRITE2]++; | ||||
| 62533 | |||||
| 62534 | /* Update any backup objects copying the contents of this pager. */ | ||||
| 62535 | sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); | ||||
| 62536 | |||||
| 62537 | PAGERTRACE(("STORE %d page %d hash(%08x)\n", | ||||
| 62538 | PAGERID(pPager), pgno, pager_pagehash(pList))); | ||||
| 62539 | IOTRACE(("PGOUT %p %d\n", pPager, pgno)); | ||||
| 62540 | PAGER_INCR(sqlite3_pager_writedb_count); | ||||
| 62541 | }else{ | ||||
| 62542 | PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno)); | ||||
| 62543 | } | ||||
| 62544 | pager_set_pagehash(pList); | ||||
| 62545 | pList = pList->pDirty; | ||||
| 62546 | } | ||||
| 62547 | |||||
| 62548 | return rc; | ||||
| 62549 | } | ||||
| 62550 | |||||
| 62551 | /* | ||||
| 62552 | ** Ensure that the sub-journal file is open. If it is already open, this | ||||
| 62553 | ** function is a no-op. | ||||
| 62554 | ** | ||||
| 62555 | ** SQLITE_OK is returned if everything goes according to plan. An | ||||
| 62556 | ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() | ||||
| 62557 | ** fails. | ||||
| 62558 | */ | ||||
| 62559 | static int openSubJournal(Pager *pPager){ | ||||
| 62560 | int rc = SQLITE_OK0; | ||||
| 62561 | if( !isOpen(pPager->sjfd)((pPager->sjfd)->pMethods!=0) ){ | ||||
| 62562 | const int flags = SQLITE_OPEN_SUBJOURNAL0x00002000 | SQLITE_OPEN_READWRITE0x00000002 | ||||
| 62563 | | SQLITE_OPEN_CREATE0x00000004 | SQLITE_OPEN_EXCLUSIVE0x00000010 | ||||
| 62564 | | SQLITE_OPEN_DELETEONCLOSE0x00000008; | ||||
| 62565 | int nStmtSpill = sqlite3Config.nStmtSpill; | ||||
| 62566 | if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY4 || pPager->subjInMemory ){ | ||||
| 62567 | nStmtSpill = -1; | ||||
| 62568 | } | ||||
| 62569 | rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill); | ||||
| 62570 | } | ||||
| 62571 | return rc; | ||||
| 62572 | } | ||||
| 62573 | |||||
| 62574 | /* | ||||
| 62575 | ** Append a record of the current state of page pPg to the sub-journal. | ||||
| 62576 | ** | ||||
| 62577 | ** If successful, set the bit corresponding to pPg->pgno in the bitvecs | ||||
| 62578 | ** for all open savepoints before returning. | ||||
| 62579 | ** | ||||
| 62580 | ** This function returns SQLITE_OK if everything is successful, an IO | ||||
| 62581 | ** error code if the attempt to write to the sub-journal fails, or | ||||
| 62582 | ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint | ||||
| 62583 | ** bitvec. | ||||
| 62584 | */ | ||||
| 62585 | static int subjournalPage(PgHdr *pPg){ | ||||
| 62586 | int rc = SQLITE_OK0; | ||||
| 62587 | Pager *pPager = pPg->pPager; | ||||
| 62588 | if( pPager->journalMode!=PAGER_JOURNALMODE_OFF2 ){ | ||||
| 62589 | |||||
| 62590 | /* Open the sub-journal, if it has not already been opened */ | ||||
| 62591 | assert( pPager->useJournal )((void) (0)); | ||||
| 62592 | assert( isOpen(pPager->jfd) || pagerUseWal(pPager) )((void) (0)); | ||||
| 62593 | assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 )((void) (0)); | ||||
| 62594 | assert( pagerUseWal(pPager)((void) (0)) | ||||
| 62595 | || pageInJournal(pPager, pPg)((void) (0)) | ||||
| 62596 | || pPg->pgno>pPager->dbOrigSize((void) (0)) | ||||
| 62597 | )((void) (0)); | ||||
| 62598 | rc = openSubJournal(pPager); | ||||
| 62599 | |||||
| 62600 | /* If the sub-journal was opened successfully (or was already open), | ||||
| 62601 | ** write the journal record into the file. */ | ||||
| 62602 | if( rc==SQLITE_OK0 ){ | ||||
| 62603 | void *pData = pPg->pData; | ||||
| 62604 | i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize); | ||||
| 62605 | char *pData2; | ||||
| 62606 | pData2 = pData; | ||||
| 62607 | PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno)); | ||||
| 62608 | rc = write32bits(pPager->sjfd, offset, pPg->pgno); | ||||
| 62609 | if( rc==SQLITE_OK0 ){ | ||||
| 62610 | rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); | ||||
| 62611 | } | ||||
| 62612 | } | ||||
| 62613 | } | ||||
| 62614 | if( rc==SQLITE_OK0 ){ | ||||
| 62615 | pPager->nSubRec++; | ||||
| 62616 | assert( pPager->nSavepoint>0 )((void) (0)); | ||||
| 62617 | rc = addToSavepointBitvecs(pPager, pPg->pgno); | ||||
| 62618 | } | ||||
| 62619 | return rc; | ||||
| 62620 | } | ||||
| 62621 | static int subjournalPageIfRequired(PgHdr *pPg){ | ||||
| 62622 | if( subjRequiresPage(pPg) ){ | ||||
| 62623 | return subjournalPage(pPg); | ||||
| 62624 | }else{ | ||||
| 62625 | return SQLITE_OK0; | ||||
| 62626 | } | ||||
| 62627 | } | ||||
| 62628 | |||||
| 62629 | /* | ||||
| 62630 | ** This function is called by the pcache layer when it has reached some | ||||
| 62631 | ** soft memory limit. The first argument is a pointer to a Pager object | ||||
| 62632 | ** (cast as a void*). The pager is always 'purgeable' (not an in-memory | ||||
| 62633 | ** database). The second argument is a reference to a page that is | ||||
| 62634 | ** currently dirty but has no outstanding references. The page | ||||
| 62635 | ** is always associated with the Pager object passed as the first | ||||
| 62636 | ** argument. | ||||
| 62637 | ** | ||||
| 62638 | ** The job of this function is to make pPg clean by writing its contents | ||||
| 62639 | ** out to the database file, if possible. This may involve syncing the | ||||
| 62640 | ** journal file. | ||||
| 62641 | ** | ||||
| 62642 | ** If successful, sqlite3PcacheMakeClean() is called on the page and | ||||
| 62643 | ** SQLITE_OK returned. If an IO error occurs while trying to make the | ||||
| 62644 | ** page clean, the IO error code is returned. If the page cannot be | ||||
| 62645 | ** made clean for some other reason, but no error occurs, then SQLITE_OK | ||||
| 62646 | ** is returned by sqlite3PcacheMakeClean() is not called. | ||||
| 62647 | */ | ||||
| 62648 | static int pagerStress(void *p, PgHdr *pPg){ | ||||
| 62649 | Pager *pPager = (Pager *)p; | ||||
| 62650 | int rc = SQLITE_OK0; | ||||
| 62651 | |||||
| 62652 | assert( pPg->pPager==pPager )((void) (0)); | ||||
| 62653 | assert( pPg->flags&PGHDR_DIRTY )((void) (0)); | ||||
| 62654 | |||||
| 62655 | /* The doNotSpill NOSYNC bit is set during times when doing a sync of | ||||
| 62656 | ** journal (and adding a new header) is not allowed. This occurs | ||||
| 62657 | ** during calls to sqlite3PagerWrite() while trying to journal multiple | ||||
| 62658 | ** pages belonging to the same sector. | ||||
| 62659 | ** | ||||
| 62660 | ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling | ||||
| 62661 | ** regardless of whether or not a sync is required. This is set during | ||||
| 62662 | ** a rollback or by user request, respectively. | ||||
| 62663 | ** | ||||
| 62664 | ** Spilling is also prohibited when in an error state since that could | ||||
| 62665 | ** lead to database corruption. In the current implementation it | ||||
| 62666 | ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3 | ||||
| 62667 | ** while in the error state, hence it is impossible for this routine to | ||||
| 62668 | ** be called in the error state. Nevertheless, we include a NEVER() | ||||
| 62669 | ** test for the error state as a safeguard against future changes. | ||||
| 62670 | */ | ||||
| 62671 | if( NEVER(pPager->errCode)(pPager->errCode) ) return SQLITE_OK0; | ||||
| 62672 | testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK ); | ||||
| 62673 | testcase( pPager->doNotSpill & SPILLFLAG_OFF ); | ||||
| 62674 | testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC ); | ||||
| 62675 | if( pPager->doNotSpill | ||||
| 62676 | && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK0x02|SPILLFLAG_OFF0x01))!=0 | ||||
| 62677 | || (pPg->flags & PGHDR_NEED_SYNC0x008)!=0) | ||||
| 62678 | ){ | ||||
| 62679 | return SQLITE_OK0; | ||||
| 62680 | } | ||||
| 62681 | |||||
| 62682 | pPager->aStat[PAGER_STAT_SPILL3]++; | ||||
| 62683 | pPg->pDirty = 0; | ||||
| 62684 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 62685 | /* Write a single frame for this page to the log. */ | ||||
| 62686 | rc = subjournalPageIfRequired(pPg); | ||||
| 62687 | if( rc==SQLITE_OK0 ){ | ||||
| 62688 | rc = pagerWalFrames(pPager, pPg, 0, 0); | ||||
| 62689 | } | ||||
| 62690 | }else{ | ||||
| 62691 | |||||
| 62692 | #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE | ||||
| 62693 | if( pPager->tempFile==0 ){ | ||||
| 62694 | rc = sqlite3JournalCreate(pPager->jfd); | ||||
| 62695 | if( rc!=SQLITE_OK0 ) return pager_error(pPager, rc); | ||||
| 62696 | } | ||||
| 62697 | #endif | ||||
| 62698 | |||||
| 62699 | /* Sync the journal file if required. */ | ||||
| 62700 | if( pPg->flags&PGHDR_NEED_SYNC0x008 | ||||
| 62701 | || pPager->eState==PAGER_WRITER_CACHEMOD3 | ||||
| 62702 | ){ | ||||
| 62703 | rc = syncJournal(pPager, 1); | ||||
| 62704 | } | ||||
| 62705 | |||||
| 62706 | /* Write the contents of the page out to the database file. */ | ||||
| 62707 | if( rc==SQLITE_OK0 ){ | ||||
| 62708 | assert( (pPg->flags&PGHDR_NEED_SYNC)==0 )((void) (0)); | ||||
| 62709 | rc = pager_write_pagelist(pPager, pPg); | ||||
| 62710 | } | ||||
| 62711 | } | ||||
| 62712 | |||||
| 62713 | /* Mark the page as clean. */ | ||||
| 62714 | if( rc==SQLITE_OK0 ){ | ||||
| 62715 | PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno)); | ||||
| 62716 | sqlite3PcacheMakeClean(pPg); | ||||
| 62717 | } | ||||
| 62718 | |||||
| 62719 | return pager_error(pPager, rc); | ||||
| 62720 | } | ||||
| 62721 | |||||
| 62722 | /* | ||||
| 62723 | ** Flush all unreferenced dirty pages to disk. | ||||
| 62724 | */ | ||||
| 62725 | SQLITE_PRIVATEstatic int sqlite3PagerFlush(Pager *pPager){ | ||||
| 62726 | int rc = pPager->errCode; | ||||
| 62727 | if( !MEMDBpPager->memDb ){ | ||||
| 62728 | PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); | ||||
| 62729 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 62730 | while( rc==SQLITE_OK0 && pList ){ | ||||
| 62731 | PgHdr *pNext = pList->pDirty; | ||||
| 62732 | if( pList->nRef==0 ){ | ||||
| 62733 | rc = pagerStress((void*)pPager, pList); | ||||
| 62734 | } | ||||
| 62735 | pList = pNext; | ||||
| 62736 | } | ||||
| 62737 | } | ||||
| 62738 | |||||
| 62739 | return rc; | ||||
| 62740 | } | ||||
| 62741 | |||||
| 62742 | /* | ||||
| 62743 | ** Allocate and initialize a new Pager object and put a pointer to it | ||||
| 62744 | ** in *ppPager. The pager should eventually be freed by passing it | ||||
| 62745 | ** to sqlite3PagerClose(). | ||||
| 62746 | ** | ||||
| 62747 | ** The zFilename argument is the path to the database file to open. | ||||
| 62748 | ** If zFilename is NULL then a randomly-named temporary file is created | ||||
| 62749 | ** and used as the file to be cached. Temporary files are be deleted | ||||
| 62750 | ** automatically when they are closed. If zFilename is ":memory:" then | ||||
| 62751 | ** all information is held in cache. It is never written to disk. | ||||
| 62752 | ** This can be used to implement an in-memory database. | ||||
| 62753 | ** | ||||
| 62754 | ** The nExtra parameter specifies the number of bytes of space allocated | ||||
| 62755 | ** along with each page reference. This space is available to the user | ||||
| 62756 | ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the | ||||
| 62757 | ** first 8 bytes of this space are zeroed but the remainder is uninitialized. | ||||
| 62758 | ** (The extra space is used by btree as the MemPage object.) | ||||
| 62759 | ** | ||||
| 62760 | ** The flags argument is used to specify properties that affect the | ||||
| 62761 | ** operation of the pager. It should be passed some bitwise combination | ||||
| 62762 | ** of the PAGER_* flags. | ||||
| 62763 | ** | ||||
| 62764 | ** The vfsFlags parameter is a bitmask to pass to the flags parameter | ||||
| 62765 | ** of the xOpen() method of the supplied VFS when opening files. | ||||
| 62766 | ** | ||||
| 62767 | ** If the pager object is allocated and the specified file opened | ||||
| 62768 | ** successfully, SQLITE_OK is returned and *ppPager set to point to | ||||
| 62769 | ** the new pager object. If an error occurs, *ppPager is set to NULL | ||||
| 62770 | ** and error code returned. This function may return SQLITE_NOMEM | ||||
| 62771 | ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or | ||||
| 62772 | ** various SQLITE_IO_XXX errors. | ||||
| 62773 | */ | ||||
| 62774 | SQLITE_PRIVATEstatic int sqlite3PagerOpen( | ||||
| 62775 | sqlite3_vfs *pVfs, /* The virtual file system to use */ | ||||
| 62776 | Pager **ppPager, /* OUT: Return the Pager structure here */ | ||||
| 62777 | const char *zFilename, /* Name of the database file to open */ | ||||
| 62778 | int nExtra, /* Extra bytes append to each in-memory page */ | ||||
| 62779 | int flags, /* flags controlling this file */ | ||||
| 62780 | int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ | ||||
| 62781 | void (*xReinit)(DbPage*) /* Function to reinitialize pages */ | ||||
| 62782 | ){ | ||||
| 62783 | u8 *pPtr; | ||||
| 62784 | Pager *pPager = 0; /* Pager object to allocate and return */ | ||||
| 62785 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 62786 | int tempFile = 0; /* True for temp files (incl. in-memory files) */ | ||||
| 62787 | int memDb = 0; /* True if this is an in-memory file */ | ||||
| 62788 | int memJM = 0; /* Memory journal mode */ | ||||
| 62789 | int readOnly = 0; /* True if this is a read-only file */ | ||||
| 62790 | int journalFileSize; /* Bytes to allocate for each journal fd */ | ||||
| 62791 | char *zPathname = 0; /* Full path to database file */ | ||||
| 62792 | int nPathname = 0; /* Number of bytes in zPathname */ | ||||
| 62793 | int useJournal = (flags & PAGER_OMIT_JOURNAL0x0001)==0; /* False to omit journal */ | ||||
| 62794 | int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ | ||||
| 62795 | u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE4096; /* Default page size */ | ||||
| 62796 | const char *zUri = 0; /* URI args to copy */ | ||||
| 62797 | int nUriByte = 1; /* Number of bytes of URI args at *zUri */ | ||||
| 62798 | |||||
| 62799 | |||||
| 62800 | /* Figure out how much space is required for each journal file-handle | ||||
| 62801 | ** (there are two of them, the main journal and the sub-journal). */ | ||||
| 62802 | journalFileSize = ROUND8(sqlite3JournalSize(pVfs))(((sqlite3JournalSize(pVfs))+7)&~7); | ||||
| 62803 | |||||
| 62804 | /* Set the output variable to NULL in case an error occurs. */ | ||||
| 62805 | *ppPager = 0; | ||||
| 62806 | |||||
| 62807 | #ifndef SQLITE_OMIT_MEMORYDB | ||||
| 62808 | if( flags & PAGER_MEMORY0x0002 ){ | ||||
| 62809 | memDb = 1; | ||||
| 62810 | if( zFilename && zFilename[0] ){ | ||||
| 62811 | zPathname = sqlite3DbStrDup(0, zFilename); | ||||
| 62812 | if( zPathname==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 62813 | nPathname = sqlite3Strlen30(zPathname); | ||||
| 62814 | zFilename = 0; | ||||
| 62815 | } | ||||
| 62816 | } | ||||
| 62817 | #endif | ||||
| 62818 | |||||
| 62819 | /* Compute and store the full pathname in an allocated buffer pointed | ||||
| 62820 | ** to by zPathname, length nPathname. Or, if this is a temporary file, | ||||
| 62821 | ** leave both nPathname and zPathname set to 0. | ||||
| 62822 | */ | ||||
| 62823 | if( zFilename && zFilename[0] ){ | ||||
| 62824 | const char *z; | ||||
| 62825 | nPathname = pVfs->mxPathname + 1; | ||||
| 62826 | zPathname = sqlite3DbMallocRaw(0, 2*(i64)nPathname); | ||||
| 62827 | if( zPathname==0 ){ | ||||
| 62828 | return SQLITE_NOMEM_BKPT7; | ||||
| 62829 | } | ||||
| 62830 | zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ | ||||
| 62831 | rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); | ||||
| 62832 | if( rc!=SQLITE_OK0 ){ | ||||
| 62833 | if( rc==SQLITE_OK_SYMLINK(0 | (2<<8)) ){ | ||||
| 62834 | if( vfsFlags & SQLITE_OPEN_NOFOLLOW0x01000000 ){ | ||||
| 62835 | rc = SQLITE_CANTOPEN_SYMLINK(14 | (6<<8)); | ||||
| 62836 | }else{ | ||||
| 62837 | rc = SQLITE_OK0; | ||||
| 62838 | } | ||||
| 62839 | } | ||||
| 62840 | } | ||||
| 62841 | nPathname = sqlite3Strlen30(zPathname); | ||||
| 62842 | z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; | ||||
| 62843 | while( *z ){ | ||||
| 62844 | z += strlen(z)+1; | ||||
| 62845 | z += strlen(z)+1; | ||||
| 62846 | } | ||||
| 62847 | nUriByte = (int)(&z[1] - zUri); | ||||
| 62848 | assert( nUriByte>=1 )((void) (0)); | ||||
| 62849 | if( rc==SQLITE_OK0 && nPathname+8>pVfs->mxPathname ){ | ||||
| 62850 | /* This branch is taken when the journal path required by | ||||
| 62851 | ** the database being opened will be more than pVfs->mxPathname | ||||
| 62852 | ** bytes in length. This means the database cannot be opened, | ||||
| 62853 | ** as it will not be possible to open the journal file or even | ||||
| 62854 | ** check for a hot-journal before reading. | ||||
| 62855 | */ | ||||
| 62856 | rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(62856); | ||||
| 62857 | } | ||||
| 62858 | if( rc!=SQLITE_OK0 ){ | ||||
| 62859 | sqlite3DbFree(0, zPathname); | ||||
| 62860 | return rc; | ||||
| 62861 | } | ||||
| 62862 | } | ||||
| 62863 | |||||
| 62864 | /* Allocate memory for the Pager structure, PCache object, the | ||||
| 62865 | ** three file descriptors, the database file name and the journal | ||||
| 62866 | ** file name. The layout in memory is as follows: | ||||
| 62867 | ** | ||||
| 62868 | ** Pager object (sizeof(Pager) bytes) | ||||
| 62869 | ** PCache object (sqlite3PcacheSize() bytes) | ||||
| 62870 | ** Database file handle (pVfs->szOsFile bytes) | ||||
| 62871 | ** Sub-journal file handle (journalFileSize bytes) | ||||
| 62872 | ** Main journal file handle (journalFileSize bytes) | ||||
| 62873 | ** Ptr back to the Pager (sizeof(Pager*) bytes) | ||||
| 62874 | ** \0\0\0\0 database prefix (4 bytes) | ||||
| 62875 | ** Database file name (nPathname+1 bytes) | ||||
| 62876 | ** URI query parameters (nUriByte bytes) | ||||
| 62877 | ** Journal filename (nPathname+8+1 bytes) | ||||
| 62878 | ** WAL filename (nPathname+4+1 bytes) | ||||
| 62879 | ** \0\0\0 terminator (3 bytes) | ||||
| 62880 | ** | ||||
| 62881 | ** Some 3rd-party software, over which we have no control, depends on | ||||
| 62882 | ** the specific order of the filenames and the \0 separators between them | ||||
| 62883 | ** so that it can (for example) find the database filename given the WAL | ||||
| 62884 | ** filename without using the sqlite3_filename_database() API. This is a | ||||
| 62885 | ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party | ||||
| 62886 | ** software is in widespread use, so we try to avoid changing the filename | ||||
| 62887 | ** order and formatting if possible. In particular, the details of the | ||||
| 62888 | ** filename format expected by 3rd-party software should be as follows: | ||||
| 62889 | ** | ||||
| 62890 | ** - Main Database Path | ||||
| 62891 | ** - \0 | ||||
| 62892 | ** - Multiple URI components consisting of: | ||||
| 62893 | ** - Key | ||||
| 62894 | ** - \0 | ||||
| 62895 | ** - Value | ||||
| 62896 | ** - \0 | ||||
| 62897 | ** - \0 | ||||
| 62898 | ** - Journal Path | ||||
| 62899 | ** - \0 | ||||
| 62900 | ** - WAL Path (zWALName) | ||||
| 62901 | ** - \0 | ||||
| 62902 | ** | ||||
| 62903 | ** The sqlite3_create_filename() interface and the databaseFilename() utility | ||||
| 62904 | ** that is used by sqlite3_filename_database() and kin also depend on the | ||||
| 62905 | ** specific formatting and order of the various filenames, so if the format | ||||
| 62906 | ** changes here, be sure to change it there as well. | ||||
| 62907 | */ | ||||
| 62908 | assert( SQLITE_PTRSIZE==sizeof(Pager*) )((void) (0)); | ||||
| 62909 | pPtr = (u8 *)sqlite3MallocZero( | ||||
| 62910 | ROUND8(sizeof(*pPager))(((sizeof(*pPager))+7)&~7) + /* Pager structure */ | ||||
| 62911 | ROUND8(pcacheSize)(((pcacheSize)+7)&~7) + /* PCache object */ | ||||
| 62912 | ROUND8(pVfs->szOsFile)(((pVfs->szOsFile)+7)&~7) + /* The main db file */ | ||||
| 62913 | (u64)journalFileSize * 2 + /* The two journal files */ | ||||
| 62914 | SQLITE_PTRSIZE8 + /* Space to hold a pointer */ | ||||
| 62915 | 4 + /* Database prefix */ | ||||
| 62916 | (u64)nPathname + 1 + /* database filename */ | ||||
| 62917 | (u64)nUriByte + /* query parameters */ | ||||
| 62918 | (u64)nPathname + 8 + 1 + /* Journal filename */ | ||||
| 62919 | #ifndef SQLITE_OMIT_WAL | ||||
| 62920 | (u64)nPathname + 4 + 1 + /* WAL filename */ | ||||
| 62921 | #endif | ||||
| 62922 | 3 /* Terminator */ | ||||
| 62923 | ); | ||||
| 62924 | assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) )((void) (0)); | ||||
| 62925 | if( !pPtr ){ | ||||
| 62926 | sqlite3DbFree(0, zPathname); | ||||
| 62927 | return SQLITE_NOMEM_BKPT7; | ||||
| 62928 | } | ||||
| 62929 | pPager = (Pager*)pPtr; pPtr += ROUND8(sizeof(*pPager))(((sizeof(*pPager))+7)&~7); | ||||
| 62930 | pPager->pPCache = (PCache*)pPtr; pPtr += ROUND8(pcacheSize)(((pcacheSize)+7)&~7); | ||||
| 62931 | pPager->fd = (sqlite3_file*)pPtr; pPtr += ROUND8(pVfs->szOsFile)(((pVfs->szOsFile)+7)&~7); | ||||
| 62932 | pPager->sjfd = (sqlite3_file*)pPtr; pPtr += journalFileSize; | ||||
| 62933 | pPager->jfd = (sqlite3_file*)pPtr; pPtr += journalFileSize; | ||||
| 62934 | assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) )((void) (0)); | ||||
| 62935 | memcpy(pPtr, &pPager, SQLITE_PTRSIZE8); pPtr += SQLITE_PTRSIZE8; | ||||
| 62936 | |||||
| 62937 | /* Fill in the Pager.zFilename and pPager.zQueryParam fields */ | ||||
| 62938 | pPtr += 4; /* Skip zero prefix */ | ||||
| 62939 | pPager->zFilename = (char*)pPtr; | ||||
| 62940 | if( nPathname>0 ){ | ||||
| 62941 | memcpy(pPtr, zPathname, nPathname); pPtr += nPathname + 1; | ||||
| 62942 | if( zUri ){ | ||||
| 62943 | memcpy(pPtr, zUri, nUriByte); pPtr += nUriByte; | ||||
| 62944 | }else{ | ||||
| 62945 | pPtr++; | ||||
| 62946 | } | ||||
| 62947 | } | ||||
| 62948 | |||||
| 62949 | |||||
| 62950 | /* Fill in Pager.zJournal */ | ||||
| 62951 | if( nPathname>0 ){ | ||||
| 62952 | pPager->zJournal = (char*)pPtr; | ||||
| 62953 | memcpy(pPtr, zPathname, nPathname); pPtr += nPathname; | ||||
| 62954 | memcpy(pPtr, "-journal",8); pPtr += 8 + 1; | ||||
| 62955 | #ifdef SQLITE_ENABLE_8_3_NAMES | ||||
| 62956 | sqlite3FileSuffix3(zFilename,pPager->zJournal); | ||||
| 62957 | pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1); | ||||
| 62958 | #endif | ||||
| 62959 | }else{ | ||||
| 62960 | pPager->zJournal = 0; | ||||
| 62961 | } | ||||
| 62962 | |||||
| 62963 | #ifndef SQLITE_OMIT_WAL | ||||
| 62964 | /* Fill in Pager.zWal */ | ||||
| 62965 | if( nPathname>0 ){ | ||||
| 62966 | pPager->zWal = (char*)pPtr; | ||||
| 62967 | memcpy(pPtr, zPathname, nPathname); pPtr += nPathname; | ||||
| 62968 | memcpy(pPtr, "-wal", 4); pPtr += 4 + 1; | ||||
| 62969 | #ifdef SQLITE_ENABLE_8_3_NAMES | ||||
| 62970 | sqlite3FileSuffix3(zFilename, pPager->zWal); | ||||
| 62971 | pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1); | ||||
| 62972 | #endif | ||||
| 62973 | }else{ | ||||
| 62974 | pPager->zWal = 0; | ||||
| 62975 | } | ||||
| 62976 | #endif | ||||
| 62977 | (void)pPtr; /* Suppress warning about unused pPtr value */ | ||||
| 62978 | |||||
| 62979 | if( nPathname ) sqlite3DbFree(0, zPathname); | ||||
| 62980 | pPager->pVfs = pVfs; | ||||
| 62981 | pPager->vfsFlags = vfsFlags; | ||||
| 62982 | |||||
| 62983 | /* Open the pager file. | ||||
| 62984 | */ | ||||
| 62985 | if( zFilename && zFilename[0] ){ | ||||
| 62986 | int fout = 0; /* VFS flags returned by xOpen() */ | ||||
| 62987 | rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); | ||||
| 62988 | assert( !memDb )((void) (0)); | ||||
| 62989 | pPager->memVfs = memJM = (fout&SQLITE_OPEN_MEMORY0x00000080)!=0; | ||||
| 62990 | readOnly = (fout&SQLITE_OPEN_READONLY0x00000001)!=0; | ||||
| 62991 | |||||
| 62992 | /* If the file was successfully opened for read/write access, | ||||
| 62993 | ** choose a default page size in case we have to create the | ||||
| 62994 | ** database file. The default page size is the maximum of: | ||||
| 62995 | ** | ||||
| 62996 | ** + SQLITE_DEFAULT_PAGE_SIZE, | ||||
| 62997 | ** + The value returned by sqlite3OsSectorSize() | ||||
| 62998 | ** + The largest page size that can be written atomically. | ||||
| 62999 | */ | ||||
| 63000 | if( rc==SQLITE_OK0 ){ | ||||
| 63001 | int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); | ||||
| 63002 | if( !readOnly ){ | ||||
| 63003 | setSectorSize(pPager); | ||||
| 63004 | assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE)((void) (0)); | ||||
| 63005 | if( szPageDflt<pPager->sectorSize ){ | ||||
| 63006 | if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE8192 ){ | ||||
| 63007 | szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE8192; | ||||
| 63008 | }else{ | ||||
| 63009 | szPageDflt = (u32)pPager->sectorSize; | ||||
| 63010 | } | ||||
| 63011 | } | ||||
| 63012 | #ifdef SQLITE_ENABLE_ATOMIC_WRITE | ||||
| 63013 | { | ||||
| 63014 | int ii; | ||||
| 63015 | assert(SQLITE_IOCAP_ATOMIC512==(512>>8))((void) (0)); | ||||
| 63016 | assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8))((void) (0)); | ||||
| 63017 | assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536)((void) (0)); | ||||
| 63018 | for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE8192; ii=ii*2){ | ||||
| 63019 | if( iDc&(SQLITE_IOCAP_ATOMIC0x00000001|(ii>>8)) ){ | ||||
| 63020 | szPageDflt = ii; | ||||
| 63021 | } | ||||
| 63022 | } | ||||
| 63023 | } | ||||
| 63024 | #endif | ||||
| 63025 | } | ||||
| 63026 | pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0); | ||||
| 63027 | if( (iDc & SQLITE_IOCAP_IMMUTABLE0x00002000)!=0 | ||||
| 63028 | || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){ | ||||
| 63029 | vfsFlags |= SQLITE_OPEN_READONLY0x00000001; | ||||
| 63030 | goto act_like_temp_file; | ||||
| 63031 | } | ||||
| 63032 | } | ||||
| 63033 | }else{ | ||||
| 63034 | /* If a temporary file is requested, it is not opened immediately. | ||||
| 63035 | ** In this case we accept the default page size and delay actually | ||||
| 63036 | ** opening the file until the first call to OsWrite(). | ||||
| 63037 | ** | ||||
| 63038 | ** This branch is also run for an in-memory database. An in-memory | ||||
| 63039 | ** database is the same as a temp-file that is never written out to | ||||
| 63040 | ** disk and uses an in-memory rollback journal. | ||||
| 63041 | ** | ||||
| 63042 | ** This branch also runs for files marked as immutable. | ||||
| 63043 | */ | ||||
| 63044 | act_like_temp_file: | ||||
| 63045 | tempFile = 1; | ||||
| 63046 | pPager->eState = PAGER_READER1; /* Pretend we already have a lock */ | ||||
| 63047 | pPager->eLock = EXCLUSIVE_LOCK4; /* Pretend we are in EXCLUSIVE mode */ | ||||
| 63048 | pPager->noLock = 1; /* Do no locking */ | ||||
| 63049 | readOnly = (vfsFlags&SQLITE_OPEN_READONLY0x00000001); | ||||
| 63050 | } | ||||
| 63051 | |||||
| 63052 | /* The following call to PagerSetPagesize() serves to set the value of | ||||
| 63053 | ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. | ||||
| 63054 | */ | ||||
| 63055 | if( rc==SQLITE_OK0 ){ | ||||
| 63056 | assert( pPager->memDb==0 )((void) (0)); | ||||
| 63057 | rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1); | ||||
| 63058 | testcase( rc!=SQLITE_OK ); | ||||
| 63059 | } | ||||
| 63060 | |||||
| 63061 | /* Initialize the PCache object. */ | ||||
| 63062 | if( rc==SQLITE_OK0 ){ | ||||
| 63063 | nExtra = ROUND8(nExtra)(((nExtra)+7)&~7); | ||||
| 63064 | assert( nExtra>=8 && nExtra<1000 )((void) (0)); | ||||
| 63065 | rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, | ||||
| 63066 | !memDb?pagerStress:0, (void *)pPager, pPager->pPCache); | ||||
| 63067 | } | ||||
| 63068 | |||||
| 63069 | /* If an error occurred above, free the Pager structure and close the file. | ||||
| 63070 | */ | ||||
| 63071 | if( rc!=SQLITE_OK0 ){ | ||||
| 63072 | sqlite3OsClose(pPager->fd); | ||||
| 63073 | sqlite3PageFree(pPager->pTmpSpace); | ||||
| 63074 | sqlite3_free(pPager); | ||||
| 63075 | return rc; | ||||
| 63076 | } | ||||
| 63077 | |||||
| 63078 | PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename)); | ||||
| 63079 | IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename)) | ||||
| 63080 | |||||
| 63081 | pPager->useJournal = (u8)useJournal; | ||||
| 63082 | /* pPager->stmtOpen = 0; */ | ||||
| 63083 | /* pPager->stmtInUse = 0; */ | ||||
| 63084 | /* pPager->nRef = 0; */ | ||||
| 63085 | /* pPager->stmtSize = 0; */ | ||||
| 63086 | /* pPager->stmtJSize = 0; */ | ||||
| 63087 | /* pPager->nPage = 0; */ | ||||
| 63088 | pPager->mxPgno = SQLITE_MAX_PAGE_COUNT0xfffffffe; | ||||
| 63089 | /* pPager->state = PAGER_UNLOCK; */ | ||||
| 63090 | /* pPager->errMask = 0; */ | ||||
| 63091 | pPager->tempFile = (u8)tempFile; | ||||
| 63092 | assert( tempFile==PAGER_LOCKINGMODE_NORMAL((void) (0)) | ||||
| 63093 | || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE )((void) (0)); | ||||
| 63094 | assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 )((void) (0)); | ||||
| 63095 | pPager->exclusiveMode = (u8)tempFile; | ||||
| 63096 | pPager->changeCountDone = pPager->tempFile; | ||||
| 63097 | pPager->memDb = (u8)memDb; | ||||
| 63098 | pPager->readOnly = (u8)readOnly; | ||||
| 63099 | assert( useJournal || pPager->tempFile )((void) (0)); | ||||
| 63100 | sqlite3PagerSetFlags(pPager, (SQLITE_DEFAULT_SYNCHRONOUS2+1)|PAGER_CACHESPILL0x20); | ||||
| 63101 | /* pPager->pFirst = 0; */ | ||||
| 63102 | /* pPager->pFirstSynced = 0; */ | ||||
| 63103 | /* pPager->pLast = 0; */ | ||||
| 63104 | pPager->nExtra = (u16)nExtra; | ||||
| 63105 | pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT32768; | ||||
| 63106 | assert( isOpen(pPager->fd) || tempFile )((void) (0)); | ||||
| 63107 | setSectorSize(pPager); | ||||
| 63108 | if( !useJournal ){ | ||||
| 63109 | pPager->journalMode = PAGER_JOURNALMODE_OFF2; | ||||
| 63110 | }else if( memDb || memJM ){ | ||||
| 63111 | pPager->journalMode = PAGER_JOURNALMODE_MEMORY4; | ||||
| 63112 | } | ||||
| 63113 | /* pPager->xBusyHandler = 0; */ | ||||
| 63114 | /* pPager->pBusyHandlerArg = 0; */ | ||||
| 63115 | pPager->xReiniter = xReinit; | ||||
| 63116 | setGetterMethod(pPager); | ||||
| 63117 | /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ | ||||
| 63118 | /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */ | ||||
| 63119 | |||||
| 63120 | *ppPager = pPager; | ||||
| 63121 | return SQLITE_OK0; | ||||
| 63122 | } | ||||
| 63123 | |||||
| 63124 | /* | ||||
| 63125 | ** Return the sqlite3_file for the main database given the name | ||||
| 63126 | ** of the corresponding WAL or Journal name as passed into | ||||
| 63127 | ** xOpen. | ||||
| 63128 | */ | ||||
| 63129 | SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){ | ||||
| 63130 | Pager *pPager; | ||||
| 63131 | const char *p; | ||||
| 63132 | while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){ | ||||
| 63133 | zName--; | ||||
| 63134 | } | ||||
| 63135 | p = zName - 4 - sizeof(Pager*); | ||||
| 63136 | assert( EIGHT_BYTE_ALIGNMENT(p) )((void) (0)); | ||||
| 63137 | pPager = *(Pager**)p; | ||||
| 63138 | return pPager->fd; | ||||
| 63139 | } | ||||
| 63140 | |||||
| 63141 | |||||
| 63142 | /* | ||||
| 63143 | ** This function is called after transitioning from PAGER_UNLOCK to | ||||
| 63144 | ** PAGER_SHARED state. It tests if there is a hot journal present in | ||||
| 63145 | ** the file-system for the given pager. A hot journal is one that | ||||
| 63146 | ** needs to be played back. According to this function, a hot-journal | ||||
| 63147 | ** file exists if the following criteria are met: | ||||
| 63148 | ** | ||||
| 63149 | ** * The journal file exists in the file system, and | ||||
| 63150 | ** * No process holds a RESERVED or greater lock on the database file, and | ||||
| 63151 | ** * The database file itself is greater than 0 bytes in size, and | ||||
| 63152 | ** * The first byte of the journal file exists and is not 0x00. | ||||
| 63153 | ** | ||||
| 63154 | ** If the current size of the database file is 0 but a journal file | ||||
| 63155 | ** exists, that is probably an old journal left over from a prior | ||||
| 63156 | ** database with the same name. In this case the journal file is | ||||
| 63157 | ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK | ||||
| 63158 | ** is returned. | ||||
| 63159 | ** | ||||
| 63160 | ** This routine does not check if there is a super-journal filename | ||||
| 63161 | ** at the end of the file. If there is, and that super-journal file | ||||
| 63162 | ** does not exist, then the journal file is not really hot. In this | ||||
| 63163 | ** case this routine will return a false-positive. The pager_playback() | ||||
| 63164 | ** routine will discover that the journal file is not really hot and | ||||
| 63165 | ** will not roll it back. | ||||
| 63166 | ** | ||||
| 63167 | ** If a hot-journal file is found to exist, *pExists is set to 1 and | ||||
| 63168 | ** SQLITE_OK returned. If no hot-journal file is present, *pExists is | ||||
| 63169 | ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying | ||||
| 63170 | ** to determine whether or not a hot-journal file exists, the IO error | ||||
| 63171 | ** code is returned and the value of *pExists is undefined. | ||||
| 63172 | */ | ||||
| 63173 | static int hasHotJournal(Pager *pPager, int *pExists){ | ||||
| 63174 | sqlite3_vfs * const pVfs = pPager->pVfs; | ||||
| 63175 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 63176 | int exists = 1; /* True if a journal file is present */ | ||||
| 63177 | int jrnlOpen = !!isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0); | ||||
| 63178 | |||||
| 63179 | assert( pPager->useJournal )((void) (0)); | ||||
| 63180 | assert( isOpen(pPager->fd) )((void) (0)); | ||||
| 63181 | assert( pPager->eState==PAGER_OPEN )((void) (0)); | ||||
| 63182 | |||||
| 63183 | assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &((void) (0)) | ||||
| 63184 | SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN((void) (0)) | ||||
| 63185 | ))((void) (0)); | ||||
| 63186 | |||||
| 63187 | *pExists = 0; | ||||
| 63188 | if( !jrnlOpen ){ | ||||
| 63189 | rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS0, &exists); | ||||
| 63190 | } | ||||
| 63191 | if( rc==SQLITE_OK0 && exists ){ | ||||
| 63192 | int locked = 0; /* True if some process holds a RESERVED lock */ | ||||
| 63193 | |||||
| 63194 | /* Race condition here: Another process might have been holding the | ||||
| 63195 | ** the RESERVED lock and have a journal open at the sqlite3OsAccess() | ||||
| 63196 | ** call above, but then delete the journal and drop the lock before | ||||
| 63197 | ** we get to the following sqlite3OsCheckReservedLock() call. If that | ||||
| 63198 | ** is the case, this routine might think there is a hot journal when | ||||
| 63199 | ** in fact there is none. This results in a false-positive which will | ||||
| 63200 | ** be dealt with by the playback routine. Ticket #3883. | ||||
| 63201 | */ | ||||
| 63202 | rc = sqlite3OsCheckReservedLock(pPager->fd, &locked); | ||||
| 63203 | if( rc==SQLITE_OK0 && !locked ){ | ||||
| 63204 | Pgno nPage; /* Number of pages in database file */ | ||||
| 63205 | |||||
| 63206 | assert( pPager->tempFile==0 )((void) (0)); | ||||
| 63207 | rc = pagerPagecount(pPager, &nPage); | ||||
| 63208 | if( rc==SQLITE_OK0 ){ | ||||
| 63209 | /* If the database is zero pages in size, that means that either (1) the | ||||
| 63210 | ** journal is a remnant from a prior database with the same name where | ||||
| 63211 | ** the database file but not the journal was deleted, or (2) the initial | ||||
| 63212 | ** transaction that populates a new database is being rolled back. | ||||
| 63213 | ** In either case, the journal file can be deleted. However, take care | ||||
| 63214 | ** not to delete the journal file if it is already open due to | ||||
| 63215 | ** journal_mode=PERSIST. | ||||
| 63216 | */ | ||||
| 63217 | if( nPage==0 && !jrnlOpen ){ | ||||
| 63218 | sqlite3BeginBenignMalloc(); | ||||
| 63219 | if( pagerLockDb(pPager, RESERVED_LOCK2)==SQLITE_OK0 ){ | ||||
| 63220 | sqlite3OsDelete(pVfs, pPager->zJournal, 0); | ||||
| 63221 | if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK1); | ||||
| 63222 | } | ||||
| 63223 | sqlite3EndBenignMalloc(); | ||||
| 63224 | }else{ | ||||
| 63225 | /* The journal file exists and no other connection has a reserved | ||||
| 63226 | ** or greater lock on the database file. Now check that there is | ||||
| 63227 | ** at least one non-zero bytes at the start of the journal file. | ||||
| 63228 | ** If there is, then we consider this journal to be hot. If not, | ||||
| 63229 | ** it can be ignored. | ||||
| 63230 | */ | ||||
| 63231 | if( !jrnlOpen ){ | ||||
| 63232 | int f = SQLITE_OPEN_READONLY0x00000001|SQLITE_OPEN_MAIN_JOURNAL0x00000800; | ||||
| 63233 | rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); | ||||
| 63234 | } | ||||
| 63235 | if( rc==SQLITE_OK0 ){ | ||||
| 63236 | u8 first = 0; | ||||
| 63237 | rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); | ||||
| 63238 | if( rc==SQLITE_IOERR_SHORT_READ(10 | (2<<8)) ){ | ||||
| 63239 | rc = SQLITE_OK0; | ||||
| 63240 | } | ||||
| 63241 | if( !jrnlOpen ){ | ||||
| 63242 | sqlite3OsClose(pPager->jfd); | ||||
| 63243 | } | ||||
| 63244 | *pExists = (first!=0); | ||||
| 63245 | }else if( rc==SQLITE_CANTOPEN14 ){ | ||||
| 63246 | /* If we cannot open the rollback journal file in order to see if | ||||
| 63247 | ** it has a zero header, that might be due to an I/O error, or | ||||
| 63248 | ** it might be due to the race condition described above and in | ||||
| 63249 | ** ticket #3883. Either way, assume that the journal is hot. | ||||
| 63250 | ** This might be a false positive. But if it is, then the | ||||
| 63251 | ** automatic journal playback and recovery mechanism will deal | ||||
| 63252 | ** with it under an EXCLUSIVE lock where we do not need to | ||||
| 63253 | ** worry so much with race conditions. | ||||
| 63254 | */ | ||||
| 63255 | *pExists = 1; | ||||
| 63256 | rc = SQLITE_OK0; | ||||
| 63257 | } | ||||
| 63258 | } | ||||
| 63259 | } | ||||
| 63260 | } | ||||
| 63261 | } | ||||
| 63262 | |||||
| 63263 | return rc; | ||||
| 63264 | } | ||||
| 63265 | |||||
| 63266 | /* | ||||
| 63267 | ** This function is called to obtain a shared lock on the database file. | ||||
| 63268 | ** It is illegal to call sqlite3PagerGet() until after this function | ||||
| 63269 | ** has been successfully called. If a shared-lock is already held when | ||||
| 63270 | ** this function is called, it is a no-op. | ||||
| 63271 | ** | ||||
| 63272 | ** The following operations are also performed by this function. | ||||
| 63273 | ** | ||||
| 63274 | ** 1) If the pager is currently in PAGER_OPEN state (no lock held | ||||
| 63275 | ** on the database file), then an attempt is made to obtain a | ||||
| 63276 | ** SHARED lock on the database file. Immediately after obtaining | ||||
| 63277 | ** the SHARED lock, the file-system is checked for a hot-journal, | ||||
| 63278 | ** which is played back if present. Following any hot-journal | ||||
| 63279 | ** rollback, the contents of the cache are validated by checking | ||||
| 63280 | ** the 'change-counter' field of the database file header and | ||||
| 63281 | ** discarded if they are found to be invalid. | ||||
| 63282 | ** | ||||
| 63283 | ** 2) If the pager is running in exclusive-mode, and there are currently | ||||
| 63284 | ** no outstanding references to any pages, and is in the error state, | ||||
| 63285 | ** then an attempt is made to clear the error state by discarding | ||||
| 63286 | ** the contents of the page cache and rolling back any open journal | ||||
| 63287 | ** file. | ||||
| 63288 | ** | ||||
| 63289 | ** If everything is successful, SQLITE_OK is returned. If an IO error | ||||
| 63290 | ** occurs while locking the database, checking for a hot-journal file or | ||||
| 63291 | ** rolling back a journal file, the IO error code is returned. | ||||
| 63292 | */ | ||||
| 63293 | SQLITE_PRIVATEstatic int sqlite3PagerSharedLock(Pager *pPager){ | ||||
| 63294 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 63295 | |||||
| 63296 | /* This routine is only called from b-tree and only when there are no | ||||
| 63297 | ** outstanding pages. This implies that the pager state should either | ||||
| 63298 | ** be OPEN or READER. READER is only possible if the pager is or was in | ||||
| 63299 | ** exclusive access mode. */ | ||||
| 63300 | assert( sqlite3PcacheRefCount(pPager->pPCache)==0 )((void) (0)); | ||||
| 63301 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 63302 | assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER )((void) (0)); | ||||
| 63303 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 63304 | |||||
| 63305 | if( !pagerUseWal(pPager)((pPager)->pWal!=0) && pPager->eState==PAGER_OPEN0 ){ | ||||
| 63306 | int bHotJournal = 1; /* True if there exists a hot journal-file */ | ||||
| 63307 | |||||
| 63308 | assert( !MEMDB )((void) (0)); | ||||
| 63309 | assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 63310 | |||||
| 63311 | rc = pager_wait_on_lock(pPager, SHARED_LOCK1); | ||||
| 63312 | if( rc!=SQLITE_OK0 ){ | ||||
| 63313 | assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK )((void) (0)); | ||||
| 63314 | goto failed; | ||||
| 63315 | } | ||||
| 63316 | |||||
| 63317 | /* If a journal file exists, and there is no RESERVED lock on the | ||||
| 63318 | ** database file, then it either needs to be played back or deleted. | ||||
| 63319 | */ | ||||
| 63320 | if( pPager->eLock<=SHARED_LOCK1 ){ | ||||
| 63321 | rc = hasHotJournal(pPager, &bHotJournal); | ||||
| 63322 | } | ||||
| 63323 | if( rc!=SQLITE_OK0 ){ | ||||
| 63324 | goto failed; | ||||
| 63325 | } | ||||
| 63326 | if( bHotJournal ){ | ||||
| 63327 | if( pPager->readOnly ){ | ||||
| 63328 | rc = SQLITE_READONLY_ROLLBACK(8 | (3<<8)); | ||||
| 63329 | goto failed; | ||||
| 63330 | } | ||||
| 63331 | |||||
| 63332 | /* Get an EXCLUSIVE lock on the database file. At this point it is | ||||
| 63333 | ** important that a RESERVED lock is not obtained on the way to the | ||||
| 63334 | ** EXCLUSIVE lock. If it were, another process might open the | ||||
| 63335 | ** database file, detect the RESERVED lock, and conclude that the | ||||
| 63336 | ** database is safe to read while this process is still rolling the | ||||
| 63337 | ** hot-journal back. | ||||
| 63338 | ** | ||||
| 63339 | ** Because the intermediate RESERVED lock is not requested, any | ||||
| 63340 | ** other process attempting to access the database file will get to | ||||
| 63341 | ** this point in the code and fail to obtain its own EXCLUSIVE lock | ||||
| 63342 | ** on the database file. | ||||
| 63343 | ** | ||||
| 63344 | ** Unless the pager is in locking_mode=exclusive mode, the lock is | ||||
| 63345 | ** downgraded to SHARED_LOCK before this function returns. | ||||
| 63346 | */ | ||||
| 63347 | rc = pagerLockDb(pPager, EXCLUSIVE_LOCK4); | ||||
| 63348 | if( rc!=SQLITE_OK0 ){ | ||||
| 63349 | goto failed; | ||||
| 63350 | } | ||||
| 63351 | |||||
| 63352 | /* If it is not already open and the file exists on disk, open the | ||||
| 63353 | ** journal for read/write access. Write access is required because | ||||
| 63354 | ** in exclusive-access mode the file descriptor will be kept open | ||||
| 63355 | ** and possibly used for a transaction later on. Also, write-access | ||||
| 63356 | ** is usually required to finalize the journal in journal_mode=persist | ||||
| 63357 | ** mode (and also for journal_mode=truncate on some systems). | ||||
| 63358 | ** | ||||
| 63359 | ** If the journal does not exist, it usually means that some | ||||
| 63360 | ** other connection managed to get in and roll it back before | ||||
| 63361 | ** this connection obtained the exclusive lock above. Or, it | ||||
| 63362 | ** may mean that the pager was in the error-state when this | ||||
| 63363 | ** function was called and the journal file does not exist. | ||||
| 63364 | */ | ||||
| 63365 | if( !isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) && pPager->journalMode!=PAGER_JOURNALMODE_OFF2 ){ | ||||
| 63366 | sqlite3_vfs * const pVfs = pPager->pVfs; | ||||
| 63367 | int bExists; /* True if journal file exists */ | ||||
| 63368 | rc = sqlite3OsAccess( | ||||
| 63369 | pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS0, &bExists); | ||||
| 63370 | if( rc==SQLITE_OK0 && bExists ){ | ||||
| 63371 | int fout = 0; | ||||
| 63372 | int f = SQLITE_OPEN_READWRITE0x00000002|SQLITE_OPEN_MAIN_JOURNAL0x00000800; | ||||
| 63373 | assert( !pPager->tempFile )((void) (0)); | ||||
| 63374 | rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); | ||||
| 63375 | assert( rc!=SQLITE_OK || isOpen(pPager->jfd) )((void) (0)); | ||||
| 63376 | if( rc==SQLITE_OK0 && fout&SQLITE_OPEN_READONLY0x00000001 ){ | ||||
| 63377 | rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(63377); | ||||
| 63378 | sqlite3OsClose(pPager->jfd); | ||||
| 63379 | } | ||||
| 63380 | } | ||||
| 63381 | } | ||||
| 63382 | |||||
| 63383 | /* Playback and delete the journal. Drop the database write | ||||
| 63384 | ** lock and reacquire the read lock. Purge the cache before | ||||
| 63385 | ** playing back the hot-journal so that we don't end up with | ||||
| 63386 | ** an inconsistent cache. Sync the hot journal before playing | ||||
| 63387 | ** it back since the process that crashed and left the hot journal | ||||
| 63388 | ** probably did not sync it and we are required to always sync | ||||
| 63389 | ** the journal before playing it back. | ||||
| 63390 | */ | ||||
| 63391 | if( isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) ){ | ||||
| 63392 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 63393 | rc = pagerSyncHotJournal(pPager); | ||||
| 63394 | if( rc==SQLITE_OK0 ){ | ||||
| 63395 | rc = pager_playback(pPager, !pPager->tempFile); | ||||
| 63396 | pPager->eState = PAGER_OPEN0; | ||||
| 63397 | } | ||||
| 63398 | }else if( !pPager->exclusiveMode ){ | ||||
| 63399 | pagerUnlockDb(pPager, SHARED_LOCK1); | ||||
| 63400 | } | ||||
| 63401 | |||||
| 63402 | if( rc!=SQLITE_OK0 ){ | ||||
| 63403 | /* This branch is taken if an error occurs while trying to open | ||||
| 63404 | ** or roll back a hot-journal while holding an EXCLUSIVE lock. The | ||||
| 63405 | ** pager_unlock() routine will be called before returning to unlock | ||||
| 63406 | ** the file. If the unlock attempt fails, then Pager.eLock must be | ||||
| 63407 | ** set to UNKNOWN_LOCK (see the comment above the #define for | ||||
| 63408 | ** UNKNOWN_LOCK above for an explanation). | ||||
| 63409 | ** | ||||
| 63410 | ** In order to get pager_unlock() to do this, set Pager.eState to | ||||
| 63411 | ** PAGER_ERROR now. This is not actually counted as a transition | ||||
| 63412 | ** to ERROR state in the state diagram at the top of this file, | ||||
| 63413 | ** since we know that the same call to pager_unlock() will very | ||||
| 63414 | ** shortly transition the pager object to the OPEN state. Calling | ||||
| 63415 | ** assert_pager_state() would fail now, as it should not be possible | ||||
| 63416 | ** to be in ERROR state when there are zero outstanding page | ||||
| 63417 | ** references. | ||||
| 63418 | */ | ||||
| 63419 | pager_error(pPager, rc); | ||||
| 63420 | goto failed; | ||||
| 63421 | } | ||||
| 63422 | |||||
| 63423 | assert( pPager->eState==PAGER_OPEN )((void) (0)); | ||||
| 63424 | assert( (pPager->eLock==SHARED_LOCK)((void) (0)) | ||||
| 63425 | || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)((void) (0)) | ||||
| 63426 | )((void) (0)); | ||||
| 63427 | } | ||||
| 63428 | |||||
| 63429 | if( !pPager->tempFile && pPager->hasHeldSharedLock ){ | ||||
| 63430 | /* The shared-lock has just been acquired then check to | ||||
| 63431 | ** see if the database has been modified. If the database has changed, | ||||
| 63432 | ** flush the cache. The hasHeldSharedLock flag prevents this from | ||||
| 63433 | ** occurring on the very first access to a file, in order to save a | ||||
| 63434 | ** single unnecessary sqlite3OsRead() call at the start-up. | ||||
| 63435 | ** | ||||
| 63436 | ** Database changes are detected by looking at 15 bytes beginning | ||||
| 63437 | ** at offset 24 into the file. The first 4 of these 16 bytes are | ||||
| 63438 | ** a 32-bit counter that is incremented with each change. The | ||||
| 63439 | ** other bytes change randomly with each file change when | ||||
| 63440 | ** a codec is in use. | ||||
| 63441 | ** | ||||
| 63442 | ** There is a vanishingly small chance that a change will not be | ||||
| 63443 | ** detected. The chance of an undetected change is so small that | ||||
| 63444 | ** it can be neglected. | ||||
| 63445 | */ | ||||
| 63446 | char dbFileVers[sizeof(pPager->dbFileVers)]; | ||||
| 63447 | |||||
| 63448 | IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); | ||||
| 63449 | rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); | ||||
| 63450 | if( rc!=SQLITE_OK0 ){ | ||||
| 63451 | if( rc!=SQLITE_IOERR_SHORT_READ(10 | (2<<8)) ){ | ||||
| 63452 | goto failed; | ||||
| 63453 | } | ||||
| 63454 | memset(dbFileVers, 0, sizeof(dbFileVers)); | ||||
| 63455 | } | ||||
| 63456 | |||||
| 63457 | if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){ | ||||
| 63458 | pager_reset(pPager); | ||||
| 63459 | |||||
| 63460 | /* Unmap the database file. It is possible that external processes | ||||
| 63461 | ** may have truncated the database file and then extended it back | ||||
| 63462 | ** to its original size while this process was not holding a lock. | ||||
| 63463 | ** In this case there may exist a Pager.pMap mapping that appears | ||||
| 63464 | ** to be the right size but is not actually valid. Avoid this | ||||
| 63465 | ** possibility by unmapping the db here. */ | ||||
| 63466 | if( USEFETCH(pPager)((pPager)->bUseFetch) ){ | ||||
| 63467 | sqlite3OsUnfetch(pPager->fd, 0, 0); | ||||
| 63468 | } | ||||
| 63469 | } | ||||
| 63470 | } | ||||
| 63471 | |||||
| 63472 | /* If there is a WAL file in the file-system, open this database in WAL | ||||
| 63473 | ** mode. Otherwise, the following function call is a no-op. | ||||
| 63474 | */ | ||||
| 63475 | rc = pagerOpenWalIfPresent(pPager); | ||||
| 63476 | #ifndef SQLITE_OMIT_WAL | ||||
| 63477 | assert( pPager->pWal==0 || rc==SQLITE_OK )((void) (0)); | ||||
| 63478 | #endif | ||||
| 63479 | } | ||||
| 63480 | |||||
| 63481 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 63482 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 63483 | rc = pagerBeginReadTransaction(pPager); | ||||
| 63484 | } | ||||
| 63485 | |||||
| 63486 | if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN0 && rc==SQLITE_OK0 ){ | ||||
| 63487 | rc = pagerPagecount(pPager, &pPager->dbSize); | ||||
| 63488 | } | ||||
| 63489 | |||||
| 63490 | failed: | ||||
| 63491 | if( rc!=SQLITE_OK0 ){ | ||||
| 63492 | assert( !MEMDB )((void) (0)); | ||||
| 63493 | pager_unlock(pPager); | ||||
| 63494 | assert( pPager->eState==PAGER_OPEN )((void) (0)); | ||||
| 63495 | }else{ | ||||
| 63496 | pPager->eState = PAGER_READER1; | ||||
| 63497 | pPager->hasHeldSharedLock = 1; | ||||
| 63498 | } | ||||
| 63499 | return rc; | ||||
| 63500 | } | ||||
| 63501 | |||||
| 63502 | /* | ||||
| 63503 | ** If the reference count has reached zero, rollback any active | ||||
| 63504 | ** transaction and unlock the pager. | ||||
| 63505 | ** | ||||
| 63506 | ** Except, in locking_mode=EXCLUSIVE when there is nothing to in | ||||
| 63507 | ** the rollback journal, the unlock is not performed and there is | ||||
| 63508 | ** nothing to rollback, so this routine is a no-op. | ||||
| 63509 | */ | ||||
| 63510 | static void pagerUnlockIfUnused(Pager *pPager){ | ||||
| 63511 | if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){ | ||||
| 63512 | assert( pPager->nMmapOut==0 )((void) (0)); /* because page1 is never memory mapped */ | ||||
| 63513 | pagerUnlockAndRollback(pPager); | ||||
| 63514 | } | ||||
| 63515 | } | ||||
| 63516 | |||||
| 63517 | /* | ||||
| 63518 | ** The page getter methods each try to acquire a reference to a | ||||
| 63519 | ** page with page number pgno. If the requested reference is | ||||
| 63520 | ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. | ||||
| 63521 | ** | ||||
| 63522 | ** There are different implementations of the getter method depending | ||||
| 63523 | ** on the current state of the pager. | ||||
| 63524 | ** | ||||
| 63525 | ** getPageNormal() -- The normal getter | ||||
| 63526 | ** getPageError() -- Used if the pager is in an error state | ||||
| 63527 | ** getPageMmap() -- Used if memory-mapped I/O is enabled | ||||
| 63528 | ** | ||||
| 63529 | ** If the requested page is already in the cache, it is returned. | ||||
| 63530 | ** Otherwise, a new page object is allocated and populated with data | ||||
| 63531 | ** read from the database file. In some cases, the pcache module may | ||||
| 63532 | ** choose not to allocate a new page object and may reuse an existing | ||||
| 63533 | ** object with no outstanding references. | ||||
| 63534 | ** | ||||
| 63535 | ** The extra data appended to a page is always initialized to zeros the | ||||
| 63536 | ** first time a page is loaded into memory. If the page requested is | ||||
| 63537 | ** already in the cache when this function is called, then the extra | ||||
| 63538 | ** data is left as it was when the page object was last used. | ||||
| 63539 | ** | ||||
| 63540 | ** If the database image is smaller than the requested page or if | ||||
| 63541 | ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the | ||||
| 63542 | ** requested page is not already stored in the cache, then no | ||||
| 63543 | ** actual disk read occurs. In this case the memory image of the | ||||
| 63544 | ** page is initialized to all zeros. | ||||
| 63545 | ** | ||||
| 63546 | ** If PAGER_GET_NOCONTENT is true, it means that we do not care about | ||||
| 63547 | ** the contents of the page. This occurs in two scenarios: | ||||
| 63548 | ** | ||||
| 63549 | ** a) When reading a free-list leaf page from the database, and | ||||
| 63550 | ** | ||||
| 63551 | ** b) When a savepoint is being rolled back and we need to load | ||||
| 63552 | ** a new page into the cache to be filled with the data read | ||||
| 63553 | ** from the savepoint journal. | ||||
| 63554 | ** | ||||
| 63555 | ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead | ||||
| 63556 | ** of being read from the database. Additionally, the bits corresponding | ||||
| 63557 | ** to pgno in Pager.pInJournal (bitvec of pages already written to the | ||||
| 63558 | ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open | ||||
| 63559 | ** savepoints are set. This means if the page is made writable at any | ||||
| 63560 | ** point in the future, using a call to sqlite3PagerWrite(), its contents | ||||
| 63561 | ** will not be journaled. This saves IO. | ||||
| 63562 | ** | ||||
| 63563 | ** The acquisition might fail for several reasons. In all cases, | ||||
| 63564 | ** an appropriate error code is returned and *ppPage is set to NULL. | ||||
| 63565 | ** | ||||
| 63566 | ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt | ||||
| 63567 | ** to find a page in the in-memory cache first. If the page is not already | ||||
| 63568 | ** in memory, this routine goes to disk to read it in whereas Lookup() | ||||
| 63569 | ** just returns 0. This routine acquires a read-lock the first time it | ||||
| 63570 | ** has to go to disk, and could also playback an old journal if necessary. | ||||
| 63571 | ** Since Lookup() never goes to disk, it never has to deal with locks | ||||
| 63572 | ** or journal files. | ||||
| 63573 | */ | ||||
| 63574 | static int getPageNormal( | ||||
| 63575 | Pager *pPager, /* The pager open on the database file */ | ||||
| 63576 | Pgno pgno, /* Page number to fetch */ | ||||
| 63577 | DbPage **ppPage, /* Write a pointer to the page here */ | ||||
| 63578 | int flags /* PAGER_GET_XXX flags */ | ||||
| 63579 | ){ | ||||
| 63580 | int rc = SQLITE_OK0; | ||||
| 63581 | PgHdr *pPg; | ||||
| 63582 | u8 noContent; /* True if PAGER_GET_NOCONTENT is set */ | ||||
| 63583 | sqlite3_pcache_page *pBase; | ||||
| 63584 | |||||
| 63585 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 63586 | assert( pPager->eState>=PAGER_READER )((void) (0)); | ||||
| 63587 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 63588 | assert( pPager->hasHeldSharedLock==1 )((void) (0)); | ||||
| 63589 | |||||
| 63590 | if( pgno==0 ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(63590); | ||||
| 63591 | pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3); | ||||
| 63592 | if( pBase==0 ){ | ||||
| 63593 | pPg = 0; | ||||
| 63594 | rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase); | ||||
| 63595 | if( rc!=SQLITE_OK0 ) goto pager_acquire_err; | ||||
| 63596 | if( pBase==0 ){ | ||||
| 63597 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 63598 | goto pager_acquire_err; | ||||
| 63599 | } | ||||
| 63600 | } | ||||
| 63601 | pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase); | ||||
| 63602 | assert( pPg==(*ppPage) )((void) (0)); | ||||
| 63603 | assert( pPg->pgno==pgno )((void) (0)); | ||||
| 63604 | assert( pPg->pPager==pPager || pPg->pPager==0 )((void) (0)); | ||||
| 63605 | |||||
| 63606 | noContent = (flags & PAGER_GET_NOCONTENT0x01)!=0; | ||||
| 63607 | if( pPg->pPager && !noContent ){ | ||||
| 63608 | /* In this case the pcache already contains an initialized copy of | ||||
| 63609 | ** the page. Return without further ado. */ | ||||
| 63610 | assert( pgno!=PAGER_SJ_PGNO(pPager) )((void) (0)); | ||||
| 63611 | pPager->aStat[PAGER_STAT_HIT0]++; | ||||
| 63612 | return SQLITE_OK0; | ||||
| 63613 | |||||
| 63614 | }else{ | ||||
| 63615 | /* The pager cache has created a new page. Its content needs to | ||||
| 63616 | ** be initialized. But first some error checks: | ||||
| 63617 | ** | ||||
| 63618 | ** (*) obsolete. Was: maximum page number is 2^31 | ||||
| 63619 | ** (2) Never try to fetch the locking page | ||||
| 63620 | */ | ||||
| 63621 | if( pgno==PAGER_SJ_PGNO(pPager)((pPager)->lckPgno) ){ | ||||
| 63622 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(63622); | ||||
| 63623 | goto pager_acquire_err; | ||||
| 63624 | } | ||||
| 63625 | |||||
| 63626 | pPg->pPager = pPager; | ||||
| 63627 | |||||
| 63628 | assert( !isOpen(pPager->fd) || !MEMDB )((void) (0)); | ||||
| 63629 | if( !isOpen(pPager->fd)((pPager->fd)->pMethods!=0) || pPager->dbSize<pgno || noContent ){ | ||||
| 63630 | if( pgno>pPager->mxPgno ){ | ||||
| 63631 | rc = SQLITE_FULL13; | ||||
| 63632 | if( pgno<=pPager->dbSize ){ | ||||
| 63633 | sqlite3PcacheRelease(pPg); | ||||
| 63634 | pPg = 0; | ||||
| 63635 | } | ||||
| 63636 | goto pager_acquire_err; | ||||
| 63637 | } | ||||
| 63638 | if( noContent ){ | ||||
| 63639 | /* Failure to set the bits in the InJournal bit-vectors is benign. | ||||
| 63640 | ** It merely means that we might do some extra work to journal a | ||||
| 63641 | ** page that does not need to be journaled. Nevertheless, be sure | ||||
| 63642 | ** to test the case where a malloc error occurs while trying to set | ||||
| 63643 | ** a bit in a bit vector. | ||||
| 63644 | */ | ||||
| 63645 | sqlite3BeginBenignMalloc(); | ||||
| 63646 | if( pgno<=pPager->dbOrigSize ){ | ||||
| 63647 | TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno); | ||||
| 63648 | testcase( rc==SQLITE_NOMEM ); | ||||
| 63649 | } | ||||
| 63650 | TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); | ||||
| 63651 | testcase( rc==SQLITE_NOMEM ); | ||||
| 63652 | sqlite3EndBenignMalloc(); | ||||
| 63653 | } | ||||
| 63654 | memset(pPg->pData, 0, pPager->pageSize); | ||||
| 63655 | IOTRACE(("ZERO %p %d\n", pPager, pgno)); | ||||
| 63656 | }else{ | ||||
| 63657 | assert( pPg->pPager==pPager )((void) (0)); | ||||
| 63658 | pPager->aStat[PAGER_STAT_MISS1]++; | ||||
| 63659 | rc = readDbPage(pPg); | ||||
| 63660 | if( rc!=SQLITE_OK0 ){ | ||||
| 63661 | goto pager_acquire_err; | ||||
| 63662 | } | ||||
| 63663 | } | ||||
| 63664 | pager_set_pagehash(pPg); | ||||
| 63665 | } | ||||
| 63666 | return SQLITE_OK0; | ||||
| 63667 | |||||
| 63668 | pager_acquire_err: | ||||
| 63669 | assert( rc!=SQLITE_OK )((void) (0)); | ||||
| 63670 | if( pPg ){ | ||||
| 63671 | sqlite3PcacheDrop(pPg); | ||||
| 63672 | } | ||||
| 63673 | pagerUnlockIfUnused(pPager); | ||||
| 63674 | *ppPage = 0; | ||||
| 63675 | return rc; | ||||
| 63676 | } | ||||
| 63677 | |||||
| 63678 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 63679 | /* The page getter for when memory-mapped I/O is enabled */ | ||||
| 63680 | static int getPageMMap( | ||||
| 63681 | Pager *pPager, /* The pager open on the database file */ | ||||
| 63682 | Pgno pgno, /* Page number to fetch */ | ||||
| 63683 | DbPage **ppPage, /* Write a pointer to the page here */ | ||||
| 63684 | int flags /* PAGER_GET_XXX flags */ | ||||
| 63685 | ){ | ||||
| 63686 | int rc = SQLITE_OK0; | ||||
| 63687 | PgHdr *pPg = 0; | ||||
| 63688 | u32 iFrame = 0; /* Frame to read from WAL file */ | ||||
| 63689 | |||||
| 63690 | /* It is acceptable to use a read-only (mmap) page for any page except | ||||
| 63691 | ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY | ||||
| 63692 | ** flag was specified by the caller. And so long as the db is not a | ||||
| 63693 | ** temporary or in-memory database. */ | ||||
| 63694 | const int bMmapOk = (pgno>1 | ||||
| 63695 | && (pPager->eState==PAGER_READER1 || (flags & PAGER_GET_READONLY0x02)) | ||||
| 63696 | ); | ||||
| 63697 | |||||
| 63698 | assert( USEFETCH(pPager) )((void) (0)); | ||||
| 63699 | |||||
| 63700 | /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here | ||||
| 63701 | ** allows the compiler optimizer to reuse the results of the "pgno>1" | ||||
| 63702 | ** test in the previous statement, and avoid testing pgno==0 in the | ||||
| 63703 | ** common case where pgno is large. */ | ||||
| 63704 | if( pgno<=1 && pgno==0 ){ | ||||
| 63705 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(63705); | ||||
| 63706 | } | ||||
| 63707 | assert( pPager->eState>=PAGER_READER )((void) (0)); | ||||
| 63708 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 63709 | assert( pPager->hasHeldSharedLock==1 )((void) (0)); | ||||
| 63710 | assert( pPager->errCode==SQLITE_OK )((void) (0)); | ||||
| 63711 | |||||
| 63712 | if( bMmapOk && pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 63713 | rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); | ||||
| 63714 | if( rc!=SQLITE_OK0 ){ | ||||
| 63715 | *ppPage = 0; | ||||
| 63716 | return rc; | ||||
| 63717 | } | ||||
| 63718 | } | ||||
| 63719 | if( bMmapOk && iFrame==0 ){ | ||||
| 63720 | void *pData = 0; | ||||
| 63721 | rc = sqlite3OsFetch(pPager->fd, | ||||
| 63722 | (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData | ||||
| 63723 | ); | ||||
| 63724 | if( rc==SQLITE_OK0 && pData ){ | ||||
| 63725 | if( pPager->eState>PAGER_READER1 || pPager->tempFile ){ | ||||
| 63726 | pPg = sqlite3PagerLookup(pPager, pgno); | ||||
| 63727 | } | ||||
| 63728 | if( pPg==0 ){ | ||||
| 63729 | rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); | ||||
| 63730 | }else{ | ||||
| 63731 | sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); | ||||
| 63732 | } | ||||
| 63733 | if( pPg ){ | ||||
| 63734 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 63735 | *ppPage = pPg; | ||||
| 63736 | return SQLITE_OK0; | ||||
| 63737 | } | ||||
| 63738 | } | ||||
| 63739 | if( rc!=SQLITE_OK0 ){ | ||||
| 63740 | *ppPage = 0; | ||||
| 63741 | return rc; | ||||
| 63742 | } | ||||
| 63743 | } | ||||
| 63744 | return getPageNormal(pPager, pgno, ppPage, flags); | ||||
| 63745 | } | ||||
| 63746 | #endif /* SQLITE_MAX_MMAP_SIZE>0 */ | ||||
| 63747 | |||||
| 63748 | /* The page getter method for when the pager is an error state */ | ||||
| 63749 | static int getPageError( | ||||
| 63750 | Pager *pPager, /* The pager open on the database file */ | ||||
| 63751 | Pgno pgno, /* Page number to fetch */ | ||||
| 63752 | DbPage **ppPage, /* Write a pointer to the page here */ | ||||
| 63753 | int flags /* PAGER_GET_XXX flags */ | ||||
| 63754 | ){ | ||||
| 63755 | UNUSED_PARAMETER(pgno)(void)(pgno); | ||||
| 63756 | UNUSED_PARAMETER(flags)(void)(flags); | ||||
| 63757 | assert( pPager->errCode!=SQLITE_OK )((void) (0)); | ||||
| 63758 | *ppPage = 0; | ||||
| 63759 | return pPager->errCode; | ||||
| 63760 | } | ||||
| 63761 | |||||
| 63762 | |||||
| 63763 | /* Dispatch all page fetch requests to the appropriate getter method. | ||||
| 63764 | */ | ||||
| 63765 | SQLITE_PRIVATEstatic int sqlite3PagerGet( | ||||
| 63766 | Pager *pPager, /* The pager open on the database file */ | ||||
| 63767 | Pgno pgno, /* Page number to fetch */ | ||||
| 63768 | DbPage **ppPage, /* Write a pointer to the page here */ | ||||
| 63769 | int flags /* PAGER_GET_XXX flags */ | ||||
| 63770 | ){ | ||||
| 63771 | #if 0 /* Trace page fetch by setting to 1 */ | ||||
| 63772 | int rc; | ||||
| 63773 | printf("PAGE %u\n", pgno); | ||||
| 63774 | fflush(stdoutstdout); | ||||
| 63775 | rc = pPager->xGet(pPager, pgno, ppPage, flags); | ||||
| 63776 | if( rc ){ | ||||
| 63777 | printf("PAGE %u failed with 0x%02x\n", pgno, rc); | ||||
| 63778 | fflush(stdoutstdout); | ||||
| 63779 | } | ||||
| 63780 | return rc; | ||||
| 63781 | #else | ||||
| 63782 | /* Normal, high-speed version of sqlite3PagerGet() */ | ||||
| 63783 | return pPager->xGet(pPager, pgno, ppPage, flags); | ||||
| 63784 | #endif | ||||
| 63785 | } | ||||
| 63786 | |||||
| 63787 | /* | ||||
| 63788 | ** Acquire a page if it is already in the in-memory cache. Do | ||||
| 63789 | ** not read the page from disk. Return a pointer to the page, | ||||
| 63790 | ** or 0 if the page is not in cache. | ||||
| 63791 | ** | ||||
| 63792 | ** See also sqlite3PagerGet(). The difference between this routine | ||||
| 63793 | ** and sqlite3PagerGet() is that _get() will go to the disk and read | ||||
| 63794 | ** in the page if the page is not already in cache. This routine | ||||
| 63795 | ** returns NULL if the page is not in cache or if a disk I/O error | ||||
| 63796 | ** has ever happened. | ||||
| 63797 | */ | ||||
| 63798 | SQLITE_PRIVATEstatic DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){ | ||||
| 63799 | sqlite3_pcache_page *pPage; | ||||
| 63800 | assert( pPager!=0 )((void) (0)); | ||||
| 63801 | assert( pgno!=0 )((void) (0)); | ||||
| 63802 | assert( pPager->pPCache!=0 )((void) (0)); | ||||
| 63803 | pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0); | ||||
| 63804 | assert( pPage==0 || pPager->hasHeldSharedLock )((void) (0)); | ||||
| 63805 | if( pPage==0 ) return 0; | ||||
| 63806 | return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage); | ||||
| 63807 | } | ||||
| 63808 | |||||
| 63809 | /* | ||||
| 63810 | ** Release a page reference. | ||||
| 63811 | ** | ||||
| 63812 | ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be used | ||||
| 63813 | ** if we know that the page being released is not the last reference to page1. | ||||
| 63814 | ** The btree layer always holds page1 open until the end, so these first | ||||
| 63815 | ** two routines can be used to release any page other than BtShared.pPage1. | ||||
| 63816 | ** The assert() at tag-20230419-2 proves that this constraint is always | ||||
| 63817 | ** honored. | ||||
| 63818 | ** | ||||
| 63819 | ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine | ||||
| 63820 | ** checks the total number of outstanding pages and if the number of | ||||
| 63821 | ** pages reaches zero it drops the database lock. | ||||
| 63822 | */ | ||||
| 63823 | SQLITE_PRIVATEstatic void sqlite3PagerUnrefNotNull(DbPage *pPg){ | ||||
| 63824 | TESTONLY( Pager *pPager = pPg->pPager; ) | ||||
| 63825 | assert( pPg!=0 )((void) (0)); | ||||
| 63826 | if( pPg->flags & PGHDR_MMAP0x020 ){ | ||||
| 63827 | assert( pPg->pgno!=1 )((void) (0)); /* Page1 is never memory mapped */ | ||||
| 63828 | pagerReleaseMapPage(pPg); | ||||
| 63829 | }else{ | ||||
| 63830 | sqlite3PcacheRelease(pPg); | ||||
| 63831 | } | ||||
| 63832 | /* Do not use this routine to release the last reference to page1 */ | ||||
| 63833 | assert( sqlite3PcacheRefCount(pPager->pPCache)>0 )((void) (0)); /* tag-20230419-2 */ | ||||
| 63834 | } | ||||
| 63835 | SQLITE_PRIVATEstatic void sqlite3PagerUnref(DbPage *pPg){ | ||||
| 63836 | if( pPg ) sqlite3PagerUnrefNotNull(pPg); | ||||
| 63837 | } | ||||
| 63838 | SQLITE_PRIVATEstatic void sqlite3PagerUnrefPageOne(DbPage *pPg){ | ||||
| 63839 | Pager *pPager; | ||||
| 63840 | assert( pPg!=0 )((void) (0)); | ||||
| 63841 | assert( pPg->pgno==1 )((void) (0)); | ||||
| 63842 | assert( (pPg->flags & PGHDR_MMAP)==0 )((void) (0)); /* Page1 is never memory mapped */ | ||||
| 63843 | pPager = pPg->pPager; | ||||
| 63844 | sqlite3PcacheRelease(pPg); | ||||
| 63845 | pagerUnlockIfUnused(pPager); | ||||
| 63846 | } | ||||
| 63847 | |||||
| 63848 | /* | ||||
| 63849 | ** This function is called at the start of every write transaction. | ||||
| 63850 | ** There must already be a RESERVED or EXCLUSIVE lock on the database | ||||
| 63851 | ** file when this routine is called. | ||||
| 63852 | ** | ||||
| 63853 | ** Open the journal file for pager pPager and write a journal header | ||||
| 63854 | ** to the start of it. If there are active savepoints, open the sub-journal | ||||
| 63855 | ** as well. This function is only used when the journal file is being | ||||
| 63856 | ** opened to write a rollback log for a transaction. It is not used | ||||
| 63857 | ** when opening a hot journal file to roll it back. | ||||
| 63858 | ** | ||||
| 63859 | ** If the journal file is already open (as it may be in exclusive mode), | ||||
| 63860 | ** then this function just writes a journal header to the start of the | ||||
| 63861 | ** already open file. | ||||
| 63862 | ** | ||||
| 63863 | ** Whether or not the journal file is opened by this function, the | ||||
| 63864 | ** Pager.pInJournal bitvec structure is allocated. | ||||
| 63865 | ** | ||||
| 63866 | ** Return SQLITE_OK if everything is successful. Otherwise, return | ||||
| 63867 | ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or | ||||
| 63868 | ** an IO error code if opening or writing the journal file fails. | ||||
| 63869 | */ | ||||
| 63870 | static int pager_open_journal(Pager *pPager){ | ||||
| 63871 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 63872 | sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ | ||||
| 63873 | |||||
| 63874 | assert( pPager->eState==PAGER_WRITER_LOCKED )((void) (0)); | ||||
| 63875 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 63876 | assert( pPager->pInJournal==0 )((void) (0)); | ||||
| 63877 | |||||
| 63878 | /* If already in the error state, this function is a no-op. But on | ||||
| 63879 | ** the other hand, this routine is never called if we are already in | ||||
| 63880 | ** an error state. */ | ||||
| 63881 | if( NEVER(pPager->errCode)(pPager->errCode) ) return pPager->errCode; | ||||
| 63882 | |||||
| 63883 | if( !pagerUseWal(pPager)((pPager)->pWal!=0) && pPager->journalMode!=PAGER_JOURNALMODE_OFF2 ){ | ||||
| 63884 | pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize); | ||||
| 63885 | if( pPager->pInJournal==0 ){ | ||||
| 63886 | return SQLITE_NOMEM_BKPT7; | ||||
| 63887 | } | ||||
| 63888 | |||||
| 63889 | /* Open the journal file if it is not already open. */ | ||||
| 63890 | if( !isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) ){ | ||||
| 63891 | if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY4 ){ | ||||
| 63892 | sqlite3MemJournalOpen(pPager->jfd); | ||||
| 63893 | }else{ | ||||
| 63894 | int flags = SQLITE_OPEN_READWRITE0x00000002|SQLITE_OPEN_CREATE0x00000004; | ||||
| 63895 | int nSpill; | ||||
| 63896 | |||||
| 63897 | if( pPager->tempFile ){ | ||||
| 63898 | flags |= (SQLITE_OPEN_DELETEONCLOSE0x00000008|SQLITE_OPEN_TEMP_JOURNAL0x00001000); | ||||
| 63899 | flags |= SQLITE_OPEN_EXCLUSIVE0x00000010; | ||||
| 63900 | nSpill = sqlite3Config.nStmtSpill; | ||||
| 63901 | }else{ | ||||
| 63902 | flags |= SQLITE_OPEN_MAIN_JOURNAL0x00000800; | ||||
| 63903 | nSpill = jrnlBufferSize(pPager); | ||||
| 63904 | } | ||||
| 63905 | |||||
| 63906 | /* Verify that the database still has the same name as it did when | ||||
| 63907 | ** it was originally opened. */ | ||||
| 63908 | rc = databaseIsUnmoved(pPager); | ||||
| 63909 | if( rc==SQLITE_OK0 ){ | ||||
| 63910 | rc = sqlite3JournalOpen ( | ||||
| 63911 | pVfs, pPager->zJournal, pPager->jfd, flags, nSpill | ||||
| 63912 | ); | ||||
| 63913 | } | ||||
| 63914 | } | ||||
| 63915 | assert( rc!=SQLITE_OK || isOpen(pPager->jfd) )((void) (0)); | ||||
| 63916 | } | ||||
| 63917 | |||||
| 63918 | |||||
| 63919 | /* Write the first journal header to the journal file and open | ||||
| 63920 | ** the sub-journal if necessary. | ||||
| 63921 | */ | ||||
| 63922 | if( rc==SQLITE_OK0 ){ | ||||
| 63923 | /* TODO: Check if all of these are really required. */ | ||||
| 63924 | pPager->nRec = 0; | ||||
| 63925 | pPager->journalOff = 0; | ||||
| 63926 | pPager->setSuper = 0; | ||||
| 63927 | pPager->journalHdr = 0; | ||||
| 63928 | rc = writeJournalHdr(pPager); | ||||
| 63929 | } | ||||
| 63930 | } | ||||
| 63931 | |||||
| 63932 | if( rc!=SQLITE_OK0 ){ | ||||
| 63933 | sqlite3BitvecDestroy(pPager->pInJournal); | ||||
| 63934 | pPager->pInJournal = 0; | ||||
| 63935 | pPager->journalOff = 0; | ||||
| 63936 | }else{ | ||||
| 63937 | assert( pPager->eState==PAGER_WRITER_LOCKED )((void) (0)); | ||||
| 63938 | pPager->eState = PAGER_WRITER_CACHEMOD3; | ||||
| 63939 | } | ||||
| 63940 | |||||
| 63941 | return rc; | ||||
| 63942 | } | ||||
| 63943 | |||||
| 63944 | /* | ||||
| 63945 | ** Begin a write-transaction on the specified pager object. If a | ||||
| 63946 | ** write-transaction has already been opened, this function is a no-op. | ||||
| 63947 | ** | ||||
| 63948 | ** If the exFlag argument is false, then acquire at least a RESERVED | ||||
| 63949 | ** lock on the database file. If exFlag is true, then acquire at least | ||||
| 63950 | ** an EXCLUSIVE lock. If such a lock is already held, no locking | ||||
| 63951 | ** functions need be called. | ||||
| 63952 | ** | ||||
| 63953 | ** If the subjInMemory argument is non-zero, then any sub-journal opened | ||||
| 63954 | ** within this transaction will be opened as an in-memory file. This | ||||
| 63955 | ** has no effect if the sub-journal is already opened (as it may be when | ||||
| 63956 | ** running in exclusive mode) or if the transaction does not require a | ||||
| 63957 | ** sub-journal. If the subjInMemory argument is zero, then any required | ||||
| 63958 | ** sub-journal is implemented in-memory if pPager is an in-memory database, | ||||
| 63959 | ** or using a temporary file otherwise. | ||||
| 63960 | */ | ||||
| 63961 | SQLITE_PRIVATEstatic int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ | ||||
| 63962 | int rc = SQLITE_OK0; | ||||
| 63963 | |||||
| 63964 | if( pPager->errCode ) return pPager->errCode; | ||||
| 63965 | assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR )((void) (0)); | ||||
| 63966 | pPager->subjInMemory = (u8)subjInMemory; | ||||
| 63967 | |||||
| 63968 | if( pPager->eState==PAGER_READER1 ){ | ||||
| 63969 | assert( pPager->pInJournal==0 )((void) (0)); | ||||
| 63970 | |||||
| 63971 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 63972 | /* If the pager is configured to use locking_mode=exclusive, and an | ||||
| 63973 | ** exclusive lock on the database is not already held, obtain it now. | ||||
| 63974 | */ | ||||
| 63975 | if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){ | ||||
| 63976 | rc = pagerLockDb(pPager, EXCLUSIVE_LOCK4); | ||||
| 63977 | if( rc!=SQLITE_OK0 ){ | ||||
| 63978 | return rc; | ||||
| 63979 | } | ||||
| 63980 | (void)sqlite3WalExclusiveMode(pPager->pWal, 1); | ||||
| 63981 | } | ||||
| 63982 | |||||
| 63983 | /* Grab the write lock on the log file. If successful, upgrade to | ||||
| 63984 | ** PAGER_RESERVED state. Otherwise, return an error code to the caller. | ||||
| 63985 | ** The busy-handler is not invoked if another connection already | ||||
| 63986 | ** holds the write-lock. If possible, the upper layer will call it. | ||||
| 63987 | */ | ||||
| 63988 | rc = sqlite3WalBeginWriteTransaction(pPager->pWal); | ||||
| 63989 | }else{ | ||||
| 63990 | /* Obtain a RESERVED lock on the database file. If the exFlag parameter | ||||
| 63991 | ** is true, then immediately upgrade this to an EXCLUSIVE lock. The | ||||
| 63992 | ** busy-handler callback can be used when upgrading to the EXCLUSIVE | ||||
| 63993 | ** lock, but not when obtaining the RESERVED lock. | ||||
| 63994 | */ | ||||
| 63995 | rc = pagerLockDb(pPager, RESERVED_LOCK2); | ||||
| 63996 | if( rc==SQLITE_OK0 && exFlag ){ | ||||
| 63997 | rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK4); | ||||
| 63998 | } | ||||
| 63999 | } | ||||
| 64000 | |||||
| 64001 | if( rc==SQLITE_OK0 ){ | ||||
| 64002 | /* Change to WRITER_LOCKED state. | ||||
| 64003 | ** | ||||
| 64004 | ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD | ||||
| 64005 | ** when it has an open transaction, but never to DBMOD or FINISHED. | ||||
| 64006 | ** This is because in those states the code to roll back savepoint | ||||
| 64007 | ** transactions may copy data from the sub-journal into the database | ||||
| 64008 | ** file as well as into the page cache. Which would be incorrect in | ||||
| 64009 | ** WAL mode. | ||||
| 64010 | */ | ||||
| 64011 | pPager->eState = PAGER_WRITER_LOCKED2; | ||||
| 64012 | pPager->dbHintSize = pPager->dbSize; | ||||
| 64013 | pPager->dbFileSize = pPager->dbSize; | ||||
| 64014 | pPager->dbOrigSize = pPager->dbSize; | ||||
| 64015 | pPager->journalOff = 0; | ||||
| 64016 | } | ||||
| 64017 | |||||
| 64018 | assert( rc==SQLITE_OK || pPager->eState==PAGER_READER )((void) (0)); | ||||
| 64019 | assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED )((void) (0)); | ||||
| 64020 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64021 | } | ||||
| 64022 | |||||
| 64023 | PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager))); | ||||
| 64024 | return rc; | ||||
| 64025 | } | ||||
| 64026 | |||||
| 64027 | /* | ||||
| 64028 | ** Write page pPg onto the end of the rollback journal. | ||||
| 64029 | */ | ||||
| 64030 | static SQLITE_NOINLINE__attribute__((noinline)) int pagerAddPageToRollbackJournal(PgHdr *pPg){ | ||||
| 64031 | Pager *pPager = pPg->pPager; | ||||
| 64032 | int rc; | ||||
| 64033 | u32 cksum; | ||||
| 64034 | char *pData2; | ||||
| 64035 | i64 iOff = pPager->journalOff; | ||||
| 64036 | |||||
| 64037 | /* We should never write to the journal file the page that | ||||
| 64038 | ** contains the database locks. The following assert verifies | ||||
| 64039 | ** that we do not. */ | ||||
| 64040 | assert( pPg->pgno!=PAGER_SJ_PGNO(pPager) )((void) (0)); | ||||
| 64041 | |||||
| 64042 | assert( pPager->journalHdr<=pPager->journalOff )((void) (0)); | ||||
| 64043 | pData2 = pPg->pData; | ||||
| 64044 | cksum = pager_cksum(pPager, (u8*)pData2); | ||||
| 64045 | |||||
| 64046 | /* Even if an IO or diskfull error occurs while journalling the | ||||
| 64047 | ** page in the block above, set the need-sync flag for the page. | ||||
| 64048 | ** Otherwise, when the transaction is rolled back, the logic in | ||||
| 64049 | ** playback_one_page() will think that the page needs to be restored | ||||
| 64050 | ** in the database file. And if an IO error occurs while doing so, | ||||
| 64051 | ** then corruption may follow. | ||||
| 64052 | */ | ||||
| 64053 | pPg->flags |= PGHDR_NEED_SYNC0x008; | ||||
| 64054 | |||||
| 64055 | rc = write32bits(pPager->jfd, iOff, pPg->pgno); | ||||
| 64056 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 64057 | rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); | ||||
| 64058 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 64059 | rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum); | ||||
| 64060 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 64061 | |||||
| 64062 | IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, | ||||
| 64063 | pPager->journalOff, pPager->pageSize)); | ||||
| 64064 | PAGER_INCR(sqlite3_pager_writej_count); | ||||
| 64065 | PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n", | ||||
| 64066 | PAGERID(pPager), pPg->pgno, | ||||
| 64067 | ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg))); | ||||
| 64068 | |||||
| 64069 | pPager->journalOff += 8 + pPager->pageSize; | ||||
| 64070 | pPager->nRec++; | ||||
| 64071 | assert( pPager->pInJournal!=0 )((void) (0)); | ||||
| 64072 | rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno); | ||||
| 64073 | testcase( rc==SQLITE_NOMEM ); | ||||
| 64074 | assert( rc==SQLITE_OK || rc==SQLITE_NOMEM )((void) (0)); | ||||
| 64075 | rc |= addToSavepointBitvecs(pPager, pPg->pgno); | ||||
| 64076 | assert( rc==SQLITE_OK || rc==SQLITE_NOMEM )((void) (0)); | ||||
| 64077 | return rc; | ||||
| 64078 | } | ||||
| 64079 | |||||
| 64080 | /* | ||||
| 64081 | ** Mark a single data page as writeable. The page is written into the | ||||
| 64082 | ** main journal or sub-journal as required. If the page is written into | ||||
| 64083 | ** one of the journals, the corresponding bit is set in the | ||||
| 64084 | ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs | ||||
| 64085 | ** of any open savepoints as appropriate. | ||||
| 64086 | */ | ||||
| 64087 | static int pager_write(PgHdr *pPg){ | ||||
| 64088 | Pager *pPager = pPg->pPager; | ||||
| 64089 | int rc = SQLITE_OK0; | ||||
| 64090 | |||||
| 64091 | /* This routine is not called unless a write-transaction has already | ||||
| 64092 | ** been started. The journal file may or may not be open at this point. | ||||
| 64093 | ** It is never called in the ERROR state. | ||||
| 64094 | */ | ||||
| 64095 | assert( pPager->eState==PAGER_WRITER_LOCKED((void) (0)) | ||||
| 64096 | || pPager->eState==PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 64097 | || pPager->eState==PAGER_WRITER_DBMOD((void) (0)) | ||||
| 64098 | )((void) (0)); | ||||
| 64099 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64100 | assert( pPager->errCode==0 )((void) (0)); | ||||
| 64101 | assert( pPager->readOnly==0 )((void) (0)); | ||||
| 64102 | CHECK_PAGE(pPg); | ||||
| 64103 | |||||
| 64104 | /* The journal file needs to be opened. Higher level routines have already | ||||
| 64105 | ** obtained the necessary locks to begin the write-transaction, but the | ||||
| 64106 | ** rollback journal might not yet be open. Open it now if this is the case. | ||||
| 64107 | ** | ||||
| 64108 | ** This is done before calling sqlite3PcacheMakeDirty() on the page. | ||||
| 64109 | ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then | ||||
| 64110 | ** an error might occur and the pager would end up in WRITER_LOCKED state | ||||
| 64111 | ** with pages marked as dirty in the cache. | ||||
| 64112 | */ | ||||
| 64113 | if( pPager->eState==PAGER_WRITER_LOCKED2 ){ | ||||
| 64114 | rc = pager_open_journal(pPager); | ||||
| 64115 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 64116 | } | ||||
| 64117 | assert( pPager->eState>=PAGER_WRITER_CACHEMOD )((void) (0)); | ||||
| 64118 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64119 | |||||
| 64120 | /* Mark the page that is about to be modified as dirty. */ | ||||
| 64121 | sqlite3PcacheMakeDirty(pPg); | ||||
| 64122 | |||||
| 64123 | /* If a rollback journal is in use, them make sure the page that is about | ||||
| 64124 | ** to change is in the rollback journal, or if the page is a new page off | ||||
| 64125 | ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC. | ||||
| 64126 | */ | ||||
| 64127 | assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) )((void) (0)); | ||||
| 64128 | if( pPager->pInJournal!=0 | ||||
| 64129 | && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0 | ||||
| 64130 | ){ | ||||
| 64131 | assert( pagerUseWal(pPager)==0 )((void) (0)); | ||||
| 64132 | if( pPg->pgno<=pPager->dbOrigSize ){ | ||||
| 64133 | rc = pagerAddPageToRollbackJournal(pPg); | ||||
| 64134 | if( rc!=SQLITE_OK0 ){ | ||||
| 64135 | return rc; | ||||
| 64136 | } | ||||
| 64137 | }else{ | ||||
| 64138 | if( pPager->eState!=PAGER_WRITER_DBMOD4 ){ | ||||
| 64139 | pPg->flags |= PGHDR_NEED_SYNC0x008; | ||||
| 64140 | } | ||||
| 64141 | PAGERTRACE(("APPEND %d page %d needSync=%d\n", | ||||
| 64142 | PAGERID(pPager), pPg->pgno, | ||||
| 64143 | ((pPg->flags&PGHDR_NEED_SYNC)?1:0))); | ||||
| 64144 | } | ||||
| 64145 | } | ||||
| 64146 | |||||
| 64147 | /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list | ||||
| 64148 | ** and before writing the page into the rollback journal. Wait until now, | ||||
| 64149 | ** after the page has been successfully journalled, before setting the | ||||
| 64150 | ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified. | ||||
| 64151 | */ | ||||
| 64152 | pPg->flags |= PGHDR_WRITEABLE0x004; | ||||
| 64153 | |||||
| 64154 | /* If the statement journal is open and the page is not in it, | ||||
| 64155 | ** then write the page into the statement journal. | ||||
| 64156 | */ | ||||
| 64157 | if( pPager->nSavepoint>0 ){ | ||||
| 64158 | rc = subjournalPageIfRequired(pPg); | ||||
| 64159 | } | ||||
| 64160 | |||||
| 64161 | /* Update the database size and return. */ | ||||
| 64162 | if( pPager->dbSize<pPg->pgno ){ | ||||
| 64163 | pPager->dbSize = pPg->pgno; | ||||
| 64164 | } | ||||
| 64165 | return rc; | ||||
| 64166 | } | ||||
| 64167 | |||||
| 64168 | /* | ||||
| 64169 | ** This is a variant of sqlite3PagerWrite() that runs when the sector size | ||||
| 64170 | ** is larger than the page size. SQLite makes the (reasonable) assumption that | ||||
| 64171 | ** all bytes of a sector are written together by hardware. Hence, all bytes of | ||||
| 64172 | ** a sector need to be journalled in case of a power loss in the middle of | ||||
| 64173 | ** a write. | ||||
| 64174 | ** | ||||
| 64175 | ** Usually, the sector size is less than or equal to the page size, in which | ||||
| 64176 | ** case pages can be individually written. This routine only runs in the | ||||
| 64177 | ** exceptional case where the page size is smaller than the sector size. | ||||
| 64178 | */ | ||||
| 64179 | static SQLITE_NOINLINE__attribute__((noinline)) int pagerWriteLargeSector(PgHdr *pPg){ | ||||
| 64180 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 64181 | Pgno nPageCount; /* Total number of pages in database file */ | ||||
| 64182 | Pgno pg1; /* First page of the sector pPg is located on. */ | ||||
| 64183 | int nPage = 0; /* Number of pages starting at pg1 to journal */ | ||||
| 64184 | int ii; /* Loop counter */ | ||||
| 64185 | int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */ | ||||
| 64186 | Pager *pPager = pPg->pPager; /* The pager that owns pPg */ | ||||
| 64187 | Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize); | ||||
| 64188 | |||||
| 64189 | /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow | ||||
| 64190 | ** a journal header to be written between the pages journaled by | ||||
| 64191 | ** this function. | ||||
| 64192 | */ | ||||
| 64193 | assert( !MEMDB )((void) (0)); | ||||
| 64194 | assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 )((void) (0)); | ||||
| 64195 | pPager->doNotSpill |= SPILLFLAG_NOSYNC0x04; | ||||
| 64196 | |||||
| 64197 | /* This trick assumes that both the page-size and sector-size are | ||||
| 64198 | ** an integer power of 2. It sets variable pg1 to the identifier | ||||
| 64199 | ** of the first page of the sector pPg is located on. | ||||
| 64200 | */ | ||||
| 64201 | pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1; | ||||
| 64202 | |||||
| 64203 | nPageCount = pPager->dbSize; | ||||
| 64204 | if( pPg->pgno>nPageCount ){ | ||||
| 64205 | nPage = (pPg->pgno - pg1)+1; | ||||
| 64206 | }else if( (pg1+nPagePerSector-1)>nPageCount ){ | ||||
| 64207 | nPage = nPageCount+1-pg1; | ||||
| 64208 | }else{ | ||||
| 64209 | nPage = nPagePerSector; | ||||
| 64210 | } | ||||
| 64211 | assert(nPage>0)((void) (0)); | ||||
| 64212 | assert(pg1<=pPg->pgno)((void) (0)); | ||||
| 64213 | assert((pg1+nPage)>pPg->pgno)((void) (0)); | ||||
| 64214 | |||||
| 64215 | for(ii=0; ii<nPage && rc==SQLITE_OK0; ii++){ | ||||
| 64216 | Pgno pg = pg1+ii; | ||||
| 64217 | PgHdr *pPage; | ||||
| 64218 | if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){ | ||||
| 64219 | if( pg!=PAGER_SJ_PGNO(pPager)((pPager)->lckPgno) ){ | ||||
| 64220 | rc = sqlite3PagerGet(pPager, pg, &pPage, 0); | ||||
| 64221 | if( rc==SQLITE_OK0 ){ | ||||
| 64222 | rc = pager_write(pPage); | ||||
| 64223 | if( pPage->flags&PGHDR_NEED_SYNC0x008 ){ | ||||
| 64224 | needSync = 1; | ||||
| 64225 | } | ||||
| 64226 | sqlite3PagerUnrefNotNull(pPage); | ||||
| 64227 | } | ||||
| 64228 | } | ||||
| 64229 | }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){ | ||||
| 64230 | if( pPage->flags&PGHDR_NEED_SYNC0x008 ){ | ||||
| 64231 | needSync = 1; | ||||
| 64232 | } | ||||
| 64233 | sqlite3PagerUnrefNotNull(pPage); | ||||
| 64234 | } | ||||
| 64235 | } | ||||
| 64236 | |||||
| 64237 | /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages | ||||
| 64238 | ** starting at pg1, then it needs to be set for all of them. Because | ||||
| 64239 | ** writing to any of these nPage pages may damage the others, the | ||||
| 64240 | ** journal file must contain sync()ed copies of all of them | ||||
| 64241 | ** before any of them can be written out to the database file. | ||||
| 64242 | */ | ||||
| 64243 | if( rc==SQLITE_OK0 && needSync ){ | ||||
| 64244 | assert( !MEMDB )((void) (0)); | ||||
| 64245 | for(ii=0; ii<nPage; ii++){ | ||||
| 64246 | PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii); | ||||
| 64247 | if( pPage ){ | ||||
| 64248 | pPage->flags |= PGHDR_NEED_SYNC0x008; | ||||
| 64249 | sqlite3PagerUnrefNotNull(pPage); | ||||
| 64250 | } | ||||
| 64251 | } | ||||
| 64252 | } | ||||
| 64253 | |||||
| 64254 | assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 )((void) (0)); | ||||
| 64255 | pPager->doNotSpill &= ~SPILLFLAG_NOSYNC0x04; | ||||
| 64256 | return rc; | ||||
| 64257 | } | ||||
| 64258 | |||||
| 64259 | /* | ||||
| 64260 | ** Mark a data page as writeable. This routine must be called before | ||||
| 64261 | ** making changes to a page. The caller must check the return value | ||||
| 64262 | ** of this function and be careful not to change any page data unless | ||||
| 64263 | ** this routine returns SQLITE_OK. | ||||
| 64264 | ** | ||||
| 64265 | ** The difference between this function and pager_write() is that this | ||||
| 64266 | ** function also deals with the special case where 2 or more pages | ||||
| 64267 | ** fit on a single disk sector. In this case all co-resident pages | ||||
| 64268 | ** must have been written to the journal file before returning. | ||||
| 64269 | ** | ||||
| 64270 | ** If an error occurs, SQLITE_NOMEM or an IO error code is returned | ||||
| 64271 | ** as appropriate. Otherwise, SQLITE_OK. | ||||
| 64272 | */ | ||||
| 64273 | SQLITE_PRIVATEstatic int sqlite3PagerWrite(PgHdr *pPg){ | ||||
| 64274 | Pager *pPager = pPg->pPager; | ||||
| 64275 | assert( (pPg->flags & PGHDR_MMAP)==0 )((void) (0)); | ||||
| 64276 | assert( pPager->eState>=PAGER_WRITER_LOCKED )((void) (0)); | ||||
| 64277 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64278 | if( (pPg->flags & PGHDR_WRITEABLE0x004)!=0 && pPager->dbSize>=pPg->pgno ){ | ||||
| 64279 | if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg); | ||||
| 64280 | return SQLITE_OK0; | ||||
| 64281 | }else if( pPager->errCode ){ | ||||
| 64282 | return pPager->errCode; | ||||
| 64283 | }else if( pPager->sectorSize > (u32)pPager->pageSize ){ | ||||
| 64284 | assert( pPager->tempFile==0 )((void) (0)); | ||||
| 64285 | return pagerWriteLargeSector(pPg); | ||||
| 64286 | }else{ | ||||
| 64287 | return pager_write(pPg); | ||||
| 64288 | } | ||||
| 64289 | } | ||||
| 64290 | |||||
| 64291 | /* | ||||
| 64292 | ** Return TRUE if the page given in the argument was previously passed | ||||
| 64293 | ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok | ||||
| 64294 | ** to change the content of the page. | ||||
| 64295 | */ | ||||
| 64296 | #ifndef NDEBUG1 | ||||
| 64297 | SQLITE_PRIVATEstatic int sqlite3PagerIswriteable(DbPage *pPg){ | ||||
| 64298 | return pPg->flags & PGHDR_WRITEABLE0x004; | ||||
| 64299 | } | ||||
| 64300 | #endif | ||||
| 64301 | |||||
| 64302 | /* | ||||
| 64303 | ** A call to this routine tells the pager that it is not necessary to | ||||
| 64304 | ** write the information on page pPg back to the disk, even though | ||||
| 64305 | ** that page might be marked as dirty. This happens, for example, when | ||||
| 64306 | ** the page has been added as a leaf of the freelist and so its | ||||
| 64307 | ** content no longer matters. | ||||
| 64308 | ** | ||||
| 64309 | ** The overlying software layer calls this routine when all of the data | ||||
| 64310 | ** on the given page is unused. The pager marks the page as clean so | ||||
| 64311 | ** that it does not get written to disk. | ||||
| 64312 | ** | ||||
| 64313 | ** Tests show that this optimization can quadruple the speed of large | ||||
| 64314 | ** DELETE operations. | ||||
| 64315 | ** | ||||
| 64316 | ** This optimization cannot be used with a temp-file, as the page may | ||||
| 64317 | ** have been dirty at the start of the transaction. In that case, if | ||||
| 64318 | ** memory pressure forces page pPg out of the cache, the data does need | ||||
| 64319 | ** to be written out to disk so that it may be read back in if the | ||||
| 64320 | ** current transaction is rolled back. | ||||
| 64321 | */ | ||||
| 64322 | SQLITE_PRIVATEstatic void sqlite3PagerDontWrite(PgHdr *pPg){ | ||||
| 64323 | Pager *pPager = pPg->pPager; | ||||
| 64324 | if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY0x002) && pPager->nSavepoint==0 ){ | ||||
| 64325 | PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager))); | ||||
| 64326 | IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) | ||||
| 64327 | pPg->flags |= PGHDR_DONT_WRITE0x010; | ||||
| 64328 | pPg->flags &= ~PGHDR_WRITEABLE0x004; | ||||
| 64329 | testcase( pPg->flags & PGHDR_NEED_SYNC ); | ||||
| 64330 | pager_set_pagehash(pPg); | ||||
| 64331 | } | ||||
| 64332 | } | ||||
| 64333 | |||||
| 64334 | /* | ||||
| 64335 | ** This routine is called to increment the value of the database file | ||||
| 64336 | ** change-counter, stored as a 4-byte big-endian integer starting at | ||||
| 64337 | ** byte offset 24 of the pager file. The secondary change counter at | ||||
| 64338 | ** 92 is also updated, as is the SQLite version number at offset 96. | ||||
| 64339 | ** | ||||
| 64340 | ** But this only happens if the pPager->changeCountDone flag is false. | ||||
| 64341 | ** To avoid excess churning of page 1, the update only happens once. | ||||
| 64342 | ** See also the pager_write_changecounter() routine that does an | ||||
| 64343 | ** unconditional update of the change counters. | ||||
| 64344 | ** | ||||
| 64345 | ** If the isDirectMode flag is zero, then this is done by calling | ||||
| 64346 | ** sqlite3PagerWrite() on page 1, then modifying the contents of the | ||||
| 64347 | ** page data. In this case the file will be updated when the current | ||||
| 64348 | ** transaction is committed. | ||||
| 64349 | ** | ||||
| 64350 | ** The isDirectMode flag may only be non-zero if the library was compiled | ||||
| 64351 | ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, | ||||
| 64352 | ** if isDirect is non-zero, then the database file is updated directly | ||||
| 64353 | ** by writing an updated version of page 1 using a call to the | ||||
| 64354 | ** sqlite3OsWrite() function. | ||||
| 64355 | */ | ||||
| 64356 | static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ | ||||
| 64357 | int rc = SQLITE_OK0; | ||||
| 64358 | |||||
| 64359 | assert( pPager->eState==PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 64360 | || pPager->eState==PAGER_WRITER_DBMOD((void) (0)) | ||||
| 64361 | )((void) (0)); | ||||
| 64362 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64363 | |||||
| 64364 | /* Declare and initialize constant integer 'isDirect'. If the | ||||
| 64365 | ** atomic-write optimization is enabled in this build, then isDirect | ||||
| 64366 | ** is initialized to the value passed as the isDirectMode parameter | ||||
| 64367 | ** to this function. Otherwise, it is always set to zero. | ||||
| 64368 | ** | ||||
| 64369 | ** The idea is that if the atomic-write optimization is not | ||||
| 64370 | ** enabled at compile time, the compiler can omit the tests of | ||||
| 64371 | ** 'isDirect' below, as well as the block enclosed in the | ||||
| 64372 | ** "if( isDirect )" condition. | ||||
| 64373 | */ | ||||
| 64374 | #ifndef SQLITE_ENABLE_ATOMIC_WRITE | ||||
| 64375 | # define DIRECT_MODE0 0 | ||||
| 64376 | assert( isDirectMode==0 )((void) (0)); | ||||
| 64377 | UNUSED_PARAMETER(isDirectMode)(void)(isDirectMode); | ||||
| 64378 | #else | ||||
| 64379 | # define DIRECT_MODE0 isDirectMode | ||||
| 64380 | #endif | ||||
| 64381 | |||||
| 64382 | if( !pPager->changeCountDone && pPager->dbSize>0 ){ | ||||
| 64383 | PgHdr *pPgHdr; /* Reference to page 1 */ | ||||
| 64384 | |||||
| 64385 | assert( !pPager->tempFile && isOpen(pPager->fd) )((void) (0)); | ||||
| 64386 | |||||
| 64387 | /* Open page 1 of the file for writing. */ | ||||
| 64388 | rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0); | ||||
| 64389 | assert( pPgHdr==0 || rc==SQLITE_OK )((void) (0)); | ||||
| 64390 | |||||
| 64391 | /* If page one was fetched successfully, and this function is not | ||||
| 64392 | ** operating in direct-mode, make page 1 writable. When not in | ||||
| 64393 | ** direct mode, page 1 is always held in cache and hence the PagerGet() | ||||
| 64394 | ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. | ||||
| 64395 | */ | ||||
| 64396 | if( !DIRECT_MODE0 && ALWAYS(rc==SQLITE_OK)(rc==0) ){ | ||||
| 64397 | rc = sqlite3PagerWrite(pPgHdr); | ||||
| 64398 | } | ||||
| 64399 | |||||
| 64400 | if( rc==SQLITE_OK0 ){ | ||||
| 64401 | /* Actually do the update of the change counter */ | ||||
| 64402 | pager_write_changecounter(pPgHdr); | ||||
| 64403 | |||||
| 64404 | /* If running in direct mode, write the contents of page 1 to the file. */ | ||||
| 64405 | if( DIRECT_MODE0 ){ | ||||
| 64406 | const void *zBuf; | ||||
| 64407 | assert( pPager->dbFileSize>0 )((void) (0)); | ||||
| 64408 | zBuf = pPgHdr->pData; | ||||
| 64409 | if( rc==SQLITE_OK0 ){ | ||||
| 64410 | rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); | ||||
| 64411 | pPager->aStat[PAGER_STAT_WRITE2]++; | ||||
| 64412 | } | ||||
| 64413 | if( rc==SQLITE_OK0 ){ | ||||
| 64414 | /* Update the pager's copy of the change-counter. Otherwise, the | ||||
| 64415 | ** next time a read transaction is opened the cache will be | ||||
| 64416 | ** flushed (as the change-counter values will not match). */ | ||||
| 64417 | const void *pCopy = (const void *)&((const char *)zBuf)[24]; | ||||
| 64418 | memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); | ||||
| 64419 | pPager->changeCountDone = 1; | ||||
| 64420 | } | ||||
| 64421 | }else{ | ||||
| 64422 | pPager->changeCountDone = 1; | ||||
| 64423 | } | ||||
| 64424 | } | ||||
| 64425 | |||||
| 64426 | /* Release the page reference. */ | ||||
| 64427 | sqlite3PagerUnref(pPgHdr); | ||||
| 64428 | } | ||||
| 64429 | return rc; | ||||
| 64430 | } | ||||
| 64431 | |||||
| 64432 | /* | ||||
| 64433 | ** Sync the database file to disk. This is a no-op for in-memory databases | ||||
| 64434 | ** or pages with the Pager.noSync flag set. | ||||
| 64435 | ** | ||||
| 64436 | ** If successful, or if called on a pager for which it is a no-op, this | ||||
| 64437 | ** function returns SQLITE_OK. Otherwise, an IO error code is returned. | ||||
| 64438 | */ | ||||
| 64439 | SQLITE_PRIVATEstatic int sqlite3PagerSync(Pager *pPager, const char *zSuper){ | ||||
| 64440 | int rc = SQLITE_OK0; | ||||
| 64441 | void *pArg = (void*)zSuper; | ||||
| 64442 | rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC21, pArg); | ||||
| 64443 | if( rc==SQLITE_NOTFOUND12 ) rc = SQLITE_OK0; | ||||
| 64444 | if( rc==SQLITE_OK0 && !pPager->noSync ){ | ||||
| 64445 | assert( !MEMDB )((void) (0)); | ||||
| 64446 | rc = sqlite3OsSync(pPager->fd, pPager->syncFlags); | ||||
| 64447 | } | ||||
| 64448 | return rc; | ||||
| 64449 | } | ||||
| 64450 | |||||
| 64451 | /* | ||||
| 64452 | ** This function may only be called while a write-transaction is active in | ||||
| 64453 | ** rollback. If the connection is in WAL mode, this call is a no-op. | ||||
| 64454 | ** Otherwise, if the connection does not already have an EXCLUSIVE lock on | ||||
| 64455 | ** the database file, an attempt is made to obtain one. | ||||
| 64456 | ** | ||||
| 64457 | ** If the EXCLUSIVE lock is already held or the attempt to obtain it is | ||||
| 64458 | ** successful, or the connection is in WAL mode, SQLITE_OK is returned. | ||||
| 64459 | ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is | ||||
| 64460 | ** returned. | ||||
| 64461 | */ | ||||
| 64462 | SQLITE_PRIVATEstatic int sqlite3PagerExclusiveLock(Pager *pPager){ | ||||
| 64463 | int rc = pPager->errCode; | ||||
| 64464 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64465 | if( rc==SQLITE_OK0 ){ | ||||
| 64466 | assert( pPager->eState==PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 64467 | || pPager->eState==PAGER_WRITER_DBMOD((void) (0)) | ||||
| 64468 | || pPager->eState==PAGER_WRITER_LOCKED((void) (0)) | ||||
| 64469 | )((void) (0)); | ||||
| 64470 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64471 | if( 0==pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 64472 | rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK4); | ||||
| 64473 | } | ||||
| 64474 | } | ||||
| 64475 | return rc; | ||||
| 64476 | } | ||||
| 64477 | |||||
| 64478 | /* | ||||
| 64479 | ** Sync the database file for the pager pPager. zSuper points to the name | ||||
| 64480 | ** of a super-journal file that should be written into the individual | ||||
| 64481 | ** journal file. zSuper may be NULL, which is interpreted as no | ||||
| 64482 | ** super-journal (a single database transaction). | ||||
| 64483 | ** | ||||
| 64484 | ** This routine ensures that: | ||||
| 64485 | ** | ||||
| 64486 | ** * The database file change-counter is updated, | ||||
| 64487 | ** * the journal is synced (unless the atomic-write optimization is used), | ||||
| 64488 | ** * all dirty pages are written to the database file, | ||||
| 64489 | ** * the database file is truncated (if required), and | ||||
| 64490 | ** * the database file synced. | ||||
| 64491 | ** | ||||
| 64492 | ** The only thing that remains to commit the transaction is to finalize | ||||
| 64493 | ** (delete, truncate or zero the first part of) the journal file (or | ||||
| 64494 | ** delete the super-journal file if specified). | ||||
| 64495 | ** | ||||
| 64496 | ** Note that if zSuper==NULL, this does not overwrite a previous value | ||||
| 64497 | ** passed to an sqlite3PagerCommitPhaseOne() call. | ||||
| 64498 | ** | ||||
| 64499 | ** If the final parameter - noSync - is true, then the database file itself | ||||
| 64500 | ** is not synced. The caller must call sqlite3PagerSync() directly to | ||||
| 64501 | ** sync the database file before calling CommitPhaseTwo() to delete the | ||||
| 64502 | ** journal file in this case. | ||||
| 64503 | */ | ||||
| 64504 | SQLITE_PRIVATEstatic int sqlite3PagerCommitPhaseOne( | ||||
| 64505 | Pager *pPager, /* Pager object */ | ||||
| 64506 | const char *zSuper, /* If not NULL, the super-journal name */ | ||||
| 64507 | int noSync /* True to omit the xSync on the db file */ | ||||
| 64508 | ){ | ||||
| 64509 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 64510 | |||||
| 64511 | assert( pPager->eState==PAGER_WRITER_LOCKED((void) (0)) | ||||
| 64512 | || pPager->eState==PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 64513 | || pPager->eState==PAGER_WRITER_DBMOD((void) (0)) | ||||
| 64514 | || pPager->eState==PAGER_ERROR((void) (0)) | ||||
| 64515 | )((void) (0)); | ||||
| 64516 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64517 | |||||
| 64518 | /* If a prior error occurred, report that error again. */ | ||||
| 64519 | if( NEVER(pPager->errCode)(pPager->errCode) ) return pPager->errCode; | ||||
| 64520 | |||||
| 64521 | /* Provide the ability to easily simulate an I/O error during testing */ | ||||
| 64522 | if( sqlite3FaultSim(400) ) return SQLITE_IOERR10; | ||||
| 64523 | |||||
| 64524 | PAGERTRACE(("DATABASE SYNC: File=%s zSuper=%s nSize=%d\n", | ||||
| 64525 | pPager->zFilename, zSuper, pPager->dbSize)); | ||||
| 64526 | |||||
| 64527 | /* If no database changes have been made, return early. */ | ||||
| 64528 | if( pPager->eState<PAGER_WRITER_CACHEMOD3 ) return SQLITE_OK0; | ||||
| 64529 | |||||
| 64530 | assert( MEMDB==0 || pPager->tempFile )((void) (0)); | ||||
| 64531 | assert( isOpen(pPager->fd) || pPager->tempFile )((void) (0)); | ||||
| 64532 | if( 0==pagerFlushOnCommit(pPager, 1) ){ | ||||
| 64533 | /* If this is an in-memory db, or no pages have been written to, or this | ||||
| 64534 | ** function has already been called, it is mostly a no-op. However, any | ||||
| 64535 | ** backup in progress needs to be restarted. */ | ||||
| 64536 | sqlite3BackupRestart(pPager->pBackup); | ||||
| 64537 | }else{ | ||||
| 64538 | PgHdr *pList; | ||||
| 64539 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 64540 | PgHdr *pPageOne = 0; | ||||
| 64541 | pList = sqlite3PcacheDirtyList(pPager->pPCache); | ||||
| 64542 | if( pList==0 ){ | ||||
| 64543 | /* Must have at least one page for the WAL commit flag. | ||||
| 64544 | ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */ | ||||
| 64545 | rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0); | ||||
| 64546 | pList = pPageOne; | ||||
| 64547 | pList->pDirty = 0; | ||||
| 64548 | } | ||||
| 64549 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 64550 | if( ALWAYS(pList)(pList) ){ | ||||
| 64551 | rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1); | ||||
| 64552 | } | ||||
| 64553 | sqlite3PagerUnref(pPageOne); | ||||
| 64554 | if( rc==SQLITE_OK0 ){ | ||||
| 64555 | sqlite3PcacheCleanAll(pPager->pPCache); | ||||
| 64556 | } | ||||
| 64557 | }else{ | ||||
| 64558 | /* The bBatch boolean is true if the batch-atomic-write commit method | ||||
| 64559 | ** should be used. No rollback journal is created if batch-atomic-write | ||||
| 64560 | ** is enabled. | ||||
| 64561 | */ | ||||
| 64562 | #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE | ||||
| 64563 | sqlite3_file *fd = pPager->fd; | ||||
| 64564 | int bBatch0 = zSuper==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */ | ||||
| 64565 | && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC0x00004000) | ||||
| 64566 | && !pPager->noSync | ||||
| 64567 | && sqlite3JournalIsInMemory(pPager->jfd); | ||||
| 64568 | #else | ||||
| 64569 | # define bBatch0 0 | ||||
| 64570 | #endif | ||||
| 64571 | |||||
| 64572 | #ifdef SQLITE_ENABLE_ATOMIC_WRITE | ||||
| 64573 | /* The following block updates the change-counter. Exactly how it | ||||
| 64574 | ** does this depends on whether or not the atomic-update optimization | ||||
| 64575 | ** was enabled at compile time, and if this transaction meets the | ||||
| 64576 | ** runtime criteria to use the operation: | ||||
| 64577 | ** | ||||
| 64578 | ** * The file-system supports the atomic-write property for | ||||
| 64579 | ** blocks of size page-size, and | ||||
| 64580 | ** * This commit is not part of a multi-file transaction, and | ||||
| 64581 | ** * Exactly one page has been modified and store in the journal file. | ||||
| 64582 | ** | ||||
| 64583 | ** If the optimization was not enabled at compile time, then the | ||||
| 64584 | ** pager_incr_changecounter() function is called to update the change | ||||
| 64585 | ** counter in 'indirect-mode'. If the optimization is compiled in but | ||||
| 64586 | ** is not applicable to this transaction, call sqlite3JournalCreate() | ||||
| 64587 | ** to make sure the journal file has actually been created, then call | ||||
| 64588 | ** pager_incr_changecounter() to update the change-counter in indirect | ||||
| 64589 | ** mode. | ||||
| 64590 | ** | ||||
| 64591 | ** Otherwise, if the optimization is both enabled and applicable, | ||||
| 64592 | ** then call pager_incr_changecounter() to update the change-counter | ||||
| 64593 | ** in 'direct' mode. In this case the journal file will never be | ||||
| 64594 | ** created for this transaction. | ||||
| 64595 | */ | ||||
| 64596 | if( bBatch0==0 ){ | ||||
| 64597 | PgHdr *pPg; | ||||
| 64598 | assert( isOpen(pPager->jfd)((void) (0)) | ||||
| 64599 | || pPager->journalMode==PAGER_JOURNALMODE_OFF((void) (0)) | ||||
| 64600 | || pPager->journalMode==PAGER_JOURNALMODE_WAL((void) (0)) | ||||
| 64601 | )((void) (0)); | ||||
| 64602 | if( !zSuper && isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) | ||||
| 64603 | && pPager->journalOff==jrnlBufferSize(pPager) | ||||
| 64604 | && pPager->dbSize>=pPager->dbOrigSize | ||||
| 64605 | && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) | ||||
| 64606 | ){ | ||||
| 64607 | /* Update the db file change counter via the direct-write method. The | ||||
| 64608 | ** following call will modify the in-memory representation of page 1 | ||||
| 64609 | ** to include the updated change counter and then write page 1 | ||||
| 64610 | ** directly to the database file. Because of the atomic-write | ||||
| 64611 | ** property of the host file-system, this is safe. | ||||
| 64612 | */ | ||||
| 64613 | rc = pager_incr_changecounter(pPager, 1); | ||||
| 64614 | }else{ | ||||
| 64615 | rc = sqlite3JournalCreate(pPager->jfd); | ||||
| 64616 | if( rc==SQLITE_OK0 ){ | ||||
| 64617 | rc = pager_incr_changecounter(pPager, 0); | ||||
| 64618 | } | ||||
| 64619 | } | ||||
| 64620 | } | ||||
| 64621 | #else /* SQLITE_ENABLE_ATOMIC_WRITE */ | ||||
| 64622 | #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE | ||||
| 64623 | if( zSuper ){ | ||||
| 64624 | rc = sqlite3JournalCreate(pPager->jfd); | ||||
| 64625 | if( rc!=SQLITE_OK0 ) goto commit_phase_one_exit; | ||||
| 64626 | assert( bBatch==0 )((void) (0)); | ||||
| 64627 | } | ||||
| 64628 | #endif | ||||
| 64629 | rc = pager_incr_changecounter(pPager, 0); | ||||
| 64630 | #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */ | ||||
| 64631 | if( rc!=SQLITE_OK0 ) goto commit_phase_one_exit; | ||||
| 64632 | |||||
| 64633 | /* Write the super-journal name into the journal file. If a | ||||
| 64634 | ** super-journal file name has already been written to the journal file, | ||||
| 64635 | ** or if zSuper is NULL (no super-journal), then this call is a no-op. | ||||
| 64636 | */ | ||||
| 64637 | rc = writeSuperJournal(pPager, zSuper); | ||||
| 64638 | if( rc!=SQLITE_OK0 ) goto commit_phase_one_exit; | ||||
| 64639 | |||||
| 64640 | /* Sync the journal file and write all dirty pages to the database. | ||||
| 64641 | ** If the atomic-update optimization is being used, this sync will not | ||||
| 64642 | ** create the journal file or perform any real IO. | ||||
| 64643 | ** | ||||
| 64644 | ** Because the change-counter page was just modified, unless the | ||||
| 64645 | ** atomic-update optimization is used it is almost certain that the | ||||
| 64646 | ** journal requires a sync here. However, in locking_mode=exclusive | ||||
| 64647 | ** on a system under memory pressure it is just possible that this is | ||||
| 64648 | ** not the case. In this case it is likely enough that the redundant | ||||
| 64649 | ** xSync() call will be changed to a no-op by the OS anyhow. | ||||
| 64650 | */ | ||||
| 64651 | rc = syncJournal(pPager, 0); | ||||
| 64652 | if( rc!=SQLITE_OK0 ) goto commit_phase_one_exit; | ||||
| 64653 | |||||
| 64654 | pList = sqlite3PcacheDirtyList(pPager->pPCache); | ||||
| 64655 | #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE | ||||
| 64656 | if( bBatch0 ){ | ||||
| 64657 | rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE31, 0); | ||||
| 64658 | if( rc==SQLITE_OK0 ){ | ||||
| 64659 | rc = pager_write_pagelist(pPager, pList); | ||||
| 64660 | if( rc==SQLITE_OK0 && pPager->dbSize>pPager->dbFileSize ){ | ||||
| 64661 | char *pTmp = pPager->pTmpSpace; | ||||
| 64662 | int szPage = (int)pPager->pageSize; | ||||
| 64663 | memset(pTmp, 0, szPage); | ||||
| 64664 | rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, | ||||
| 64665 | ((i64)pPager->dbSize*pPager->pageSize)-szPage); | ||||
| 64666 | } | ||||
| 64667 | if( rc==SQLITE_OK0 ){ | ||||
| 64668 | rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE32, 0); | ||||
| 64669 | } | ||||
| 64670 | if( rc!=SQLITE_OK0 ){ | ||||
| 64671 | sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE33, 0); | ||||
| 64672 | } | ||||
| 64673 | } | ||||
| 64674 | |||||
| 64675 | if( (rc&0xFF)==SQLITE_IOERR10 && rc!=SQLITE_IOERR_NOMEM(10 | (12<<8)) ){ | ||||
| 64676 | rc = sqlite3JournalCreate(pPager->jfd); | ||||
| 64677 | if( rc!=SQLITE_OK0 ){ | ||||
| 64678 | sqlite3OsClose(pPager->jfd); | ||||
| 64679 | goto commit_phase_one_exit; | ||||
| 64680 | } | ||||
| 64681 | bBatch0 = 0; | ||||
| 64682 | }else{ | ||||
| 64683 | sqlite3OsClose(pPager->jfd); | ||||
| 64684 | } | ||||
| 64685 | } | ||||
| 64686 | #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ | ||||
| 64687 | |||||
| 64688 | if( bBatch0==0 ){ | ||||
| 64689 | rc = pager_write_pagelist(pPager, pList); | ||||
| 64690 | } | ||||
| 64691 | if( rc!=SQLITE_OK0 ){ | ||||
| 64692 | assert( rc!=SQLITE_IOERR_BLOCKED )((void) (0)); | ||||
| 64693 | goto commit_phase_one_exit; | ||||
| 64694 | } | ||||
| 64695 | sqlite3PcacheCleanAll(pPager->pPCache); | ||||
| 64696 | |||||
| 64697 | /* If the file on disk is smaller than the database image, use | ||||
| 64698 | ** pager_truncate to grow the file here. This can happen if the database | ||||
| 64699 | ** image was extended as part of the current transaction and then the | ||||
| 64700 | ** last page in the db image moved to the free-list. In this case the | ||||
| 64701 | ** last page is never written out to disk, leaving the database file | ||||
| 64702 | ** undersized. Fix this now if it is the case. */ | ||||
| 64703 | if( pPager->dbSize>pPager->dbFileSize ){ | ||||
| 64704 | Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_SJ_PGNO(pPager)((pPager)->lckPgno)); | ||||
| 64705 | assert( pPager->eState==PAGER_WRITER_DBMOD )((void) (0)); | ||||
| 64706 | rc = pager_truncate(pPager, nNew); | ||||
| 64707 | if( rc!=SQLITE_OK0 ) goto commit_phase_one_exit; | ||||
| 64708 | } | ||||
| 64709 | |||||
| 64710 | /* Finally, sync the database file. */ | ||||
| 64711 | if( !noSync ){ | ||||
| 64712 | rc = sqlite3PagerSync(pPager, zSuper); | ||||
| 64713 | } | ||||
| 64714 | IOTRACE(("DBSYNC %p\n", pPager)) | ||||
| 64715 | } | ||||
| 64716 | } | ||||
| 64717 | |||||
| 64718 | commit_phase_one_exit: | ||||
| 64719 | if( rc==SQLITE_OK0 && !pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 64720 | pPager->eState = PAGER_WRITER_FINISHED5; | ||||
| 64721 | } | ||||
| 64722 | return rc; | ||||
| 64723 | } | ||||
| 64724 | |||||
| 64725 | |||||
| 64726 | /* | ||||
| 64727 | ** When this function is called, the database file has been completely | ||||
| 64728 | ** updated to reflect the changes made by the current transaction and | ||||
| 64729 | ** synced to disk. The journal file still exists in the file-system | ||||
| 64730 | ** though, and if a failure occurs at this point it will eventually | ||||
| 64731 | ** be used as a hot-journal and the current transaction rolled back. | ||||
| 64732 | ** | ||||
| 64733 | ** This function finalizes the journal file, either by deleting, | ||||
| 64734 | ** truncating or partially zeroing it, so that it cannot be used | ||||
| 64735 | ** for hot-journal rollback. Once this is done the transaction is | ||||
| 64736 | ** irrevocably committed. | ||||
| 64737 | ** | ||||
| 64738 | ** If an error occurs, an IO error code is returned and the pager | ||||
| 64739 | ** moves into the error state. Otherwise, SQLITE_OK is returned. | ||||
| 64740 | */ | ||||
| 64741 | SQLITE_PRIVATEstatic int sqlite3PagerCommitPhaseTwo(Pager *pPager){ | ||||
| 64742 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 64743 | |||||
| 64744 | /* This routine should not be called if a prior error has occurred. | ||||
| 64745 | ** But if (due to a coding error elsewhere in the system) it does get | ||||
| 64746 | ** called, just return the same error code without doing anything. */ | ||||
| 64747 | if( NEVER(pPager->errCode)(pPager->errCode) ) return pPager->errCode; | ||||
| 64748 | pPager->iDataVersion++; | ||||
| 64749 | |||||
| 64750 | assert( pPager->eState==PAGER_WRITER_LOCKED((void) (0)) | ||||
| 64751 | || pPager->eState==PAGER_WRITER_FINISHED((void) (0)) | ||||
| 64752 | || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)((void) (0)) | ||||
| 64753 | )((void) (0)); | ||||
| 64754 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64755 | |||||
| 64756 | /* An optimization. If the database was not actually modified during | ||||
| 64757 | ** this transaction, the pager is running in exclusive-mode and is | ||||
| 64758 | ** using persistent journals, then this function is a no-op. | ||||
| 64759 | ** | ||||
| 64760 | ** The start of the journal file currently contains a single journal | ||||
| 64761 | ** header with the nRec field set to 0. If such a journal is used as | ||||
| 64762 | ** a hot-journal during hot-journal rollback, 0 changes will be made | ||||
| 64763 | ** to the database file. So there is no need to zero the journal | ||||
| 64764 | ** header. Since the pager is in exclusive mode, there is no need | ||||
| 64765 | ** to drop any locks either. | ||||
| 64766 | */ | ||||
| 64767 | if( pPager->eState==PAGER_WRITER_LOCKED2 | ||||
| 64768 | && pPager->exclusiveMode | ||||
| 64769 | && pPager->journalMode==PAGER_JOURNALMODE_PERSIST1 | ||||
| 64770 | ){ | ||||
| 64771 | assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff )((void) (0)); | ||||
| 64772 | pPager->eState = PAGER_READER1; | ||||
| 64773 | return SQLITE_OK0; | ||||
| 64774 | } | ||||
| 64775 | |||||
| 64776 | PAGERTRACE(("COMMIT %d\n", PAGERID(pPager))); | ||||
| 64777 | rc = pager_end_transaction(pPager, pPager->setSuper, 1); | ||||
| 64778 | return pager_error(pPager, rc); | ||||
| 64779 | } | ||||
| 64780 | |||||
| 64781 | /* | ||||
| 64782 | ** If a write transaction is open, then all changes made within the | ||||
| 64783 | ** transaction are reverted and the current write-transaction is closed. | ||||
| 64784 | ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR | ||||
| 64785 | ** state if an error occurs. | ||||
| 64786 | ** | ||||
| 64787 | ** If the pager is already in PAGER_ERROR state when this function is called, | ||||
| 64788 | ** it returns Pager.errCode immediately. No work is performed in this case. | ||||
| 64789 | ** | ||||
| 64790 | ** Otherwise, in rollback mode, this function performs two functions: | ||||
| 64791 | ** | ||||
| 64792 | ** 1) It rolls back the journal file, restoring all database file and | ||||
| 64793 | ** in-memory cache pages to the state they were in when the transaction | ||||
| 64794 | ** was opened, and | ||||
| 64795 | ** | ||||
| 64796 | ** 2) It finalizes the journal file, so that it is not used for hot | ||||
| 64797 | ** rollback at any point in the future. | ||||
| 64798 | ** | ||||
| 64799 | ** Finalization of the journal file (task 2) is only performed if the | ||||
| 64800 | ** rollback is successful. | ||||
| 64801 | ** | ||||
| 64802 | ** In WAL mode, all cache-entries containing data modified within the | ||||
| 64803 | ** current transaction are either expelled from the cache or reverted to | ||||
| 64804 | ** their pre-transaction state by re-reading data from the database or | ||||
| 64805 | ** WAL files. The WAL transaction is then closed. | ||||
| 64806 | */ | ||||
| 64807 | SQLITE_PRIVATEstatic int sqlite3PagerRollback(Pager *pPager){ | ||||
| 64808 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 64809 | PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager))); | ||||
| 64810 | |||||
| 64811 | /* PagerRollback() is a no-op if called in READER or OPEN state. If | ||||
| 64812 | ** the pager is already in the ERROR state, the rollback is not | ||||
| 64813 | ** attempted here. Instead, the error code is returned to the caller. | ||||
| 64814 | */ | ||||
| 64815 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64816 | if( pPager->eState==PAGER_ERROR6 ) return pPager->errCode; | ||||
| 64817 | if( pPager->eState<=PAGER_READER1 ) return SQLITE_OK0; | ||||
| 64818 | |||||
| 64819 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 64820 | int rc2; | ||||
| 64821 | rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK2, -1); | ||||
| 64822 | rc2 = pager_end_transaction(pPager, pPager->setSuper, 0); | ||||
| 64823 | if( rc==SQLITE_OK0 ) rc = rc2; | ||||
| 64824 | }else if( !isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) || pPager->eState==PAGER_WRITER_LOCKED2 ){ | ||||
| 64825 | int eState = pPager->eState; | ||||
| 64826 | rc = pager_end_transaction(pPager, 0, 0); | ||||
| 64827 | if( !MEMDBpPager->memDb && eState>PAGER_WRITER_LOCKED2 ){ | ||||
| 64828 | /* This can happen using journal_mode=off. Move the pager to the error | ||||
| 64829 | ** state to indicate that the contents of the cache may not be trusted. | ||||
| 64830 | ** Any active readers will get SQLITE_ABORT. | ||||
| 64831 | */ | ||||
| 64832 | pPager->errCode = SQLITE_ABORT4; | ||||
| 64833 | pPager->eState = PAGER_ERROR6; | ||||
| 64834 | setGetterMethod(pPager); | ||||
| 64835 | return rc; | ||||
| 64836 | } | ||||
| 64837 | }else{ | ||||
| 64838 | rc = pager_playback(pPager, 0); | ||||
| 64839 | } | ||||
| 64840 | |||||
| 64841 | assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK )((void) (0)); | ||||
| 64842 | assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT((void) (0)) | ||||
| 64843 | || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR((void) (0)) | ||||
| 64844 | || rc==SQLITE_CANTOPEN((void) (0)) | ||||
| 64845 | )((void) (0)); | ||||
| 64846 | |||||
| 64847 | /* If an error occurs during a ROLLBACK, we can no longer trust the pager | ||||
| 64848 | ** cache. So call pager_error() on the way out to make any error persistent. | ||||
| 64849 | */ | ||||
| 64850 | return pager_error(pPager, rc); | ||||
| 64851 | } | ||||
| 64852 | |||||
| 64853 | /* | ||||
| 64854 | ** Return TRUE if the database file is opened read-only. Return FALSE | ||||
| 64855 | ** if the database is (in theory) writable. | ||||
| 64856 | */ | ||||
| 64857 | SQLITE_PRIVATEstatic u8 sqlite3PagerIsreadonly(Pager *pPager){ | ||||
| 64858 | return pPager->readOnly; | ||||
| 64859 | } | ||||
| 64860 | |||||
| 64861 | #ifdef SQLITE_DEBUG | ||||
| 64862 | /* | ||||
| 64863 | ** Return the sum of the reference counts for all pages held by pPager. | ||||
| 64864 | */ | ||||
| 64865 | SQLITE_PRIVATEstatic int sqlite3PagerRefcount(Pager *pPager){ | ||||
| 64866 | return sqlite3PcacheRefCount(pPager->pPCache); | ||||
| 64867 | } | ||||
| 64868 | #endif | ||||
| 64869 | |||||
| 64870 | /* | ||||
| 64871 | ** Return the approximate number of bytes of memory currently | ||||
| 64872 | ** used by the pager and its associated cache. | ||||
| 64873 | */ | ||||
| 64874 | SQLITE_PRIVATEstatic int sqlite3PagerMemUsed(Pager *pPager){ | ||||
| 64875 | int perPageSize = pPager->pageSize + pPager->nExtra | ||||
| 64876 | + (int)(sizeof(PgHdr) + 5*sizeof(void*)); | ||||
| 64877 | return perPageSize*sqlite3PcachePagecount(pPager->pPCache) | ||||
| 64878 | + sqlite3MallocSize(pPager) | ||||
| 64879 | + pPager->pageSize; | ||||
| 64880 | } | ||||
| 64881 | |||||
| 64882 | /* | ||||
| 64883 | ** Return the number of references to the specified page. | ||||
| 64884 | */ | ||||
| 64885 | SQLITE_PRIVATEstatic int sqlite3PagerPageRefcount(DbPage *pPage){ | ||||
| 64886 | return sqlite3PcachePageRefcount(pPage); | ||||
| 64887 | } | ||||
| 64888 | |||||
| 64889 | #ifdef SQLITE_TEST | ||||
| 64890 | /* | ||||
| 64891 | ** This routine is used for testing and analysis only. | ||||
| 64892 | */ | ||||
| 64893 | SQLITE_PRIVATEstatic int *sqlite3PagerStats(Pager *pPager){ | ||||
| 64894 | static int a[11]; | ||||
| 64895 | a[0] = sqlite3PcacheRefCount(pPager->pPCache); | ||||
| 64896 | a[1] = sqlite3PcachePagecount(pPager->pPCache); | ||||
| 64897 | a[2] = sqlite3PcacheGetCachesize(pPager->pPCache); | ||||
| 64898 | a[3] = pPager->eState==PAGER_OPEN0 ? -1 : (int) pPager->dbSize; | ||||
| 64899 | a[4] = pPager->eState; | ||||
| 64900 | a[5] = pPager->errCode; | ||||
| 64901 | a[6] = (int)pPager->aStat[PAGER_STAT_HIT0] & 0x7fffffff; | ||||
| 64902 | a[7] = (int)pPager->aStat[PAGER_STAT_MISS1] & 0x7fffffff; | ||||
| 64903 | a[8] = 0; /* Used to be pPager->nOvfl */ | ||||
| 64904 | a[9] = pPager->nRead; | ||||
| 64905 | a[10] = (int)pPager->aStat[PAGER_STAT_WRITE2] & 0x7fffffff; | ||||
| 64906 | return a; | ||||
| 64907 | } | ||||
| 64908 | #endif | ||||
| 64909 | |||||
| 64910 | /* | ||||
| 64911 | ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE, | ||||
| 64912 | ** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation | ||||
| 64913 | ** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because | ||||
| 64914 | ** it was added later. | ||||
| 64915 | ** | ||||
| 64916 | ** Before returning, *pnVal is incremented by the | ||||
| 64917 | ** current cache hit or miss count, according to the value of eStat. If the | ||||
| 64918 | ** reset parameter is non-zero, the cache hit or miss count is zeroed before | ||||
| 64919 | ** returning. | ||||
| 64920 | */ | ||||
| 64921 | SQLITE_PRIVATEstatic void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, u64 *pnVal){ | ||||
| 64922 | |||||
| 64923 | assert( eStat==SQLITE_DBSTATUS_CACHE_HIT((void) (0)) | ||||
| 64924 | || eStat==SQLITE_DBSTATUS_CACHE_MISS((void) (0)) | ||||
| 64925 | || eStat==SQLITE_DBSTATUS_CACHE_WRITE((void) (0)) | ||||
| 64926 | || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1((void) (0)) | ||||
| 64927 | )((void) (0)); | ||||
| 64928 | |||||
| 64929 | assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS )((void) (0)); | ||||
| 64930 | assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE )((void) (0)); | ||||
| 64931 | assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1((void) (0)) | ||||
| 64932 | && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 )((void) (0)); | ||||
| 64933 | |||||
| 64934 | eStat -= SQLITE_DBSTATUS_CACHE_HIT7; | ||||
| 64935 | *pnVal += pPager->aStat[eStat]; | ||||
| 64936 | if( reset ){ | ||||
| 64937 | pPager->aStat[eStat] = 0; | ||||
| 64938 | } | ||||
| 64939 | } | ||||
| 64940 | |||||
| 64941 | /* | ||||
| 64942 | ** Return true if this is an in-memory or temp-file backed pager. | ||||
| 64943 | */ | ||||
| 64944 | SQLITE_PRIVATEstatic int sqlite3PagerIsMemdb(Pager *pPager){ | ||||
| 64945 | return pPager->tempFile || pPager->memVfs; | ||||
| 64946 | } | ||||
| 64947 | |||||
| 64948 | /* | ||||
| 64949 | ** Check that there are at least nSavepoint savepoints open. If there are | ||||
| 64950 | ** currently less than nSavepoints open, then open one or more savepoints | ||||
| 64951 | ** to make up the difference. If the number of savepoints is already | ||||
| 64952 | ** equal to nSavepoint, then this function is a no-op. | ||||
| 64953 | ** | ||||
| 64954 | ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error | ||||
| 64955 | ** occurs while opening the sub-journal file, then an IO error code is | ||||
| 64956 | ** returned. Otherwise, SQLITE_OK. | ||||
| 64957 | */ | ||||
| 64958 | static SQLITE_NOINLINE__attribute__((noinline)) int pagerOpenSavepoint(Pager *pPager, int nSavepoint){ | ||||
| 64959 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 64960 | int nCurrent = pPager->nSavepoint; /* Current number of savepoints */ | ||||
| 64961 | int ii; /* Iterator variable */ | ||||
| 64962 | PagerSavepoint *aNew; /* New Pager.aSavepoint array */ | ||||
| 64963 | |||||
| 64964 | assert( pPager->eState>=PAGER_WRITER_LOCKED )((void) (0)); | ||||
| 64965 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 64966 | assert( nSavepoint>nCurrent && pPager->useJournal )((void) (0)); | ||||
| 64967 | |||||
| 64968 | /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM | ||||
| 64969 | ** if the allocation fails. Otherwise, zero the new portion in case a | ||||
| 64970 | ** malloc failure occurs while populating it in the for(...) loop below. | ||||
| 64971 | */ | ||||
| 64972 | aNew = (PagerSavepoint *)sqlite3Realloc( | ||||
| 64973 | pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint | ||||
| 64974 | ); | ||||
| 64975 | if( !aNew ){ | ||||
| 64976 | return SQLITE_NOMEM_BKPT7; | ||||
| 64977 | } | ||||
| 64978 | memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); | ||||
| 64979 | pPager->aSavepoint = aNew; | ||||
| 64980 | |||||
| 64981 | /* Populate the PagerSavepoint structures just allocated. */ | ||||
| 64982 | for(ii=nCurrent; ii<nSavepoint; ii++){ | ||||
| 64983 | aNew[ii].nOrig = pPager->dbSize; | ||||
| 64984 | if( isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) && pPager->journalOff>0 ){ | ||||
| 64985 | aNew[ii].iOffset = pPager->journalOff; | ||||
| 64986 | }else{ | ||||
| 64987 | aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager)(pPager->sectorSize); | ||||
| 64988 | } | ||||
| 64989 | aNew[ii].iSubRec = pPager->nSubRec; | ||||
| 64990 | aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize); | ||||
| 64991 | aNew[ii].bTruncateOnRelease = 1; | ||||
| 64992 | if( !aNew[ii].pInSavepoint ){ | ||||
| 64993 | return SQLITE_NOMEM_BKPT7; | ||||
| 64994 | } | ||||
| 64995 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 64996 | sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); | ||||
| 64997 | } | ||||
| 64998 | pPager->nSavepoint = ii+1; | ||||
| 64999 | } | ||||
| 65000 | assert( pPager->nSavepoint==nSavepoint )((void) (0)); | ||||
| 65001 | assertTruncateConstraint(pPager); | ||||
| 65002 | return rc; | ||||
| 65003 | } | ||||
| 65004 | SQLITE_PRIVATEstatic int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ | ||||
| 65005 | assert( pPager->eState>=PAGER_WRITER_LOCKED )((void) (0)); | ||||
| 65006 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 65007 | |||||
| 65008 | if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){ | ||||
| 65009 | return pagerOpenSavepoint(pPager, nSavepoint); | ||||
| 65010 | }else{ | ||||
| 65011 | return SQLITE_OK0; | ||||
| 65012 | } | ||||
| 65013 | } | ||||
| 65014 | |||||
| 65015 | |||||
| 65016 | /* | ||||
| 65017 | ** This function is called to rollback or release (commit) a savepoint. | ||||
| 65018 | ** The savepoint to release or rollback need not be the most recently | ||||
| 65019 | ** created savepoint. | ||||
| 65020 | ** | ||||
| 65021 | ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. | ||||
| 65022 | ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with | ||||
| 65023 | ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes | ||||
| 65024 | ** that have occurred since the specified savepoint was created. | ||||
| 65025 | ** | ||||
| 65026 | ** The savepoint to rollback or release is identified by parameter | ||||
| 65027 | ** iSavepoint. A value of 0 means to operate on the outermost savepoint | ||||
| 65028 | ** (the first created). A value of (Pager.nSavepoint-1) means operate | ||||
| 65029 | ** on the most recently created savepoint. If iSavepoint is greater than | ||||
| 65030 | ** (Pager.nSavepoint-1), then this function is a no-op. | ||||
| 65031 | ** | ||||
| 65032 | ** If a negative value is passed to this function, then the current | ||||
| 65033 | ** transaction is rolled back. This is different to calling | ||||
| 65034 | ** sqlite3PagerRollback() because this function does not terminate | ||||
| 65035 | ** the transaction or unlock the database, it just restores the | ||||
| 65036 | ** contents of the database to its original state. | ||||
| 65037 | ** | ||||
| 65038 | ** In any case, all savepoints with an index greater than iSavepoint | ||||
| 65039 | ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), | ||||
| 65040 | ** then savepoint iSavepoint is also destroyed. | ||||
| 65041 | ** | ||||
| 65042 | ** This function may return SQLITE_NOMEM if a memory allocation fails, | ||||
| 65043 | ** or an IO error code if an IO error occurs while rolling back a | ||||
| 65044 | ** savepoint. If no errors occur, SQLITE_OK is returned. | ||||
| 65045 | */ | ||||
| 65046 | SQLITE_PRIVATEstatic int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ | ||||
| 65047 | int rc = pPager->errCode; | ||||
| 65048 | |||||
| 65049 | #ifdef SQLITE_ENABLE_ZIPVFS | ||||
| 65050 | if( op==SAVEPOINT_RELEASE1 ) rc = SQLITE_OK0; | ||||
| 65051 | #endif | ||||
| 65052 | |||||
| 65053 | assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK )((void) (0)); | ||||
| 65054 | assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK )((void) (0)); | ||||
| 65055 | |||||
| 65056 | if( rc==SQLITE_OK0 && iSavepoint<pPager->nSavepoint ){ | ||||
| 65057 | int ii; /* Iterator variable */ | ||||
| 65058 | int nNew; /* Number of remaining savepoints after this op. */ | ||||
| 65059 | |||||
| 65060 | /* Figure out how many savepoints will still be active after this | ||||
| 65061 | ** operation. Store this value in nNew. Then free resources associated | ||||
| 65062 | ** with any savepoints that are destroyed by this operation. | ||||
| 65063 | */ | ||||
| 65064 | nNew = iSavepoint + (( op==SAVEPOINT_RELEASE1 ) ? 0 : 1); | ||||
| 65065 | for(ii=nNew; ii<pPager->nSavepoint; ii++){ | ||||
| 65066 | sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); | ||||
| 65067 | } | ||||
| 65068 | pPager->nSavepoint = nNew; | ||||
| 65069 | |||||
| 65070 | /* Truncate the sub-journal so that it only includes the parts | ||||
| 65071 | ** that are still in use. */ | ||||
| 65072 | if( op==SAVEPOINT_RELEASE1 ){ | ||||
| 65073 | PagerSavepoint *pRel = &pPager->aSavepoint[nNew]; | ||||
| 65074 | if( pRel->bTruncateOnRelease && isOpen(pPager->sjfd)((pPager->sjfd)->pMethods!=0) ){ | ||||
| 65075 | /* Only truncate if it is an in-memory sub-journal. */ | ||||
| 65076 | if( sqlite3JournalIsInMemory(pPager->sjfd) ){ | ||||
| 65077 | i64 sz = (pPager->pageSize+4)*(i64)pRel->iSubRec; | ||||
| 65078 | rc = sqlite3OsTruncate(pPager->sjfd, sz); | ||||
| 65079 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 65080 | } | ||||
| 65081 | pPager->nSubRec = pRel->iSubRec; | ||||
| 65082 | } | ||||
| 65083 | } | ||||
| 65084 | /* Else this is a rollback operation, playback the specified savepoint. | ||||
| 65085 | ** If this is a temp-file, it is possible that the journal file has | ||||
| 65086 | ** not yet been opened. In this case there have been no changes to | ||||
| 65087 | ** the database file, so the playback operation can be skipped. | ||||
| 65088 | */ | ||||
| 65089 | else if( pagerUseWal(pPager)((pPager)->pWal!=0) || isOpen(pPager->jfd)((pPager->jfd)->pMethods!=0) ){ | ||||
| 65090 | PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; | ||||
| 65091 | rc = pagerPlaybackSavepoint(pPager, pSavepoint); | ||||
| 65092 | assert(rc!=SQLITE_DONE)((void) (0)); | ||||
| 65093 | } | ||||
| 65094 | |||||
| 65095 | #ifdef SQLITE_ENABLE_ZIPVFS | ||||
| 65096 | /* If the cache has been modified but the savepoint cannot be rolled | ||||
| 65097 | ** back journal_mode=off, put the pager in the error state. This way, | ||||
| 65098 | ** if the VFS used by this pager includes ZipVFS, the entire transaction | ||||
| 65099 | ** can be rolled back at the ZipVFS level. */ | ||||
| 65100 | else if( | ||||
| 65101 | pPager->journalMode==PAGER_JOURNALMODE_OFF2 | ||||
| 65102 | && pPager->eState>=PAGER_WRITER_CACHEMOD3 | ||||
| 65103 | ){ | ||||
| 65104 | pPager->errCode = SQLITE_ABORT4; | ||||
| 65105 | pPager->eState = PAGER_ERROR6; | ||||
| 65106 | setGetterMethod(pPager); | ||||
| 65107 | } | ||||
| 65108 | #endif | ||||
| 65109 | } | ||||
| 65110 | |||||
| 65111 | return rc; | ||||
| 65112 | } | ||||
| 65113 | |||||
| 65114 | /* | ||||
| 65115 | ** Return the full pathname of the database file. | ||||
| 65116 | ** | ||||
| 65117 | ** Except, if the pager is in-memory only, then return an empty string if | ||||
| 65118 | ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when | ||||
| 65119 | ** used to report the filename to the user, for compatibility with legacy | ||||
| 65120 | ** behavior. But when the Btree needs to know the filename for matching to | ||||
| 65121 | ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can | ||||
| 65122 | ** participate in shared-cache. | ||||
| 65123 | ** | ||||
| 65124 | ** The return value to this routine is always safe to use with | ||||
| 65125 | ** sqlite3_uri_parameter() and sqlite3_filename_database() and friends. | ||||
| 65126 | */ | ||||
| 65127 | SQLITE_PRIVATEstatic const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){ | ||||
| 65128 | static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; | ||||
| 65129 | if( nullIfMemDb && (pPager->memDb || sqlite3IsMemdb(pPager->pVfs)) ){ | ||||
| 65130 | return &zFake[4]; | ||||
| 65131 | }else{ | ||||
| 65132 | return pPager->zFilename; | ||||
| 65133 | } | ||||
| 65134 | } | ||||
| 65135 | |||||
| 65136 | /* | ||||
| 65137 | ** Return the VFS structure for the pager. | ||||
| 65138 | */ | ||||
| 65139 | SQLITE_PRIVATEstatic sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ | ||||
| 65140 | return pPager->pVfs; | ||||
| 65141 | } | ||||
| 65142 | |||||
| 65143 | /* | ||||
| 65144 | ** Return the file handle for the database file associated | ||||
| 65145 | ** with the pager. This might return NULL if the file has | ||||
| 65146 | ** not yet been opened. | ||||
| 65147 | */ | ||||
| 65148 | SQLITE_PRIVATEstatic sqlite3_file *sqlite3PagerFile(Pager *pPager){ | ||||
| 65149 | return pPager->fd; | ||||
| 65150 | } | ||||
| 65151 | |||||
| 65152 | /* | ||||
| 65153 | ** Return the file handle for the journal file (if it exists). | ||||
| 65154 | ** This will be either the rollback journal or the WAL file. | ||||
| 65155 | */ | ||||
| 65156 | SQLITE_PRIVATEstatic sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){ | ||||
| 65157 | #ifdef SQLITE_OMIT_WAL | ||||
| 65158 | return pPager->jfd; | ||||
| 65159 | #else | ||||
| 65160 | return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd; | ||||
| 65161 | #endif | ||||
| 65162 | } | ||||
| 65163 | |||||
| 65164 | /* | ||||
| 65165 | ** Return the full pathname of the journal file. | ||||
| 65166 | */ | ||||
| 65167 | SQLITE_PRIVATEstatic const char *sqlite3PagerJournalname(Pager *pPager){ | ||||
| 65168 | return pPager->zJournal; | ||||
| 65169 | } | ||||
| 65170 | |||||
| 65171 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 65172 | /* | ||||
| 65173 | ** Move the page pPg to location pgno in the file. | ||||
| 65174 | ** | ||||
| 65175 | ** There must be no references to the page previously located at | ||||
| 65176 | ** pgno (which we call pPgOld) though that page is allowed to be | ||||
| 65177 | ** in cache. If the page previously located at pgno is not already | ||||
| 65178 | ** in the rollback journal, it is not put there by by this routine. | ||||
| 65179 | ** | ||||
| 65180 | ** References to the page pPg remain valid. Updating any | ||||
| 65181 | ** meta-data associated with pPg (i.e. data stored in the nExtra bytes | ||||
| 65182 | ** allocated along with the page) is the responsibility of the caller. | ||||
| 65183 | ** | ||||
| 65184 | ** A transaction must be active when this routine is called. It used to be | ||||
| 65185 | ** required that a statement transaction was not active, but this restriction | ||||
| 65186 | ** has been removed (CREATE INDEX needs to move a page when a statement | ||||
| 65187 | ** transaction is active). | ||||
| 65188 | ** | ||||
| 65189 | ** If the fourth argument, isCommit, is non-zero, then this page is being | ||||
| 65190 | ** moved as part of a database reorganization just before the transaction | ||||
| 65191 | ** is being committed. In this case, it is guaranteed that the database page | ||||
| 65192 | ** pPg refers to will not be written to again within this transaction. | ||||
| 65193 | ** | ||||
| 65194 | ** This function may return SQLITE_NOMEM or an IO error code if an error | ||||
| 65195 | ** occurs. Otherwise, it returns SQLITE_OK. | ||||
| 65196 | */ | ||||
| 65197 | SQLITE_PRIVATEstatic int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ | ||||
| 65198 | PgHdr *pPgOld; /* The page being overwritten. */ | ||||
| 65199 | Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */ | ||||
| 65200 | int rc; /* Return code */ | ||||
| 65201 | Pgno origPgno; /* The original page number */ | ||||
| 65202 | |||||
| 65203 | assert( pPg->nRef>0 )((void) (0)); | ||||
| 65204 | assert( pPager->eState==PAGER_WRITER_CACHEMOD((void) (0)) | ||||
| 65205 | || pPager->eState==PAGER_WRITER_DBMOD((void) (0)) | ||||
| 65206 | )((void) (0)); | ||||
| 65207 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 65208 | |||||
| 65209 | /* In order to be able to rollback, an in-memory database must journal | ||||
| 65210 | ** the page we are moving from. | ||||
| 65211 | */ | ||||
| 65212 | assert( pPager->tempFile || !MEMDB )((void) (0)); | ||||
| 65213 | if( pPager->tempFile ){ | ||||
| 65214 | rc = sqlite3PagerWrite(pPg); | ||||
| 65215 | if( rc ) return rc; | ||||
| 65216 | } | ||||
| 65217 | |||||
| 65218 | /* If the page being moved is dirty and has not been saved by the latest | ||||
| 65219 | ** savepoint, then save the current contents of the page into the | ||||
| 65220 | ** sub-journal now. This is required to handle the following scenario: | ||||
| 65221 | ** | ||||
| 65222 | ** BEGIN; | ||||
| 65223 | ** <journal page X, then modify it in memory> | ||||
| 65224 | ** SAVEPOINT one; | ||||
| 65225 | ** <Move page X to location Y> | ||||
| 65226 | ** ROLLBACK TO one; | ||||
| 65227 | ** | ||||
| 65228 | ** If page X were not written to the sub-journal here, it would not | ||||
| 65229 | ** be possible to restore its contents when the "ROLLBACK TO one" | ||||
| 65230 | ** statement were is processed. | ||||
| 65231 | ** | ||||
| 65232 | ** subjournalPage() may need to allocate space to store pPg->pgno into | ||||
| 65233 | ** one or more savepoint bitvecs. This is the reason this function | ||||
| 65234 | ** may return SQLITE_NOMEM. | ||||
| 65235 | */ | ||||
| 65236 | if( (pPg->flags & PGHDR_DIRTY0x002)!=0 | ||||
| 65237 | && SQLITE_OK0!=(rc = subjournalPageIfRequired(pPg)) | ||||
| 65238 | ){ | ||||
| 65239 | return rc; | ||||
| 65240 | } | ||||
| 65241 | |||||
| 65242 | PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", | ||||
| 65243 | PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno)); | ||||
| 65244 | IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno)) | ||||
| 65245 | |||||
| 65246 | /* If the journal needs to be sync()ed before page pPg->pgno can | ||||
| 65247 | ** be written to, store pPg->pgno in local variable needSyncPgno. | ||||
| 65248 | ** | ||||
| 65249 | ** If the isCommit flag is set, there is no need to remember that | ||||
| 65250 | ** the journal needs to be sync()ed before database page pPg->pgno | ||||
| 65251 | ** can be written to. The caller has already promised not to write to it. | ||||
| 65252 | */ | ||||
| 65253 | if( (pPg->flags&PGHDR_NEED_SYNC0x008) && !isCommit ){ | ||||
| 65254 | needSyncPgno = pPg->pgno; | ||||
| 65255 | assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||((void) (0)) | ||||
| 65256 | pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize )((void) (0)); | ||||
| 65257 | assert( pPg->flags&PGHDR_DIRTY )((void) (0)); | ||||
| 65258 | } | ||||
| 65259 | |||||
| 65260 | /* If the cache contains a page with page-number pgno, remove it | ||||
| 65261 | ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for | ||||
| 65262 | ** page pgno before the 'move' operation, it needs to be retained | ||||
| 65263 | ** for the page moved there. | ||||
| 65264 | */ | ||||
| 65265 | pPg->flags &= ~PGHDR_NEED_SYNC0x008; | ||||
| 65266 | pPgOld = sqlite3PagerLookup(pPager, pgno); | ||||
| 65267 | assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB )((void) (0)); | ||||
| 65268 | if( pPgOld ){ | ||||
| 65269 | if( NEVER(pPgOld->nRef>1)(pPgOld->nRef>1) ){ | ||||
| 65270 | sqlite3PagerUnrefNotNull(pPgOld); | ||||
| 65271 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(65271); | ||||
| 65272 | } | ||||
| 65273 | pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC0x008); | ||||
| 65274 | if( pPager->tempFile ){ | ||||
| 65275 | /* Do not discard pages from an in-memory database since we might | ||||
| 65276 | ** need to rollback later. Just move the page out of the way. */ | ||||
| 65277 | sqlite3PcacheMove(pPgOld, pPager->dbSize+1); | ||||
| 65278 | }else{ | ||||
| 65279 | sqlite3PcacheDrop(pPgOld); | ||||
| 65280 | } | ||||
| 65281 | } | ||||
| 65282 | |||||
| 65283 | origPgno = pPg->pgno; | ||||
| 65284 | sqlite3PcacheMove(pPg, pgno); | ||||
| 65285 | sqlite3PcacheMakeDirty(pPg); | ||||
| 65286 | |||||
| 65287 | /* For an in-memory database, make sure the original page continues | ||||
| 65288 | ** to exist, in case the transaction needs to roll back. Use pPgOld | ||||
| 65289 | ** as the original page since it has already been allocated. | ||||
| 65290 | */ | ||||
| 65291 | if( pPager->tempFile && pPgOld ){ | ||||
| 65292 | sqlite3PcacheMove(pPgOld, origPgno); | ||||
| 65293 | sqlite3PagerUnrefNotNull(pPgOld); | ||||
| 65294 | } | ||||
| 65295 | |||||
| 65296 | if( needSyncPgno ){ | ||||
| 65297 | /* If needSyncPgno is non-zero, then the journal file needs to be | ||||
| 65298 | ** sync()ed before any data is written to database file page needSyncPgno. | ||||
| 65299 | ** Currently, no such page exists in the page-cache and the | ||||
| 65300 | ** "is journaled" bitvec flag has been set. This needs to be remedied by | ||||
| 65301 | ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC | ||||
| 65302 | ** flag. | ||||
| 65303 | ** | ||||
| 65304 | ** If the attempt to load the page into the page-cache fails, (due | ||||
| 65305 | ** to a malloc() or IO failure), clear the bit in the pInJournal[] | ||||
| 65306 | ** array. Otherwise, if the page is loaded and written again in | ||||
| 65307 | ** this transaction, it may be written to the database file before | ||||
| 65308 | ** it is synced into the journal file. This way, it may end up in | ||||
| 65309 | ** the journal file twice, but that is not a problem. | ||||
| 65310 | */ | ||||
| 65311 | PgHdr *pPgHdr; | ||||
| 65312 | rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0); | ||||
| 65313 | if( rc!=SQLITE_OK0 ){ | ||||
| 65314 | if( needSyncPgno<=pPager->dbOrigSize ){ | ||||
| 65315 | assert( pPager->pTmpSpace!=0 )((void) (0)); | ||||
| 65316 | sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); | ||||
| 65317 | } | ||||
| 65318 | return rc; | ||||
| 65319 | } | ||||
| 65320 | pPgHdr->flags |= PGHDR_NEED_SYNC0x008; | ||||
| 65321 | sqlite3PcacheMakeDirty(pPgHdr); | ||||
| 65322 | sqlite3PagerUnrefNotNull(pPgHdr); | ||||
| 65323 | } | ||||
| 65324 | |||||
| 65325 | return SQLITE_OK0; | ||||
| 65326 | } | ||||
| 65327 | #endif | ||||
| 65328 | |||||
| 65329 | /* | ||||
| 65330 | ** The page handle passed as the first argument refers to a dirty page | ||||
| 65331 | ** with a page number other than iNew. This function changes the page's | ||||
| 65332 | ** page number to iNew and sets the value of the PgHdr.flags field to | ||||
| 65333 | ** the value passed as the third parameter. | ||||
| 65334 | */ | ||||
| 65335 | SQLITE_PRIVATEstatic void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){ | ||||
| 65336 | assert( pPg->pgno!=iNew )((void) (0)); | ||||
| 65337 | pPg->flags = flags; | ||||
| 65338 | sqlite3PcacheMove(pPg, iNew); | ||||
| 65339 | } | ||||
| 65340 | |||||
| 65341 | /* | ||||
| 65342 | ** Return a pointer to the data for the specified page. | ||||
| 65343 | */ | ||||
| 65344 | SQLITE_PRIVATEstatic void *sqlite3PagerGetData(DbPage *pPg){ | ||||
| 65345 | assert( pPg->nRef>0 || pPg->pPager->memDb )((void) (0)); | ||||
| 65346 | return pPg->pData; | ||||
| 65347 | } | ||||
| 65348 | |||||
| 65349 | /* | ||||
| 65350 | ** Return a pointer to the Pager.nExtra bytes of "extra" space | ||||
| 65351 | ** allocated along with the specified page. | ||||
| 65352 | */ | ||||
| 65353 | SQLITE_PRIVATEstatic void *sqlite3PagerGetExtra(DbPage *pPg){ | ||||
| 65354 | return pPg->pExtra; | ||||
| 65355 | } | ||||
| 65356 | |||||
| 65357 | /* | ||||
| 65358 | ** Get/set the locking-mode for this pager. Parameter eMode must be one | ||||
| 65359 | ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or | ||||
| 65360 | ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then | ||||
| 65361 | ** the locking-mode is set to the value specified. | ||||
| 65362 | ** | ||||
| 65363 | ** The returned value is either PAGER_LOCKINGMODE_NORMAL or | ||||
| 65364 | ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) | ||||
| 65365 | ** locking-mode. | ||||
| 65366 | */ | ||||
| 65367 | SQLITE_PRIVATEstatic int sqlite3PagerLockingMode(Pager *pPager, int eMode){ | ||||
| 65368 | assert( eMode==PAGER_LOCKINGMODE_QUERY((void) (0)) | ||||
| 65369 | || eMode==PAGER_LOCKINGMODE_NORMAL((void) (0)) | ||||
| 65370 | || eMode==PAGER_LOCKINGMODE_EXCLUSIVE )((void) (0)); | ||||
| 65371 | assert( PAGER_LOCKINGMODE_QUERY<0 )((void) (0)); | ||||
| 65372 | assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 )((void) (0)); | ||||
| 65373 | assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) )((void) (0)); | ||||
| 65374 | if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){ | ||||
| 65375 | pPager->exclusiveMode = (u8)eMode; | ||||
| 65376 | } | ||||
| 65377 | return (int)pPager->exclusiveMode; | ||||
| 65378 | } | ||||
| 65379 | |||||
| 65380 | /* | ||||
| 65381 | ** Set the journal-mode for this pager. Parameter eMode must be one of: | ||||
| 65382 | ** | ||||
| 65383 | ** PAGER_JOURNALMODE_DELETE | ||||
| 65384 | ** PAGER_JOURNALMODE_TRUNCATE | ||||
| 65385 | ** PAGER_JOURNALMODE_PERSIST | ||||
| 65386 | ** PAGER_JOURNALMODE_OFF | ||||
| 65387 | ** PAGER_JOURNALMODE_MEMORY | ||||
| 65388 | ** PAGER_JOURNALMODE_WAL | ||||
| 65389 | ** | ||||
| 65390 | ** The journalmode is set to the value specified if the change is allowed. | ||||
| 65391 | ** The change may be disallowed for the following reasons: | ||||
| 65392 | ** | ||||
| 65393 | ** * An in-memory database can only have its journal_mode set to _OFF | ||||
| 65394 | ** or _MEMORY. | ||||
| 65395 | ** | ||||
| 65396 | ** * Temporary databases cannot have _WAL journalmode. | ||||
| 65397 | ** | ||||
| 65398 | ** The returned indicate the current (possibly updated) journal-mode. | ||||
| 65399 | */ | ||||
| 65400 | SQLITE_PRIVATEstatic int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ | ||||
| 65401 | u8 eOld = pPager->journalMode; /* Prior journalmode */ | ||||
| 65402 | |||||
| 65403 | /* The eMode parameter is always valid */ | ||||
| 65404 | assert( eMode==PAGER_JOURNALMODE_DELETE /* 0 */((void) (0)) | ||||
| 65405 | || eMode==PAGER_JOURNALMODE_PERSIST /* 1 */((void) (0)) | ||||
| 65406 | || eMode==PAGER_JOURNALMODE_OFF /* 2 */((void) (0)) | ||||
| 65407 | || eMode==PAGER_JOURNALMODE_TRUNCATE /* 3 */((void) (0)) | ||||
| 65408 | || eMode==PAGER_JOURNALMODE_MEMORY /* 4 */((void) (0)) | ||||
| 65409 | || eMode==PAGER_JOURNALMODE_WAL /* 5 */ )((void) (0)); | ||||
| 65410 | |||||
| 65411 | /* This routine is only called from the OP_JournalMode opcode, and | ||||
| 65412 | ** the logic there will never allow a temporary file to be changed | ||||
| 65413 | ** to WAL mode. | ||||
| 65414 | */ | ||||
| 65415 | assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL )((void) (0)); | ||||
| 65416 | |||||
| 65417 | /* Do allow the journalmode of an in-memory database to be set to | ||||
| 65418 | ** anything other than MEMORY or OFF | ||||
| 65419 | */ | ||||
| 65420 | if( MEMDBpPager->memDb ){ | ||||
| 65421 | assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF )((void) (0)); | ||||
| 65422 | if( eMode!=PAGER_JOURNALMODE_MEMORY4 && eMode!=PAGER_JOURNALMODE_OFF2 ){ | ||||
| 65423 | eMode = eOld; | ||||
| 65424 | } | ||||
| 65425 | } | ||||
| 65426 | |||||
| 65427 | if( eMode!=eOld ){ | ||||
| 65428 | |||||
| 65429 | /* Change the journal mode. */ | ||||
| 65430 | assert( pPager->eState!=PAGER_ERROR )((void) (0)); | ||||
| 65431 | pPager->journalMode = (u8)eMode; | ||||
| 65432 | |||||
| 65433 | /* When transitioning from TRUNCATE or PERSIST to any other journal | ||||
| 65434 | ** mode except WAL, unless the pager is in locking_mode=exclusive mode, | ||||
| 65435 | ** delete the journal file. | ||||
| 65436 | */ | ||||
| 65437 | assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 )((void) (0)); | ||||
| 65438 | assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 )((void) (0)); | ||||
| 65439 | assert( (PAGER_JOURNALMODE_DELETE & 5)==0 )((void) (0)); | ||||
| 65440 | assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 )((void) (0)); | ||||
| 65441 | assert( (PAGER_JOURNALMODE_OFF & 5)==0 )((void) (0)); | ||||
| 65442 | assert( (PAGER_JOURNALMODE_WAL & 5)==5 )((void) (0)); | ||||
| 65443 | |||||
| 65444 | assert( isOpen(pPager->fd) || pPager->exclusiveMode )((void) (0)); | ||||
| 65445 | if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){ | ||||
| 65446 | /* In this case we would like to delete the journal file. If it is | ||||
| 65447 | ** not possible, then that is not a problem. Deleting the journal file | ||||
| 65448 | ** here is an optimization only. | ||||
| 65449 | ** | ||||
| 65450 | ** Before deleting the journal file, obtain a RESERVED lock on the | ||||
| 65451 | ** database file. This ensures that the journal file is not deleted | ||||
| 65452 | ** while it is in use by some other client. | ||||
| 65453 | */ | ||||
| 65454 | sqlite3OsClose(pPager->jfd); | ||||
| 65455 | if( pPager->eLock>=RESERVED_LOCK2 ){ | ||||
| 65456 | sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); | ||||
| 65457 | }else{ | ||||
| 65458 | int rc = SQLITE_OK0; | ||||
| 65459 | int state = pPager->eState; | ||||
| 65460 | assert( state==PAGER_OPEN || state==PAGER_READER )((void) (0)); | ||||
| 65461 | if( state==PAGER_OPEN0 ){ | ||||
| 65462 | rc = sqlite3PagerSharedLock(pPager); | ||||
| 65463 | } | ||||
| 65464 | if( pPager->eState==PAGER_READER1 ){ | ||||
| 65465 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 65466 | rc = pagerLockDb(pPager, RESERVED_LOCK2); | ||||
| 65467 | } | ||||
| 65468 | if( rc==SQLITE_OK0 ){ | ||||
| 65469 | sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); | ||||
| 65470 | } | ||||
| 65471 | if( rc==SQLITE_OK0 && state==PAGER_READER1 ){ | ||||
| 65472 | pagerUnlockDb(pPager, SHARED_LOCK1); | ||||
| 65473 | }else if( state==PAGER_OPEN0 ){ | ||||
| 65474 | pager_unlock(pPager); | ||||
| 65475 | } | ||||
| 65476 | assert( state==pPager->eState )((void) (0)); | ||||
| 65477 | } | ||||
| 65478 | }else if( eMode==PAGER_JOURNALMODE_OFF2 || eMode==PAGER_JOURNALMODE_MEMORY4 ){ | ||||
| 65479 | sqlite3OsClose(pPager->jfd); | ||||
| 65480 | } | ||||
| 65481 | } | ||||
| 65482 | |||||
| 65483 | /* Return the new journal mode */ | ||||
| 65484 | return (int)pPager->journalMode; | ||||
| 65485 | } | ||||
| 65486 | |||||
| 65487 | /* | ||||
| 65488 | ** Return the current journal mode. | ||||
| 65489 | */ | ||||
| 65490 | SQLITE_PRIVATEstatic int sqlite3PagerGetJournalMode(Pager *pPager){ | ||||
| 65491 | return (int)pPager->journalMode; | ||||
| 65492 | } | ||||
| 65493 | |||||
| 65494 | /* | ||||
| 65495 | ** Return TRUE if the pager is in a state where it is OK to change the | ||||
| 65496 | ** journalmode. Journalmode changes can only happen when the database | ||||
| 65497 | ** is unmodified. | ||||
| 65498 | */ | ||||
| 65499 | SQLITE_PRIVATEstatic int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ | ||||
| 65500 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 65501 | if( pPager->eState>=PAGER_WRITER_CACHEMOD3 ) return 0; | ||||
| 65502 | if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0)(((pPager->jfd)->pMethods!=0) && pPager->journalOff >0) ) return 0; | ||||
| 65503 | return 1; | ||||
| 65504 | } | ||||
| 65505 | |||||
| 65506 | /* | ||||
| 65507 | ** Get/set the size-limit used for persistent journal files. | ||||
| 65508 | ** | ||||
| 65509 | ** Setting the size limit to -1 means no limit is enforced. | ||||
| 65510 | ** An attempt to set a limit smaller than -1 is a no-op. | ||||
| 65511 | */ | ||||
| 65512 | SQLITE_PRIVATEstatic i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ | ||||
| 65513 | if( iLimit>=-1 ){ | ||||
| 65514 | pPager->journalSizeLimit = iLimit; | ||||
| 65515 | sqlite3WalLimit(pPager->pWal, iLimit); | ||||
| 65516 | } | ||||
| 65517 | return pPager->journalSizeLimit; | ||||
| 65518 | } | ||||
| 65519 | |||||
| 65520 | /* | ||||
| 65521 | ** Return a pointer to the pPager->pBackup variable. The backup module | ||||
| 65522 | ** in backup.c maintains the content of this variable. This module | ||||
| 65523 | ** uses it opaquely as an argument to sqlite3BackupRestart() and | ||||
| 65524 | ** sqlite3BackupUpdate() only. | ||||
| 65525 | */ | ||||
| 65526 | SQLITE_PRIVATEstatic sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ | ||||
| 65527 | return &pPager->pBackup; | ||||
| 65528 | } | ||||
| 65529 | |||||
| 65530 | #ifndef SQLITE_OMIT_VACUUM | ||||
| 65531 | /* | ||||
| 65532 | ** Unless this is an in-memory or temporary database, clear the pager cache. | ||||
| 65533 | */ | ||||
| 65534 | SQLITE_PRIVATEstatic void sqlite3PagerClearCache(Pager *pPager){ | ||||
| 65535 | assert( MEMDB==0 || pPager->tempFile )((void) (0)); | ||||
| 65536 | if( pPager->tempFile==0 ) pager_reset(pPager); | ||||
| 65537 | } | ||||
| 65538 | #endif | ||||
| 65539 | |||||
| 65540 | |||||
| 65541 | #ifndef SQLITE_OMIT_WAL | ||||
| 65542 | /* | ||||
| 65543 | ** This function is called when the user invokes "PRAGMA wal_checkpoint", | ||||
| 65544 | ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() | ||||
| 65545 | ** or wal_blocking_checkpoint() API functions. | ||||
| 65546 | ** | ||||
| 65547 | ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. | ||||
| 65548 | */ | ||||
| 65549 | SQLITE_PRIVATEstatic int sqlite3PagerCheckpoint( | ||||
| 65550 | Pager *pPager, /* Checkpoint on this pager */ | ||||
| 65551 | sqlite3 *db, /* Db handle used to check for interrupts */ | ||||
| 65552 | int eMode, /* Type of checkpoint */ | ||||
| 65553 | int *pnLog, /* OUT: Final number of frames in log */ | ||||
| 65554 | int *pnCkpt /* OUT: Final number of checkpointed frames */ | ||||
| 65555 | ){ | ||||
| 65556 | int rc = SQLITE_OK0; | ||||
| 65557 | if( pPager->pWal==0 && pPager->journalMode==PAGER_JOURNALMODE_WAL5 ){ | ||||
| 65558 | /* This only happens when a database file is zero bytes in size opened and | ||||
| 65559 | ** then "PRAGMA journal_mode=WAL" is run and then sqlite3_wal_checkpoint() | ||||
| 65560 | ** is invoked without any intervening transactions. We need to start | ||||
| 65561 | ** a transaction to initialize pWal. The PRAGMA table_list statement is | ||||
| 65562 | ** used for this since it starts transactions on every database file, | ||||
| 65563 | ** including all ATTACHed databases. This seems expensive for a single | ||||
| 65564 | ** sqlite3_wal_checkpoint() call, but it happens very rarely. | ||||
| 65565 | ** https://sqlite.org/forum/forumpost/fd0f19d229156939 | ||||
| 65566 | */ | ||||
| 65567 | sqlite3_exec(db, "PRAGMA table_list",0,0,0); | ||||
| 65568 | } | ||||
| 65569 | if( pPager->pWal ){ | ||||
| 65570 | rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode, | ||||
| 65571 | (eMode==SQLITE_CHECKPOINT_PASSIVE0 ? 0 : pPager->xBusyHandler), | ||||
| 65572 | pPager->pBusyHandlerArg, | ||||
| 65573 | pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, | ||||
| 65574 | pnLog, pnCkpt | ||||
| 65575 | ); | ||||
| 65576 | } | ||||
| 65577 | return rc; | ||||
| 65578 | } | ||||
| 65579 | |||||
| 65580 | SQLITE_PRIVATEstatic int sqlite3PagerWalCallback(Pager *pPager){ | ||||
| 65581 | return sqlite3WalCallback(pPager->pWal); | ||||
| 65582 | } | ||||
| 65583 | |||||
| 65584 | /* | ||||
| 65585 | ** Return true if the underlying VFS for the given pager supports the | ||||
| 65586 | ** primitives necessary for write-ahead logging. | ||||
| 65587 | */ | ||||
| 65588 | SQLITE_PRIVATEstatic int sqlite3PagerWalSupported(Pager *pPager){ | ||||
| 65589 | const sqlite3_io_methods *pMethods = pPager->fd->pMethods; | ||||
| 65590 | if( pPager->noLock ) return 0; | ||||
| 65591 | return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); | ||||
| 65592 | } | ||||
| 65593 | |||||
| 65594 | /* | ||||
| 65595 | ** Attempt to take an exclusive lock on the database file. If a PENDING lock | ||||
| 65596 | ** is obtained instead, immediately release it. | ||||
| 65597 | */ | ||||
| 65598 | static int pagerExclusiveLock(Pager *pPager){ | ||||
| 65599 | int rc; /* Return code */ | ||||
| 65600 | u8 eOrigLock; /* Original lock */ | ||||
| 65601 | |||||
| 65602 | assert( pPager->eLock>=SHARED_LOCK )((void) (0)); | ||||
| 65603 | eOrigLock = pPager->eLock; | ||||
| 65604 | rc = pagerLockDb(pPager, EXCLUSIVE_LOCK4); | ||||
| 65605 | if( rc!=SQLITE_OK0 ){ | ||||
| 65606 | /* If the attempt to grab the exclusive lock failed, release the | ||||
| 65607 | ** pending lock that may have been obtained instead. */ | ||||
| 65608 | pagerUnlockDb(pPager, eOrigLock); | ||||
| 65609 | } | ||||
| 65610 | |||||
| 65611 | return rc; | ||||
| 65612 | } | ||||
| 65613 | |||||
| 65614 | /* | ||||
| 65615 | ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in | ||||
| 65616 | ** exclusive-locking mode when this function is called, take an EXCLUSIVE | ||||
| 65617 | ** lock on the database file and use heap-memory to store the wal-index | ||||
| 65618 | ** in. Otherwise, use the normal shared-memory. | ||||
| 65619 | */ | ||||
| 65620 | static int pagerOpenWal(Pager *pPager){ | ||||
| 65621 | int rc = SQLITE_OK0; | ||||
| 65622 | |||||
| 65623 | assert( pPager->pWal==0 && pPager->tempFile==0 )((void) (0)); | ||||
| 65624 | assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK )((void) (0)); | ||||
| 65625 | |||||
| 65626 | /* If the pager is already in exclusive-mode, the WAL module will use | ||||
| 65627 | ** heap-memory for the wal-index instead of the VFS shared-memory | ||||
| 65628 | ** implementation. Take the exclusive lock now, before opening the WAL | ||||
| 65629 | ** file, to make sure this is safe. | ||||
| 65630 | */ | ||||
| 65631 | if( pPager->exclusiveMode ){ | ||||
| 65632 | rc = pagerExclusiveLock(pPager); | ||||
| 65633 | } | ||||
| 65634 | |||||
| 65635 | /* Open the connection to the log file. If this operation fails, | ||||
| 65636 | ** (e.g. due to malloc() failure), return an error code. | ||||
| 65637 | */ | ||||
| 65638 | if( rc==SQLITE_OK0 ){ | ||||
| 65639 | rc = sqlite3WalOpen(pPager->pVfs, | ||||
| 65640 | pPager->fd, pPager->zWal, pPager->exclusiveMode, | ||||
| 65641 | pPager->journalSizeLimit, &pPager->pWal | ||||
| 65642 | ); | ||||
| 65643 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 65644 | if( rc==SQLITE_OK0 ){ | ||||
| 65645 | sqlite3WalDb(pPager->pWal, pPager->dbWal); | ||||
| 65646 | } | ||||
| 65647 | #endif | ||||
| 65648 | } | ||||
| 65649 | pagerFixMaplimit(pPager); | ||||
| 65650 | |||||
| 65651 | return rc; | ||||
| 65652 | } | ||||
| 65653 | |||||
| 65654 | |||||
| 65655 | /* | ||||
| 65656 | ** The caller must be holding a SHARED lock on the database file to call | ||||
| 65657 | ** this function. | ||||
| 65658 | ** | ||||
| 65659 | ** If the pager passed as the first argument is open on a real database | ||||
| 65660 | ** file (not a temp file or an in-memory database), and the WAL file | ||||
| 65661 | ** is not already open, make an attempt to open it now. If successful, | ||||
| 65662 | ** return SQLITE_OK. If an error occurs or the VFS used by the pager does | ||||
| 65663 | ** not support the xShmXXX() methods, return an error code. *pbOpen is | ||||
| 65664 | ** not modified in either case. | ||||
| 65665 | ** | ||||
| 65666 | ** If the pager is open on a temp-file (or in-memory database), or if | ||||
| 65667 | ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK | ||||
| 65668 | ** without doing anything. | ||||
| 65669 | */ | ||||
| 65670 | SQLITE_PRIVATEstatic int sqlite3PagerOpenWal( | ||||
| 65671 | Pager *pPager, /* Pager object */ | ||||
| 65672 | int *pbOpen /* OUT: Set to true if call is a no-op */ | ||||
| 65673 | ){ | ||||
| 65674 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 65675 | |||||
| 65676 | assert( assert_pager_state(pPager) )((void) (0)); | ||||
| 65677 | assert( pPager->eState==PAGER_OPEN || pbOpen )((void) (0)); | ||||
| 65678 | assert( pPager->eState==PAGER_READER || !pbOpen )((void) (0)); | ||||
| 65679 | assert( pbOpen==0 || *pbOpen==0 )((void) (0)); | ||||
| 65680 | assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) )((void) (0)); | ||||
| 65681 | |||||
| 65682 | if( !pPager->tempFile && !pPager->pWal ){ | ||||
| 65683 | if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN14; | ||||
| 65684 | |||||
| 65685 | /* Close any rollback journal previously open */ | ||||
| 65686 | sqlite3OsClose(pPager->jfd); | ||||
| 65687 | |||||
| 65688 | rc = pagerOpenWal(pPager); | ||||
| 65689 | if( rc==SQLITE_OK0 ){ | ||||
| 65690 | pPager->journalMode = PAGER_JOURNALMODE_WAL5; | ||||
| 65691 | pPager->eState = PAGER_OPEN0; | ||||
| 65692 | } | ||||
| 65693 | }else{ | ||||
| 65694 | *pbOpen = 1; | ||||
| 65695 | } | ||||
| 65696 | |||||
| 65697 | return rc; | ||||
| 65698 | } | ||||
| 65699 | |||||
| 65700 | /* | ||||
| 65701 | ** This function is called to close the connection to the log file prior | ||||
| 65702 | ** to switching from WAL to rollback mode. | ||||
| 65703 | ** | ||||
| 65704 | ** Before closing the log file, this function attempts to take an | ||||
| 65705 | ** EXCLUSIVE lock on the database file. If this cannot be obtained, an | ||||
| 65706 | ** error (SQLITE_BUSY) is returned and the log connection is not closed. | ||||
| 65707 | ** If successful, the EXCLUSIVE lock is not released before returning. | ||||
| 65708 | */ | ||||
| 65709 | SQLITE_PRIVATEstatic int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){ | ||||
| 65710 | int rc = SQLITE_OK0; | ||||
| 65711 | |||||
| 65712 | assert( pPager->journalMode==PAGER_JOURNALMODE_WAL )((void) (0)); | ||||
| 65713 | |||||
| 65714 | /* If the log file is not already open, but does exist in the file-system, | ||||
| 65715 | ** it may need to be checkpointed before the connection can switch to | ||||
| 65716 | ** rollback mode. Open it now so this can happen. | ||||
| 65717 | */ | ||||
| 65718 | if( !pPager->pWal ){ | ||||
| 65719 | int logexists = 0; | ||||
| 65720 | rc = pagerLockDb(pPager, SHARED_LOCK1); | ||||
| 65721 | if( rc==SQLITE_OK0 ){ | ||||
| 65722 | rc = sqlite3OsAccess( | ||||
| 65723 | pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS0, &logexists | ||||
| 65724 | ); | ||||
| 65725 | } | ||||
| 65726 | if( rc==SQLITE_OK0 && logexists ){ | ||||
| 65727 | rc = pagerOpenWal(pPager); | ||||
| 65728 | } | ||||
| 65729 | } | ||||
| 65730 | |||||
| 65731 | /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on | ||||
| 65732 | ** the database file, the log and log-summary files will be deleted. | ||||
| 65733 | */ | ||||
| 65734 | if( rc==SQLITE_OK0 && pPager->pWal ){ | ||||
| 65735 | rc = pagerExclusiveLock(pPager); | ||||
| 65736 | if( rc==SQLITE_OK0 ){ | ||||
| 65737 | rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, | ||||
| 65738 | pPager->pageSize, (u8*)pPager->pTmpSpace); | ||||
| 65739 | pPager->pWal = 0; | ||||
| 65740 | pagerFixMaplimit(pPager); | ||||
| 65741 | if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK1); | ||||
| 65742 | } | ||||
| 65743 | } | ||||
| 65744 | return rc; | ||||
| 65745 | } | ||||
| 65746 | |||||
| 65747 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 65748 | /* | ||||
| 65749 | ** If pager pPager is a wal-mode database not in exclusive locking mode, | ||||
| 65750 | ** invoke the sqlite3WalWriteLock() function on the associated Wal object | ||||
| 65751 | ** with the same db and bLock parameters as were passed to this function. | ||||
| 65752 | ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise. | ||||
| 65753 | */ | ||||
| 65754 | SQLITE_PRIVATEstatic int sqlite3PagerWalWriteLock(Pager *pPager, int bLock)0{ | ||||
| 65755 | int rc = SQLITE_OK0; | ||||
| 65756 | if( pagerUseWal(pPager)((pPager)->pWal!=0) && pPager->exclusiveMode==0 ){ | ||||
| 65757 | rc = sqlite3WalWriteLock(pPager->pWal, bLock); | ||||
| 65758 | } | ||||
| 65759 | return rc; | ||||
| 65760 | } | ||||
| 65761 | |||||
| 65762 | /* | ||||
| 65763 | ** Set the database handle used by the wal layer to determine if | ||||
| 65764 | ** blocking locks are required. | ||||
| 65765 | */ | ||||
| 65766 | SQLITE_PRIVATEstatic void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){ | ||||
| 65767 | pPager->dbWal = db; | ||||
| 65768 | if( pagerUseWal(pPager)((pPager)->pWal!=0) ){ | ||||
| 65769 | sqlite3WalDb(pPager->pWal, db); | ||||
| 65770 | } | ||||
| 65771 | } | ||||
| 65772 | #endif | ||||
| 65773 | |||||
| 65774 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 65775 | /* | ||||
| 65776 | ** If this is a WAL database, obtain a snapshot handle for the snapshot | ||||
| 65777 | ** currently open. Otherwise, return an error. | ||||
| 65778 | */ | ||||
| 65779 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){ | ||||
| 65780 | int rc = SQLITE_ERROR1; | ||||
| 65781 | if( pPager->pWal ){ | ||||
| 65782 | rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot); | ||||
| 65783 | } | ||||
| 65784 | return rc; | ||||
| 65785 | } | ||||
| 65786 | |||||
| 65787 | /* | ||||
| 65788 | ** If this is a WAL database, store a pointer to pSnapshot. Next time a | ||||
| 65789 | ** read transaction is opened, attempt to read from the snapshot it | ||||
| 65790 | ** identifies. If this is not a WAL database, return an error. | ||||
| 65791 | */ | ||||
| 65792 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotOpen( | ||||
| 65793 | Pager *pPager, | ||||
| 65794 | sqlite3_snapshot *pSnapshot | ||||
| 65795 | ){ | ||||
| 65796 | int rc = SQLITE_OK0; | ||||
| 65797 | if( pPager->pWal ){ | ||||
| 65798 | sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot); | ||||
| 65799 | }else{ | ||||
| 65800 | rc = SQLITE_ERROR1; | ||||
| 65801 | } | ||||
| 65802 | return rc; | ||||
| 65803 | } | ||||
| 65804 | |||||
| 65805 | /* | ||||
| 65806 | ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this | ||||
| 65807 | ** is not a WAL database, return an error. | ||||
| 65808 | */ | ||||
| 65809 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotRecover(Pager *pPager){ | ||||
| 65810 | int rc; | ||||
| 65811 | if( pPager->pWal ){ | ||||
| 65812 | rc = sqlite3WalSnapshotRecover(pPager->pWal); | ||||
| 65813 | }else{ | ||||
| 65814 | rc = SQLITE_ERROR1; | ||||
| 65815 | } | ||||
| 65816 | return rc; | ||||
| 65817 | } | ||||
| 65818 | |||||
| 65819 | /* | ||||
| 65820 | ** The caller currently has a read transaction open on the database. | ||||
| 65821 | ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise, | ||||
| 65822 | ** this function takes a SHARED lock on the CHECKPOINTER slot and then | ||||
| 65823 | ** checks if the snapshot passed as the second argument is still | ||||
| 65824 | ** available. If so, SQLITE_OK is returned. | ||||
| 65825 | ** | ||||
| 65826 | ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if | ||||
| 65827 | ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error | ||||
| 65828 | ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER | ||||
| 65829 | ** lock is released before returning. | ||||
| 65830 | */ | ||||
| 65831 | SQLITE_PRIVATEstatic int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){ | ||||
| 65832 | int rc; | ||||
| 65833 | if( pPager->pWal ){ | ||||
| 65834 | rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot); | ||||
| 65835 | }else{ | ||||
| 65836 | rc = SQLITE_ERROR1; | ||||
| 65837 | } | ||||
| 65838 | return rc; | ||||
| 65839 | } | ||||
| 65840 | |||||
| 65841 | /* | ||||
| 65842 | ** Release a lock obtained by an earlier successful call to | ||||
| 65843 | ** sqlite3PagerSnapshotCheck(). | ||||
| 65844 | */ | ||||
| 65845 | SQLITE_PRIVATEstatic void sqlite3PagerSnapshotUnlock(Pager *pPager){ | ||||
| 65846 | assert( pPager->pWal )((void) (0)); | ||||
| 65847 | sqlite3WalSnapshotUnlock(pPager->pWal); | ||||
| 65848 | } | ||||
| 65849 | |||||
| 65850 | #endif /* SQLITE_ENABLE_SNAPSHOT */ | ||||
| 65851 | #endif /* !SQLITE_OMIT_WAL */ | ||||
| 65852 | |||||
| 65853 | #ifdef SQLITE_ENABLE_ZIPVFS | ||||
| 65854 | /* | ||||
| 65855 | ** A read-lock must be held on the pager when this function is called. If | ||||
| 65856 | ** the pager is in WAL mode and the WAL file currently contains one or more | ||||
| 65857 | ** frames, return the size in bytes of the page images stored within the | ||||
| 65858 | ** WAL frames. Otherwise, if this is not a WAL database or the WAL file | ||||
| 65859 | ** is empty, return 0. | ||||
| 65860 | */ | ||||
| 65861 | SQLITE_PRIVATEstatic int sqlite3PagerWalFramesize(Pager *pPager){ | ||||
| 65862 | assert( pPager->eState>=PAGER_READER )((void) (0)); | ||||
| 65863 | return sqlite3WalFramesize(pPager->pWal); | ||||
| 65864 | } | ||||
| 65865 | #endif | ||||
| 65866 | |||||
| 65867 | #if defined(SQLITE_USE_SEH) && !defined(SQLITE_OMIT_WAL) | ||||
| 65868 | SQLITE_PRIVATEstatic int sqlite3PagerWalSystemErrno(Pager *pPager){ | ||||
| 65869 | return sqlite3WalSystemErrno(pPager->pWal); | ||||
| 65870 | } | ||||
| 65871 | #endif | ||||
| 65872 | |||||
| 65873 | #endif /* SQLITE_OMIT_DISKIO */ | ||||
| 65874 | |||||
| 65875 | /************** End of pager.c ***********************************************/ | ||||
| 65876 | /************** Begin file wal.c *********************************************/ | ||||
| 65877 | /* | ||||
| 65878 | ** 2010 February 1 | ||||
| 65879 | ** | ||||
| 65880 | ** The author disclaims copyright to this source code. In place of | ||||
| 65881 | ** a legal notice, here is a blessing: | ||||
| 65882 | ** | ||||
| 65883 | ** May you do good and not evil. | ||||
| 65884 | ** May you find forgiveness for yourself and forgive others. | ||||
| 65885 | ** May you share freely, never taking more than you give. | ||||
| 65886 | ** | ||||
| 65887 | ************************************************************************* | ||||
| 65888 | ** | ||||
| 65889 | ** This file contains the implementation of a write-ahead log (WAL) used in | ||||
| 65890 | ** "journal_mode=WAL" mode. | ||||
| 65891 | ** | ||||
| 65892 | ** WRITE-AHEAD LOG (WAL) FILE FORMAT | ||||
| 65893 | ** | ||||
| 65894 | ** A WAL file consists of a header followed by zero or more "frames". | ||||
| 65895 | ** Each frame records the revised content of a single page from the | ||||
| 65896 | ** database file. All changes to the database are recorded by writing | ||||
| 65897 | ** frames into the WAL. Transactions commit when a frame is written that | ||||
| 65898 | ** contains a commit marker. A single WAL can and usually does record | ||||
| 65899 | ** multiple transactions. Periodically, the content of the WAL is | ||||
| 65900 | ** transferred back into the database file in an operation called a | ||||
| 65901 | ** "checkpoint". | ||||
| 65902 | ** | ||||
| 65903 | ** A single WAL file can be used multiple times. In other words, the | ||||
| 65904 | ** WAL can fill up with frames and then be checkpointed and then new | ||||
| 65905 | ** frames can overwrite the old ones. A WAL always grows from beginning | ||||
| 65906 | ** toward the end. Checksums and counters attached to each frame are | ||||
| 65907 | ** used to determine which frames within the WAL are valid and which | ||||
| 65908 | ** are leftovers from prior checkpoints. | ||||
| 65909 | ** | ||||
| 65910 | ** The WAL header is 32 bytes in size and consists of the following eight | ||||
| 65911 | ** big-endian 32-bit unsigned integer values: | ||||
| 65912 | ** | ||||
| 65913 | ** 0: Magic number. 0x377f0682 or 0x377f0683 | ||||
| 65914 | ** 4: File format version. Currently 3007000 | ||||
| 65915 | ** 8: Database page size. Example: 1024 | ||||
| 65916 | ** 12: Checkpoint sequence number | ||||
| 65917 | ** 16: Salt-1, random integer incremented with each checkpoint | ||||
| 65918 | ** 20: Salt-2, a different random integer changing with each ckpt | ||||
| 65919 | ** 24: Checksum-1 (first part of checksum for first 24 bytes of header). | ||||
| 65920 | ** 28: Checksum-2 (second part of checksum for first 24 bytes of header). | ||||
| 65921 | ** | ||||
| 65922 | ** Immediately following the wal-header are zero or more frames. Each | ||||
| 65923 | ** frame consists of a 24-byte frame-header followed by <page-size> bytes | ||||
| 65924 | ** of page data. The frame-header is six big-endian 32-bit unsigned | ||||
| 65925 | ** integer values, as follows: | ||||
| 65926 | ** | ||||
| 65927 | ** 0: Page number. | ||||
| 65928 | ** 4: For commit records, the size of the database image in pages | ||||
| 65929 | ** after the commit. For all other records, zero. | ||||
| 65930 | ** 8: Salt-1 (copied from the header) | ||||
| 65931 | ** 12: Salt-2 (copied from the header) | ||||
| 65932 | ** 16: Checksum-1. | ||||
| 65933 | ** 20: Checksum-2. | ||||
| 65934 | ** | ||||
| 65935 | ** A frame is considered valid if and only if the following conditions are | ||||
| 65936 | ** true: | ||||
| 65937 | ** | ||||
| 65938 | ** (1) The salt-1 and salt-2 values in the frame-header match | ||||
| 65939 | ** salt values in the wal-header | ||||
| 65940 | ** | ||||
| 65941 | ** (2) The checksum values in the final 8 bytes of the frame-header | ||||
| 65942 | ** exactly match the checksum computed consecutively on the | ||||
| 65943 | ** WAL header and the first 8 bytes and the content of all frames | ||||
| 65944 | ** up to and including the current frame. | ||||
| 65945 | ** | ||||
| 65946 | ** The checksum is computed using 32-bit big-endian integers if the | ||||
| 65947 | ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it | ||||
| 65948 | ** is computed using little-endian if the magic number is 0x377f0682. | ||||
| 65949 | ** The checksum values are always stored in the frame header in a | ||||
| 65950 | ** big-endian format regardless of which byte order is used to compute | ||||
| 65951 | ** the checksum. The checksum is computed by interpreting the input as | ||||
| 65952 | ** an even number of unsigned 32-bit integers: x[0] through x[N]. The | ||||
| 65953 | ** algorithm used for the checksum is as follows: | ||||
| 65954 | ** | ||||
| 65955 | ** for i from 0 to n-1 step 2: | ||||
| 65956 | ** s0 += x[i] + s1; | ||||
| 65957 | ** s1 += x[i+1] + s0; | ||||
| 65958 | ** endfor | ||||
| 65959 | ** | ||||
| 65960 | ** Note that s0 and s1 are both weighted checksums using fibonacci weights | ||||
| 65961 | ** in reverse order (the largest fibonacci weight occurs on the first element | ||||
| 65962 | ** of the sequence being summed.) The s1 value spans all 32-bit | ||||
| 65963 | ** terms of the sequence whereas s0 omits the final term. | ||||
| 65964 | ** | ||||
| 65965 | ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the | ||||
| 65966 | ** WAL is transferred into the database, then the database is VFS.xSync-ed. | ||||
| 65967 | ** The VFS.xSync operations serve as write barriers - all writes launched | ||||
| 65968 | ** before the xSync must complete before any write that launches after the | ||||
| 65969 | ** xSync begins. | ||||
| 65970 | ** | ||||
| 65971 | ** After each checkpoint, the salt-1 value is incremented and the salt-2 | ||||
| 65972 | ** value is randomized. This prevents old and new frames in the WAL from | ||||
| 65973 | ** being considered valid at the same time and being checkpointing together | ||||
| 65974 | ** following a crash. | ||||
| 65975 | ** | ||||
| 65976 | ** READER ALGORITHM | ||||
| 65977 | ** | ||||
| 65978 | ** To read a page from the database (call it page number P), a reader | ||||
| 65979 | ** first checks the WAL to see if it contains page P. If so, then the | ||||
| 65980 | ** last valid instance of page P that is a followed by a commit frame | ||||
| 65981 | ** or is a commit frame itself becomes the value read. If the WAL | ||||
| 65982 | ** contains no copies of page P that are valid and which are a commit | ||||
| 65983 | ** frame or are followed by a commit frame, then page P is read from | ||||
| 65984 | ** the database file. | ||||
| 65985 | ** | ||||
| 65986 | ** To start a read transaction, the reader records the index of the last | ||||
| 65987 | ** valid frame in the WAL. The reader uses this recorded "mxFrame" value | ||||
| 65988 | ** for all subsequent read operations. New transactions can be appended | ||||
| 65989 | ** to the WAL, but as long as the reader uses its original mxFrame value | ||||
| 65990 | ** and ignores the newly appended content, it will see a consistent snapshot | ||||
| 65991 | ** of the database from a single point in time. This technique allows | ||||
| 65992 | ** multiple concurrent readers to view different versions of the database | ||||
| 65993 | ** content simultaneously. | ||||
| 65994 | ** | ||||
| 65995 | ** The reader algorithm in the previous paragraphs works correctly, but | ||||
| 65996 | ** because frames for page P can appear anywhere within the WAL, the | ||||
| 65997 | ** reader has to scan the entire WAL looking for page P frames. If the | ||||
| 65998 | ** WAL is large (multiple megabytes is typical) that scan can be slow, | ||||
| 65999 | ** and read performance suffers. To overcome this problem, a separate | ||||
| 66000 | ** data structure called the wal-index is maintained to expedite the | ||||
| 66001 | ** search for frames of a particular page. | ||||
| 66002 | ** | ||||
| 66003 | ** WAL-INDEX FORMAT | ||||
| 66004 | ** | ||||
| 66005 | ** Conceptually, the wal-index is shared memory, though VFS implementations | ||||
| 66006 | ** might choose to implement the wal-index using a mmapped file. Because | ||||
| 66007 | ** the wal-index is shared memory, SQLite does not support journal_mode=WAL | ||||
| 66008 | ** on a network filesystem. All users of the database must be able to | ||||
| 66009 | ** share memory. | ||||
| 66010 | ** | ||||
| 66011 | ** In the default unix and windows implementation, the wal-index is a mmapped | ||||
| 66012 | ** file whose name is the database name with a "-shm" suffix added. For that | ||||
| 66013 | ** reason, the wal-index is sometimes called the "shm" file. | ||||
| 66014 | ** | ||||
| 66015 | ** The wal-index is transient. After a crash, the wal-index can (and should | ||||
| 66016 | ** be) reconstructed from the original WAL file. In fact, the VFS is required | ||||
| 66017 | ** to either truncate or zero the header of the wal-index when the last | ||||
| 66018 | ** connection to it closes. Because the wal-index is transient, it can | ||||
| 66019 | ** use an architecture-specific format; it does not have to be cross-platform. | ||||
| 66020 | ** Hence, unlike the database and WAL file formats which store all values | ||||
| 66021 | ** as big endian, the wal-index can store multi-byte values in the native | ||||
| 66022 | ** byte order of the host computer. | ||||
| 66023 | ** | ||||
| 66024 | ** The purpose of the wal-index is to answer this question quickly: Given | ||||
| 66025 | ** a page number P and a maximum frame index M, return the index of the | ||||
| 66026 | ** last frame in the wal before frame M for page P in the WAL, or return | ||||
| 66027 | ** NULL if there are no frames for page P in the WAL prior to M. | ||||
| 66028 | ** | ||||
| 66029 | ** The wal-index consists of a header region, followed by an one or | ||||
| 66030 | ** more index blocks. | ||||
| 66031 | ** | ||||
| 66032 | ** The wal-index header contains the total number of frames within the WAL | ||||
| 66033 | ** in the mxFrame field. | ||||
| 66034 | ** | ||||
| 66035 | ** Each index block except for the first contains information on | ||||
| 66036 | ** HASHTABLE_NPAGE frames. The first index block contains information on | ||||
| 66037 | ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and | ||||
| 66038 | ** HASHTABLE_NPAGE are selected so that together the wal-index header and | ||||
| 66039 | ** first index block are the same size as all other index blocks in the | ||||
| 66040 | ** wal-index. The values are: | ||||
| 66041 | ** | ||||
| 66042 | ** HASHTABLE_NPAGE 4096 | ||||
| 66043 | ** HASHTABLE_NPAGE_ONE 4062 | ||||
| 66044 | ** | ||||
| 66045 | ** Each index block contains two sections, a page-mapping that contains the | ||||
| 66046 | ** database page number associated with each wal frame, and a hash-table | ||||
| 66047 | ** that allows readers to query an index block for a specific page number. | ||||
| 66048 | ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE | ||||
| 66049 | ** for the first index block) 32-bit page numbers. The first entry in the | ||||
| 66050 | ** first index-block contains the database page number corresponding to the | ||||
| 66051 | ** first frame in the WAL file. The first entry in the second index block | ||||
| 66052 | ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in | ||||
| 66053 | ** the log, and so on. | ||||
| 66054 | ** | ||||
| 66055 | ** The last index block in a wal-index usually contains less than the full | ||||
| 66056 | ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers, | ||||
| 66057 | ** depending on the contents of the WAL file. This does not change the | ||||
| 66058 | ** allocated size of the page-mapping array - the page-mapping array merely | ||||
| 66059 | ** contains unused entries. | ||||
| 66060 | ** | ||||
| 66061 | ** Even without using the hash table, the last frame for page P | ||||
| 66062 | ** can be found by scanning the page-mapping sections of each index block | ||||
| 66063 | ** starting with the last index block and moving toward the first, and | ||||
| 66064 | ** within each index block, starting at the end and moving toward the | ||||
| 66065 | ** beginning. The first entry that equals P corresponds to the frame | ||||
| 66066 | ** holding the content for that page. | ||||
| 66067 | ** | ||||
| 66068 | ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers. | ||||
| 66069 | ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the | ||||
| 66070 | ** hash table for each page number in the mapping section, so the hash | ||||
| 66071 | ** table is never more than half full. The expected number of collisions | ||||
| 66072 | ** prior to finding a match is 1. Each entry of the hash table is an | ||||
| 66073 | ** 1-based index of an entry in the mapping section of the same | ||||
| 66074 | ** index block. Let K be the 1-based index of the largest entry in | ||||
| 66075 | ** the mapping section. (For index blocks other than the last, K will | ||||
| 66076 | ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block | ||||
| 66077 | ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table | ||||
| 66078 | ** contain a value of 0. | ||||
| 66079 | ** | ||||
| 66080 | ** To look for page P in the hash table, first compute a hash iKey on | ||||
| 66081 | ** P as follows: | ||||
| 66082 | ** | ||||
| 66083 | ** iKey = (P * 383) % HASHTABLE_NSLOT | ||||
| 66084 | ** | ||||
| 66085 | ** Then start scanning entries of the hash table, starting with iKey | ||||
| 66086 | ** (wrapping around to the beginning when the end of the hash table is | ||||
| 66087 | ** reached) until an unused hash slot is found. Let the first unused slot | ||||
| 66088 | ** be at index iUnused. (iUnused might be less than iKey if there was | ||||
| 66089 | ** wrap-around.) Because the hash table is never more than half full, | ||||
| 66090 | ** the search is guaranteed to eventually hit an unused entry. Let | ||||
| 66091 | ** iMax be the value between iKey and iUnused, closest to iUnused, | ||||
| 66092 | ** where aHash[iMax]==P. If there is no iMax entry (if there exists | ||||
| 66093 | ** no hash slot such that aHash[i]==p) then page P is not in the | ||||
| 66094 | ** current index block. Otherwise the iMax-th mapping entry of the | ||||
| 66095 | ** current index block corresponds to the last entry that references | ||||
| 66096 | ** page P. | ||||
| 66097 | ** | ||||
| 66098 | ** A hash search begins with the last index block and moves toward the | ||||
| 66099 | ** first index block, looking for entries corresponding to page P. On | ||||
| 66100 | ** average, only two or three slots in each index block need to be | ||||
| 66101 | ** examined in order to either find the last entry for page P, or to | ||||
| 66102 | ** establish that no such entry exists in the block. Each index block | ||||
| 66103 | ** holds over 4000 entries. So two or three index blocks are sufficient | ||||
| 66104 | ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10 | ||||
| 66105 | ** comparisons (on average) suffice to either locate a frame in the | ||||
| 66106 | ** WAL or to establish that the frame does not exist in the WAL. This | ||||
| 66107 | ** is much faster than scanning the entire 10MB WAL. | ||||
| 66108 | ** | ||||
| 66109 | ** Note that entries are added in order of increasing K. Hence, one | ||||
| 66110 | ** reader might be using some value K0 and a second reader that started | ||||
| 66111 | ** at a later time (after additional transactions were added to the WAL | ||||
| 66112 | ** and to the wal-index) might be using a different value K1, where K1>K0. | ||||
| 66113 | ** Both readers can use the same hash table and mapping section to get | ||||
| 66114 | ** the correct result. There may be entries in the hash table with | ||||
| 66115 | ** K>K0 but to the first reader, those entries will appear to be unused | ||||
| 66116 | ** slots in the hash table and so the first reader will get an answer as | ||||
| 66117 | ** if no values greater than K0 had ever been inserted into the hash table | ||||
| 66118 | ** in the first place - which is what reader one wants. Meanwhile, the | ||||
| 66119 | ** second reader using K1 will see additional values that were inserted | ||||
| 66120 | ** later, which is exactly what reader two wants. | ||||
| 66121 | ** | ||||
| 66122 | ** When a rollback occurs, the value of K is decreased. Hash table entries | ||||
| 66123 | ** that correspond to frames greater than the new K value are removed | ||||
| 66124 | ** from the hash table at this point. | ||||
| 66125 | */ | ||||
| 66126 | #ifndef SQLITE_OMIT_WAL | ||||
| 66127 | |||||
| 66128 | /* #include "wal.h" */ | ||||
| 66129 | |||||
| 66130 | /* | ||||
| 66131 | ** Trace output macros | ||||
| 66132 | */ | ||||
| 66133 | #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) | ||||
| 66134 | SQLITE_PRIVATEstatic int sqlite3WalTrace = 0; | ||||
| 66135 | # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X | ||||
| 66136 | #else | ||||
| 66137 | # define WALTRACE(X) | ||||
| 66138 | #endif | ||||
| 66139 | |||||
| 66140 | /* | ||||
| 66141 | ** The maximum (and only) versions of the wal and wal-index formats | ||||
| 66142 | ** that may be interpreted by this version of SQLite. | ||||
| 66143 | ** | ||||
| 66144 | ** If a client begins recovering a WAL file and finds that (a) the checksum | ||||
| 66145 | ** values in the wal-header are correct and (b) the version field is not | ||||
| 66146 | ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN. | ||||
| 66147 | ** | ||||
| 66148 | ** Similarly, if a client successfully reads a wal-index header (i.e. the | ||||
| 66149 | ** checksum test is successful) and finds that the version field is not | ||||
| 66150 | ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite | ||||
| 66151 | ** returns SQLITE_CANTOPEN. | ||||
| 66152 | */ | ||||
| 66153 | #define WAL_MAX_VERSION3007000 3007000 | ||||
| 66154 | #define WALINDEX_MAX_VERSION3007000 3007000 | ||||
| 66155 | |||||
| 66156 | /* | ||||
| 66157 | ** Index numbers for various locking bytes. WAL_NREADER is the number | ||||
| 66158 | ** of available reader locks and should be at least 3. The default | ||||
| 66159 | ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5. | ||||
| 66160 | ** | ||||
| 66161 | ** Technically, the various VFSes are free to implement these locks however | ||||
| 66162 | ** they see fit. However, compatibility is encouraged so that VFSes can | ||||
| 66163 | ** interoperate. The standard implementation used on both unix and windows | ||||
| 66164 | ** is for the index number to indicate a byte offset into the | ||||
| 66165 | ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all | ||||
| 66166 | ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which | ||||
| 66167 | ** should be 120) is the location in the shm file for the first locking | ||||
| 66168 | ** byte. | ||||
| 66169 | */ | ||||
| 66170 | #define WAL_WRITE_LOCK0 0 | ||||
| 66171 | #define WAL_ALL_BUT_WRITE1 1 | ||||
| 66172 | #define WAL_CKPT_LOCK1 1 | ||||
| 66173 | #define WAL_RECOVER_LOCK2 2 | ||||
| 66174 | #define WAL_READ_LOCK(I)(3+(I)) (3+(I)) | ||||
| 66175 | #define WAL_NREADER(8 -3) (SQLITE_SHM_NLOCK8-3) | ||||
| 66176 | |||||
| 66177 | |||||
| 66178 | /* Object declarations */ | ||||
| 66179 | typedef struct WalIndexHdr WalIndexHdr; | ||||
| 66180 | typedef struct WalIterator WalIterator; | ||||
| 66181 | typedef struct WalCkptInfo WalCkptInfo; | ||||
| 66182 | |||||
| 66183 | |||||
| 66184 | /* | ||||
| 66185 | ** The following object holds a copy of the wal-index header content. | ||||
| 66186 | ** | ||||
| 66187 | ** The actual header in the wal-index consists of two copies of this | ||||
| 66188 | ** object followed by one instance of the WalCkptInfo object. | ||||
| 66189 | ** For all versions of SQLite through 3.10.0 and probably beyond, | ||||
| 66190 | ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and | ||||
| 66191 | ** the total header size is 136 bytes. | ||||
| 66192 | ** | ||||
| 66193 | ** The szPage value can be any power of 2 between 512 and 32768, inclusive. | ||||
| 66194 | ** Or it can be 1 to represent a 65536-byte page. The latter case was | ||||
| 66195 | ** added in 3.7.1 when support for 64K pages was added. | ||||
| 66196 | */ | ||||
| 66197 | struct WalIndexHdr { | ||||
| 66198 | u32 iVersion; /* Wal-index version */ | ||||
| 66199 | u32 unused; /* Unused (padding) field */ | ||||
| 66200 | u32 iChange; /* Counter incremented each transaction */ | ||||
| 66201 | u8 isInit; /* 1 when initialized */ | ||||
| 66202 | u8 bigEndCksum; /* True if checksums in WAL are big-endian */ | ||||
| 66203 | u16 szPage; /* Database page size in bytes. 1==64K */ | ||||
| 66204 | u32 mxFrame; /* Index of last valid frame in the WAL */ | ||||
| 66205 | u32 nPage; /* Size of database in pages */ | ||||
| 66206 | u32 aFrameCksum[2]; /* Checksum of last frame in log */ | ||||
| 66207 | u32 aSalt[2]; /* Two salt values copied from WAL header */ | ||||
| 66208 | u32 aCksum[2]; /* Checksum over all prior fields */ | ||||
| 66209 | }; | ||||
| 66210 | |||||
| 66211 | /* | ||||
| 66212 | ** A copy of the following object occurs in the wal-index immediately | ||||
| 66213 | ** following the second copy of the WalIndexHdr. This object stores | ||||
| 66214 | ** information used by checkpoint. | ||||
| 66215 | ** | ||||
| 66216 | ** nBackfill is the number of frames in the WAL that have been written | ||||
| 66217 | ** back into the database. (We call the act of moving content from WAL to | ||||
| 66218 | ** database "backfilling".) The nBackfill number is never greater than | ||||
| 66219 | ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads | ||||
| 66220 | ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread). | ||||
| 66221 | ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from | ||||
| 66222 | ** mxFrame back to zero when the WAL is reset. | ||||
| 66223 | ** | ||||
| 66224 | ** nBackfillAttempted is the largest value of nBackfill that a checkpoint | ||||
| 66225 | ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however | ||||
| 66226 | ** the nBackfillAttempted is set before any backfilling is done and the | ||||
| 66227 | ** nBackfill is only set after all backfilling completes. So if a checkpoint | ||||
| 66228 | ** crashes, nBackfillAttempted might be larger than nBackfill. The | ||||
| 66229 | ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted. | ||||
| 66230 | ** | ||||
| 66231 | ** The aLock[] field is a set of bytes used for locking. These bytes should | ||||
| 66232 | ** never be read or written. | ||||
| 66233 | ** | ||||
| 66234 | ** There is one entry in aReadMark[] for each reader lock. If a reader | ||||
| 66235 | ** holds read-lock K, then the value in aReadMark[K] is no greater than | ||||
| 66236 | ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff) | ||||
| 66237 | ** for any aReadMark[] means that entry is unused. aReadMark[0] is | ||||
| 66238 | ** a special case; its value is never used and it exists as a place-holder | ||||
| 66239 | ** to avoid having to offset aReadMark[] indexes by one. Readers holding | ||||
| 66240 | ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content | ||||
| 66241 | ** directly from the database. | ||||
| 66242 | ** | ||||
| 66243 | ** The value of aReadMark[K] may only be changed by a thread that | ||||
| 66244 | ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of | ||||
| 66245 | ** aReadMark[K] cannot changed while there is a reader is using that mark | ||||
| 66246 | ** since the reader will be holding a shared lock on WAL_READ_LOCK(K). | ||||
| 66247 | ** | ||||
| 66248 | ** The checkpointer may only transfer frames from WAL to database where | ||||
| 66249 | ** the frame numbers are less than or equal to every aReadMark[] that is | ||||
| 66250 | ** in use (that is, every aReadMark[j] for which there is a corresponding | ||||
| 66251 | ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the | ||||
| 66252 | ** largest value and will increase an unused aReadMark[] to mxFrame if there | ||||
| 66253 | ** is not already an aReadMark[] equal to mxFrame. The exception to the | ||||
| 66254 | ** previous sentence is when nBackfill equals mxFrame (meaning that everything | ||||
| 66255 | ** in the WAL has been backfilled into the database) then new readers | ||||
| 66256 | ** will choose aReadMark[0] which has value 0 and hence such reader will | ||||
| 66257 | ** get all their all content directly from the database file and ignore | ||||
| 66258 | ** the WAL. | ||||
| 66259 | ** | ||||
| 66260 | ** Writers normally append new frames to the end of the WAL. However, | ||||
| 66261 | ** if nBackfill equals mxFrame (meaning that all WAL content has been | ||||
| 66262 | ** written back into the database) and if no readers are using the WAL | ||||
| 66263 | ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then | ||||
| 66264 | ** the writer will first "reset" the WAL back to the beginning and start | ||||
| 66265 | ** writing new content beginning at frame 1. | ||||
| 66266 | ** | ||||
| 66267 | ** We assume that 32-bit loads are atomic and so no locks are needed in | ||||
| 66268 | ** order to read from any aReadMark[] entries. | ||||
| 66269 | */ | ||||
| 66270 | struct WalCkptInfo { | ||||
| 66271 | u32 nBackfill; /* Number of WAL frames backfilled into DB */ | ||||
| 66272 | u32 aReadMark[WAL_NREADER(8 -3)]; /* Reader marks */ | ||||
| 66273 | u8 aLock[SQLITE_SHM_NLOCK8]; /* Reserved space for locks */ | ||||
| 66274 | u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */ | ||||
| 66275 | u32 notUsed0; /* Available for future enhancements */ | ||||
| 66276 | }; | ||||
| 66277 | #define READMARK_NOT_USED0xffffffff 0xffffffff | ||||
| 66278 | |||||
| 66279 | /* | ||||
| 66280 | ** This is a schematic view of the complete 136-byte header of the | ||||
| 66281 | ** wal-index file (also known as the -shm file): | ||||
| 66282 | ** | ||||
| 66283 | ** +-----------------------------+ | ||||
| 66284 | ** 0: | iVersion | \ | ||||
| 66285 | ** +-----------------------------+ | | ||||
| 66286 | ** 4: | (unused padding) | | | ||||
| 66287 | ** +-----------------------------+ | | ||||
| 66288 | ** 8: | iChange | | | ||||
| 66289 | ** +-------+-------+-------------+ | | ||||
| 66290 | ** 12: | bInit | bBig | szPage | | | ||||
| 66291 | ** +-------+-------+-------------+ | | ||||
| 66292 | ** 16: | mxFrame | | First copy of the | ||||
| 66293 | ** +-----------------------------+ | WalIndexHdr object | ||||
| 66294 | ** 20: | nPage | | | ||||
| 66295 | ** +-----------------------------+ | | ||||
| 66296 | ** 24: | aFrameCksum | | | ||||
| 66297 | ** | | | | ||||
| 66298 | ** +-----------------------------+ | | ||||
| 66299 | ** 32: | aSalt | | | ||||
| 66300 | ** | | | | ||||
| 66301 | ** +-----------------------------+ | | ||||
| 66302 | ** 40: | aCksum | | | ||||
| 66303 | ** | | / | ||||
| 66304 | ** +-----------------------------+ | ||||
| 66305 | ** 48: | iVersion | \ | ||||
| 66306 | ** +-----------------------------+ | | ||||
| 66307 | ** 52: | (unused padding) | | | ||||
| 66308 | ** +-----------------------------+ | | ||||
| 66309 | ** 56: | iChange | | | ||||
| 66310 | ** +-------+-------+-------------+ | | ||||
| 66311 | ** 60: | bInit | bBig | szPage | | | ||||
| 66312 | ** +-------+-------+-------------+ | Second copy of the | ||||
| 66313 | ** 64: | mxFrame | | WalIndexHdr | ||||
| 66314 | ** +-----------------------------+ | | ||||
| 66315 | ** 68: | nPage | | | ||||
| 66316 | ** +-----------------------------+ | | ||||
| 66317 | ** 72: | aFrameCksum | | | ||||
| 66318 | ** | | | | ||||
| 66319 | ** +-----------------------------+ | | ||||
| 66320 | ** 80: | aSalt | | | ||||
| 66321 | ** | | | | ||||
| 66322 | ** +-----------------------------+ | | ||||
| 66323 | ** 88: | aCksum | | | ||||
| 66324 | ** | | / | ||||
| 66325 | ** +-----------------------------+ | ||||
| 66326 | ** 96: | nBackfill | | ||||
| 66327 | ** +-----------------------------+ | ||||
| 66328 | ** 100: | 5 read marks | | ||||
| 66329 | ** | | | ||||
| 66330 | ** | | | ||||
| 66331 | ** | | | ||||
| 66332 | ** | | | ||||
| 66333 | ** +-------+-------+------+------+ | ||||
| 66334 | ** 120: | Write | Ckpt | Rcvr | Rd0 | \ | ||||
| 66335 | ** +-------+-------+------+------+ ) 8 lock bytes | ||||
| 66336 | ** | Read1 | Read2 | Rd3 | Rd4 | / | ||||
| 66337 | ** +-------+-------+------+------+ | ||||
| 66338 | ** 128: | nBackfillAttempted | | ||||
| 66339 | ** +-----------------------------+ | ||||
| 66340 | ** 132: | (unused padding) | | ||||
| 66341 | ** +-----------------------------+ | ||||
| 66342 | */ | ||||
| 66343 | |||||
| 66344 | /* A block of WALINDEX_LOCK_RESERVED bytes beginning at | ||||
| 66345 | ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems | ||||
| 66346 | ** only support mandatory file-locks, we do not read or write data | ||||
| 66347 | ** from the region of the file on which locks are applied. | ||||
| 66348 | */ | ||||
| 66349 | #define WALINDEX_LOCK_OFFSET(sizeof(WalIndexHdr)*2+__builtin_offsetof(WalCkptInfo, aLock) ) (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock)__builtin_offsetof(WalCkptInfo, aLock)) | ||||
| 66350 | #define WALINDEX_HDR_SIZE(sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo)) (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo)) | ||||
| 66351 | |||||
| 66352 | /* Size of header before each frame in wal */ | ||||
| 66353 | #define WAL_FRAME_HDRSIZE24 24 | ||||
| 66354 | |||||
| 66355 | /* Size of write ahead log header, including checksum. */ | ||||
| 66356 | #define WAL_HDRSIZE32 32 | ||||
| 66357 | |||||
| 66358 | /* WAL magic value. Either this value, or the same value with the least | ||||
| 66359 | ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit | ||||
| 66360 | ** big-endian format in the first 4 bytes of a WAL file. | ||||
| 66361 | ** | ||||
| 66362 | ** If the LSB is set, then the checksums for each frame within the WAL | ||||
| 66363 | ** file are calculated by treating all data as an array of 32-bit | ||||
| 66364 | ** big-endian words. Otherwise, they are calculated by interpreting | ||||
| 66365 | ** all data as 32-bit little-endian words. | ||||
| 66366 | */ | ||||
| 66367 | #define WAL_MAGIC0x377f0682 0x377f0682 | ||||
| 66368 | |||||
| 66369 | /* | ||||
| 66370 | ** Return the offset of frame iFrame in the write-ahead log file, | ||||
| 66371 | ** assuming a database page size of szPage bytes. The offset returned | ||||
| 66372 | ** is to the start of the write-ahead log frame-header. | ||||
| 66373 | */ | ||||
| 66374 | #define walFrameOffset(iFrame, szPage)( 32 + ((iFrame)-1)*(i64)((szPage)+24) ) ( \ | ||||
| 66375 | WAL_HDRSIZE32 + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE24) \ | ||||
| 66376 | ) | ||||
| 66377 | |||||
| 66378 | /* | ||||
| 66379 | ** An open write-ahead log file is represented by an instance of the | ||||
| 66380 | ** following object. | ||||
| 66381 | ** | ||||
| 66382 | ** writeLock: | ||||
| 66383 | ** This is usually set to 1 whenever the WRITER lock is held. However, | ||||
| 66384 | ** if it is set to 2, then the WRITER lock is held but must be released | ||||
| 66385 | ** by walHandleException() if a SEH exception is thrown. | ||||
| 66386 | */ | ||||
| 66387 | struct Wal { | ||||
| 66388 | sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ | ||||
| 66389 | sqlite3_file *pDbFd; /* File handle for the database file */ | ||||
| 66390 | sqlite3_file *pWalFd; /* File handle for WAL file */ | ||||
| 66391 | u32 iCallback; /* Value to pass to log callback (or 0) */ | ||||
| 66392 | i64 mxWalSize; /* Truncate WAL to this size upon reset */ | ||||
| 66393 | int nWiData; /* Size of array apWiData */ | ||||
| 66394 | int szFirstBlock; /* Size of first block written to WAL file */ | ||||
| 66395 | volatile u32 **apWiData; /* Pointer to wal-index content in memory */ | ||||
| 66396 | u32 szPage; /* Database page size */ | ||||
| 66397 | i16 readLock; /* Which read lock is being held. -1 for none */ | ||||
| 66398 | u8 syncFlags; /* Flags to use to sync header writes */ | ||||
| 66399 | u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */ | ||||
| 66400 | u8 writeLock; /* True if in a write transaction */ | ||||
| 66401 | u8 ckptLock; /* True if holding a checkpoint lock */ | ||||
| 66402 | u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */ | ||||
| 66403 | u8 truncateOnCommit; /* True to truncate WAL file on commit */ | ||||
| 66404 | u8 syncHeader; /* Fsync the WAL header if true */ | ||||
| 66405 | u8 padToSectorBoundary; /* Pad transactions out to the next sector */ | ||||
| 66406 | u8 bShmUnreliable; /* SHM content is read-only and unreliable */ | ||||
| 66407 | WalIndexHdr hdr; /* Wal-index header for current transaction */ | ||||
| 66408 | u32 minFrame; /* Ignore wal frames before this one */ | ||||
| 66409 | u32 iReCksum; /* On commit, recalculate checksums from here */ | ||||
| 66410 | const char *zWalName; /* Name of WAL file */ | ||||
| 66411 | u32 nCkpt; /* Checkpoint sequence counter in the wal-header */ | ||||
| 66412 | #ifdef SQLITE_USE_SEH | ||||
| 66413 | u32 lockMask; /* Mask of locks held */ | ||||
| 66414 | void *pFree; /* Pointer to sqlite3_free() if exception thrown */ | ||||
| 66415 | u32 *pWiValue; /* Value to write into apWiData[iWiPg] */ | ||||
| 66416 | int iWiPg; /* Write pWiValue into apWiData[iWiPg] */ | ||||
| 66417 | int iSysErrno; /* System error code following exception */ | ||||
| 66418 | #endif | ||||
| 66419 | #ifdef SQLITE_DEBUG | ||||
| 66420 | int nSehTry; /* Number of nested SEH_TRY{} blocks */ | ||||
| 66421 | u8 lockError; /* True if a locking error has occurred */ | ||||
| 66422 | #endif | ||||
| 66423 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 66424 | WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */ | ||||
| 66425 | int bGetSnapshot; /* Transaction opened for sqlite3_get_snapshot() */ | ||||
| 66426 | #endif | ||||
| 66427 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 66428 | sqlite3 *db; | ||||
| 66429 | #endif | ||||
| 66430 | }; | ||||
| 66431 | |||||
| 66432 | /* | ||||
| 66433 | ** Candidate values for Wal.exclusiveMode. | ||||
| 66434 | */ | ||||
| 66435 | #define WAL_NORMAL_MODE0 0 | ||||
| 66436 | #define WAL_EXCLUSIVE_MODE1 1 | ||||
| 66437 | #define WAL_HEAPMEMORY_MODE2 2 | ||||
| 66438 | |||||
| 66439 | /* | ||||
| 66440 | ** Possible values for WAL.readOnly | ||||
| 66441 | */ | ||||
| 66442 | #define WAL_RDWR0 0 /* Normal read/write connection */ | ||||
| 66443 | #define WAL_RDONLY1 1 /* The WAL file is readonly */ | ||||
| 66444 | #define WAL_SHM_RDONLY2 2 /* The SHM file is readonly */ | ||||
| 66445 | |||||
| 66446 | /* | ||||
| 66447 | ** Each page of the wal-index mapping contains a hash-table made up of | ||||
| 66448 | ** an array of HASHTABLE_NSLOT elements of the following type. | ||||
| 66449 | */ | ||||
| 66450 | typedef u16 ht_slot; | ||||
| 66451 | |||||
| 66452 | /* | ||||
| 66453 | ** This structure is used to implement an iterator that loops through | ||||
| 66454 | ** all frames in the WAL in database page order. Where two or more frames | ||||
| 66455 | ** correspond to the same database page, the iterator visits only the | ||||
| 66456 | ** frame most recently written to the WAL (in other words, the frame with | ||||
| 66457 | ** the largest index). | ||||
| 66458 | ** | ||||
| 66459 | ** The internals of this structure are only accessed by: | ||||
| 66460 | ** | ||||
| 66461 | ** walIteratorInit() - Create a new iterator, | ||||
| 66462 | ** walIteratorNext() - Step an iterator, | ||||
| 66463 | ** walIteratorFree() - Free an iterator. | ||||
| 66464 | ** | ||||
| 66465 | ** This functionality is used by the checkpoint code (see walCheckpoint()). | ||||
| 66466 | */ | ||||
| 66467 | struct WalIterator { | ||||
| 66468 | u32 iPrior; /* Last result returned from the iterator */ | ||||
| 66469 | int nSegment; /* Number of entries in aSegment[] */ | ||||
| 66470 | struct WalSegment { | ||||
| 66471 | int iNext; /* Next slot in aIndex[] not yet returned */ | ||||
| 66472 | ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */ | ||||
| 66473 | u32 *aPgno; /* Array of page numbers. */ | ||||
| 66474 | int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */ | ||||
| 66475 | int iZero; /* Frame number associated with aPgno[0] */ | ||||
| 66476 | } aSegment[FLEXARRAY]; /* One for every 32KB page in the wal-index */ | ||||
| 66477 | }; | ||||
| 66478 | |||||
| 66479 | /* Size (in bytes) of a WalIterator object suitable for N or fewer segments */ | ||||
| 66480 | #define SZ_WALITERATOR(N)(__builtin_offsetof(WalIterator, aSegment)*(N)*sizeof(struct WalSegment )) \ | ||||
| 66481 | (offsetof(WalIterator,aSegment)__builtin_offsetof(WalIterator, aSegment)*(N)*sizeof(struct WalSegment)) | ||||
| 66482 | |||||
| 66483 | /* | ||||
| 66484 | ** Define the parameters of the hash tables in the wal-index file. There | ||||
| 66485 | ** is a hash-table following every HASHTABLE_NPAGE page numbers in the | ||||
| 66486 | ** wal-index. | ||||
| 66487 | ** | ||||
| 66488 | ** Changing any of these constants will alter the wal-index format and | ||||
| 66489 | ** create incompatibilities. | ||||
| 66490 | */ | ||||
| 66491 | #define HASHTABLE_NPAGE4096 4096 /* Must be power of 2 */ | ||||
| 66492 | #define HASHTABLE_HASH_1383 383 /* Should be prime */ | ||||
| 66493 | #define HASHTABLE_NSLOT(4096*2) (HASHTABLE_NPAGE4096*2) /* Must be a power of 2 */ | ||||
| 66494 | |||||
| 66495 | /* | ||||
| 66496 | ** The block of page numbers associated with the first hash-table in a | ||||
| 66497 | ** wal-index is smaller than usual. This is so that there is a complete | ||||
| 66498 | ** hash-table on each aligned 32KB page of the wal-index. | ||||
| 66499 | */ | ||||
| 66500 | #define HASHTABLE_NPAGE_ONE(4096 - ((sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32 ))) (HASHTABLE_NPAGE4096 - (WALINDEX_HDR_SIZE(sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32))) | ||||
| 66501 | |||||
| 66502 | /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */ | ||||
| 66503 | #define WALINDEX_PGSZ( sizeof(ht_slot)*(4096*2) + 4096*sizeof(u32) ) ( \ | ||||
| 66504 | sizeof(ht_slot)*HASHTABLE_NSLOT(4096*2) + HASHTABLE_NPAGE4096*sizeof(u32) \ | ||||
| 66505 | ) | ||||
| 66506 | |||||
| 66507 | /* | ||||
| 66508 | ** Structured Exception Handling (SEH) is a Windows-specific technique | ||||
| 66509 | ** for catching exceptions raised while accessing memory-mapped files. | ||||
| 66510 | ** | ||||
| 66511 | ** The -DSQLITE_USE_SEH compile-time option means to use SEH to catch and | ||||
| 66512 | ** deal with system-level errors that arise during WAL -shm file processing. | ||||
| 66513 | ** Without this compile-time option, any system-level faults that appear | ||||
| 66514 | ** while accessing the memory-mapped -shm file will cause a process-wide | ||||
| 66515 | ** signal to be deliver, which will more than likely cause the entire | ||||
| 66516 | ** process to exit. | ||||
| 66517 | */ | ||||
| 66518 | #ifdef SQLITE_USE_SEH | ||||
| 66519 | #include <Windows.h> | ||||
| 66520 | |||||
| 66521 | /* Beginning of a block of code in which an exception might occur */ | ||||
| 66522 | # define SEH_TRY; __try { \ | ||||
| 66523 | assert( walAssertLockmask(pWal) && pWal->nSehTry==0 )((void) (0)); \ | ||||
| 66524 | VVA_ONLY(pWal->nSehTry++); | ||||
| 66525 | |||||
| 66526 | /* The end of a block of code in which an exception might occur */ | ||||
| 66527 | # define SEH_EXCEPT(X); ((void) (0)); \ | ||||
| 66528 | VVA_ONLY(pWal->nSehTry--); \ | ||||
| 66529 | assert( pWal->nSehTry==0 )((void) (0)); \ | ||||
| 66530 | } __except( sehExceptionFilter(pWal, GetExceptionCode(), GetExceptionInformation() ) ){ X } | ||||
| 66531 | |||||
| 66532 | /* Simulate a memory-mapping fault in the -shm file for testing purposes */ | ||||
| 66533 | # define SEH_INJECT_FAULT((void) (0)); sehInjectFault(pWal) | ||||
| 66534 | |||||
| 66535 | /* | ||||
| 66536 | ** The second argument is the return value of GetExceptionCode() for the | ||||
| 66537 | ** current exception. Return EXCEPTION_EXECUTE_HANDLER if the exception code | ||||
| 66538 | ** indicates that the exception may have been caused by accessing the *-shm | ||||
| 66539 | ** file mapping. Or EXCEPTION_CONTINUE_SEARCH otherwise. | ||||
| 66540 | */ | ||||
| 66541 | static int sehExceptionFilter(Wal *pWal, int eCode, EXCEPTION_POINTERS *p){ | ||||
| 66542 | VVA_ONLY(pWal->nSehTry--); | ||||
| 66543 | if( eCode==EXCEPTION_IN_PAGE_ERROR ){ | ||||
| 66544 | if( p && p->ExceptionRecord && p->ExceptionRecord->NumberParameters>=3 ){ | ||||
| 66545 | /* From MSDN: For this type of exception, the first element of the | ||||
| 66546 | ** ExceptionInformation[] array is a read-write flag - 0 if the exception | ||||
| 66547 | ** was thrown while reading, 1 if while writing. The second element is | ||||
| 66548 | ** the virtual address being accessed. The "third array element specifies | ||||
| 66549 | ** the underlying NTSTATUS code that resulted in the exception". */ | ||||
| 66550 | pWal->iSysErrno = (int)p->ExceptionRecord->ExceptionInformation[2]; | ||||
| 66551 | } | ||||
| 66552 | return EXCEPTION_EXECUTE_HANDLER; | ||||
| 66553 | } | ||||
| 66554 | return EXCEPTION_CONTINUE_SEARCH; | ||||
| 66555 | } | ||||
| 66556 | |||||
| 66557 | /* | ||||
| 66558 | ** If one is configured, invoke the xTestCallback callback with 650 as | ||||
| 66559 | ** the argument. If it returns true, throw the same exception that is | ||||
| 66560 | ** thrown by the system if the *-shm file mapping is accessed after it | ||||
| 66561 | ** has been invalidated. | ||||
| 66562 | */ | ||||
| 66563 | static void sehInjectFault(Wal *pWal){ | ||||
| 66564 | int res; | ||||
| 66565 | assert( pWal->nSehTry>0 )((void) (0)); | ||||
| 66566 | |||||
| 66567 | res = sqlite3FaultSim(650); | ||||
| 66568 | if( res!=0 ){ | ||||
| 66569 | ULONG_PTR aArg[3]; | ||||
| 66570 | aArg[0] = 0; | ||||
| 66571 | aArg[1] = 0; | ||||
| 66572 | aArg[2] = (ULONG_PTR)res; | ||||
| 66573 | RaiseException(EXCEPTION_IN_PAGE_ERROR, 0, 3, (const ULONG_PTR*)aArg); | ||||
| 66574 | } | ||||
| 66575 | } | ||||
| 66576 | |||||
| 66577 | /* | ||||
| 66578 | ** There are two ways to use this macro. To set a pointer to be freed | ||||
| 66579 | ** if an exception is thrown: | ||||
| 66580 | ** | ||||
| 66581 | ** SEH_FREE_ON_ERROR(0, pPtr); | ||||
| 66582 | ** | ||||
| 66583 | ** and to cancel the same: | ||||
| 66584 | ** | ||||
| 66585 | ** SEH_FREE_ON_ERROR(pPtr, 0); | ||||
| 66586 | ** | ||||
| 66587 | ** In the first case, there must not already be a pointer registered to | ||||
| 66588 | ** be freed. In the second case, pPtr must be the registered pointer. | ||||
| 66589 | */ | ||||
| 66590 | #define SEH_FREE_ON_ERROR(X,Y) \ | ||||
| 66591 | assert( (X==0 || Y==0) && pWal->pFree==X )((void) (0)); pWal->pFree = Y | ||||
| 66592 | |||||
| 66593 | /* | ||||
| 66594 | ** There are two ways to use this macro. To arrange for pWal->apWiData[iPg] | ||||
| 66595 | ** to be set to pValue if an exception is thrown: | ||||
| 66596 | ** | ||||
| 66597 | ** SEH_SET_ON_ERROR(iPg, pValue); | ||||
| 66598 | ** | ||||
| 66599 | ** and to cancel the same: | ||||
| 66600 | ** | ||||
| 66601 | ** SEH_SET_ON_ERROR(0, 0); | ||||
| 66602 | */ | ||||
| 66603 | #define SEH_SET_ON_ERROR(X,Y) pWal->iWiPg = X; pWal->pWiValue = Y | ||||
| 66604 | |||||
| 66605 | #else | ||||
| 66606 | # define SEH_TRY; VVA_ONLY(pWal->nSehTry++); | ||||
| 66607 | # define SEH_EXCEPT(X); ((void) (0)); VVA_ONLY(pWal->nSehTry--); assert( pWal->nSehTry==0 )((void) (0)); | ||||
| 66608 | # define SEH_INJECT_FAULT((void) (0)); assert( pWal->nSehTry>0 )((void) (0)); | ||||
| 66609 | # define SEH_FREE_ON_ERROR(X,Y) | ||||
| 66610 | # define SEH_SET_ON_ERROR(X,Y) | ||||
| 66611 | #endif /* ifdef SQLITE_USE_SEH */ | ||||
| 66612 | |||||
| 66613 | |||||
| 66614 | /* | ||||
| 66615 | ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index | ||||
| 66616 | ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are | ||||
| 66617 | ** numbered from zero. | ||||
| 66618 | ** | ||||
| 66619 | ** If the wal-index is currently smaller the iPage pages then the size | ||||
| 66620 | ** of the wal-index might be increased, but only if it is safe to do | ||||
| 66621 | ** so. It is safe to enlarge the wal-index if pWal->writeLock is true | ||||
| 66622 | ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE. | ||||
| 66623 | ** | ||||
| 66624 | ** Three possible result scenarios: | ||||
| 66625 | ** | ||||
| 66626 | ** (1) rc==SQLITE_OK and *ppPage==Requested-Wal-Index-Page | ||||
| 66627 | ** (2) rc>=SQLITE_ERROR and *ppPage==NULL | ||||
| 66628 | ** (3) rc==SQLITE_OK and *ppPage==NULL // only if iPage==0 | ||||
| 66629 | ** | ||||
| 66630 | ** Scenario (3) can only occur when pWal->writeLock is false and iPage==0 | ||||
| 66631 | */ | ||||
| 66632 | static SQLITE_NOINLINE__attribute__((noinline)) int walIndexPageRealloc( | ||||
| 66633 | Wal *pWal, /* The WAL context */ | ||||
| 66634 | int iPage, /* The page we seek */ | ||||
| 66635 | volatile u32 **ppPage /* Write the page pointer here */ | ||||
| 66636 | ){ | ||||
| 66637 | int rc = SQLITE_OK0; | ||||
| 66638 | |||||
| 66639 | /* Enlarge the pWal->apWiData[] array if required */ | ||||
| 66640 | if( pWal->nWiData<=iPage ){ | ||||
| 66641 | sqlite3_int64 nByte = sizeof(u32*)*(1+(i64)iPage); | ||||
| 66642 | volatile u32 **apNew; | ||||
| 66643 | apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte); | ||||
| 66644 | if( !apNew ){ | ||||
| 66645 | *ppPage = 0; | ||||
| 66646 | return SQLITE_NOMEM_BKPT7; | ||||
| 66647 | } | ||||
| 66648 | memset((void*)&apNew[pWal->nWiData], 0, | ||||
| 66649 | sizeof(u32*)*(iPage+1-pWal->nWiData)); | ||||
| 66650 | pWal->apWiData = apNew; | ||||
| 66651 | pWal->nWiData = iPage+1; | ||||
| 66652 | } | ||||
| 66653 | |||||
| 66654 | /* Request a pointer to the required page from the VFS */ | ||||
| 66655 | assert( pWal->apWiData[iPage]==0 )((void) (0)); | ||||
| 66656 | if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE2 ){ | ||||
| 66657 | pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ( sizeof(ht_slot)*(4096*2) + 4096*sizeof(u32) )); | ||||
| 66658 | if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT7; | ||||
| 66659 | }else{ | ||||
| 66660 | rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ( sizeof(ht_slot)*(4096*2) + 4096*sizeof(u32) ), | ||||
| 66661 | pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] | ||||
| 66662 | ); | ||||
| 66663 | assert( pWal->apWiData[iPage]!=0((void) (0)) | ||||
| 66664 | || rc!=SQLITE_OK((void) (0)) | ||||
| 66665 | || (pWal->writeLock==0 && iPage==0) )((void) (0)); | ||||
| 66666 | testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK ); | ||||
| 66667 | if( rc==SQLITE_OK0 ){ | ||||
| 66668 | if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM7; | ||||
| 66669 | }else if( (rc&0xff)==SQLITE_READONLY8 ){ | ||||
| 66670 | pWal->readOnly |= WAL_SHM_RDONLY2; | ||||
| 66671 | if( rc==SQLITE_READONLY8 ){ | ||||
| 66672 | rc = SQLITE_OK0; | ||||
| 66673 | } | ||||
| 66674 | } | ||||
| 66675 | } | ||||
| 66676 | |||||
| 66677 | *ppPage = pWal->apWiData[iPage]; | ||||
| 66678 | assert( iPage==0 || *ppPage || rc!=SQLITE_OK )((void) (0)); | ||||
| 66679 | return rc; | ||||
| 66680 | } | ||||
| 66681 | static int walIndexPage( | ||||
| 66682 | Wal *pWal, /* The WAL context */ | ||||
| 66683 | int iPage, /* The page we seek */ | ||||
| 66684 | volatile u32 **ppPage /* Write the page pointer here */ | ||||
| 66685 | ){ | ||||
| 66686 | SEH_INJECT_FAULT((void) (0));; | ||||
| 66687 | if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){ | ||||
| 66688 | return walIndexPageRealloc(pWal, iPage, ppPage); | ||||
| 66689 | } | ||||
| 66690 | return SQLITE_OK0; | ||||
| 66691 | } | ||||
| 66692 | |||||
| 66693 | /* | ||||
| 66694 | ** Return a pointer to the WalCkptInfo structure in the wal-index. | ||||
| 66695 | */ | ||||
| 66696 | static volatile WalCkptInfo *walCkptInfo(Wal *pWal){ | ||||
| 66697 | assert( pWal->nWiData>0 && pWal->apWiData[0] )((void) (0)); | ||||
| 66698 | SEH_INJECT_FAULT((void) (0));; | ||||
| 66699 | return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]); | ||||
| 66700 | } | ||||
| 66701 | |||||
| 66702 | /* | ||||
| 66703 | ** Return a pointer to the WalIndexHdr structure in the wal-index. | ||||
| 66704 | */ | ||||
| 66705 | static volatile WalIndexHdr *walIndexHdr(Wal *pWal){ | ||||
| 66706 | assert( pWal->nWiData>0 && pWal->apWiData[0] )((void) (0)); | ||||
| 66707 | SEH_INJECT_FAULT((void) (0));; | ||||
| 66708 | return (volatile WalIndexHdr*)pWal->apWiData[0]; | ||||
| 66709 | } | ||||
| 66710 | |||||
| 66711 | /* | ||||
| 66712 | ** The argument to this macro must be of type u32. On a little-endian | ||||
| 66713 | ** architecture, it returns the u32 value that results from interpreting | ||||
| 66714 | ** the 4 bytes as a big-endian value. On a big-endian architecture, it | ||||
| 66715 | ** returns the value that would be produced by interpreting the 4 bytes | ||||
| 66716 | ** of the input value as a little-endian integer. | ||||
| 66717 | */ | ||||
| 66718 | #define BYTESWAP32(x)( (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<< 8) + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>> 24) ) ( \ | ||||
| 66719 | (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \ | ||||
| 66720 | + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \ | ||||
| 66721 | ) | ||||
| 66722 | |||||
| 66723 | /* | ||||
| 66724 | ** Generate or extend an 8 byte checksum based on the data in | ||||
| 66725 | ** array aByte[] and the initial values of aIn[0] and aIn[1] (or | ||||
| 66726 | ** initial values of 0 and 0 if aIn==NULL). | ||||
| 66727 | ** | ||||
| 66728 | ** The checksum is written back into aOut[] before returning. | ||||
| 66729 | ** | ||||
| 66730 | ** nByte must be a positive multiple of 8. | ||||
| 66731 | */ | ||||
| 66732 | static void walChecksumBytes( | ||||
| 66733 | int nativeCksum, /* True for native byte-order, false for non-native */ | ||||
| 66734 | u8 *a, /* Content to be checksummed */ | ||||
| 66735 | int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */ | ||||
| 66736 | const u32 *aIn, /* Initial checksum value input */ | ||||
| 66737 | u32 *aOut /* OUT: Final checksum value output */ | ||||
| 66738 | ){ | ||||
| 66739 | u32 s1, s2; | ||||
| 66740 | u32 *aData = (u32 *)a; | ||||
| 66741 | u32 *aEnd = (u32 *)&a[nByte]; | ||||
| 66742 | |||||
| 66743 | if( aIn ){ | ||||
| 66744 | s1 = aIn[0]; | ||||
| 66745 | s2 = aIn[1]; | ||||
| 66746 | }else{ | ||||
| 66747 | s1 = s2 = 0; | ||||
| 66748 | } | ||||
| 66749 | |||||
| 66750 | /* nByte is a multiple of 8 between 8 and 65536 */ | ||||
| 66751 | assert( nByte>=8 && (nByte&7)==0 && nByte<=65536 )((void) (0)); | ||||
| 66752 | |||||
| 66753 | if( !nativeCksum ){ | ||||
| 66754 | do { | ||||
| 66755 | s1 += BYTESWAP32(aData[0])( (((aData[0])&0x000000FF)<<24) + (((aData[0])& 0x0000FF00)<<8) + (((aData[0])&0x00FF0000)>>8 ) + (((aData[0])&0xFF000000)>>24) ) + s2; | ||||
| 66756 | s2 += BYTESWAP32(aData[1])( (((aData[1])&0x000000FF)<<24) + (((aData[1])& 0x0000FF00)<<8) + (((aData[1])&0x00FF0000)>>8 ) + (((aData[1])&0xFF000000)>>24) ) + s1; | ||||
| 66757 | aData += 2; | ||||
| 66758 | }while( aData<aEnd ); | ||||
| 66759 | }else if( nByte%64==0 ){ | ||||
| 66760 | do { | ||||
| 66761 | s1 += *aData++ + s2; | ||||
| 66762 | s2 += *aData++ + s1; | ||||
| 66763 | s1 += *aData++ + s2; | ||||
| 66764 | s2 += *aData++ + s1; | ||||
| 66765 | s1 += *aData++ + s2; | ||||
| 66766 | s2 += *aData++ + s1; | ||||
| 66767 | s1 += *aData++ + s2; | ||||
| 66768 | s2 += *aData++ + s1; | ||||
| 66769 | s1 += *aData++ + s2; | ||||
| 66770 | s2 += *aData++ + s1; | ||||
| 66771 | s1 += *aData++ + s2; | ||||
| 66772 | s2 += *aData++ + s1; | ||||
| 66773 | s1 += *aData++ + s2; | ||||
| 66774 | s2 += *aData++ + s1; | ||||
| 66775 | s1 += *aData++ + s2; | ||||
| 66776 | s2 += *aData++ + s1; | ||||
| 66777 | }while( aData<aEnd ); | ||||
| 66778 | }else{ | ||||
| 66779 | do { | ||||
| 66780 | s1 += *aData++ + s2; | ||||
| 66781 | s2 += *aData++ + s1; | ||||
| 66782 | }while( aData<aEnd ); | ||||
| 66783 | } | ||||
| 66784 | assert( aData==aEnd )((void) (0)); | ||||
| 66785 | |||||
| 66786 | aOut[0] = s1; | ||||
| 66787 | aOut[1] = s2; | ||||
| 66788 | } | ||||
| 66789 | |||||
| 66790 | /* | ||||
| 66791 | ** If there is the possibility of concurrent access to the SHM file | ||||
| 66792 | ** from multiple threads and/or processes, then do a memory barrier. | ||||
| 66793 | */ | ||||
| 66794 | static void walShmBarrier(Wal *pWal){ | ||||
| 66795 | if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE2 ){ | ||||
| 66796 | sqlite3OsShmBarrier(pWal->pDbFd); | ||||
| 66797 | } | ||||
| 66798 | } | ||||
| 66799 | |||||
| 66800 | /* | ||||
| 66801 | ** Add the SQLITE_NO_TSAN as part of the return-type of a function | ||||
| 66802 | ** definition as a hint that the function contains constructs that | ||||
| 66803 | ** might give false-positive TSAN warnings. | ||||
| 66804 | ** | ||||
| 66805 | ** See tag-20200519-1. | ||||
| 66806 | */ | ||||
| 66807 | #if defined(__clang__1) && !defined(SQLITE_NO_TSAN__attribute__((no_sanitize_thread))) | ||||
| 66808 | # define SQLITE_NO_TSAN__attribute__((no_sanitize_thread)) __attribute__((no_sanitize_thread)) | ||||
| 66809 | #else | ||||
| 66810 | # define SQLITE_NO_TSAN__attribute__((no_sanitize_thread)) | ||||
| 66811 | #endif | ||||
| 66812 | |||||
| 66813 | /* | ||||
| 66814 | ** Write the header information in pWal->hdr into the wal-index. | ||||
| 66815 | ** | ||||
| 66816 | ** The checksum on pWal->hdr is updated before it is written. | ||||
| 66817 | */ | ||||
| 66818 | static SQLITE_NO_TSAN__attribute__((no_sanitize_thread)) void walIndexWriteHdr(Wal *pWal){ | ||||
| 66819 | volatile WalIndexHdr *aHdr = walIndexHdr(pWal); | ||||
| 66820 | const int nCksum = offsetof(WalIndexHdr, aCksum)__builtin_offsetof(WalIndexHdr, aCksum); | ||||
| 66821 | |||||
| 66822 | assert( pWal->writeLock )((void) (0)); | ||||
| 66823 | pWal->hdr.isInit = 1; | ||||
| 66824 | pWal->hdr.iVersion = WALINDEX_MAX_VERSION3007000; | ||||
| 66825 | walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum); | ||||
| 66826 | /* Possible TSAN false-positive. See tag-20200519-1 */ | ||||
| 66827 | memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); | ||||
| 66828 | walShmBarrier(pWal); | ||||
| 66829 | memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); | ||||
| 66830 | } | ||||
| 66831 | |||||
| 66832 | /* | ||||
| 66833 | ** This function encodes a single frame header and writes it to a buffer | ||||
| 66834 | ** supplied by the caller. A frame-header is made up of a series of | ||||
| 66835 | ** 4-byte big-endian integers, as follows: | ||||
| 66836 | ** | ||||
| 66837 | ** 0: Page number. | ||||
| 66838 | ** 4: For commit records, the size of the database image in pages | ||||
| 66839 | ** after the commit. For all other records, zero. | ||||
| 66840 | ** 8: Salt-1 (copied from the wal-header) | ||||
| 66841 | ** 12: Salt-2 (copied from the wal-header) | ||||
| 66842 | ** 16: Checksum-1. | ||||
| 66843 | ** 20: Checksum-2. | ||||
| 66844 | */ | ||||
| 66845 | static void walEncodeFrame( | ||||
| 66846 | Wal *pWal, /* The write-ahead log */ | ||||
| 66847 | u32 iPage, /* Database page number for frame */ | ||||
| 66848 | u32 nTruncate, /* New db size (or 0 for non-commit frames) */ | ||||
| 66849 | u8 *aData, /* Pointer to page data */ | ||||
| 66850 | u8 *aFrame /* OUT: Write encoded frame here */ | ||||
| 66851 | ){ | ||||
| 66852 | int nativeCksum; /* True for native byte-order checksums */ | ||||
| 66853 | u32 *aCksum = pWal->hdr.aFrameCksum; | ||||
| 66854 | assert( WAL_FRAME_HDRSIZE==24 )((void) (0)); | ||||
| 66855 | sqlite3Put4byte(&aFrame[0], iPage); | ||||
| 66856 | sqlite3Put4byte(&aFrame[4], nTruncate); | ||||
| 66857 | if( pWal->iReCksum==0 ){ | ||||
| 66858 | memcpy(&aFrame[8], pWal->hdr.aSalt, 8); | ||||
| 66859 | |||||
| 66860 | nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN0); | ||||
| 66861 | walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); | ||||
| 66862 | walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); | ||||
| 66863 | |||||
| 66864 | sqlite3Put4byte(&aFrame[16], aCksum[0]); | ||||
| 66865 | sqlite3Put4byte(&aFrame[20], aCksum[1]); | ||||
| 66866 | }else{ | ||||
| 66867 | memset(&aFrame[8], 0, 16); | ||||
| 66868 | } | ||||
| 66869 | } | ||||
| 66870 | |||||
| 66871 | /* | ||||
| 66872 | ** Check to see if the frame with header in aFrame[] and content | ||||
| 66873 | ** in aData[] is valid. If it is a valid frame, fill *piPage and | ||||
| 66874 | ** *pnTruncate and return true. Return if the frame is not valid. | ||||
| 66875 | */ | ||||
| 66876 | static int walDecodeFrame( | ||||
| 66877 | Wal *pWal, /* The write-ahead log */ | ||||
| 66878 | u32 *piPage, /* OUT: Database page number for frame */ | ||||
| 66879 | u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */ | ||||
| 66880 | u8 *aData, /* Pointer to page data (for checksum) */ | ||||
| 66881 | u8 *aFrame /* Frame data */ | ||||
| 66882 | ){ | ||||
| 66883 | int nativeCksum; /* True for native byte-order checksums */ | ||||
| 66884 | u32 *aCksum = pWal->hdr.aFrameCksum; | ||||
| 66885 | u32 pgno; /* Page number of the frame */ | ||||
| 66886 | assert( WAL_FRAME_HDRSIZE==24 )((void) (0)); | ||||
| 66887 | |||||
| 66888 | /* A frame is only valid if the salt values in the frame-header | ||||
| 66889 | ** match the salt values in the wal-header. | ||||
| 66890 | */ | ||||
| 66891 | if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){ | ||||
| 66892 | return 0; | ||||
| 66893 | } | ||||
| 66894 | |||||
| 66895 | /* A frame is only valid if the page number is greater than zero. | ||||
| 66896 | */ | ||||
| 66897 | pgno = sqlite3Get4byte(&aFrame[0]); | ||||
| 66898 | if( pgno==0 ){ | ||||
| 66899 | return 0; | ||||
| 66900 | } | ||||
| 66901 | |||||
| 66902 | /* A frame is only valid if a checksum of the WAL header, | ||||
| 66903 | ** all prior frames, the first 16 bytes of this frame-header, | ||||
| 66904 | ** and the frame-data matches the checksum in the last 8 | ||||
| 66905 | ** bytes of this frame-header. | ||||
| 66906 | */ | ||||
| 66907 | nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN0); | ||||
| 66908 | walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); | ||||
| 66909 | walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); | ||||
| 66910 | if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) | ||||
| 66911 | || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) | ||||
| 66912 | ){ | ||||
| 66913 | /* Checksum failed. */ | ||||
| 66914 | return 0; | ||||
| 66915 | } | ||||
| 66916 | |||||
| 66917 | /* If we reach this point, the frame is valid. Return the page number | ||||
| 66918 | ** and the new database size. | ||||
| 66919 | */ | ||||
| 66920 | *piPage = pgno; | ||||
| 66921 | *pnTruncate = sqlite3Get4byte(&aFrame[4]); | ||||
| 66922 | return 1; | ||||
| 66923 | } | ||||
| 66924 | |||||
| 66925 | |||||
| 66926 | #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) | ||||
| 66927 | /* | ||||
| 66928 | ** Names of locks. This routine is used to provide debugging output and is not | ||||
| 66929 | ** a part of an ordinary build. | ||||
| 66930 | */ | ||||
| 66931 | static const char *walLockName(int lockIdx){ | ||||
| 66932 | if( lockIdx==WAL_WRITE_LOCK0 ){ | ||||
| 66933 | return "WRITE-LOCK"; | ||||
| 66934 | }else if( lockIdx==WAL_CKPT_LOCK1 ){ | ||||
| 66935 | return "CKPT-LOCK"; | ||||
| 66936 | }else if( lockIdx==WAL_RECOVER_LOCK2 ){ | ||||
| 66937 | return "RECOVER-LOCK"; | ||||
| 66938 | }else{ | ||||
| 66939 | static char zName[15]; | ||||
| 66940 | sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", | ||||
| 66941 | lockIdx-WAL_READ_LOCK(0)(3+(0))); | ||||
| 66942 | return zName; | ||||
| 66943 | } | ||||
| 66944 | } | ||||
| 66945 | #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ | ||||
| 66946 | |||||
| 66947 | |||||
| 66948 | /* | ||||
| 66949 | ** Set or release locks on the WAL. Locks are either shared or exclusive. | ||||
| 66950 | ** A lock cannot be moved directly between shared and exclusive - it must go | ||||
| 66951 | ** through the unlocked state first. | ||||
| 66952 | ** | ||||
| 66953 | ** In locking_mode=EXCLUSIVE, all of these routines become no-ops. | ||||
| 66954 | */ | ||||
| 66955 | static int walLockShared(Wal *pWal, int lockIdx){ | ||||
| 66956 | int rc; | ||||
| 66957 | if( pWal->exclusiveMode ) return SQLITE_OK0; | ||||
| 66958 | rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, | ||||
| 66959 | SQLITE_SHM_LOCK2 | SQLITE_SHM_SHARED4); | ||||
| 66960 | WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal, | ||||
| 66961 | walLockName(lockIdx), rc ? "failed" : "ok")); | ||||
| 66962 | VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); ) | ||||
| 66963 | #ifdef SQLITE_USE_SEH | ||||
| 66964 | if( rc==SQLITE_OK0 ) pWal->lockMask |= (1 << lockIdx); | ||||
| 66965 | #endif | ||||
| 66966 | return rc; | ||||
| 66967 | } | ||||
| 66968 | static void walUnlockShared(Wal *pWal, int lockIdx){ | ||||
| 66969 | if( pWal->exclusiveMode ) return; | ||||
| 66970 | (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, | ||||
| 66971 | SQLITE_SHM_UNLOCK1 | SQLITE_SHM_SHARED4); | ||||
| 66972 | #ifdef SQLITE_USE_SEH | ||||
| 66973 | pWal->lockMask &= ~(1 << lockIdx); | ||||
| 66974 | #endif | ||||
| 66975 | WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx))); | ||||
| 66976 | } | ||||
| 66977 | static int walLockExclusive(Wal *pWal, int lockIdx, int n){ | ||||
| 66978 | int rc; | ||||
| 66979 | if( pWal->exclusiveMode ) return SQLITE_OK0; | ||||
| 66980 | rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, | ||||
| 66981 | SQLITE_SHM_LOCK2 | SQLITE_SHM_EXCLUSIVE8); | ||||
| 66982 | WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal, | ||||
| 66983 | walLockName(lockIdx), n, rc ? "failed" : "ok")); | ||||
| 66984 | VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); ) | ||||
| 66985 | #ifdef SQLITE_USE_SEH | ||||
| 66986 | if( rc==SQLITE_OK0 ){ | ||||
| 66987 | pWal->lockMask |= (((1<<n)-1) << (SQLITE_SHM_NLOCK8+lockIdx)); | ||||
| 66988 | } | ||||
| 66989 | #endif | ||||
| 66990 | return rc; | ||||
| 66991 | } | ||||
| 66992 | static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ | ||||
| 66993 | if( pWal->exclusiveMode ) return; | ||||
| 66994 | (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, | ||||
| 66995 | SQLITE_SHM_UNLOCK1 | SQLITE_SHM_EXCLUSIVE8); | ||||
| 66996 | #ifdef SQLITE_USE_SEH | ||||
| 66997 | pWal->lockMask &= ~(((1<<n)-1) << (SQLITE_SHM_NLOCK8+lockIdx)); | ||||
| 66998 | #endif | ||||
| 66999 | WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal, | ||||
| 67000 | walLockName(lockIdx), n)); | ||||
| 67001 | } | ||||
| 67002 | |||||
| 67003 | /* | ||||
| 67004 | ** Compute a hash on a page number. The resulting hash value must land | ||||
| 67005 | ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances | ||||
| 67006 | ** the hash to the next value in the event of a collision. | ||||
| 67007 | */ | ||||
| 67008 | static int walHash(u32 iPage){ | ||||
| 67009 | assert( iPage>0 )((void) (0)); | ||||
| 67010 | assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 )((void) (0)); | ||||
| 67011 | return (iPage*HASHTABLE_HASH_1383) & (HASHTABLE_NSLOT(4096*2)-1); | ||||
| 67012 | } | ||||
| 67013 | static int walNextHash(int iPriorHash){ | ||||
| 67014 | return (iPriorHash+1)&(HASHTABLE_NSLOT(4096*2)-1); | ||||
| 67015 | } | ||||
| 67016 | |||||
| 67017 | /* | ||||
| 67018 | ** An instance of the WalHashLoc object is used to describe the location | ||||
| 67019 | ** of a page hash table in the wal-index. This becomes the return value | ||||
| 67020 | ** from walHashGet(). | ||||
| 67021 | */ | ||||
| 67022 | typedef struct WalHashLoc WalHashLoc; | ||||
| 67023 | struct WalHashLoc { | ||||
| 67024 | volatile ht_slot *aHash; /* Start of the wal-index hash table */ | ||||
| 67025 | volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */ | ||||
| 67026 | u32 iZero; /* One less than the frame number of first indexed*/ | ||||
| 67027 | }; | ||||
| 67028 | |||||
| 67029 | /* | ||||
| 67030 | ** Return pointers to the hash table and page number array stored on | ||||
| 67031 | ** page iHash of the wal-index. The wal-index is broken into 32KB pages | ||||
| 67032 | ** numbered starting from 0. | ||||
| 67033 | ** | ||||
| 67034 | ** Set output variable pLoc->aHash to point to the start of the hash table | ||||
| 67035 | ** in the wal-index file. Set pLoc->iZero to one less than the frame | ||||
| 67036 | ** number of the first frame indexed by this hash table. If a | ||||
| 67037 | ** slot in the hash table is set to N, it refers to frame number | ||||
| 67038 | ** (pLoc->iZero+N) in the log. | ||||
| 67039 | ** | ||||
| 67040 | ** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the | ||||
| 67041 | ** first frame indexed by the hash table, frame (pLoc->iZero). | ||||
| 67042 | */ | ||||
| 67043 | static int walHashGet( | ||||
| 67044 | Wal *pWal, /* WAL handle */ | ||||
| 67045 | int iHash, /* Find the iHash'th table */ | ||||
| 67046 | WalHashLoc *pLoc /* OUT: Hash table location */ | ||||
| 67047 | ){ | ||||
| 67048 | int rc; /* Return code */ | ||||
| 67049 | |||||
| 67050 | rc = walIndexPage(pWal, iHash, &pLoc->aPgno); | ||||
| 67051 | assert( rc==SQLITE_OK || iHash>0 )((void) (0)); | ||||
| 67052 | |||||
| 67053 | if( pLoc->aPgno ){ | ||||
| 67054 | pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE4096]; | ||||
| 67055 | if( iHash==0 ){ | ||||
| 67056 | pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE(sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32)]; | ||||
| 67057 | pLoc->iZero = 0; | ||||
| 67058 | }else{ | ||||
| 67059 | pLoc->iZero = HASHTABLE_NPAGE_ONE(4096 - ((sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32 ))) + (iHash-1)*HASHTABLE_NPAGE4096; | ||||
| 67060 | } | ||||
| 67061 | }else if( NEVER(rc==SQLITE_OK)(rc==0) ){ | ||||
| 67062 | rc = SQLITE_ERROR1; | ||||
| 67063 | } | ||||
| 67064 | return rc; | ||||
| 67065 | } | ||||
| 67066 | |||||
| 67067 | /* | ||||
| 67068 | ** Return the number of the wal-index page that contains the hash-table | ||||
| 67069 | ** and page-number array that contain entries corresponding to WAL frame | ||||
| 67070 | ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages | ||||
| 67071 | ** are numbered starting from 0. | ||||
| 67072 | */ | ||||
| 67073 | static int walFramePage(u32 iFrame){ | ||||
| 67074 | int iHash = (iFrame+HASHTABLE_NPAGE4096-HASHTABLE_NPAGE_ONE(4096 - ((sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32 )))-1) / HASHTABLE_NPAGE4096; | ||||
| 67075 | assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)((void) (0)) | ||||
| 67076 | && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)((void) (0)) | ||||
| 67077 | && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))((void) (0)) | ||||
| 67078 | && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)((void) (0)) | ||||
| 67079 | && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))((void) (0)) | ||||
| 67080 | )((void) (0)); | ||||
| 67081 | assert( iHash>=0 )((void) (0)); | ||||
| 67082 | return iHash; | ||||
| 67083 | } | ||||
| 67084 | |||||
| 67085 | /* | ||||
| 67086 | ** Return the page number associated with frame iFrame in this WAL. | ||||
| 67087 | */ | ||||
| 67088 | static u32 walFramePgno(Wal *pWal, u32 iFrame){ | ||||
| 67089 | int iHash = walFramePage(iFrame); | ||||
| 67090 | SEH_INJECT_FAULT((void) (0));; | ||||
| 67091 | if( iHash==0 ){ | ||||
| 67092 | return pWal->apWiData[0][WALINDEX_HDR_SIZE(sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32) + iFrame - 1]; | ||||
| 67093 | } | ||||
| 67094 | return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE(4096 - ((sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32 ))))%HASHTABLE_NPAGE4096]; | ||||
| 67095 | } | ||||
| 67096 | |||||
| 67097 | /* | ||||
| 67098 | ** Remove entries from the hash table that point to WAL slots greater | ||||
| 67099 | ** than pWal->hdr.mxFrame. | ||||
| 67100 | ** | ||||
| 67101 | ** This function is called whenever pWal->hdr.mxFrame is decreased due | ||||
| 67102 | ** to a rollback or savepoint. | ||||
| 67103 | ** | ||||
| 67104 | ** At most only the hash table containing pWal->hdr.mxFrame needs to be | ||||
| 67105 | ** updated. Any later hash tables will be automatically cleared when | ||||
| 67106 | ** pWal->hdr.mxFrame advances to the point where those hash tables are | ||||
| 67107 | ** actually needed. | ||||
| 67108 | */ | ||||
| 67109 | static void walCleanupHash(Wal *pWal){ | ||||
| 67110 | WalHashLoc sLoc; /* Hash table location */ | ||||
| 67111 | int iLimit = 0; /* Zero values greater than this */ | ||||
| 67112 | int nByte; /* Number of bytes to zero in aPgno[] */ | ||||
| 67113 | int i; /* Used to iterate through aHash[] */ | ||||
| 67114 | |||||
| 67115 | assert( pWal->writeLock )((void) (0)); | ||||
| 67116 | testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 ); | ||||
| 67117 | testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE ); | ||||
| 67118 | testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 ); | ||||
| 67119 | |||||
| 67120 | if( pWal->hdr.mxFrame==0 ) return; | ||||
| 67121 | |||||
| 67122 | /* Obtain pointers to the hash-table and page-number array containing | ||||
| 67123 | ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed | ||||
| 67124 | ** that the page said hash-table and array reside on is already mapped.(1) | ||||
| 67125 | */ | ||||
| 67126 | assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) )((void) (0)); | ||||
| 67127 | assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] )((void) (0)); | ||||
| 67128 | i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc); | ||||
| 67129 | if( NEVER(i)(i) ) return; /* Defense-in-depth, in case (1) above is wrong */ | ||||
| 67130 | |||||
| 67131 | /* Zero all hash-table entries that correspond to frame numbers greater | ||||
| 67132 | ** than pWal->hdr.mxFrame. | ||||
| 67133 | */ | ||||
| 67134 | iLimit = pWal->hdr.mxFrame - sLoc.iZero; | ||||
| 67135 | assert( iLimit>0 )((void) (0)); | ||||
| 67136 | for(i=0; i<HASHTABLE_NSLOT(4096*2); i++){ | ||||
| 67137 | if( sLoc.aHash[i]>iLimit ){ | ||||
| 67138 | sLoc.aHash[i] = 0; | ||||
| 67139 | } | ||||
| 67140 | } | ||||
| 67141 | |||||
| 67142 | /* Zero the entries in the aPgno array that correspond to frames with | ||||
| 67143 | ** frame numbers greater than pWal->hdr.mxFrame. | ||||
| 67144 | */ | ||||
| 67145 | nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]); | ||||
| 67146 | assert( nByte>=0 )((void) (0)); | ||||
| 67147 | memset((void *)&sLoc.aPgno[iLimit], 0, nByte); | ||||
| 67148 | |||||
| 67149 | #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT | ||||
| 67150 | /* Verify that the every entry in the mapping region is still reachable | ||||
| 67151 | ** via the hash table even after the cleanup. | ||||
| 67152 | */ | ||||
| 67153 | if( iLimit ){ | ||||
| 67154 | int j; /* Loop counter */ | ||||
| 67155 | int iKey; /* Hash key */ | ||||
| 67156 | for(j=0; j<iLimit; j++){ | ||||
| 67157 | for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){ | ||||
| 67158 | if( sLoc.aHash[iKey]==j+1 ) break; | ||||
| 67159 | } | ||||
| 67160 | assert( sLoc.aHash[iKey]==j+1 )((void) (0)); | ||||
| 67161 | } | ||||
| 67162 | } | ||||
| 67163 | #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ | ||||
| 67164 | } | ||||
| 67165 | |||||
| 67166 | |||||
| 67167 | /* | ||||
| 67168 | ** Set an entry in the wal-index that will map database page number | ||||
| 67169 | ** pPage into WAL frame iFrame. | ||||
| 67170 | */ | ||||
| 67171 | static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ | ||||
| 67172 | int rc; /* Return code */ | ||||
| 67173 | WalHashLoc sLoc; /* Wal-index hash table location */ | ||||
| 67174 | |||||
| 67175 | rc = walHashGet(pWal, walFramePage(iFrame), &sLoc); | ||||
| 67176 | |||||
| 67177 | /* Assuming the wal-index file was successfully mapped, populate the | ||||
| 67178 | ** page number array and hash table entry. | ||||
| 67179 | */ | ||||
| 67180 | if( rc==SQLITE_OK0 ){ | ||||
| 67181 | int iKey; /* Hash table key */ | ||||
| 67182 | int idx; /* Value to write to hash-table slot */ | ||||
| 67183 | int nCollide; /* Number of hash collisions */ | ||||
| 67184 | |||||
| 67185 | idx = iFrame - sLoc.iZero; | ||||
| 67186 | assert( idx <= HASHTABLE_NSLOT/2 + 1 )((void) (0)); | ||||
| 67187 | |||||
| 67188 | /* If this is the first entry to be added to this hash-table, zero the | ||||
| 67189 | ** entire hash table and aPgno[] array before proceeding. | ||||
| 67190 | */ | ||||
| 67191 | if( idx==1 ){ | ||||
| 67192 | int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT(4096*2)] - (u8*)sLoc.aPgno); | ||||
| 67193 | assert( nByte>=0 )((void) (0)); | ||||
| 67194 | memset((void*)sLoc.aPgno, 0, nByte); | ||||
| 67195 | } | ||||
| 67196 | |||||
| 67197 | /* If the entry in aPgno[] is already set, then the previous writer | ||||
| 67198 | ** must have exited unexpectedly in the middle of a transaction (after | ||||
| 67199 | ** writing one or more dirty pages to the WAL to free up memory). | ||||
| 67200 | ** Remove the remnants of that writers uncommitted transaction from | ||||
| 67201 | ** the hash-table before writing any new entries. | ||||
| 67202 | */ | ||||
| 67203 | if( sLoc.aPgno[idx-1] ){ | ||||
| 67204 | walCleanupHash(pWal); | ||||
| 67205 | assert( !sLoc.aPgno[idx-1] )((void) (0)); | ||||
| 67206 | } | ||||
| 67207 | |||||
| 67208 | /* Write the aPgno[] array entry and the hash-table slot. */ | ||||
| 67209 | nCollide = idx; | ||||
| 67210 | for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){ | ||||
| 67211 | if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(67211); | ||||
| 67212 | } | ||||
| 67213 | sLoc.aPgno[idx-1] = iPage; | ||||
| 67214 | AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx)__atomic_store_n((&sLoc.aHash[iKey]),((ht_slot)idx),0); | ||||
| 67215 | |||||
| 67216 | #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT | ||||
| 67217 | /* Verify that the number of entries in the hash table exactly equals | ||||
| 67218 | ** the number of entries in the mapping region. | ||||
| 67219 | */ | ||||
| 67220 | { | ||||
| 67221 | int i; /* Loop counter */ | ||||
| 67222 | int nEntry = 0; /* Number of entries in the hash table */ | ||||
| 67223 | for(i=0; i<HASHTABLE_NSLOT(4096*2); i++){ if( sLoc.aHash[i] ) nEntry++; } | ||||
| 67224 | assert( nEntry==idx )((void) (0)); | ||||
| 67225 | } | ||||
| 67226 | |||||
| 67227 | /* Verify that the every entry in the mapping region is reachable | ||||
| 67228 | ** via the hash table. This turns out to be a really, really expensive | ||||
| 67229 | ** thing to check, so only do this occasionally - not on every | ||||
| 67230 | ** iteration. | ||||
| 67231 | */ | ||||
| 67232 | if( (idx&0x3ff)==0 ){ | ||||
| 67233 | int i; /* Loop counter */ | ||||
| 67234 | for(i=0; i<idx; i++){ | ||||
| 67235 | for(iKey=walHash(sLoc.aPgno[i]); | ||||
| 67236 | sLoc.aHash[iKey]; | ||||
| 67237 | iKey=walNextHash(iKey)){ | ||||
| 67238 | if( sLoc.aHash[iKey]==i+1 ) break; | ||||
| 67239 | } | ||||
| 67240 | assert( sLoc.aHash[iKey]==i+1 )((void) (0)); | ||||
| 67241 | } | ||||
| 67242 | } | ||||
| 67243 | #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ | ||||
| 67244 | } | ||||
| 67245 | |||||
| 67246 | return rc; | ||||
| 67247 | } | ||||
| 67248 | |||||
| 67249 | |||||
| 67250 | /* | ||||
| 67251 | ** Recover the wal-index by reading the write-ahead log file. | ||||
| 67252 | ** | ||||
| 67253 | ** This routine first tries to establish an exclusive lock on the | ||||
| 67254 | ** wal-index to prevent other threads/processes from doing anything | ||||
| 67255 | ** with the WAL or wal-index while recovery is running. The | ||||
| 67256 | ** WAL_RECOVER_LOCK is also held so that other threads will know | ||||
| 67257 | ** that this thread is running recovery. If unable to establish | ||||
| 67258 | ** the necessary locks, this routine returns SQLITE_BUSY. | ||||
| 67259 | */ | ||||
| 67260 | static int walIndexRecover(Wal *pWal){ | ||||
| 67261 | int rc; /* Return Code */ | ||||
| 67262 | i64 nSize; /* Size of log file */ | ||||
| 67263 | u32 aFrameCksum[2] = {0, 0}; | ||||
| 67264 | int iLock; /* Lock offset to lock for checkpoint */ | ||||
| 67265 | |||||
| 67266 | /* Obtain an exclusive lock on all byte in the locking range not already | ||||
| 67267 | ** locked by the caller. The caller is guaranteed to have locked the | ||||
| 67268 | ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte. | ||||
| 67269 | ** If successful, the same bytes that are locked here are unlocked before | ||||
| 67270 | ** this function returns. | ||||
| 67271 | */ | ||||
| 67272 | assert( pWal->ckptLock==1 || pWal->ckptLock==0 )((void) (0)); | ||||
| 67273 | assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 )((void) (0)); | ||||
| 67274 | assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE )((void) (0)); | ||||
| 67275 | assert( pWal->writeLock )((void) (0)); | ||||
| 67276 | iLock = WAL_ALL_BUT_WRITE1 + pWal->ckptLock; | ||||
| 67277 | rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)(3+(0))-iLock); | ||||
| 67278 | if( rc ){ | ||||
| 67279 | return rc; | ||||
| 67280 | } | ||||
| 67281 | |||||
| 67282 | WALTRACE(("WAL%p: recovery begin...\n", pWal)); | ||||
| 67283 | |||||
| 67284 | memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); | ||||
| 67285 | |||||
| 67286 | rc = sqlite3OsFileSize(pWal->pWalFd, &nSize); | ||||
| 67287 | if( rc!=SQLITE_OK0 ){ | ||||
| 67288 | goto recovery_error; | ||||
| 67289 | } | ||||
| 67290 | |||||
| 67291 | if( nSize>WAL_HDRSIZE32 ){ | ||||
| 67292 | u8 aBuf[WAL_HDRSIZE32]; /* Buffer to load WAL header into */ | ||||
| 67293 | u32 *aPrivate = 0; /* Heap copy of *-shm hash being populated */ | ||||
| 67294 | u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ | ||||
| 67295 | int szFrame; /* Number of bytes in buffer aFrame[] */ | ||||
| 67296 | u8 *aData; /* Pointer to data part of aFrame buffer */ | ||||
| 67297 | int szPage; /* Page size according to the log */ | ||||
| 67298 | u32 magic; /* Magic value read from WAL header */ | ||||
| 67299 | u32 version; /* Magic value read from WAL header */ | ||||
| 67300 | int isValid; /* True if this frame is valid */ | ||||
| 67301 | u32 iPg; /* Current 32KB wal-index page */ | ||||
| 67302 | u32 iLastFrame; /* Last frame in wal, based on nSize alone */ | ||||
| 67303 | |||||
| 67304 | /* Read in the WAL header. */ | ||||
| 67305 | rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE32, 0); | ||||
| 67306 | if( rc!=SQLITE_OK0 ){ | ||||
| 67307 | goto recovery_error; | ||||
| 67308 | } | ||||
| 67309 | |||||
| 67310 | /* If the database page size is not a power of two, or is greater than | ||||
| 67311 | ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid | ||||
| 67312 | ** data. Similarly, if the 'magic' value is invalid, ignore the whole | ||||
| 67313 | ** WAL file. | ||||
| 67314 | */ | ||||
| 67315 | magic = sqlite3Get4byte(&aBuf[0]); | ||||
| 67316 | szPage = sqlite3Get4byte(&aBuf[8]); | ||||
| 67317 | if( (magic&0xFFFFFFFE)!=WAL_MAGIC0x377f0682 | ||||
| 67318 | || szPage&(szPage-1) | ||||
| 67319 | || szPage>SQLITE_MAX_PAGE_SIZE65536 | ||||
| 67320 | || szPage<512 | ||||
| 67321 | ){ | ||||
| 67322 | goto finished; | ||||
| 67323 | } | ||||
| 67324 | pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); | ||||
| 67325 | pWal->szPage = szPage; | ||||
| 67326 | pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); | ||||
| 67327 | memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); | ||||
| 67328 | |||||
| 67329 | /* Verify that the WAL header checksum is correct */ | ||||
| 67330 | walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN0, | ||||
| 67331 | aBuf, WAL_HDRSIZE32-2*4, 0, pWal->hdr.aFrameCksum | ||||
| 67332 | ); | ||||
| 67333 | if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24]) | ||||
| 67334 | || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28]) | ||||
| 67335 | ){ | ||||
| 67336 | goto finished; | ||||
| 67337 | } | ||||
| 67338 | |||||
| 67339 | /* Verify that the version number on the WAL format is one that | ||||
| 67340 | ** are able to understand */ | ||||
| 67341 | version = sqlite3Get4byte(&aBuf[4]); | ||||
| 67342 | if( version!=WAL_MAX_VERSION3007000 ){ | ||||
| 67343 | rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(67343); | ||||
| 67344 | goto finished; | ||||
| 67345 | } | ||||
| 67346 | |||||
| 67347 | /* Malloc a buffer to read frames into. */ | ||||
| 67348 | szFrame = szPage + WAL_FRAME_HDRSIZE24; | ||||
| 67349 | aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ( sizeof(ht_slot)*(4096*2) + 4096*sizeof(u32) )); | ||||
| 67350 | SEH_FREE_ON_ERROR(0, aFrame); | ||||
| 67351 | if( !aFrame ){ | ||||
| 67352 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 67353 | goto recovery_error; | ||||
| 67354 | } | ||||
| 67355 | aData = &aFrame[WAL_FRAME_HDRSIZE24]; | ||||
| 67356 | aPrivate = (u32*)&aData[szPage]; | ||||
| 67357 | |||||
| 67358 | /* Read all frames from the log file. */ | ||||
| 67359 | iLastFrame = (nSize - WAL_HDRSIZE32) / szFrame; | ||||
| 67360 | for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){ | ||||
| 67361 | u32 *aShare; | ||||
| 67362 | u32 iFrame; /* Index of last frame read */ | ||||
| 67363 | u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE)((iLastFrame)<((4096 - ((sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo ))/sizeof(u32)))+iPg*4096)?(iLastFrame):((4096 - ((sizeof(WalIndexHdr )*2+sizeof(WalCkptInfo))/sizeof(u32)))+iPg*4096)); | ||||
| 67364 | u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE(4096 - ((sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))/sizeof(u32 )))+(iPg-1)*HASHTABLE_NPAGE4096); | ||||
| 67365 | u32 nHdr, nHdr32; | ||||
| 67366 | rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare); | ||||
| 67367 | assert( aShare!=0 || rc!=SQLITE_OK )((void) (0)); | ||||
| 67368 | if( aShare==0 ) break; | ||||
| 67369 | SEH_SET_ON_ERROR(iPg, aShare); | ||||
| 67370 | pWal->apWiData[iPg] = aPrivate; | ||||
| 67371 | |||||
| 67372 | for(iFrame=iFirst; iFrame<=iLast; iFrame++){ | ||||
| 67373 | i64 iOffset = walFrameOffset(iFrame, szPage)( 32 + ((iFrame)-1)*(i64)((szPage)+24) ); | ||||
| 67374 | u32 pgno; /* Database page number for frame */ | ||||
| 67375 | u32 nTruncate; /* dbsize field from frame header */ | ||||
| 67376 | |||||
| 67377 | /* Read and decode the next log frame. */ | ||||
| 67378 | rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); | ||||
| 67379 | if( rc!=SQLITE_OK0 ) break; | ||||
| 67380 | isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame); | ||||
| 67381 | if( !isValid ) break; | ||||
| 67382 | rc = walIndexAppend(pWal, iFrame, pgno); | ||||
| 67383 | if( NEVER(rc!=SQLITE_OK)(rc!=0) ) break; | ||||
| 67384 | |||||
| 67385 | /* If nTruncate is non-zero, this is a commit record. */ | ||||
| 67386 | if( nTruncate ){ | ||||
| 67387 | pWal->hdr.mxFrame = iFrame; | ||||
| 67388 | pWal->hdr.nPage = nTruncate; | ||||
| 67389 | pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); | ||||
| 67390 | testcase( szPage<=32768 ); | ||||
| 67391 | testcase( szPage>=65536 ); | ||||
| 67392 | aFrameCksum[0] = pWal->hdr.aFrameCksum[0]; | ||||
| 67393 | aFrameCksum[1] = pWal->hdr.aFrameCksum[1]; | ||||
| 67394 | } | ||||
| 67395 | } | ||||
| 67396 | pWal->apWiData[iPg] = aShare; | ||||
| 67397 | SEH_SET_ON_ERROR(0,0); | ||||
| 67398 | nHdr = (iPg==0 ? WALINDEX_HDR_SIZE(sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo)) : 0); | ||||
| 67399 | nHdr32 = nHdr / sizeof(u32); | ||||
| 67400 | #ifndef SQLITE_SAFER_WALINDEX_RECOVERY | ||||
| 67401 | /* Memcpy() should work fine here, on all reasonable implementations. | ||||
| 67402 | ** Technically, memcpy() might change the destination to some | ||||
| 67403 | ** intermediate value before setting to the final value, and that might | ||||
| 67404 | ** cause a concurrent reader to malfunction. Memcpy() is allowed to | ||||
| 67405 | ** do that, according to the spec, but no memcpy() implementation that | ||||
| 67406 | ** we know of actually does that, which is why we say that memcpy() | ||||
| 67407 | ** is safe for this. Memcpy() is certainly a lot faster. | ||||
| 67408 | */ | ||||
| 67409 | memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ( sizeof(ht_slot)*(4096*2) + 4096*sizeof(u32) )-nHdr); | ||||
| 67410 | #else | ||||
| 67411 | /* In the event that some platform is found for which memcpy() | ||||
| 67412 | ** changes the destination to some intermediate value before | ||||
| 67413 | ** setting the final value, this alternative copy routine is | ||||
| 67414 | ** provided. | ||||
| 67415 | */ | ||||
| 67416 | { | ||||
| 67417 | int i; | ||||
| 67418 | for(i=nHdr32; i<WALINDEX_PGSZ( sizeof(ht_slot)*(4096*2) + 4096*sizeof(u32) )/sizeof(u32); i++){ | ||||
| 67419 | if( aShare[i]!=aPrivate[i] ){ | ||||
| 67420 | /* Atomic memory operations are not required here because if | ||||
| 67421 | ** the value needs to be changed, that means it is not being | ||||
| 67422 | ** accessed concurrently. */ | ||||
| 67423 | aShare[i] = aPrivate[i]; | ||||
| 67424 | } | ||||
| 67425 | } | ||||
| 67426 | } | ||||
| 67427 | #endif | ||||
| 67428 | SEH_INJECT_FAULT((void) (0));; | ||||
| 67429 | if( iFrame<=iLast ) break; | ||||
| 67430 | } | ||||
| 67431 | |||||
| 67432 | SEH_FREE_ON_ERROR(aFrame, 0); | ||||
| 67433 | sqlite3_free(aFrame); | ||||
| 67434 | } | ||||
| 67435 | |||||
| 67436 | finished: | ||||
| 67437 | if( rc==SQLITE_OK0 ){ | ||||
| 67438 | volatile WalCkptInfo *pInfo; | ||||
| 67439 | int i; | ||||
| 67440 | pWal->hdr.aFrameCksum[0] = aFrameCksum[0]; | ||||
| 67441 | pWal->hdr.aFrameCksum[1] = aFrameCksum[1]; | ||||
| 67442 | walIndexWriteHdr(pWal); | ||||
| 67443 | |||||
| 67444 | /* Reset the checkpoint-header. This is safe because this thread is | ||||
| 67445 | ** currently holding locks that exclude all other writers and | ||||
| 67446 | ** checkpointers. Then set the values of read-mark slots 1 through N. | ||||
| 67447 | */ | ||||
| 67448 | pInfo = walCkptInfo(pWal); | ||||
| 67449 | pInfo->nBackfill = 0; | ||||
| 67450 | pInfo->nBackfillAttempted = pWal->hdr.mxFrame; | ||||
| 67451 | pInfo->aReadMark[0] = 0; | ||||
| 67452 | for(i=1; i<WAL_NREADER(8 -3); i++){ | ||||
| 67453 | rc = walLockExclusive(pWal, WAL_READ_LOCK(i)(3+(i)), 1); | ||||
| 67454 | if( rc==SQLITE_OK0 ){ | ||||
| 67455 | if( i==1 && pWal->hdr.mxFrame ){ | ||||
| 67456 | pInfo->aReadMark[i] = pWal->hdr.mxFrame; | ||||
| 67457 | }else{ | ||||
| 67458 | pInfo->aReadMark[i] = READMARK_NOT_USED0xffffffff; | ||||
| 67459 | } | ||||
| 67460 | SEH_INJECT_FAULT((void) (0));; | ||||
| 67461 | walUnlockExclusive(pWal, WAL_READ_LOCK(i)(3+(i)), 1); | ||||
| 67462 | }else if( rc!=SQLITE_BUSY5 ){ | ||||
| 67463 | goto recovery_error; | ||||
| 67464 | } | ||||
| 67465 | } | ||||
| 67466 | |||||
| 67467 | /* If more than one frame was recovered from the log file, report an | ||||
| 67468 | ** event via sqlite3_log(). This is to help with identifying performance | ||||
| 67469 | ** problems caused by applications routinely shutting down without | ||||
| 67470 | ** checkpointing the log file. | ||||
| 67471 | */ | ||||
| 67472 | if( pWal->hdr.nPage ){ | ||||
| 67473 | sqlite3_log(SQLITE_NOTICE_RECOVER_WAL(27 | (1<<8)), | ||||
| 67474 | "recovered %d frames from WAL file %s", | ||||
| 67475 | pWal->hdr.mxFrame, pWal->zWalName | ||||
| 67476 | ); | ||||
| 67477 | } | ||||
| 67478 | } | ||||
| 67479 | |||||
| 67480 | recovery_error: | ||||
| 67481 | WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok")); | ||||
| 67482 | walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)(3+(0))-iLock); | ||||
| 67483 | return rc; | ||||
| 67484 | } | ||||
| 67485 | |||||
| 67486 | /* | ||||
| 67487 | ** Close an open wal-index. | ||||
| 67488 | */ | ||||
| 67489 | static void walIndexClose(Wal *pWal, int isDelete){ | ||||
| 67490 | if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE2 || pWal->bShmUnreliable ){ | ||||
| 67491 | int i; | ||||
| 67492 | for(i=0; i<pWal->nWiData; i++){ | ||||
| 67493 | sqlite3_free((void *)pWal->apWiData[i]); | ||||
| 67494 | pWal->apWiData[i] = 0; | ||||
| 67495 | } | ||||
| 67496 | } | ||||
| 67497 | if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE2 ){ | ||||
| 67498 | sqlite3OsShmUnmap(pWal->pDbFd, isDelete); | ||||
| 67499 | } | ||||
| 67500 | } | ||||
| 67501 | |||||
| 67502 | /* | ||||
| 67503 | ** Open a connection to the WAL file zWalName. The database file must | ||||
| 67504 | ** already be opened on connection pDbFd. The buffer that zWalName points | ||||
| 67505 | ** to must remain valid for the lifetime of the returned Wal* handle. | ||||
| 67506 | ** | ||||
| 67507 | ** A SHARED lock should be held on the database file when this function | ||||
| 67508 | ** is called. The purpose of this SHARED lock is to prevent any other | ||||
| 67509 | ** client from unlinking the WAL or wal-index file. If another process | ||||
| 67510 | ** were to do this just after this client opened one of these files, the | ||||
| 67511 | ** system would be badly broken. | ||||
| 67512 | ** | ||||
| 67513 | ** If the log file is successfully opened, SQLITE_OK is returned and | ||||
| 67514 | ** *ppWal is set to point to a new WAL handle. If an error occurs, | ||||
| 67515 | ** an SQLite error code is returned and *ppWal is left unmodified. | ||||
| 67516 | */ | ||||
| 67517 | SQLITE_PRIVATEstatic int sqlite3WalOpen( | ||||
| 67518 | sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ | ||||
| 67519 | sqlite3_file *pDbFd, /* The open database file */ | ||||
| 67520 | const char *zWalName, /* Name of the WAL file */ | ||||
| 67521 | int bNoShm, /* True to run in heap-memory mode */ | ||||
| 67522 | i64 mxWalSize, /* Truncate WAL to this size on reset */ | ||||
| 67523 | Wal **ppWal /* OUT: Allocated Wal handle */ | ||||
| 67524 | ){ | ||||
| 67525 | int rc; /* Return Code */ | ||||
| 67526 | Wal *pRet; /* Object to allocate and return */ | ||||
| 67527 | int flags; /* Flags passed to OsOpen() */ | ||||
| 67528 | |||||
| 67529 | assert( zWalName && zWalName[0] )((void) (0)); | ||||
| 67530 | assert( pDbFd )((void) (0)); | ||||
| 67531 | |||||
| 67532 | /* Verify the values of various constants. Any changes to the values | ||||
| 67533 | ** of these constants would result in an incompatible on-disk format | ||||
| 67534 | ** for the -shm file. Any change that causes one of these asserts to | ||||
| 67535 | ** fail is a backward compatibility problem, even if the change otherwise | ||||
| 67536 | ** works. | ||||
| 67537 | ** | ||||
| 67538 | ** This table also serves as a helpful cross-reference when trying to | ||||
| 67539 | ** interpret hex dumps of the -shm file. | ||||
| 67540 | */ | ||||
| 67541 | assert( 48 == sizeof(WalIndexHdr) )((void) (0)); | ||||
| 67542 | assert( 40 == sizeof(WalCkptInfo) )((void) (0)); | ||||
| 67543 | assert( 120 == WALINDEX_LOCK_OFFSET )((void) (0)); | ||||
| 67544 | assert( 136 == WALINDEX_HDR_SIZE )((void) (0)); | ||||
| 67545 | assert( 4096 == HASHTABLE_NPAGE )((void) (0)); | ||||
| 67546 | assert( 4062 == HASHTABLE_NPAGE_ONE )((void) (0)); | ||||
| 67547 | assert( 8192 == HASHTABLE_NSLOT )((void) (0)); | ||||
| 67548 | assert( 383 == HASHTABLE_HASH_1 )((void) (0)); | ||||
| 67549 | assert( 32768 == WALINDEX_PGSZ )((void) (0)); | ||||
| 67550 | assert( 8 == SQLITE_SHM_NLOCK )((void) (0)); | ||||
| 67551 | assert( 5 == WAL_NREADER )((void) (0)); | ||||
| 67552 | assert( 24 == WAL_FRAME_HDRSIZE )((void) (0)); | ||||
| 67553 | assert( 32 == WAL_HDRSIZE )((void) (0)); | ||||
| 67554 | assert( 120 == WALINDEX_LOCK_OFFSET + WAL_WRITE_LOCK )((void) (0)); | ||||
| 67555 | assert( 121 == WALINDEX_LOCK_OFFSET + WAL_CKPT_LOCK )((void) (0)); | ||||
| 67556 | assert( 122 == WALINDEX_LOCK_OFFSET + WAL_RECOVER_LOCK )((void) (0)); | ||||
| 67557 | assert( 123 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(0) )((void) (0)); | ||||
| 67558 | assert( 124 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(1) )((void) (0)); | ||||
| 67559 | assert( 125 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(2) )((void) (0)); | ||||
| 67560 | assert( 126 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(3) )((void) (0)); | ||||
| 67561 | assert( 127 == WALINDEX_LOCK_OFFSET + WAL_READ_LOCK(4) )((void) (0)); | ||||
| 67562 | |||||
| 67563 | /* In the amalgamation, the os_unix.c and os_win.c source files come before | ||||
| 67564 | ** this source file. Verify that the #defines of the locking byte offsets | ||||
| 67565 | ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value. | ||||
| 67566 | ** For that matter, if the lock offset ever changes from its initial design | ||||
| 67567 | ** value of 120, we need to know that so there is an assert() to check it. | ||||
| 67568 | */ | ||||
| 67569 | #ifdef WIN_SHM_BASE | ||||
| 67570 | assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET )((void) (0)); | ||||
| 67571 | #endif | ||||
| 67572 | #ifdef UNIX_SHM_BASE((22+8)*4) | ||||
| 67573 | assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET )((void) (0)); | ||||
| 67574 | #endif | ||||
| 67575 | |||||
| 67576 | |||||
| 67577 | /* Allocate an instance of struct Wal to return. */ | ||||
| 67578 | *ppWal = 0; | ||||
| 67579 | pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); | ||||
| 67580 | if( !pRet ){ | ||||
| 67581 | return SQLITE_NOMEM_BKPT7; | ||||
| 67582 | } | ||||
| 67583 | |||||
| 67584 | pRet->pVfs = pVfs; | ||||
| 67585 | pRet->pWalFd = (sqlite3_file *)&pRet[1]; | ||||
| 67586 | pRet->pDbFd = pDbFd; | ||||
| 67587 | pRet->readLock = -1; | ||||
| 67588 | pRet->mxWalSize = mxWalSize; | ||||
| 67589 | pRet->zWalName = zWalName; | ||||
| 67590 | pRet->syncHeader = 1; | ||||
| 67591 | pRet->padToSectorBoundary = 1; | ||||
| 67592 | pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE2: WAL_NORMAL_MODE0); | ||||
| 67593 | |||||
| 67594 | /* Open file handle on the write-ahead log file. */ | ||||
| 67595 | flags = (SQLITE_OPEN_READWRITE0x00000002|SQLITE_OPEN_CREATE0x00000004|SQLITE_OPEN_WAL0x00080000); | ||||
| 67596 | rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); | ||||
| 67597 | if( rc==SQLITE_OK0 && flags&SQLITE_OPEN_READONLY0x00000001 ){ | ||||
| 67598 | pRet->readOnly = WAL_RDONLY1; | ||||
| 67599 | } | ||||
| 67600 | |||||
| 67601 | if( rc!=SQLITE_OK0 ){ | ||||
| 67602 | walIndexClose(pRet, 0); | ||||
| 67603 | sqlite3OsClose(pRet->pWalFd); | ||||
| 67604 | sqlite3_free(pRet); | ||||
| 67605 | }else{ | ||||
| 67606 | int iDC = sqlite3OsDeviceCharacteristics(pDbFd); | ||||
| 67607 | if( iDC & SQLITE_IOCAP_SEQUENTIAL0x00000400 ){ pRet->syncHeader = 0; } | ||||
| 67608 | if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE0x00001000 ){ | ||||
| 67609 | pRet->padToSectorBoundary = 0; | ||||
| 67610 | } | ||||
| 67611 | *ppWal = pRet; | ||||
| 67612 | WALTRACE(("WAL%d: opened\n", pRet)); | ||||
| 67613 | } | ||||
| 67614 | return rc; | ||||
| 67615 | } | ||||
| 67616 | |||||
| 67617 | /* | ||||
| 67618 | ** Change the size to which the WAL file is truncated on each reset. | ||||
| 67619 | */ | ||||
| 67620 | SQLITE_PRIVATEstatic void sqlite3WalLimit(Wal *pWal, i64 iLimit){ | ||||
| 67621 | if( pWal ) pWal->mxWalSize = iLimit; | ||||
| 67622 | } | ||||
| 67623 | |||||
| 67624 | /* | ||||
| 67625 | ** Find the smallest page number out of all pages held in the WAL that | ||||
| 67626 | ** has not been returned by any prior invocation of this method on the | ||||
| 67627 | ** same WalIterator object. Write into *piFrame the frame index where | ||||
| 67628 | ** that page was last written into the WAL. Write into *piPage the page | ||||
| 67629 | ** number. | ||||
| 67630 | ** | ||||
| 67631 | ** Return 0 on success. If there are no pages in the WAL with a page | ||||
| 67632 | ** number larger than *piPage, then return 1. | ||||
| 67633 | */ | ||||
| 67634 | static int walIteratorNext( | ||||
| 67635 | WalIterator *p, /* Iterator */ | ||||
| 67636 | u32 *piPage, /* OUT: The page number of the next page */ | ||||
| 67637 | u32 *piFrame /* OUT: Wal frame index of next page */ | ||||
| 67638 | ){ | ||||
| 67639 | u32 iMin; /* Result pgno must be greater than iMin */ | ||||
| 67640 | u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */ | ||||
| 67641 | int i; /* For looping through segments */ | ||||
| 67642 | |||||
| 67643 | iMin = p->iPrior; | ||||
| 67644 | assert( iMin<0xffffffff )((void) (0)); | ||||
| 67645 | for(i=p->nSegment-1; i>=0; i--){ | ||||
| 67646 | struct WalSegment *pSegment = &p->aSegment[i]; | ||||
| 67647 | while( pSegment->iNext<pSegment->nEntry ){ | ||||
| 67648 | u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; | ||||
| 67649 | if( iPg>iMin ){ | ||||
| 67650 | if( iPg<iRet ){ | ||||
| 67651 | iRet = iPg; | ||||
| 67652 | *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext]; | ||||
| 67653 | } | ||||
| 67654 | break; | ||||
| 67655 | } | ||||
| 67656 | pSegment->iNext++; | ||||
| 67657 | } | ||||
| 67658 | } | ||||
| 67659 | |||||
| 67660 | *piPage = p->iPrior = iRet; | ||||
| 67661 | return (iRet==0xFFFFFFFF); | ||||
| 67662 | } | ||||
| 67663 | |||||
| 67664 | /* | ||||
| 67665 | ** This function merges two sorted lists into a single sorted list. | ||||
| 67666 | ** | ||||
| 67667 | ** aLeft[] and aRight[] are arrays of indices. The sort key is | ||||
| 67668 | ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following | ||||
| 67669 | ** is guaranteed for all J<K: | ||||
| 67670 | ** | ||||
| 67671 | ** aContent[aLeft[J]] < aContent[aLeft[K]] | ||||
| 67672 | ** aContent[aRight[J]] < aContent[aRight[K]] | ||||
| 67673 | ** | ||||
| 67674 | ** This routine overwrites aRight[] with a new (probably longer) sequence | ||||
| 67675 | ** of indices such that the aRight[] contains every index that appears in | ||||
| 67676 | ** either aLeft[] or the old aRight[] and such that the second condition | ||||
| 67677 | ** above is still met. | ||||
| 67678 | ** | ||||
| 67679 | ** The aContent[aLeft[X]] values will be unique for all X. And the | ||||
| 67680 | ** aContent[aRight[X]] values will be unique too. But there might be | ||||
| 67681 | ** one or more combinations of X and Y such that | ||||
| 67682 | ** | ||||
| 67683 | ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]] | ||||
| 67684 | ** | ||||
| 67685 | ** When that happens, omit the aLeft[X] and use the aRight[Y] index. | ||||
| 67686 | */ | ||||
| 67687 | static void walMerge( | ||||
| 67688 | const u32 *aContent, /* Pages in wal - keys for the sort */ | ||||
| 67689 | ht_slot *aLeft, /* IN: Left hand input list */ | ||||
| 67690 | int nLeft, /* IN: Elements in array *paLeft */ | ||||
| 67691 | ht_slot **paRight, /* IN/OUT: Right hand input list */ | ||||
| 67692 | int *pnRight, /* IN/OUT: Elements in *paRight */ | ||||
| 67693 | ht_slot *aTmp /* Temporary buffer */ | ||||
| 67694 | ){ | ||||
| 67695 | int iLeft = 0; /* Current index in aLeft */ | ||||
| 67696 | int iRight = 0; /* Current index in aRight */ | ||||
| 67697 | int iOut = 0; /* Current index in output buffer */ | ||||
| 67698 | int nRight = *pnRight; | ||||
| 67699 | ht_slot *aRight = *paRight; | ||||
| 67700 | |||||
| 67701 | assert( nLeft>0 && nRight>0 )((void) (0)); | ||||
| 67702 | while( iRight<nRight || iLeft<nLeft ){ | ||||
| 67703 | ht_slot logpage; | ||||
| 67704 | Pgno dbpage; | ||||
| 67705 | |||||
| 67706 | if( (iLeft<nLeft) | ||||
| 67707 | && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]]) | ||||
| 67708 | ){ | ||||
| 67709 | logpage = aLeft[iLeft++]; | ||||
| 67710 | }else{ | ||||
| 67711 | logpage = aRight[iRight++]; | ||||
| 67712 | } | ||||
| 67713 | dbpage = aContent[logpage]; | ||||
| 67714 | |||||
| 67715 | aTmp[iOut++] = logpage; | ||||
| 67716 | if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++; | ||||
| 67717 | |||||
| 67718 | assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage )((void) (0)); | ||||
| 67719 | assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage )((void) (0)); | ||||
| 67720 | } | ||||
| 67721 | |||||
| 67722 | *paRight = aLeft; | ||||
| 67723 | *pnRight = iOut; | ||||
| 67724 | memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut); | ||||
| 67725 | } | ||||
| 67726 | |||||
| 67727 | /* | ||||
| 67728 | ** Sort the elements in list aList using aContent[] as the sort key. | ||||
| 67729 | ** Remove elements with duplicate keys, preferring to keep the | ||||
| 67730 | ** larger aList[] values. | ||||
| 67731 | ** | ||||
| 67732 | ** The aList[] entries are indices into aContent[]. The values in | ||||
| 67733 | ** aList[] are to be sorted so that for all J<K: | ||||
| 67734 | ** | ||||
| 67735 | ** aContent[aList[J]] < aContent[aList[K]] | ||||
| 67736 | ** | ||||
| 67737 | ** For any X and Y such that | ||||
| 67738 | ** | ||||
| 67739 | ** aContent[aList[X]] == aContent[aList[Y]] | ||||
| 67740 | ** | ||||
| 67741 | ** Keep the larger of the two values aList[X] and aList[Y] and discard | ||||
| 67742 | ** the smaller. | ||||
| 67743 | */ | ||||
| 67744 | static void walMergesort( | ||||
| 67745 | const u32 *aContent, /* Pages in wal */ | ||||
| 67746 | ht_slot *aBuffer, /* Buffer of at least *pnList items to use */ | ||||
| 67747 | ht_slot *aList, /* IN/OUT: List to sort */ | ||||
| 67748 | int *pnList /* IN/OUT: Number of elements in aList[] */ | ||||
| 67749 | ){ | ||||
| 67750 | struct Sublist { | ||||
| 67751 | int nList; /* Number of elements in aList */ | ||||
| 67752 | ht_slot *aList; /* Pointer to sub-list content */ | ||||
| 67753 | }; | ||||
| 67754 | |||||
| 67755 | const int nList = *pnList; /* Size of input list */ | ||||
| 67756 | int nMerge = 0; /* Number of elements in list aMerge */ | ||||
| 67757 | ht_slot *aMerge = 0; /* List to be merged */ | ||||
| 67758 | int iList; /* Index into input list */ | ||||
| 67759 | u32 iSub = 0; /* Index into aSub array */ | ||||
| 67760 | struct Sublist aSub[13]; /* Array of sub-lists */ | ||||
| 67761 | |||||
| 67762 | memset(aSub, 0, sizeof(aSub)); | ||||
| 67763 | assert( nList<=HASHTABLE_NPAGE && nList>0 )((void) (0)); | ||||
| 67764 | assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) )((void) (0)); | ||||
| 67765 | |||||
| 67766 | for(iList=0; iList<nList; iList++){ | ||||
| 67767 | nMerge = 1; | ||||
| 67768 | aMerge = &aList[iList]; | ||||
| 67769 | for(iSub=0; iList & (1<<iSub); iSub++){ | ||||
| 67770 | struct Sublist *p; | ||||
| 67771 | assert( iSub<ArraySize(aSub) )((void) (0)); | ||||
| 67772 | p = &aSub[iSub]; | ||||
| 67773 | assert( p->aList && p->nList<=(1<<iSub) )((void) (0)); | ||||
| 67774 | assert( p->aList==&aList[iList&~((2<<iSub)-1)] )((void) (0)); | ||||
| 67775 | walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer); | ||||
| 67776 | } | ||||
| 67777 | aSub[iSub].aList = aMerge; | ||||
| 67778 | aSub[iSub].nList = nMerge; | ||||
| 67779 | } | ||||
| 67780 | |||||
| 67781 | for(iSub++; iSub<ArraySize(aSub)((int)(sizeof(aSub)/sizeof(aSub[0]))); iSub++){ | ||||
| 67782 | if( nList & (1<<iSub) ){ | ||||
| 67783 | struct Sublist *p; | ||||
| 67784 | assert( iSub<ArraySize(aSub) )((void) (0)); | ||||
| 67785 | p = &aSub[iSub]; | ||||
| 67786 | assert( p->nList<=(1<<iSub) )((void) (0)); | ||||
| 67787 | assert( p->aList==&aList[nList&~((2<<iSub)-1)] )((void) (0)); | ||||
| 67788 | walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer); | ||||
| 67789 | } | ||||
| 67790 | } | ||||
| 67791 | assert( aMerge==aList )((void) (0)); | ||||
| 67792 | *pnList = nMerge; | ||||
| 67793 | |||||
| 67794 | #ifdef SQLITE_DEBUG | ||||
| 67795 | { | ||||
| 67796 | int i; | ||||
| 67797 | for(i=1; i<*pnList; i++){ | ||||
| 67798 | assert( aContent[aList[i]] > aContent[aList[i-1]] )((void) (0)); | ||||
| 67799 | } | ||||
| 67800 | } | ||||
| 67801 | #endif | ||||
| 67802 | } | ||||
| 67803 | |||||
| 67804 | /* | ||||
| 67805 | ** Free an iterator allocated by walIteratorInit(). | ||||
| 67806 | */ | ||||
| 67807 | static void walIteratorFree(WalIterator *p){ | ||||
| 67808 | sqlite3_free(p); | ||||
| 67809 | } | ||||
| 67810 | |||||
| 67811 | /* | ||||
| 67812 | ** Construct a WalInterator object that can be used to loop over all | ||||
| 67813 | ** pages in the WAL following frame nBackfill in ascending order. Frames | ||||
| 67814 | ** nBackfill or earlier may be included - excluding them is an optimization | ||||
| 67815 | ** only. The caller must hold the checkpoint lock. | ||||
| 67816 | ** | ||||
| 67817 | ** On success, make *pp point to the newly allocated WalInterator object | ||||
| 67818 | ** return SQLITE_OK. Otherwise, return an error code. If this routine | ||||
| 67819 | ** returns an error, the value of *pp is undefined. | ||||
| 67820 | ** | ||||
| 67821 | ** The calling routine should invoke walIteratorFree() to destroy the | ||||
| 67822 | ** WalIterator object when it has finished with it. | ||||
| 67823 | */ | ||||
| 67824 | static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){ | ||||
| 67825 | WalIterator *p; /* Return value */ | ||||
| 67826 | int nSegment; /* Number of segments to merge */ | ||||
| 67827 | u32 iLast; /* Last frame in log */ | ||||
| 67828 | sqlite3_int64 nByte; /* Number of bytes to allocate */ | ||||
| 67829 | int i; /* Iterator variable */ | ||||
| 67830 | ht_slot *aTmp; /* Temp space used by merge-sort */ | ||||
| 67831 | int rc = SQLITE_OK0; /* Return Code */ | ||||
| 67832 | |||||
| 67833 | /* This routine only runs while holding the checkpoint lock. And | ||||
| 67834 | ** it only runs if there is actually content in the log (mxFrame>0). | ||||
| 67835 | */ | ||||
| 67836 | assert( pWal->ckptLock && pWal->hdr.mxFrame>0 )((void) (0)); | ||||
| 67837 | iLast = pWal->hdr.mxFrame; | ||||
| 67838 | |||||
| 67839 | /* Allocate space for the WalIterator object. */ | ||||
| 67840 | nSegment = walFramePage(iLast) + 1; | ||||
| 67841 | nByte = SZ_WALITERATOR(nSegment)(__builtin_offsetof(WalIterator, aSegment)*(nSegment)*sizeof( struct WalSegment)) | ||||
| 67842 | + iLast*sizeof(ht_slot); | ||||
| 67843 | p = (WalIterator *)sqlite3_malloc64(nByte | ||||
| 67844 | + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE4096?HASHTABLE_NPAGE4096:iLast) | ||||
| 67845 | ); | ||||
| 67846 | if( !p ){ | ||||
| 67847 | return SQLITE_NOMEM_BKPT7; | ||||
| 67848 | } | ||||
| 67849 | memset(p, 0, nByte); | ||||
| 67850 | p->nSegment = nSegment; | ||||
| 67851 | aTmp = (ht_slot*)&(((u8*)p)[nByte]); | ||||
| 67852 | SEH_FREE_ON_ERROR(0, p); | ||||
| 67853 | for(i=walFramePage(nBackfill+1); rc==SQLITE_OK0 && i<nSegment; i++){ | ||||
| 67854 | WalHashLoc sLoc; | ||||
| 67855 | |||||
| 67856 | rc = walHashGet(pWal, i, &sLoc); | ||||
| 67857 | if( rc==SQLITE_OK0 ){ | ||||
| 67858 | int j; /* Counter variable */ | ||||
| 67859 | int nEntry; /* Number of entries in this segment */ | ||||
| 67860 | ht_slot *aIndex; /* Sorted index for this segment */ | ||||
| 67861 | |||||
| 67862 | if( (i+1)==nSegment ){ | ||||
| 67863 | nEntry = (int)(iLast - sLoc.iZero); | ||||
| 67864 | }else{ | ||||
| 67865 | nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno); | ||||
| 67866 | } | ||||
| 67867 | aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero]; | ||||
| 67868 | sLoc.iZero++; | ||||
| 67869 | |||||
| 67870 | for(j=0; j<nEntry; j++){ | ||||
| 67871 | aIndex[j] = (ht_slot)j; | ||||
| 67872 | } | ||||
| 67873 | walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry); | ||||
| 67874 | p->aSegment[i].iZero = sLoc.iZero; | ||||
| 67875 | p->aSegment[i].nEntry = nEntry; | ||||
| 67876 | p->aSegment[i].aIndex = aIndex; | ||||
| 67877 | p->aSegment[i].aPgno = (u32 *)sLoc.aPgno; | ||||
| 67878 | } | ||||
| 67879 | } | ||||
| 67880 | if( rc!=SQLITE_OK0 ){ | ||||
| 67881 | SEH_FREE_ON_ERROR(p, 0); | ||||
| 67882 | walIteratorFree(p); | ||||
| 67883 | p = 0; | ||||
| 67884 | } | ||||
| 67885 | *pp = p; | ||||
| 67886 | return rc; | ||||
| 67887 | } | ||||
| 67888 | |||||
| 67889 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 67890 | |||||
| 67891 | |||||
| 67892 | /* | ||||
| 67893 | ** Attempt to enable blocking locks that block for nMs ms. Return 1 if | ||||
| 67894 | ** blocking locks are successfully enabled, or 0 otherwise. | ||||
| 67895 | */ | ||||
| 67896 | static int walEnableBlockingMs(Wal *pWal, int nMs)0{ | ||||
| 67897 | int rc = sqlite3OsFileControl( | ||||
| 67898 | pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT34, (void*)&nMs | ||||
| 67899 | ); | ||||
| 67900 | return (rc==SQLITE_OK0); | ||||
| 67901 | } | ||||
| 67902 | |||||
| 67903 | /* | ||||
| 67904 | ** Attempt to enable blocking locks. Blocking locks are enabled only if (a) | ||||
| 67905 | ** they are supported by the VFS, and (b) the database handle is configured | ||||
| 67906 | ** with a busy-timeout. Return 1 if blocking locks are successfully enabled, | ||||
| 67907 | ** or 0 otherwise. | ||||
| 67908 | */ | ||||
| 67909 | static int walEnableBlocking(Wal *pWal)0{ | ||||
| 67910 | int res = 0; | ||||
| 67911 | if( pWal->db ){ | ||||
| 67912 | int tmout = pWal->db->setlkTimeout; | ||||
| 67913 | if( tmout ){ | ||||
| 67914 | res = walEnableBlockingMs(pWal, tmout)0; | ||||
| 67915 | } | ||||
| 67916 | } | ||||
| 67917 | return res; | ||||
| 67918 | } | ||||
| 67919 | |||||
| 67920 | /* | ||||
| 67921 | ** Disable blocking locks. | ||||
| 67922 | */ | ||||
| 67923 | static void walDisableBlocking(Wal *pWal){ | ||||
| 67924 | int tmout = 0; | ||||
| 67925 | sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT34, (void*)&tmout); | ||||
| 67926 | } | ||||
| 67927 | |||||
| 67928 | /* | ||||
| 67929 | ** If parameter bLock is true, attempt to enable blocking locks, take | ||||
| 67930 | ** the WRITER lock, and then disable blocking locks. If blocking locks | ||||
| 67931 | ** cannot be enabled, no attempt to obtain the WRITER lock is made. Return | ||||
| 67932 | ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not | ||||
| 67933 | ** an error if blocking locks can not be enabled. | ||||
| 67934 | ** | ||||
| 67935 | ** If the bLock parameter is false and the WRITER lock is held, release it. | ||||
| 67936 | */ | ||||
| 67937 | SQLITE_PRIVATEstatic int sqlite3WalWriteLock(Wal *pWal, int bLock){ | ||||
| 67938 | int rc = SQLITE_OK0; | ||||
| 67939 | assert( pWal->readLock<0 || bLock==0 )((void) (0)); | ||||
| 67940 | if( bLock ){ | ||||
| 67941 | assert( pWal->db )((void) (0)); | ||||
| 67942 | if( walEnableBlocking(pWal)0 ){ | ||||
| 67943 | rc = walLockExclusive(pWal, WAL_WRITE_LOCK0, 1); | ||||
| 67944 | if( rc==SQLITE_OK0 ){ | ||||
| 67945 | pWal->writeLock = 1; | ||||
| 67946 | } | ||||
| 67947 | walDisableBlocking(pWal); | ||||
| 67948 | } | ||||
| 67949 | }else if( pWal->writeLock ){ | ||||
| 67950 | walUnlockExclusive(pWal, WAL_WRITE_LOCK0, 1); | ||||
| 67951 | pWal->writeLock = 0; | ||||
| 67952 | } | ||||
| 67953 | return rc; | ||||
| 67954 | } | ||||
| 67955 | |||||
| 67956 | /* | ||||
| 67957 | ** Set the database handle used to determine if blocking locks are required. | ||||
| 67958 | */ | ||||
| 67959 | SQLITE_PRIVATEstatic void sqlite3WalDb(Wal *pWal, sqlite3 *db){ | ||||
| 67960 | pWal->db = db; | ||||
| 67961 | } | ||||
| 67962 | |||||
| 67963 | #else | ||||
| 67964 | # define walEnableBlocking(x)0 0 | ||||
| 67965 | # define walDisableBlocking(x) | ||||
| 67966 | # define walEnableBlockingMs(pWal, ms)0 0 | ||||
| 67967 | # define sqlite3WalDb(pWal, db) | ||||
| 67968 | #endif /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */ | ||||
| 67969 | |||||
| 67970 | |||||
| 67971 | /* | ||||
| 67972 | ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and | ||||
| 67973 | ** n. If the attempt fails and parameter xBusy is not NULL, then it is a | ||||
| 67974 | ** busy-handler function. Invoke it and retry the lock until either the | ||||
| 67975 | ** lock is successfully obtained or the busy-handler returns 0. | ||||
| 67976 | */ | ||||
| 67977 | static int walBusyLock( | ||||
| 67978 | Wal *pWal, /* WAL connection */ | ||||
| 67979 | int (*xBusy)(void*), /* Function to call when busy */ | ||||
| 67980 | void *pBusyArg, /* Context argument for xBusyHandler */ | ||||
| 67981 | int lockIdx, /* Offset of first byte to lock */ | ||||
| 67982 | int n /* Number of bytes to lock */ | ||||
| 67983 | ){ | ||||
| 67984 | int rc; | ||||
| 67985 | do { | ||||
| 67986 | rc = walLockExclusive(pWal, lockIdx, n); | ||||
| 67987 | }while( xBusy && rc==SQLITE_BUSY5 && xBusy(pBusyArg) ); | ||||
| 67988 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 67989 | if( rc==SQLITE_BUSY_TIMEOUT(5 | (3<<8)) ){ | ||||
| 67990 | walDisableBlocking(pWal); | ||||
| 67991 | rc = SQLITE_BUSY5; | ||||
| 67992 | } | ||||
| 67993 | #endif | ||||
| 67994 | return rc; | ||||
| 67995 | } | ||||
| 67996 | |||||
| 67997 | /* | ||||
| 67998 | ** The cache of the wal-index header must be valid to call this function. | ||||
| 67999 | ** Return the page-size in bytes used by the database. | ||||
| 68000 | */ | ||||
| 68001 | static int walPagesize(Wal *pWal){ | ||||
| 68002 | return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); | ||||
| 68003 | } | ||||
| 68004 | |||||
| 68005 | /* | ||||
| 68006 | ** The following is guaranteed when this function is called: | ||||
| 68007 | ** | ||||
| 68008 | ** a) the WRITER lock is held, | ||||
| 68009 | ** b) the entire log file has been checkpointed, and | ||||
| 68010 | ** c) any existing readers are reading exclusively from the database | ||||
| 68011 | ** file - there are no readers that may attempt to read a frame from | ||||
| 68012 | ** the log file. | ||||
| 68013 | ** | ||||
| 68014 | ** This function updates the shared-memory structures so that the next | ||||
| 68015 | ** client to write to the database (which may be this one) does so by | ||||
| 68016 | ** writing frames into the start of the log file. | ||||
| 68017 | ** | ||||
| 68018 | ** The value of parameter salt1 is used as the aSalt[1] value in the | ||||
| 68019 | ** new wal-index header. It should be passed a pseudo-random value (i.e. | ||||
| 68020 | ** one obtained from sqlite3_randomness()). | ||||
| 68021 | */ | ||||
| 68022 | static void walRestartHdr(Wal *pWal, u32 salt1){ | ||||
| 68023 | volatile WalCkptInfo *pInfo = walCkptInfo(pWal); | ||||
| 68024 | int i; /* Loop counter */ | ||||
| 68025 | u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */ | ||||
| 68026 | pWal->nCkpt++; | ||||
| 68027 | pWal->hdr.mxFrame = 0; | ||||
| 68028 | sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); | ||||
| 68029 | memcpy(&pWal->hdr.aSalt[1], &salt1, 4); | ||||
| 68030 | walIndexWriteHdr(pWal); | ||||
| 68031 | AtomicStore(&pInfo->nBackfill, 0)__atomic_store_n((&pInfo->nBackfill),(0),0); | ||||
| 68032 | pInfo->nBackfillAttempted = 0; | ||||
| 68033 | pInfo->aReadMark[1] = 0; | ||||
| 68034 | for(i=2; i<WAL_NREADER(8 -3); i++) pInfo->aReadMark[i] = READMARK_NOT_USED0xffffffff; | ||||
| 68035 | assert( pInfo->aReadMark[0]==0 )((void) (0)); | ||||
| 68036 | } | ||||
| 68037 | |||||
| 68038 | /* | ||||
| 68039 | ** Copy as much content as we can from the WAL back into the database file | ||||
| 68040 | ** in response to an sqlite3_wal_checkpoint() request or the equivalent. | ||||
| 68041 | ** | ||||
| 68042 | ** The amount of information copies from WAL to database might be limited | ||||
| 68043 | ** by active readers. This routine will never overwrite a database page | ||||
| 68044 | ** that a concurrent reader might be using. | ||||
| 68045 | ** | ||||
| 68046 | ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when | ||||
| 68047 | ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if | ||||
| 68048 | ** checkpoints are always run by a background thread or background | ||||
| 68049 | ** process, foreground threads will never block on a lengthy fsync call. | ||||
| 68050 | ** | ||||
| 68051 | ** Fsync is called on the WAL before writing content out of the WAL and | ||||
| 68052 | ** into the database. This ensures that if the new content is persistent | ||||
| 68053 | ** in the WAL and can be recovered following a power-loss or hard reset. | ||||
| 68054 | ** | ||||
| 68055 | ** Fsync is also called on the database file if (and only if) the entire | ||||
| 68056 | ** WAL content is copied into the database file. This second fsync makes | ||||
| 68057 | ** it safe to delete the WAL since the new content will persist in the | ||||
| 68058 | ** database file. | ||||
| 68059 | ** | ||||
| 68060 | ** This routine uses and updates the nBackfill field of the wal-index header. | ||||
| 68061 | ** This is the only routine that will increase the value of nBackfill. | ||||
| 68062 | ** (A WAL reset or recovery will revert nBackfill to zero, but not increase | ||||
| 68063 | ** its value.) | ||||
| 68064 | ** | ||||
| 68065 | ** The caller must be holding sufficient locks to ensure that no other | ||||
| 68066 | ** checkpoint is running (in any other thread or process) at the same | ||||
| 68067 | ** time. | ||||
| 68068 | */ | ||||
| 68069 | static int walCheckpoint( | ||||
| 68070 | Wal *pWal, /* Wal connection */ | ||||
| 68071 | sqlite3 *db, /* Check for interrupts on this handle */ | ||||
| 68072 | int eMode, /* One of PASSIVE, FULL or RESTART */ | ||||
| 68073 | int (*xBusy)(void*), /* Function to call when busy */ | ||||
| 68074 | void *pBusyArg, /* Context argument for xBusyHandler */ | ||||
| 68075 | int sync_flags, /* Flags for OsSync() (or 0) */ | ||||
| 68076 | u8 *zBuf /* Temporary buffer to use */ | ||||
| 68077 | ){ | ||||
| 68078 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 68079 | int szPage; /* Database page-size */ | ||||
| 68080 | WalIterator *pIter = 0; /* Wal iterator context */ | ||||
| 68081 | u32 iDbpage = 0; /* Next database page to write */ | ||||
| 68082 | u32 iFrame = 0; /* Wal frame containing data for iDbpage */ | ||||
| 68083 | u32 mxSafeFrame; /* Max frame that can be backfilled */ | ||||
| 68084 | u32 mxPage; /* Max database page to write */ | ||||
| 68085 | int i; /* Loop counter */ | ||||
| 68086 | volatile WalCkptInfo *pInfo; /* The checkpoint status information */ | ||||
| 68087 | |||||
| 68088 | szPage = walPagesize(pWal); | ||||
| 68089 | testcase( szPage<=32768 ); | ||||
| 68090 | testcase( szPage>=65536 ); | ||||
| 68091 | pInfo = walCkptInfo(pWal); | ||||
| 68092 | if( pInfo->nBackfill<pWal->hdr.mxFrame ){ | ||||
| 68093 | |||||
| 68094 | /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked | ||||
| 68095 | ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ | ||||
| 68096 | assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 )((void) (0)); | ||||
| 68097 | |||||
| 68098 | /* Compute in mxSafeFrame the index of the last frame of the WAL that is | ||||
| 68099 | ** safe to write into the database. Frames beyond mxSafeFrame might | ||||
| 68100 | ** overwrite database pages that are in use by active readers and thus | ||||
| 68101 | ** cannot be backfilled from the WAL. | ||||
| 68102 | */ | ||||
| 68103 | mxSafeFrame = pWal->hdr.mxFrame; | ||||
| 68104 | mxPage = pWal->hdr.nPage; | ||||
| 68105 | for(i=1; i<WAL_NREADER(8 -3); i++){ | ||||
| 68106 | u32 y = AtomicLoad(pInfo->aReadMark+i)__atomic_load_n((pInfo->aReadMark+i),0); SEH_INJECT_FAULT((void) (0));; | ||||
| 68107 | if( mxSafeFrame>y ){ | ||||
| 68108 | assert( y<=pWal->hdr.mxFrame )((void) (0)); | ||||
| 68109 | rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i)(3+(i)), 1); | ||||
| 68110 | if( rc==SQLITE_OK0 ){ | ||||
| 68111 | u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED0xffffffff); | ||||
| 68112 | AtomicStore(pInfo->aReadMark+i, iMark)__atomic_store_n((pInfo->aReadMark+i),(iMark),0); SEH_INJECT_FAULT((void) (0));; | ||||
| 68113 | walUnlockExclusive(pWal, WAL_READ_LOCK(i)(3+(i)), 1); | ||||
| 68114 | }else if( rc==SQLITE_BUSY5 ){ | ||||
| 68115 | mxSafeFrame = y; | ||||
| 68116 | xBusy = 0; | ||||
| 68117 | }else{ | ||||
| 68118 | goto walcheckpoint_out; | ||||
| 68119 | } | ||||
| 68120 | } | ||||
| 68121 | } | ||||
| 68122 | |||||
| 68123 | /* Allocate the iterator */ | ||||
| 68124 | if( pInfo->nBackfill<mxSafeFrame ){ | ||||
| 68125 | rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter); | ||||
| 68126 | assert( rc==SQLITE_OK || pIter==0 )((void) (0)); | ||||
| 68127 | } | ||||
| 68128 | |||||
| 68129 | if( pIter | ||||
| 68130 | && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0)(3+(0)),1))==SQLITE_OK0 | ||||
| 68131 | ){ | ||||
| 68132 | u32 nBackfill = pInfo->nBackfill; | ||||
| 68133 | pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT((void) (0));; | ||||
| 68134 | |||||
| 68135 | /* Sync the WAL to disk */ | ||||
| 68136 | rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)(((sync_flags)>>2)&0x03)); | ||||
| 68137 | |||||
| 68138 | /* If the database may grow as a result of this checkpoint, hint | ||||
| 68139 | ** about the eventual size of the db file to the VFS layer. | ||||
| 68140 | */ | ||||
| 68141 | if( rc==SQLITE_OK0 ){ | ||||
| 68142 | i64 nReq = ((i64)mxPage * szPage); | ||||
| 68143 | i64 nSize; /* Current size of database file */ | ||||
| 68144 | sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START39, 0); | ||||
| 68145 | rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); | ||||
| 68146 | if( rc==SQLITE_OK0 && nSize<nReq ){ | ||||
| 68147 | if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){ | ||||
| 68148 | /* If the size of the final database is larger than the current | ||||
| 68149 | ** database plus the amount of data in the wal file, plus the | ||||
| 68150 | ** maximum size of the pending-byte page (65536 bytes), then | ||||
| 68151 | ** must be corruption somewhere. */ | ||||
| 68152 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(68152); | ||||
| 68153 | }else{ | ||||
| 68154 | sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT5,&nReq); | ||||
| 68155 | } | ||||
| 68156 | } | ||||
| 68157 | |||||
| 68158 | } | ||||
| 68159 | |||||
| 68160 | /* Iterate through the contents of the WAL, copying data to the db file */ | ||||
| 68161 | while( rc==SQLITE_OK0 && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ | ||||
| 68162 | i64 iOffset; | ||||
| 68163 | assert( walFramePgno(pWal, iFrame)==iDbpage )((void) (0)); | ||||
| 68164 | SEH_INJECT_FAULT((void) (0));; | ||||
| 68165 | if( AtomicLoad(&db->u1.isInterrupted)__atomic_load_n((&db->u1.isInterrupted),0) ){ | ||||
| 68166 | rc = db->mallocFailed ? SQLITE_NOMEM_BKPT7 : SQLITE_INTERRUPT9; | ||||
| 68167 | break; | ||||
| 68168 | } | ||||
| 68169 | if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){ | ||||
| 68170 | continue; | ||||
| 68171 | } | ||||
| 68172 | iOffset = walFrameOffset(iFrame, szPage)( 32 + ((iFrame)-1)*(i64)((szPage)+24) ) + WAL_FRAME_HDRSIZE24; | ||||
| 68173 | /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ | ||||
| 68174 | rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); | ||||
| 68175 | if( rc!=SQLITE_OK0 ) break; | ||||
| 68176 | iOffset = (iDbpage-1)*(i64)szPage; | ||||
| 68177 | testcase( IS_BIG_INT(iOffset) ); | ||||
| 68178 | rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); | ||||
| 68179 | if( rc!=SQLITE_OK0 ) break; | ||||
| 68180 | } | ||||
| 68181 | sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE37, 0); | ||||
| 68182 | |||||
| 68183 | /* If work was actually accomplished... */ | ||||
| 68184 | if( rc==SQLITE_OK0 ){ | ||||
| 68185 | if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ | ||||
| 68186 | i64 szDb = pWal->hdr.nPage*(i64)szPage; | ||||
| 68187 | testcase( IS_BIG_INT(szDb) ); | ||||
| 68188 | rc = sqlite3OsTruncate(pWal->pDbFd, szDb); | ||||
| 68189 | if( rc==SQLITE_OK0 ){ | ||||
| 68190 | rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags)(((sync_flags)>>2)&0x03)); | ||||
| 68191 | } | ||||
| 68192 | } | ||||
| 68193 | if( rc==SQLITE_OK0 ){ | ||||
| 68194 | AtomicStore(&pInfo->nBackfill, mxSafeFrame)__atomic_store_n((&pInfo->nBackfill),(mxSafeFrame),0); SEH_INJECT_FAULT((void) (0));; | ||||
| 68195 | } | ||||
| 68196 | } | ||||
| 68197 | |||||
| 68198 | /* Release the reader lock held while backfilling */ | ||||
| 68199 | walUnlockExclusive(pWal, WAL_READ_LOCK(0)(3+(0)), 1); | ||||
| 68200 | } | ||||
| 68201 | |||||
| 68202 | if( rc==SQLITE_BUSY5 ){ | ||||
| 68203 | /* Reset the return code so as not to report a checkpoint failure | ||||
| 68204 | ** just because there are active readers. */ | ||||
| 68205 | rc = SQLITE_OK0; | ||||
| 68206 | } | ||||
| 68207 | } | ||||
| 68208 | |||||
| 68209 | /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the | ||||
| 68210 | ** entire wal file has been copied into the database file, then block | ||||
| 68211 | ** until all readers have finished using the wal file. This ensures that | ||||
| 68212 | ** the next process to write to the database restarts the wal file. | ||||
| 68213 | */ | ||||
| 68214 | if( rc==SQLITE_OK0 && eMode!=SQLITE_CHECKPOINT_PASSIVE0 ){ | ||||
| 68215 | assert( pWal->writeLock )((void) (0)); | ||||
| 68216 | SEH_INJECT_FAULT((void) (0));; | ||||
| 68217 | if( pInfo->nBackfill<pWal->hdr.mxFrame ){ | ||||
| 68218 | rc = SQLITE_BUSY5; | ||||
| 68219 | }else if( eMode>=SQLITE_CHECKPOINT_RESTART2 ){ | ||||
| 68220 | u32 salt1; | ||||
| 68221 | sqlite3_randomness(4, &salt1); | ||||
| 68222 | assert( pInfo->nBackfill==pWal->hdr.mxFrame )((void) (0)); | ||||
| 68223 | rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1)(3+(1)), WAL_NREADER(8 -3)-1); | ||||
| 68224 | if( rc==SQLITE_OK0 ){ | ||||
| 68225 | if( eMode==SQLITE_CHECKPOINT_TRUNCATE3 ){ | ||||
| 68226 | /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as | ||||
| 68227 | ** SQLITE_CHECKPOINT_RESTART with the addition that it also | ||||
| 68228 | ** truncates the log file to zero bytes just prior to a | ||||
| 68229 | ** successful return. | ||||
| 68230 | ** | ||||
| 68231 | ** In theory, it might be safe to do this without updating the | ||||
| 68232 | ** wal-index header in shared memory, as all subsequent reader or | ||||
| 68233 | ** writer clients should see that the entire log file has been | ||||
| 68234 | ** checkpointed and behave accordingly. This seems unsafe though, | ||||
| 68235 | ** as it would leave the system in a state where the contents of | ||||
| 68236 | ** the wal-index header do not match the contents of the | ||||
| 68237 | ** file-system. To avoid this, update the wal-index header to | ||||
| 68238 | ** indicate that the log file contains zero valid frames. */ | ||||
| 68239 | walRestartHdr(pWal, salt1); | ||||
| 68240 | rc = sqlite3OsTruncate(pWal->pWalFd, 0); | ||||
| 68241 | } | ||||
| 68242 | walUnlockExclusive(pWal, WAL_READ_LOCK(1)(3+(1)), WAL_NREADER(8 -3)-1); | ||||
| 68243 | } | ||||
| 68244 | } | ||||
| 68245 | } | ||||
| 68246 | |||||
| 68247 | walcheckpoint_out: | ||||
| 68248 | SEH_FREE_ON_ERROR(pIter, 0); | ||||
| 68249 | walIteratorFree(pIter); | ||||
| 68250 | return rc; | ||||
| 68251 | } | ||||
| 68252 | |||||
| 68253 | /* | ||||
| 68254 | ** If the WAL file is currently larger than nMax bytes in size, truncate | ||||
| 68255 | ** it to exactly nMax bytes. If an error occurs while doing so, ignore it. | ||||
| 68256 | */ | ||||
| 68257 | static void walLimitSize(Wal *pWal, i64 nMax){ | ||||
| 68258 | i64 sz; | ||||
| 68259 | int rx; | ||||
| 68260 | sqlite3BeginBenignMalloc(); | ||||
| 68261 | rx = sqlite3OsFileSize(pWal->pWalFd, &sz); | ||||
| 68262 | if( rx==SQLITE_OK0 && (sz > nMax ) ){ | ||||
| 68263 | rx = sqlite3OsTruncate(pWal->pWalFd, nMax); | ||||
| 68264 | } | ||||
| 68265 | sqlite3EndBenignMalloc(); | ||||
| 68266 | if( rx ){ | ||||
| 68267 | sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); | ||||
| 68268 | } | ||||
| 68269 | } | ||||
| 68270 | |||||
| 68271 | #ifdef SQLITE_USE_SEH | ||||
| 68272 | /* | ||||
| 68273 | ** This is the "standard" exception handler used in a few places to handle | ||||
| 68274 | ** an exception thrown by reading from the *-shm mapping after it has become | ||||
| 68275 | ** invalid in SQLITE_USE_SEH builds. It is used as follows: | ||||
| 68276 | ** | ||||
| 68277 | ** SEH_TRY { ... } | ||||
| 68278 | ** SEH_EXCEPT( rc = walHandleException(pWal); ) | ||||
| 68279 | ** | ||||
| 68280 | ** This function does three things: | ||||
| 68281 | ** | ||||
| 68282 | ** 1) Determines the locks that should be held, based on the contents of | ||||
| 68283 | ** the Wal.readLock, Wal.writeLock and Wal.ckptLock variables. All other | ||||
| 68284 | ** held locks are assumed to be transient locks that would have been | ||||
| 68285 | ** released had the exception not been thrown and are dropped. | ||||
| 68286 | ** | ||||
| 68287 | ** 2) Frees the pointer at Wal.pFree, if any, using sqlite3_free(). | ||||
| 68288 | ** | ||||
| 68289 | ** 3) Set pWal->apWiData[pWal->iWiPg] to pWal->pWiValue if not NULL | ||||
| 68290 | ** | ||||
| 68291 | ** 4) Returns SQLITE_IOERR. | ||||
| 68292 | */ | ||||
| 68293 | static int walHandleException(Wal *pWal){ | ||||
| 68294 | if( pWal->exclusiveMode==0 ){ | ||||
| 68295 | static const int S = 1; | ||||
| 68296 | static const int E = (1<<SQLITE_SHM_NLOCK8); | ||||
| 68297 | int ii; | ||||
| 68298 | u32 mUnlock; | ||||
| 68299 | if( pWal->writeLock==2 ) pWal->writeLock = 0; | ||||
| 68300 | mUnlock = pWal->lockMask & ~( | ||||
| 68301 | (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)(3+(pWal->readLock)))) | ||||
| 68302 | | (pWal->writeLock ? (E << WAL_WRITE_LOCK0) : 0) | ||||
| 68303 | | (pWal->ckptLock ? (E << WAL_CKPT_LOCK1) : 0) | ||||
| 68304 | ); | ||||
| 68305 | for(ii=0; ii<SQLITE_SHM_NLOCK8; ii++){ | ||||
| 68306 | if( (S<<ii) & mUnlock ) walUnlockShared(pWal, ii); | ||||
| 68307 | if( (E<<ii) & mUnlock ) walUnlockExclusive(pWal, ii, 1); | ||||
| 68308 | } | ||||
| 68309 | } | ||||
| 68310 | sqlite3_free(pWal->pFree); | ||||
| 68311 | pWal->pFree = 0; | ||||
| 68312 | if( pWal->pWiValue ){ | ||||
| 68313 | pWal->apWiData[pWal->iWiPg] = pWal->pWiValue; | ||||
| 68314 | pWal->pWiValue = 0; | ||||
| 68315 | } | ||||
| 68316 | return SQLITE_IOERR_IN_PAGE(10 | (34<<8)); | ||||
| 68317 | } | ||||
| 68318 | |||||
| 68319 | /* | ||||
| 68320 | ** Assert that the Wal.lockMask mask, which indicates the locks held | ||||
| 68321 | ** by the connection, is consistent with the Wal.readLock, Wal.writeLock | ||||
| 68322 | ** and Wal.ckptLock variables. To be used as: | ||||
| 68323 | ** | ||||
| 68324 | ** assert( walAssertLockmask(pWal) ); | ||||
| 68325 | */ | ||||
| 68326 | static int walAssertLockmask(Wal *pWal)1{ | ||||
| 68327 | if( pWal->exclusiveMode==0 ){ | ||||
| 68328 | static const int S = 1; | ||||
| 68329 | static const int E = (1<<SQLITE_SHM_NLOCK8); | ||||
| 68330 | u32 mExpect = ( | ||||
| 68331 | (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)(3+(pWal->readLock)))) | ||||
| 68332 | | (pWal->writeLock ? (E << WAL_WRITE_LOCK0) : 0) | ||||
| 68333 | | (pWal->ckptLock ? (E << WAL_CKPT_LOCK1) : 0) | ||||
| 68334 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 68335 | | (pWal->pSnapshot ? (pWal->lockMask & (1 << WAL_CKPT_LOCK1)) : 0) | ||||
| 68336 | #endif | ||||
| 68337 | ); | ||||
| 68338 | assert( mExpect==pWal->lockMask )((void) (0)); | ||||
| 68339 | } | ||||
| 68340 | return 1; | ||||
| 68341 | } | ||||
| 68342 | |||||
| 68343 | /* | ||||
| 68344 | ** Return and zero the "system error" field set when an | ||||
| 68345 | ** EXCEPTION_IN_PAGE_ERROR exception is caught. | ||||
| 68346 | */ | ||||
| 68347 | SQLITE_PRIVATEstatic int sqlite3WalSystemErrno(Wal *pWal){ | ||||
| 68348 | int iRet = 0; | ||||
| 68349 | if( pWal ){ | ||||
| 68350 | iRet = pWal->iSysErrno; | ||||
| 68351 | pWal->iSysErrno = 0; | ||||
| 68352 | } | ||||
| 68353 | return iRet; | ||||
| 68354 | } | ||||
| 68355 | |||||
| 68356 | #else | ||||
| 68357 | # define walAssertLockmask(x)1 1 | ||||
| 68358 | #endif /* ifdef SQLITE_USE_SEH */ | ||||
| 68359 | |||||
| 68360 | /* | ||||
| 68361 | ** Close a connection to a log file. | ||||
| 68362 | */ | ||||
| 68363 | SQLITE_PRIVATEstatic int sqlite3WalClose( | ||||
| 68364 | Wal *pWal, /* Wal to close */ | ||||
| 68365 | sqlite3 *db, /* For interrupt flag */ | ||||
| 68366 | int sync_flags, /* Flags to pass to OsSync() (or 0) */ | ||||
| 68367 | int nBuf, | ||||
| 68368 | u8 *zBuf /* Buffer of at least nBuf bytes */ | ||||
| 68369 | ){ | ||||
| 68370 | int rc = SQLITE_OK0; | ||||
| 68371 | if( pWal ){ | ||||
| 68372 | int isDelete = 0; /* True to unlink wal and wal-index files */ | ||||
| 68373 | |||||
| 68374 | assert( walAssertLockmask(pWal) )((void) (0)); | ||||
| 68375 | |||||
| 68376 | /* If an EXCLUSIVE lock can be obtained on the database file (using the | ||||
| 68377 | ** ordinary, rollback-mode locking methods, this guarantees that the | ||||
| 68378 | ** connection associated with this log file is the only connection to | ||||
| 68379 | ** the database. In this case checkpoint the database and unlink both | ||||
| 68380 | ** the wal and wal-index files. | ||||
| 68381 | ** | ||||
| 68382 | ** The EXCLUSIVE lock is not released before returning. | ||||
| 68383 | */ | ||||
| 68384 | if( zBuf!=0 | ||||
| 68385 | && SQLITE_OK0==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE4)) | ||||
| 68386 | ){ | ||||
| 68387 | if( pWal->exclusiveMode==WAL_NORMAL_MODE0 ){ | ||||
| 68388 | pWal->exclusiveMode = WAL_EXCLUSIVE_MODE1; | ||||
| 68389 | } | ||||
| 68390 | rc = sqlite3WalCheckpoint(pWal, db, | ||||
| 68391 | SQLITE_CHECKPOINT_PASSIVE0, 0, 0, sync_flags, nBuf, zBuf, 0, 0 | ||||
| 68392 | ); | ||||
| 68393 | if( rc==SQLITE_OK0 ){ | ||||
| 68394 | int bPersist = -1; | ||||
| 68395 | sqlite3OsFileControlHint( | ||||
| 68396 | pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL10, &bPersist | ||||
| 68397 | ); | ||||
| 68398 | if( bPersist!=1 ){ | ||||
| 68399 | /* Try to delete the WAL file if the checkpoint completed and | ||||
| 68400 | ** fsynced (rc==SQLITE_OK) and if we are not in persistent-wal | ||||
| 68401 | ** mode (!bPersist) */ | ||||
| 68402 | isDelete = 1; | ||||
| 68403 | }else if( pWal->mxWalSize>=0 ){ | ||||
| 68404 | /* Try to truncate the WAL file to zero bytes if the checkpoint | ||||
| 68405 | ** completed and fsynced (rc==SQLITE_OK) and we are in persistent | ||||
| 68406 | ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a | ||||
| 68407 | ** non-negative value (pWal->mxWalSize>=0). Note that we truncate | ||||
| 68408 | ** to zero bytes as truncating to the journal_size_limit might | ||||
| 68409 | ** leave a corrupt WAL file on disk. */ | ||||
| 68410 | walLimitSize(pWal, 0); | ||||
| 68411 | } | ||||
| 68412 | } | ||||
| 68413 | } | ||||
| 68414 | |||||
| 68415 | walIndexClose(pWal, isDelete); | ||||
| 68416 | sqlite3OsClose(pWal->pWalFd); | ||||
| 68417 | if( isDelete ){ | ||||
| 68418 | sqlite3BeginBenignMalloc(); | ||||
| 68419 | sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); | ||||
| 68420 | sqlite3EndBenignMalloc(); | ||||
| 68421 | } | ||||
| 68422 | WALTRACE(("WAL%p: closed\n", pWal)); | ||||
| 68423 | sqlite3_free((void *)pWal->apWiData); | ||||
| 68424 | sqlite3_free(pWal); | ||||
| 68425 | } | ||||
| 68426 | return rc; | ||||
| 68427 | } | ||||
| 68428 | |||||
| 68429 | /* | ||||
| 68430 | ** Try to read the wal-index header. Return 0 on success and 1 if | ||||
| 68431 | ** there is a problem. | ||||
| 68432 | ** | ||||
| 68433 | ** The wal-index is in shared memory. Another thread or process might | ||||
| 68434 | ** be writing the header at the same time this procedure is trying to | ||||
| 68435 | ** read it, which might result in inconsistency. A dirty read is detected | ||||
| 68436 | ** by verifying that both copies of the header are the same and also by | ||||
| 68437 | ** a checksum on the header. | ||||
| 68438 | ** | ||||
| 68439 | ** If and only if the read is consistent and the header is different from | ||||
| 68440 | ** pWal->hdr, then pWal->hdr is updated to the content of the new header | ||||
| 68441 | ** and *pChanged is set to 1. | ||||
| 68442 | ** | ||||
| 68443 | ** If the checksum cannot be verified return non-zero. If the header | ||||
| 68444 | ** is read successfully and the checksum verified, return zero. | ||||
| 68445 | */ | ||||
| 68446 | static SQLITE_NO_TSAN__attribute__((no_sanitize_thread)) int walIndexTryHdr(Wal *pWal, int *pChanged){ | ||||
| 68447 | u32 aCksum[2]; /* Checksum on the header content */ | ||||
| 68448 | WalIndexHdr h1, h2; /* Two copies of the header content */ | ||||
| 68449 | WalIndexHdr volatile *aHdr; /* Header in shared memory */ | ||||
| 68450 | |||||
| 68451 | /* The first page of the wal-index must be mapped at this point. */ | ||||
| 68452 | assert( pWal->nWiData>0 && pWal->apWiData[0] )((void) (0)); | ||||
| 68453 | |||||
| 68454 | /* Read the header. This might happen concurrently with a write to the | ||||
| 68455 | ** same area of shared memory on a different CPU in a SMP, | ||||
| 68456 | ** meaning it is possible that an inconsistent snapshot is read | ||||
| 68457 | ** from the file. If this happens, return non-zero. | ||||
| 68458 | ** | ||||
| 68459 | ** tag-20200519-1: | ||||
| 68460 | ** There are two copies of the header at the beginning of the wal-index. | ||||
| 68461 | ** When reading, read [0] first then [1]. Writes are in the reverse order. | ||||
| 68462 | ** Memory barriers are used to prevent the compiler or the hardware from | ||||
| 68463 | ** reordering the reads and writes. TSAN and similar tools can sometimes | ||||
| 68464 | ** give false-positive warnings about these accesses because the tools do not | ||||
| 68465 | ** account for the double-read and the memory barrier. The use of mutexes | ||||
| 68466 | ** here would be problematic as the memory being accessed is potentially | ||||
| 68467 | ** shared among multiple processes and not all mutex implementations work | ||||
| 68468 | ** reliably in that environment. | ||||
| 68469 | */ | ||||
| 68470 | aHdr = walIndexHdr(pWal); | ||||
| 68471 | memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */ | ||||
| 68472 | walShmBarrier(pWal); | ||||
| 68473 | memcpy(&h2, (void *)&aHdr[1], sizeof(h2)); | ||||
| 68474 | |||||
| 68475 | if( memcmp(&h1, &h2, sizeof(h1))!=0 ){ | ||||
| 68476 | return 1; /* Dirty read */ | ||||
| 68477 | } | ||||
| 68478 | if( h1.isInit==0 ){ | ||||
| 68479 | return 1; /* Malformed header - probably all zeros */ | ||||
| 68480 | } | ||||
| 68481 | walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum); | ||||
| 68482 | if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){ | ||||
| 68483 | return 1; /* Checksum does not match */ | ||||
| 68484 | } | ||||
| 68485 | |||||
| 68486 | if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){ | ||||
| 68487 | *pChanged = 1; | ||||
| 68488 | memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr)); | ||||
| 68489 | pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); | ||||
| 68490 | testcase( pWal->szPage<=32768 ); | ||||
| 68491 | testcase( pWal->szPage>=65536 ); | ||||
| 68492 | } | ||||
| 68493 | |||||
| 68494 | /* The header was successfully read. Return zero. */ | ||||
| 68495 | return 0; | ||||
| 68496 | } | ||||
| 68497 | |||||
| 68498 | /* | ||||
| 68499 | ** This is the value that walTryBeginRead returns when it needs to | ||||
| 68500 | ** be retried. | ||||
| 68501 | */ | ||||
| 68502 | #define WAL_RETRY(-1) (-1) | ||||
| 68503 | |||||
| 68504 | /* | ||||
| 68505 | ** Read the wal-index header from the wal-index and into pWal->hdr. | ||||
| 68506 | ** If the wal-header appears to be corrupt, try to reconstruct the | ||||
| 68507 | ** wal-index from the WAL before returning. | ||||
| 68508 | ** | ||||
| 68509 | ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is | ||||
| 68510 | ** changed by this operation. If pWal->hdr is unchanged, set *pChanged | ||||
| 68511 | ** to 0. | ||||
| 68512 | ** | ||||
| 68513 | ** If the wal-index header is successfully read, return SQLITE_OK. | ||||
| 68514 | ** Otherwise an SQLite error code. | ||||
| 68515 | */ | ||||
| 68516 | static int walIndexReadHdr(Wal *pWal, int *pChanged){ | ||||
| 68517 | int rc; /* Return code */ | ||||
| 68518 | int badHdr; /* True if a header read failed */ | ||||
| 68519 | volatile u32 *page0; /* Chunk of wal-index containing header */ | ||||
| 68520 | |||||
| 68521 | /* Ensure that page 0 of the wal-index (the page that contains the | ||||
| 68522 | ** wal-index header) is mapped. Return early if an error occurs here. | ||||
| 68523 | */ | ||||
| 68524 | assert( pChanged )((void) (0)); | ||||
| 68525 | rc = walIndexPage(pWal, 0, &page0); | ||||
| 68526 | if( rc!=SQLITE_OK0 ){ | ||||
| 68527 | assert( rc!=SQLITE_READONLY )((void) (0)); /* READONLY changed to OK in walIndexPage */ | ||||
| 68528 | if( rc==SQLITE_READONLY_CANTINIT(8 | (5<<8)) ){ | ||||
| 68529 | /* The SQLITE_READONLY_CANTINIT return means that the shared-memory | ||||
| 68530 | ** was openable but is not writable, and this thread is unable to | ||||
| 68531 | ** confirm that another write-capable connection has the shared-memory | ||||
| 68532 | ** open, and hence the content of the shared-memory is unreliable, | ||||
| 68533 | ** since the shared-memory might be inconsistent with the WAL file | ||||
| 68534 | ** and there is no writer on hand to fix it. */ | ||||
| 68535 | assert( page0==0 )((void) (0)); | ||||
| 68536 | assert( pWal->writeLock==0 )((void) (0)); | ||||
| 68537 | assert( pWal->readOnly & WAL_SHM_RDONLY )((void) (0)); | ||||
| 68538 | pWal->bShmUnreliable = 1; | ||||
| 68539 | pWal->exclusiveMode = WAL_HEAPMEMORY_MODE2; | ||||
| 68540 | *pChanged = 1; | ||||
| 68541 | }else{ | ||||
| 68542 | return rc; /* Any other non-OK return is just an error */ | ||||
| 68543 | } | ||||
| 68544 | }else{ | ||||
| 68545 | /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock | ||||
| 68546 | ** is zero, which prevents the SHM from growing */ | ||||
| 68547 | testcase( page0!=0 ); | ||||
| 68548 | } | ||||
| 68549 | assert( page0!=0 || pWal->writeLock==0 )((void) (0)); | ||||
| 68550 | |||||
| 68551 | /* If the first page of the wal-index has been mapped, try to read the | ||||
| 68552 | ** wal-index header immediately, without holding any lock. This usually | ||||
| 68553 | ** works, but may fail if the wal-index header is corrupt or currently | ||||
| 68554 | ** being modified by another thread or process. | ||||
| 68555 | */ | ||||
| 68556 | badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1); | ||||
| 68557 | |||||
| 68558 | /* If the first attempt failed, it might have been due to a race | ||||
| 68559 | ** with a writer. So get a WRITE lock and try again. | ||||
| 68560 | */ | ||||
| 68561 | if( badHdr ){ | ||||
| 68562 | if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY2) ){ | ||||
| 68563 | if( SQLITE_OK0==(rc = walLockShared(pWal, WAL_WRITE_LOCK0)) ){ | ||||
| 68564 | walUnlockShared(pWal, WAL_WRITE_LOCK0); | ||||
| 68565 | rc = SQLITE_READONLY_RECOVERY(8 | (1<<8)); | ||||
| 68566 | } | ||||
| 68567 | }else{ | ||||
| 68568 | int bWriteLock = pWal->writeLock; | ||||
| 68569 | if( bWriteLock | ||||
| 68570 | || SQLITE_OK0==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK0, 1)) | ||||
| 68571 | ){ | ||||
| 68572 | /* If the write-lock was just obtained, set writeLock to 2 instead of | ||||
| 68573 | ** the usual 1. This causes walIndexPage() to behave as if the | ||||
| 68574 | ** write-lock were held (so that it allocates new pages as required), | ||||
| 68575 | ** and walHandleException() to unlock the write-lock if a SEH exception | ||||
| 68576 | ** is thrown. */ | ||||
| 68577 | if( !bWriteLock ) pWal->writeLock = 2; | ||||
| 68578 | if( SQLITE_OK0==(rc = walIndexPage(pWal, 0, &page0)) ){ | ||||
| 68579 | badHdr = walIndexTryHdr(pWal, pChanged); | ||||
| 68580 | if( badHdr ){ | ||||
| 68581 | /* If the wal-index header is still malformed even while holding | ||||
| 68582 | ** a WRITE lock, it can only mean that the header is corrupted and | ||||
| 68583 | ** needs to be reconstructed. So run recovery to do exactly that. | ||||
| 68584 | ** Disable blocking locks first. */ | ||||
| 68585 | walDisableBlocking(pWal); | ||||
| 68586 | rc = walIndexRecover(pWal); | ||||
| 68587 | *pChanged = 1; | ||||
| 68588 | } | ||||
| 68589 | } | ||||
| 68590 | if( bWriteLock==0 ){ | ||||
| 68591 | pWal->writeLock = 0; | ||||
| 68592 | walUnlockExclusive(pWal, WAL_WRITE_LOCK0, 1); | ||||
| 68593 | } | ||||
| 68594 | } | ||||
| 68595 | } | ||||
| 68596 | } | ||||
| 68597 | |||||
| 68598 | /* If the header is read successfully, check the version number to make | ||||
| 68599 | ** sure the wal-index was not constructed with some future format that | ||||
| 68600 | ** this version of SQLite cannot understand. | ||||
| 68601 | */ | ||||
| 68602 | if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION3007000 ){ | ||||
| 68603 | rc = SQLITE_CANTOPEN_BKPTsqlite3CantopenError(68603); | ||||
| 68604 | } | ||||
| 68605 | if( pWal->bShmUnreliable ){ | ||||
| 68606 | if( rc!=SQLITE_OK0 ){ | ||||
| 68607 | walIndexClose(pWal, 0); | ||||
| 68608 | pWal->bShmUnreliable = 0; | ||||
| 68609 | assert( pWal->nWiData>0 && pWal->apWiData[0]==0 )((void) (0)); | ||||
| 68610 | /* walIndexRecover() might have returned SHORT_READ if a concurrent | ||||
| 68611 | ** writer truncated the WAL out from under it. If that happens, it | ||||
| 68612 | ** indicates that a writer has fixed the SHM file for us, so retry */ | ||||
| 68613 | if( rc==SQLITE_IOERR_SHORT_READ(10 | (2<<8)) ) rc = WAL_RETRY(-1); | ||||
| 68614 | } | ||||
| 68615 | pWal->exclusiveMode = WAL_NORMAL_MODE0; | ||||
| 68616 | } | ||||
| 68617 | |||||
| 68618 | return rc; | ||||
| 68619 | } | ||||
| 68620 | |||||
| 68621 | /* | ||||
| 68622 | ** Open a transaction in a connection where the shared-memory is read-only | ||||
| 68623 | ** and where we cannot verify that there is a separate write-capable connection | ||||
| 68624 | ** on hand to keep the shared-memory up-to-date with the WAL file. | ||||
| 68625 | ** | ||||
| 68626 | ** This can happen, for example, when the shared-memory is implemented by | ||||
| 68627 | ** memory-mapping a *-shm file, where a prior writer has shut down and | ||||
| 68628 | ** left the *-shm file on disk, and now the present connection is trying | ||||
| 68629 | ** to use that database but lacks write permission on the *-shm file. | ||||
| 68630 | ** Other scenarios are also possible, depending on the VFS implementation. | ||||
| 68631 | ** | ||||
| 68632 | ** Precondition: | ||||
| 68633 | ** | ||||
| 68634 | ** The *-wal file has been read and an appropriate wal-index has been | ||||
| 68635 | ** constructed in pWal->apWiData[] using heap memory instead of shared | ||||
| 68636 | ** memory. | ||||
| 68637 | ** | ||||
| 68638 | ** If this function returns SQLITE_OK, then the read transaction has | ||||
| 68639 | ** been successfully opened. In this case output variable (*pChanged) | ||||
| 68640 | ** is set to true before returning if the caller should discard the | ||||
| 68641 | ** contents of the page cache before proceeding. Or, if it returns | ||||
| 68642 | ** WAL_RETRY, then the heap memory wal-index has been discarded and | ||||
| 68643 | ** the caller should retry opening the read transaction from the | ||||
| 68644 | ** beginning (including attempting to map the *-shm file). | ||||
| 68645 | ** | ||||
| 68646 | ** If an error occurs, an SQLite error code is returned. | ||||
| 68647 | */ | ||||
| 68648 | static int walBeginShmUnreliable(Wal *pWal, int *pChanged){ | ||||
| 68649 | i64 szWal; /* Size of wal file on disk in bytes */ | ||||
| 68650 | i64 iOffset; /* Current offset when reading wal file */ | ||||
| 68651 | u8 aBuf[WAL_HDRSIZE32]; /* Buffer to load WAL header into */ | ||||
| 68652 | u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ | ||||
| 68653 | int szFrame; /* Number of bytes in buffer aFrame[] */ | ||||
| 68654 | u8 *aData; /* Pointer to data part of aFrame buffer */ | ||||
| 68655 | volatile void *pDummy; /* Dummy argument for xShmMap */ | ||||
| 68656 | int rc; /* Return code */ | ||||
| 68657 | u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */ | ||||
| 68658 | |||||
| 68659 | assert( pWal->bShmUnreliable )((void) (0)); | ||||
| 68660 | assert( pWal->readOnly & WAL_SHM_RDONLY )((void) (0)); | ||||
| 68661 | assert( pWal->nWiData>0 && pWal->apWiData[0] )((void) (0)); | ||||
| 68662 | |||||
| 68663 | /* Take WAL_READ_LOCK(0). This has the effect of preventing any | ||||
| 68664 | ** writers from running a checkpoint, but does not stop them | ||||
| 68665 | ** from running recovery. */ | ||||
| 68666 | rc = walLockShared(pWal, WAL_READ_LOCK(0)(3+(0))); | ||||
| 68667 | if( rc!=SQLITE_OK0 ){ | ||||
| 68668 | if( rc==SQLITE_BUSY5 ) rc = WAL_RETRY(-1); | ||||
| 68669 | goto begin_unreliable_shm_out; | ||||
| 68670 | } | ||||
| 68671 | pWal->readLock = 0; | ||||
| 68672 | |||||
| 68673 | /* Check to see if a separate writer has attached to the shared-memory area, | ||||
| 68674 | ** thus making the shared-memory "reliable" again. Do this by invoking | ||||
| 68675 | ** the xShmMap() routine of the VFS and looking to see if the return | ||||
| 68676 | ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT. | ||||
| 68677 | ** | ||||
| 68678 | ** If the shared-memory is now "reliable" return WAL_RETRY, which will | ||||
| 68679 | ** cause the heap-memory WAL-index to be discarded and the actual | ||||
| 68680 | ** shared memory to be used in its place. | ||||
| 68681 | ** | ||||
| 68682 | ** This step is important because, even though this connection is holding | ||||
| 68683 | ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might | ||||
| 68684 | ** have already checkpointed the WAL file and, while the current | ||||
| 68685 | ** is active, wrap the WAL and start overwriting frames that this | ||||
| 68686 | ** process wants to use. | ||||
| 68687 | ** | ||||
| 68688 | ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has | ||||
| 68689 | ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY | ||||
| 68690 | ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations, | ||||
| 68691 | ** even if some external agent does a "chmod" to make the shared-memory | ||||
| 68692 | ** writable by us, until sqlite3OsShmUnmap() has been called. | ||||
| 68693 | ** This is a requirement on the VFS implementation. | ||||
| 68694 | */ | ||||
| 68695 | rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ( sizeof(ht_slot)*(4096*2) + 4096*sizeof(u32) ), 0, &pDummy); | ||||
| 68696 | assert( rc!=SQLITE_OK )((void) (0)); /* SQLITE_OK not possible for read-only connection */ | ||||
| 68697 | if( rc!=SQLITE_READONLY_CANTINIT(8 | (5<<8)) ){ | ||||
| 68698 | rc = (rc==SQLITE_READONLY8 ? WAL_RETRY(-1) : rc); | ||||
| 68699 | goto begin_unreliable_shm_out; | ||||
| 68700 | } | ||||
| 68701 | |||||
| 68702 | /* We reach this point only if the real shared-memory is still unreliable. | ||||
| 68703 | ** Assume the in-memory WAL-index substitute is correct and load it | ||||
| 68704 | ** into pWal->hdr. | ||||
| 68705 | */ | ||||
| 68706 | memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr)); | ||||
| 68707 | |||||
| 68708 | /* Make sure some writer hasn't come in and changed the WAL file out | ||||
| 68709 | ** from under us, then disconnected, while we were not looking. | ||||
| 68710 | */ | ||||
| 68711 | rc = sqlite3OsFileSize(pWal->pWalFd, &szWal); | ||||
| 68712 | if( rc!=SQLITE_OK0 ){ | ||||
| 68713 | goto begin_unreliable_shm_out; | ||||
| 68714 | } | ||||
| 68715 | if( szWal<WAL_HDRSIZE32 ){ | ||||
| 68716 | /* If the wal file is too small to contain a wal-header and the | ||||
| 68717 | ** wal-index header has mxFrame==0, then it must be safe to proceed | ||||
| 68718 | ** reading the database file only. However, the page cache cannot | ||||
| 68719 | ** be trusted, as a read/write connection may have connected, written | ||||
| 68720 | ** the db, run a checkpoint, truncated the wal file and disconnected | ||||
| 68721 | ** since this client's last read transaction. */ | ||||
| 68722 | *pChanged = 1; | ||||
| 68723 | rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK0 : WAL_RETRY(-1)); | ||||
| 68724 | goto begin_unreliable_shm_out; | ||||
| 68725 | } | ||||
| 68726 | |||||
| 68727 | /* Check the salt keys at the start of the wal file still match. */ | ||||
| 68728 | rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE32, 0); | ||||
| 68729 | if( rc!=SQLITE_OK0 ){ | ||||
| 68730 | goto begin_unreliable_shm_out; | ||||
| 68731 | } | ||||
| 68732 | if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){ | ||||
| 68733 | /* Some writer has wrapped the WAL file while we were not looking. | ||||
| 68734 | ** Return WAL_RETRY which will cause the in-memory WAL-index to be | ||||
| 68735 | ** rebuilt. */ | ||||
| 68736 | rc = WAL_RETRY(-1); | ||||
| 68737 | goto begin_unreliable_shm_out; | ||||
| 68738 | } | ||||
| 68739 | |||||
| 68740 | /* Allocate a buffer to read frames into */ | ||||
| 68741 | assert( (pWal->szPage & (pWal->szPage-1))==0 )((void) (0)); | ||||
| 68742 | assert( pWal->szPage>=512 && pWal->szPage<=65536 )((void) (0)); | ||||
| 68743 | szFrame = pWal->szPage + WAL_FRAME_HDRSIZE24; | ||||
| 68744 | aFrame = (u8 *)sqlite3_malloc64(szFrame); | ||||
| 68745 | if( aFrame==0 ){ | ||||
| 68746 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 68747 | goto begin_unreliable_shm_out; | ||||
| 68748 | } | ||||
| 68749 | aData = &aFrame[WAL_FRAME_HDRSIZE24]; | ||||
| 68750 | |||||
| 68751 | /* Check to see if a complete transaction has been appended to the | ||||
| 68752 | ** wal file since the heap-memory wal-index was created. If so, the | ||||
| 68753 | ** heap-memory wal-index is discarded and WAL_RETRY returned to | ||||
| 68754 | ** the caller. */ | ||||
| 68755 | aSaveCksum[0] = pWal->hdr.aFrameCksum[0]; | ||||
| 68756 | aSaveCksum[1] = pWal->hdr.aFrameCksum[1]; | ||||
| 68757 | for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage)( 32 + ((pWal->hdr.mxFrame+1)-1)*(i64)((pWal->szPage)+24 ) ); | ||||
| 68758 | iOffset+szFrame<=szWal; | ||||
| 68759 | iOffset+=szFrame | ||||
| 68760 | ){ | ||||
| 68761 | u32 pgno; /* Database page number for frame */ | ||||
| 68762 | u32 nTruncate; /* dbsize field from frame header */ | ||||
| 68763 | |||||
| 68764 | /* Read and decode the next log frame. */ | ||||
| 68765 | rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); | ||||
| 68766 | if( rc!=SQLITE_OK0 ) break; | ||||
| 68767 | if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break; | ||||
| 68768 | |||||
| 68769 | /* If nTruncate is non-zero, then a complete transaction has been | ||||
| 68770 | ** appended to this wal file. Set rc to WAL_RETRY and break out of | ||||
| 68771 | ** the loop. */ | ||||
| 68772 | if( nTruncate ){ | ||||
| 68773 | rc = WAL_RETRY(-1); | ||||
| 68774 | break; | ||||
| 68775 | } | ||||
| 68776 | } | ||||
| 68777 | pWal->hdr.aFrameCksum[0] = aSaveCksum[0]; | ||||
| 68778 | pWal->hdr.aFrameCksum[1] = aSaveCksum[1]; | ||||
| 68779 | |||||
| 68780 | begin_unreliable_shm_out: | ||||
| 68781 | sqlite3_free(aFrame); | ||||
| 68782 | if( rc!=SQLITE_OK0 ){ | ||||
| 68783 | int i; | ||||
| 68784 | for(i=0; i<pWal->nWiData; i++){ | ||||
| 68785 | sqlite3_free((void*)pWal->apWiData[i]); | ||||
| 68786 | pWal->apWiData[i] = 0; | ||||
| 68787 | } | ||||
| 68788 | pWal->bShmUnreliable = 0; | ||||
| 68789 | sqlite3WalEndReadTransaction(pWal); | ||||
| 68790 | *pChanged = 1; | ||||
| 68791 | } | ||||
| 68792 | return rc; | ||||
| 68793 | } | ||||
| 68794 | |||||
| 68795 | /* | ||||
| 68796 | ** The final argument passed to walTryBeginRead() is of type (int*). The | ||||
| 68797 | ** caller should invoke walTryBeginRead as follows: | ||||
| 68798 | ** | ||||
| 68799 | ** int cnt = 0; | ||||
| 68800 | ** do { | ||||
| 68801 | ** rc = walTryBeginRead(..., &cnt); | ||||
| 68802 | ** }while( rc==WAL_RETRY ); | ||||
| 68803 | ** | ||||
| 68804 | ** The final value of "cnt" is of no use to the caller. It is used by | ||||
| 68805 | ** the implementation of walTryBeginRead() as follows: | ||||
| 68806 | ** | ||||
| 68807 | ** + Each time walTryBeginRead() is called, it is incremented. Once | ||||
| 68808 | ** it reaches WAL_RETRY_PROTOCOL_LIMIT - indicating that walTryBeginRead() | ||||
| 68809 | ** has many times been invoked and failed with WAL_RETRY - walTryBeginRead() | ||||
| 68810 | ** returns SQLITE_PROTOCOL. | ||||
| 68811 | ** | ||||
| 68812 | ** + If SQLITE_ENABLE_SETLK_TIMEOUT is defined and walTryBeginRead() failed | ||||
| 68813 | ** because a blocking lock timed out (SQLITE_BUSY_TIMEOUT from the OS | ||||
| 68814 | ** layer), the WAL_RETRY_BLOCKED_MASK bit is set in "cnt". In this case | ||||
| 68815 | ** the next invocation of walTryBeginRead() may omit an expected call to | ||||
| 68816 | ** sqlite3OsSleep(). There has already been a delay when the previous call | ||||
| 68817 | ** waited on a lock. | ||||
| 68818 | */ | ||||
| 68819 | #define WAL_RETRY_PROTOCOL_LIMIT100 100 | ||||
| 68820 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 68821 | # define WAL_RETRY_BLOCKED_MASK0 0x10000000 | ||||
| 68822 | #else | ||||
| 68823 | # define WAL_RETRY_BLOCKED_MASK0 0 | ||||
| 68824 | #endif | ||||
| 68825 | |||||
| 68826 | /* | ||||
| 68827 | ** Attempt to start a read transaction. This might fail due to a race or | ||||
| 68828 | ** other transient condition. When that happens, it returns WAL_RETRY to | ||||
| 68829 | ** indicate to the caller that it is safe to retry immediately. | ||||
| 68830 | ** | ||||
| 68831 | ** On success return SQLITE_OK. On a permanent failure (such an | ||||
| 68832 | ** I/O error or an SQLITE_BUSY because another process is running | ||||
| 68833 | ** recovery) return a positive error code. | ||||
| 68834 | ** | ||||
| 68835 | ** The useWal parameter is true to force the use of the WAL and disable | ||||
| 68836 | ** the case where the WAL is bypassed because it has been completely | ||||
| 68837 | ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr() | ||||
| 68838 | ** to make a copy of the wal-index header into pWal->hdr. If the | ||||
| 68839 | ** wal-index header has changed, *pChanged is set to 1 (as an indication | ||||
| 68840 | ** to the caller that the local page cache is obsolete and needs to be | ||||
| 68841 | ** flushed.) When useWal==1, the wal-index header is assumed to already | ||||
| 68842 | ** be loaded and the pChanged parameter is unused. | ||||
| 68843 | ** | ||||
| 68844 | ** The caller must set the cnt parameter to the number of prior calls to | ||||
| 68845 | ** this routine during the current read attempt that returned WAL_RETRY. | ||||
| 68846 | ** This routine will start taking more aggressive measures to clear the | ||||
| 68847 | ** race conditions after multiple WAL_RETRY returns, and after an excessive | ||||
| 68848 | ** number of errors will ultimately return SQLITE_PROTOCOL. The | ||||
| 68849 | ** SQLITE_PROTOCOL return indicates that some other process has gone rogue | ||||
| 68850 | ** and is not honoring the locking protocol. There is a vanishingly small | ||||
| 68851 | ** chance that SQLITE_PROTOCOL could be returned because of a run of really | ||||
| 68852 | ** bad luck when there is lots of contention for the wal-index, but that | ||||
| 68853 | ** possibility is so small that it can be safely neglected, we believe. | ||||
| 68854 | ** | ||||
| 68855 | ** On success, this routine obtains a read lock on | ||||
| 68856 | ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is | ||||
| 68857 | ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1) | ||||
| 68858 | ** that means the Wal does not hold any read lock. The reader must not | ||||
| 68859 | ** access any database page that is modified by a WAL frame up to and | ||||
| 68860 | ** including frame number aReadMark[pWal->readLock]. The reader will | ||||
| 68861 | ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0 | ||||
| 68862 | ** Or if pWal->readLock==0, then the reader will ignore the WAL | ||||
| 68863 | ** completely and get all content directly from the database file. | ||||
| 68864 | ** If the useWal parameter is 1 then the WAL will never be ignored and | ||||
| 68865 | ** this routine will always set pWal->readLock>0 on success. | ||||
| 68866 | ** When the read transaction is completed, the caller must release the | ||||
| 68867 | ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1. | ||||
| 68868 | ** | ||||
| 68869 | ** This routine uses the nBackfill and aReadMark[] fields of the header | ||||
| 68870 | ** to select a particular WAL_READ_LOCK() that strives to let the | ||||
| 68871 | ** checkpoint process do as much work as possible. This routine might | ||||
| 68872 | ** update values of the aReadMark[] array in the header, but if it does | ||||
| 68873 | ** so it takes care to hold an exclusive lock on the corresponding | ||||
| 68874 | ** WAL_READ_LOCK() while changing values. | ||||
| 68875 | */ | ||||
| 68876 | static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){ | ||||
| 68877 | volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */ | ||||
| 68878 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 68879 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 68880 | int nBlockTmout = 0; | ||||
| 68881 | #endif | ||||
| 68882 | |||||
| 68883 | assert( pWal->readLock<0 )((void) (0)); /* Not currently locked */ | ||||
| 68884 | |||||
| 68885 | /* useWal may only be set for read/write connections */ | ||||
| 68886 | assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 )((void) (0)); | ||||
| 68887 | |||||
| 68888 | /* Take steps to avoid spinning forever if there is a protocol error. | ||||
| 68889 | ** | ||||
| 68890 | ** Circumstances that cause a RETRY should only last for the briefest | ||||
| 68891 | ** instances of time. No I/O or other system calls are done while the | ||||
| 68892 | ** locks are held, so the locks should not be held for very long. But | ||||
| 68893 | ** if we are unlucky, another process that is holding a lock might get | ||||
| 68894 | ** paged out or take a page-fault that is time-consuming to resolve, | ||||
| 68895 | ** during the few nanoseconds that it is holding the lock. In that case, | ||||
| 68896 | ** it might take longer than normal for the lock to free. | ||||
| 68897 | ** | ||||
| 68898 | ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few | ||||
| 68899 | ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this | ||||
| 68900 | ** is more of a scheduler yield than an actual delay. But on the 10th | ||||
| 68901 | ** an subsequent retries, the delays start becoming longer and longer, | ||||
| 68902 | ** so that on the 100th (and last) RETRY we delay for 323 milliseconds. | ||||
| 68903 | ** The total delay time before giving up is less than 10 seconds. | ||||
| 68904 | */ | ||||
| 68905 | (*pCnt)++; | ||||
| 68906 | if( *pCnt>5 ){ | ||||
| 68907 | int nDelay = 1; /* Pause time in microseconds */ | ||||
| 68908 | int cnt = (*pCnt & ~WAL_RETRY_BLOCKED_MASK0); | ||||
| 68909 | if( cnt>WAL_RETRY_PROTOCOL_LIMIT100 ){ | ||||
| 68910 | VVA_ONLY( pWal->lockError = 1; ) | ||||
| 68911 | return SQLITE_PROTOCOL15; | ||||
| 68912 | } | ||||
| 68913 | if( *pCnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39; | ||||
| 68914 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 68915 | /* In SQLITE_ENABLE_SETLK_TIMEOUT builds, configure the file-descriptor | ||||
| 68916 | ** to block for locks for approximately nDelay us. This affects three | ||||
| 68917 | ** locks: (a) the shared lock taken on the DMS slot in os_unix.c (if | ||||
| 68918 | ** using os_unix.c), (b) the WRITER lock taken in walIndexReadHdr() if the | ||||
| 68919 | ** first attempted read fails, and (c) the shared lock taken on the | ||||
| 68920 | ** read-mark. | ||||
| 68921 | ** | ||||
| 68922 | ** If the previous call failed due to an SQLITE_BUSY_TIMEOUT error, | ||||
| 68923 | ** then sleep for the minimum of 1us. The previous call already provided | ||||
| 68924 | ** an extra delay while it was blocking on the lock. | ||||
| 68925 | */ | ||||
| 68926 | nBlockTmout = (nDelay+998) / 1000; | ||||
| 68927 | if( !useWal && walEnableBlockingMs(pWal, nBlockTmout)0 ){ | ||||
| 68928 | if( *pCnt & WAL_RETRY_BLOCKED_MASK0 ) nDelay = 1; | ||||
| 68929 | } | ||||
| 68930 | #endif | ||||
| 68931 | sqlite3OsSleep(pWal->pVfs, nDelay); | ||||
| 68932 | *pCnt &= ~WAL_RETRY_BLOCKED_MASK0; | ||||
| 68933 | } | ||||
| 68934 | |||||
| 68935 | if( !useWal ){ | ||||
| 68936 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 68937 | if( pWal->bShmUnreliable==0 ){ | ||||
| 68938 | rc = walIndexReadHdr(pWal, pChanged); | ||||
| 68939 | } | ||||
| 68940 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 68941 | if( rc==SQLITE_BUSY_TIMEOUT(5 | (3<<8)) ){ | ||||
| 68942 | rc = SQLITE_BUSY5; | ||||
| 68943 | *pCnt |= WAL_RETRY_BLOCKED_MASK0; | ||||
| 68944 | } | ||||
| 68945 | #endif | ||||
| 68946 | if( rc==SQLITE_BUSY5 ){ | ||||
| 68947 | /* If there is not a recovery running in another thread or process | ||||
| 68948 | ** then convert BUSY errors to WAL_RETRY. If recovery is known to | ||||
| 68949 | ** be running, convert BUSY to BUSY_RECOVERY. There is a race here | ||||
| 68950 | ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY | ||||
| 68951 | ** would be technically correct. But the race is benign since with | ||||
| 68952 | ** WAL_RETRY this routine will be called again and will probably be | ||||
| 68953 | ** right on the second iteration. | ||||
| 68954 | */ | ||||
| 68955 | (void)walEnableBlocking(pWal)0; | ||||
| 68956 | if( pWal->apWiData[0]==0 ){ | ||||
| 68957 | /* This branch is taken when the xShmMap() method returns SQLITE_BUSY. | ||||
| 68958 | ** We assume this is a transient condition, so return WAL_RETRY. The | ||||
| 68959 | ** xShmMap() implementation used by the default unix and win32 VFS | ||||
| 68960 | ** modules may return SQLITE_BUSY due to a race condition in the | ||||
| 68961 | ** code that determines whether or not the shared-memory region | ||||
| 68962 | ** must be zeroed before the requested page is returned. | ||||
| 68963 | */ | ||||
| 68964 | rc = WAL_RETRY(-1); | ||||
| 68965 | }else if( SQLITE_OK0==(rc = walLockShared(pWal, WAL_RECOVER_LOCK2)) ){ | ||||
| 68966 | walUnlockShared(pWal, WAL_RECOVER_LOCK2); | ||||
| 68967 | rc = WAL_RETRY(-1); | ||||
| 68968 | }else if( rc==SQLITE_BUSY5 ){ | ||||
| 68969 | rc = SQLITE_BUSY_RECOVERY(5 | (1<<8)); | ||||
| 68970 | } | ||||
| 68971 | } | ||||
| 68972 | walDisableBlocking(pWal); | ||||
| 68973 | if( rc!=SQLITE_OK0 ){ | ||||
| 68974 | return rc; | ||||
| 68975 | } | ||||
| 68976 | else if( pWal->bShmUnreliable ){ | ||||
| 68977 | return walBeginShmUnreliable(pWal, pChanged); | ||||
| 68978 | } | ||||
| 68979 | } | ||||
| 68980 | |||||
| 68981 | assert( pWal->nWiData>0 )((void) (0)); | ||||
| 68982 | assert( pWal->apWiData[0]!=0 )((void) (0)); | ||||
| 68983 | pInfo = walCkptInfo(pWal); | ||||
| 68984 | SEH_INJECT_FAULT((void) (0));; | ||||
| 68985 | { | ||||
| 68986 | u32 mxReadMark; /* Largest aReadMark[] value */ | ||||
| 68987 | int mxI; /* Index of largest aReadMark[] value */ | ||||
| 68988 | int i; /* Loop counter */ | ||||
| 68989 | u32 mxFrame; /* Wal frame to lock to */ | ||||
| 68990 | if( !useWal && AtomicLoad(&pInfo->nBackfill)__atomic_load_n((&pInfo->nBackfill),0)==pWal->hdr.mxFrame | ||||
| 68991 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 68992 | && ((pWal->bGetSnapshot==0 && pWal->pSnapshot==0) || pWal->hdr.mxFrame==0) | ||||
| 68993 | #endif | ||||
| 68994 | ){ | ||||
| 68995 | /* The WAL has been completely backfilled (or it is empty). | ||||
| 68996 | ** and can be safely ignored. | ||||
| 68997 | */ | ||||
| 68998 | rc = walLockShared(pWal, WAL_READ_LOCK(0)(3+(0))); | ||||
| 68999 | walShmBarrier(pWal); | ||||
| 69000 | if( rc==SQLITE_OK0 ){ | ||||
| 69001 | if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr,sizeof(WalIndexHdr)) ){ | ||||
| 69002 | /* It is not safe to allow the reader to continue here if frames | ||||
| 69003 | ** may have been appended to the log before READ_LOCK(0) was obtained. | ||||
| 69004 | ** When holding READ_LOCK(0), the reader ignores the entire log file, | ||||
| 69005 | ** which implies that the database file contains a trustworthy | ||||
| 69006 | ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from | ||||
| 69007 | ** happening, this is usually correct. | ||||
| 69008 | ** | ||||
| 69009 | ** However, if frames have been appended to the log (or if the log | ||||
| 69010 | ** is wrapped and written for that matter) before the READ_LOCK(0) | ||||
| 69011 | ** is obtained, that is not necessarily true. A checkpointer may | ||||
| 69012 | ** have started to backfill the appended frames but crashed before | ||||
| 69013 | ** it finished. Leaving a corrupt image in the database file. | ||||
| 69014 | */ | ||||
| 69015 | walUnlockShared(pWal, WAL_READ_LOCK(0)(3+(0))); | ||||
| 69016 | return WAL_RETRY(-1); | ||||
| 69017 | } | ||||
| 69018 | pWal->readLock = 0; | ||||
| 69019 | return SQLITE_OK0; | ||||
| 69020 | }else if( rc!=SQLITE_BUSY5 ){ | ||||
| 69021 | return rc; | ||||
| 69022 | } | ||||
| 69023 | } | ||||
| 69024 | |||||
| 69025 | /* If we get this far, it means that the reader will want to use | ||||
| 69026 | ** the WAL to get at content from recent commits. The job now is | ||||
| 69027 | ** to select one of the aReadMark[] entries that is closest to | ||||
| 69028 | ** but not exceeding pWal->hdr.mxFrame and lock that entry. | ||||
| 69029 | */ | ||||
| 69030 | mxReadMark = 0; | ||||
| 69031 | mxI = 0; | ||||
| 69032 | mxFrame = pWal->hdr.mxFrame; | ||||
| 69033 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 69034 | if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){ | ||||
| 69035 | mxFrame = pWal->pSnapshot->mxFrame; | ||||
| 69036 | } | ||||
| 69037 | #endif | ||||
| 69038 | for(i=1; i<WAL_NREADER(8 -3); i++){ | ||||
| 69039 | u32 thisMark = AtomicLoad(pInfo->aReadMark+i)__atomic_load_n((pInfo->aReadMark+i),0); SEH_INJECT_FAULT((void) (0));; | ||||
| 69040 | if( mxReadMark<=thisMark && thisMark<=mxFrame ){ | ||||
| 69041 | assert( thisMark!=READMARK_NOT_USED )((void) (0)); | ||||
| 69042 | mxReadMark = thisMark; | ||||
| 69043 | mxI = i; | ||||
| 69044 | } | ||||
| 69045 | } | ||||
| 69046 | if( (pWal->readOnly & WAL_SHM_RDONLY2)==0 | ||||
| 69047 | && (mxReadMark<mxFrame || mxI==0) | ||||
| 69048 | ){ | ||||
| 69049 | for(i=1; i<WAL_NREADER(8 -3); i++){ | ||||
| 69050 | rc = walLockExclusive(pWal, WAL_READ_LOCK(i)(3+(i)), 1); | ||||
| 69051 | if( rc==SQLITE_OK0 ){ | ||||
| 69052 | AtomicStore(pInfo->aReadMark+i,mxFrame)__atomic_store_n((pInfo->aReadMark+i),(mxFrame),0); | ||||
| 69053 | mxReadMark = mxFrame; | ||||
| 69054 | mxI = i; | ||||
| 69055 | walUnlockExclusive(pWal, WAL_READ_LOCK(i)(3+(i)), 1); | ||||
| 69056 | break; | ||||
| 69057 | }else if( rc!=SQLITE_BUSY5 ){ | ||||
| 69058 | return rc; | ||||
| 69059 | } | ||||
| 69060 | } | ||||
| 69061 | } | ||||
| 69062 | if( mxI==0 ){ | ||||
| 69063 | assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 )((void) (0)); | ||||
| 69064 | return rc==SQLITE_BUSY5 ? WAL_RETRY(-1) : SQLITE_READONLY_CANTINIT(8 | (5<<8)); | ||||
| 69065 | } | ||||
| 69066 | |||||
| 69067 | (void)walEnableBlockingMs(pWal, nBlockTmout)0; | ||||
| 69068 | rc = walLockShared(pWal, WAL_READ_LOCK(mxI)(3+(mxI))); | ||||
| 69069 | walDisableBlocking(pWal); | ||||
| 69070 | if( rc ){ | ||||
| 69071 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 69072 | if( rc==SQLITE_BUSY_TIMEOUT(5 | (3<<8)) ){ | ||||
| 69073 | *pCnt |= WAL_RETRY_BLOCKED_MASK0; | ||||
| 69074 | } | ||||
| 69075 | #else | ||||
| 69076 | assert( rc!=SQLITE_BUSY_TIMEOUT )((void) (0)); | ||||
| 69077 | #endif | ||||
| 69078 | assert((rc&0xFF)!=SQLITE_BUSY||rc==SQLITE_BUSY||rc==SQLITE_BUSY_TIMEOUT)((void) (0)); | ||||
| 69079 | return (rc&0xFF)==SQLITE_BUSY5 ? WAL_RETRY(-1) : rc; | ||||
| 69080 | } | ||||
| 69081 | /* Now that the read-lock has been obtained, check that neither the | ||||
| 69082 | ** value in the aReadMark[] array or the contents of the wal-index | ||||
| 69083 | ** header have changed. | ||||
| 69084 | ** | ||||
| 69085 | ** It is necessary to check that the wal-index header did not change | ||||
| 69086 | ** between the time it was read and when the shared-lock was obtained | ||||
| 69087 | ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility | ||||
| 69088 | ** that the log file may have been wrapped by a writer, or that frames | ||||
| 69089 | ** that occur later in the log than pWal->hdr.mxFrame may have been | ||||
| 69090 | ** copied into the database by a checkpointer. If either of these things | ||||
| 69091 | ** happened, then reading the database with the current value of | ||||
| 69092 | ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry | ||||
| 69093 | ** instead. | ||||
| 69094 | ** | ||||
| 69095 | ** Before checking that the live wal-index header has not changed | ||||
| 69096 | ** since it was read, set Wal.minFrame to the first frame in the wal | ||||
| 69097 | ** file that has not yet been checkpointed. This client will not need | ||||
| 69098 | ** to read any frames earlier than minFrame from the wal file - they | ||||
| 69099 | ** can be safely read directly from the database file. | ||||
| 69100 | ** | ||||
| 69101 | ** Because a ShmBarrier() call is made between taking the copy of | ||||
| 69102 | ** nBackfill and checking that the wal-header in shared-memory still | ||||
| 69103 | ** matches the one cached in pWal->hdr, it is guaranteed that the | ||||
| 69104 | ** checkpointer that set nBackfill was not working with a wal-index | ||||
| 69105 | ** header newer than that cached in pWal->hdr. If it were, that could | ||||
| 69106 | ** cause a problem. The checkpointer could omit to checkpoint | ||||
| 69107 | ** a version of page X that lies before pWal->minFrame (call that version | ||||
| 69108 | ** A) on the basis that there is a newer version (version B) of the same | ||||
| 69109 | ** page later in the wal file. But if version B happens to like past | ||||
| 69110 | ** frame pWal->hdr.mxFrame - then the client would incorrectly assume | ||||
| 69111 | ** that it can read version A from the database file. However, since | ||||
| 69112 | ** we can guarantee that the checkpointer that set nBackfill could not | ||||
| 69113 | ** see any pages past pWal->hdr.mxFrame, this problem does not come up. | ||||
| 69114 | */ | ||||
| 69115 | pWal->minFrame = AtomicLoad(&pInfo->nBackfill)__atomic_load_n((&pInfo->nBackfill),0)+1; SEH_INJECT_FAULT((void) (0));; | ||||
| 69116 | walShmBarrier(pWal); | ||||
| 69117 | if( AtomicLoad(pInfo->aReadMark+mxI)__atomic_load_n((pInfo->aReadMark+mxI),0)!=mxReadMark | ||||
| 69118 | || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) | ||||
| 69119 | ){ | ||||
| 69120 | walUnlockShared(pWal, WAL_READ_LOCK(mxI)(3+(mxI))); | ||||
| 69121 | return WAL_RETRY(-1); | ||||
| 69122 | }else{ | ||||
| 69123 | assert( mxReadMark<=pWal->hdr.mxFrame )((void) (0)); | ||||
| 69124 | pWal->readLock = (i16)mxI; | ||||
| 69125 | } | ||||
| 69126 | } | ||||
| 69127 | return rc; | ||||
| 69128 | } | ||||
| 69129 | |||||
| 69130 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 69131 | /* | ||||
| 69132 | ** This function does the work of sqlite3WalSnapshotRecover(). | ||||
| 69133 | */ | ||||
| 69134 | static int walSnapshotRecover( | ||||
| 69135 | Wal *pWal, /* WAL handle */ | ||||
| 69136 | void *pBuf1, /* Temp buffer pWal->szPage bytes in size */ | ||||
| 69137 | void *pBuf2 /* Temp buffer pWal->szPage bytes in size */ | ||||
| 69138 | ){ | ||||
| 69139 | int szPage = (int)pWal->szPage; | ||||
| 69140 | int rc; | ||||
| 69141 | i64 szDb; /* Size of db file in bytes */ | ||||
| 69142 | |||||
| 69143 | rc = sqlite3OsFileSize(pWal->pDbFd, &szDb); | ||||
| 69144 | if( rc==SQLITE_OK0 ){ | ||||
| 69145 | volatile WalCkptInfo *pInfo = walCkptInfo(pWal); | ||||
| 69146 | u32 i = pInfo->nBackfillAttempted; | ||||
| 69147 | for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill)__atomic_load_n((&pInfo->nBackfill),0); i--){ | ||||
| 69148 | WalHashLoc sLoc; /* Hash table location */ | ||||
| 69149 | u32 pgno; /* Page number in db file */ | ||||
| 69150 | i64 iDbOff; /* Offset of db file entry */ | ||||
| 69151 | i64 iWalOff; /* Offset of wal file entry */ | ||||
| 69152 | |||||
| 69153 | rc = walHashGet(pWal, walFramePage(i), &sLoc); | ||||
| 69154 | if( rc!=SQLITE_OK0 ) break; | ||||
| 69155 | assert( i - sLoc.iZero - 1 >=0 )((void) (0)); | ||||
| 69156 | pgno = sLoc.aPgno[i-sLoc.iZero-1]; | ||||
| 69157 | iDbOff = (i64)(pgno-1) * szPage; | ||||
| 69158 | |||||
| 69159 | if( iDbOff+szPage<=szDb ){ | ||||
| 69160 | iWalOff = walFrameOffset(i, szPage)( 32 + ((i)-1)*(i64)((szPage)+24) ) + WAL_FRAME_HDRSIZE24; | ||||
| 69161 | rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff); | ||||
| 69162 | |||||
| 69163 | if( rc==SQLITE_OK0 ){ | ||||
| 69164 | rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff); | ||||
| 69165 | } | ||||
| 69166 | |||||
| 69167 | if( rc!=SQLITE_OK0 || 0==memcmp(pBuf1, pBuf2, szPage) ){ | ||||
| 69168 | break; | ||||
| 69169 | } | ||||
| 69170 | } | ||||
| 69171 | |||||
| 69172 | pInfo->nBackfillAttempted = i-1; | ||||
| 69173 | } | ||||
| 69174 | } | ||||
| 69175 | |||||
| 69176 | return rc; | ||||
| 69177 | } | ||||
| 69178 | |||||
| 69179 | /* | ||||
| 69180 | ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted | ||||
| 69181 | ** variable so that older snapshots can be accessed. To do this, loop | ||||
| 69182 | ** through all wal frames from nBackfillAttempted to (nBackfill+1), | ||||
| 69183 | ** comparing their content to the corresponding page with the database | ||||
| 69184 | ** file, if any. Set nBackfillAttempted to the frame number of the | ||||
| 69185 | ** first frame for which the wal file content matches the db file. | ||||
| 69186 | ** | ||||
| 69187 | ** This is only really safe if the file-system is such that any page | ||||
| 69188 | ** writes made by earlier checkpointers were atomic operations, which | ||||
| 69189 | ** is not always true. It is also possible that nBackfillAttempted | ||||
| 69190 | ** may be left set to a value larger than expected, if a wal frame | ||||
| 69191 | ** contains content that duplicate of an earlier version of the same | ||||
| 69192 | ** page. | ||||
| 69193 | ** | ||||
| 69194 | ** SQLITE_OK is returned if successful, or an SQLite error code if an | ||||
| 69195 | ** error occurs. It is not an error if nBackfillAttempted cannot be | ||||
| 69196 | ** decreased at all. | ||||
| 69197 | */ | ||||
| 69198 | SQLITE_PRIVATEstatic int sqlite3WalSnapshotRecover(Wal *pWal){ | ||||
| 69199 | int rc; | ||||
| 69200 | |||||
| 69201 | assert( pWal->readLock>=0 )((void) (0)); | ||||
| 69202 | rc = walLockExclusive(pWal, WAL_CKPT_LOCK1, 1); | ||||
| 69203 | if( rc==SQLITE_OK0 ){ | ||||
| 69204 | void *pBuf1 = sqlite3_malloc(pWal->szPage); | ||||
| 69205 | void *pBuf2 = sqlite3_malloc(pWal->szPage); | ||||
| 69206 | if( pBuf1==0 || pBuf2==0 ){ | ||||
| 69207 | rc = SQLITE_NOMEM7; | ||||
| 69208 | }else{ | ||||
| 69209 | pWal->ckptLock = 1; | ||||
| 69210 | SEH_TRY; { | ||||
| 69211 | rc = walSnapshotRecover(pWal, pBuf1, pBuf2); | ||||
| 69212 | } | ||||
| 69213 | SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; ); ((void) (0)); | ||||
| 69214 | pWal->ckptLock = 0; | ||||
| 69215 | } | ||||
| 69216 | |||||
| 69217 | sqlite3_free(pBuf1); | ||||
| 69218 | sqlite3_free(pBuf2); | ||||
| 69219 | walUnlockExclusive(pWal, WAL_CKPT_LOCK1, 1); | ||||
| 69220 | } | ||||
| 69221 | |||||
| 69222 | return rc; | ||||
| 69223 | } | ||||
| 69224 | #endif /* SQLITE_ENABLE_SNAPSHOT */ | ||||
| 69225 | |||||
| 69226 | /* | ||||
| 69227 | ** This function does the work of sqlite3WalBeginReadTransaction() (see | ||||
| 69228 | ** below). That function simply calls this one inside an SEH_TRY{...} block. | ||||
| 69229 | */ | ||||
| 69230 | static int walBeginReadTransaction(Wal *pWal, int *pChanged){ | ||||
| 69231 | int rc; /* Return code */ | ||||
| 69232 | int cnt = 0; /* Number of TryBeginRead attempts */ | ||||
| 69233 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 69234 | int ckptLock = 0; | ||||
| 69235 | int bChanged = 0; | ||||
| 69236 | WalIndexHdr *pSnapshot = pWal->pSnapshot; | ||||
| 69237 | #endif | ||||
| 69238 | |||||
| 69239 | assert( pWal->ckptLock==0 )((void) (0)); | ||||
| 69240 | assert( pWal->nSehTry>0 )((void) (0)); | ||||
| 69241 | |||||
| 69242 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 69243 | if( pSnapshot ){ | ||||
| 69244 | if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ | ||||
| 69245 | bChanged = 1; | ||||
| 69246 | } | ||||
| 69247 | |||||
| 69248 | /* It is possible that there is a checkpointer thread running | ||||
| 69249 | ** concurrent with this code. If this is the case, it may be that the | ||||
| 69250 | ** checkpointer has already determined that it will checkpoint | ||||
| 69251 | ** snapshot X, where X is later in the wal file than pSnapshot, but | ||||
| 69252 | ** has not yet set the pInfo->nBackfillAttempted variable to indicate | ||||
| 69253 | ** its intent. To avoid the race condition this leads to, ensure that | ||||
| 69254 | ** there is no checkpointer process by taking a shared CKPT lock | ||||
| 69255 | ** before checking pInfo->nBackfillAttempted. */ | ||||
| 69256 | (void)walEnableBlocking(pWal)0; | ||||
| 69257 | rc = walLockShared(pWal, WAL_CKPT_LOCK1); | ||||
| 69258 | walDisableBlocking(pWal); | ||||
| 69259 | |||||
| 69260 | if( rc!=SQLITE_OK0 ){ | ||||
| 69261 | return rc; | ||||
| 69262 | } | ||||
| 69263 | ckptLock = 1; | ||||
| 69264 | } | ||||
| 69265 | #endif | ||||
| 69266 | |||||
| 69267 | do{ | ||||
| 69268 | rc = walTryBeginRead(pWal, pChanged, 0, &cnt); | ||||
| 69269 | }while( rc==WAL_RETRY(-1) ); | ||||
| 69270 | testcase( (rc&0xff)==SQLITE_BUSY ); | ||||
| 69271 | testcase( (rc&0xff)==SQLITE_IOERR ); | ||||
| 69272 | testcase( rc==SQLITE_PROTOCOL ); | ||||
| 69273 | testcase( rc==SQLITE_OK ); | ||||
| 69274 | |||||
| 69275 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 69276 | if( rc==SQLITE_OK0 ){ | ||||
| 69277 | if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ | ||||
| 69278 | /* At this point the client has a lock on an aReadMark[] slot holding | ||||
| 69279 | ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr | ||||
| 69280 | ** is populated with the wal-index header corresponding to the head | ||||
| 69281 | ** of the wal file. Verify that pSnapshot is still valid before | ||||
| 69282 | ** continuing. Reasons why pSnapshot might no longer be valid: | ||||
| 69283 | ** | ||||
| 69284 | ** (1) The WAL file has been reset since the snapshot was taken. | ||||
| 69285 | ** In this case, the salt will have changed. | ||||
| 69286 | ** | ||||
| 69287 | ** (2) A checkpoint as been attempted that wrote frames past | ||||
| 69288 | ** pSnapshot->mxFrame into the database file. Note that the | ||||
| 69289 | ** checkpoint need not have completed for this to cause problems. | ||||
| 69290 | */ | ||||
| 69291 | volatile WalCkptInfo *pInfo = walCkptInfo(pWal); | ||||
| 69292 | |||||
| 69293 | assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 )((void) (0)); | ||||
| 69294 | assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame )((void) (0)); | ||||
| 69295 | |||||
| 69296 | /* Check that the wal file has not been wrapped. Assuming that it has | ||||
| 69297 | ** not, also check that no checkpointer has attempted to checkpoint any | ||||
| 69298 | ** frames beyond pSnapshot->mxFrame. If either of these conditions are | ||||
| 69299 | ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr | ||||
| 69300 | ** with *pSnapshot and set *pChanged as appropriate for opening the | ||||
| 69301 | ** snapshot. */ | ||||
| 69302 | if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) | ||||
| 69303 | && pSnapshot->mxFrame>=pInfo->nBackfillAttempted | ||||
| 69304 | ){ | ||||
| 69305 | assert( pWal->readLock>0 )((void) (0)); | ||||
| 69306 | memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr)); | ||||
| 69307 | *pChanged = bChanged; | ||||
| 69308 | }else{ | ||||
| 69309 | rc = SQLITE_ERROR_SNAPSHOT(1 | (3<<8)); | ||||
| 69310 | } | ||||
| 69311 | |||||
| 69312 | /* A client using a non-current snapshot may not ignore any frames | ||||
| 69313 | ** from the start of the wal file. This is because, for a system | ||||
| 69314 | ** where (minFrame < iSnapshot < maxFrame), a checkpointer may | ||||
| 69315 | ** have omitted to checkpoint a frame earlier than minFrame in | ||||
| 69316 | ** the file because there exists a frame after iSnapshot that | ||||
| 69317 | ** is the same database page. */ | ||||
| 69318 | pWal->minFrame = 1; | ||||
| 69319 | |||||
| 69320 | if( rc!=SQLITE_OK0 ){ | ||||
| 69321 | sqlite3WalEndReadTransaction(pWal); | ||||
| 69322 | } | ||||
| 69323 | } | ||||
| 69324 | } | ||||
| 69325 | |||||
| 69326 | /* Release the shared CKPT lock obtained above. */ | ||||
| 69327 | if( ckptLock ){ | ||||
| 69328 | assert( pSnapshot )((void) (0)); | ||||
| 69329 | walUnlockShared(pWal, WAL_CKPT_LOCK1); | ||||
| 69330 | } | ||||
| 69331 | #endif | ||||
| 69332 | return rc; | ||||
| 69333 | } | ||||
| 69334 | |||||
| 69335 | /* | ||||
| 69336 | ** Begin a read transaction on the database. | ||||
| 69337 | ** | ||||
| 69338 | ** This routine used to be called sqlite3OpenSnapshot() and with good reason: | ||||
| 69339 | ** it takes a snapshot of the state of the WAL and wal-index for the current | ||||
| 69340 | ** instant in time. The current thread will continue to use this snapshot. | ||||
| 69341 | ** Other threads might append new content to the WAL and wal-index but | ||||
| 69342 | ** that extra content is ignored by the current thread. | ||||
| 69343 | ** | ||||
| 69344 | ** If the database contents have changes since the previous read | ||||
| 69345 | ** transaction, then *pChanged is set to 1 before returning. The | ||||
| 69346 | ** Pager layer will use this to know that its cache is stale and | ||||
| 69347 | ** needs to be flushed. | ||||
| 69348 | */ | ||||
| 69349 | SQLITE_PRIVATEstatic int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ | ||||
| 69350 | int rc; | ||||
| 69351 | SEH_TRY; { | ||||
| 69352 | rc = walBeginReadTransaction(pWal, pChanged); | ||||
| 69353 | } | ||||
| 69354 | SEH_EXCEPT( rc = walHandleException(pWal); ); ((void) (0)); | ||||
| 69355 | return rc; | ||||
| 69356 | } | ||||
| 69357 | |||||
| 69358 | /* | ||||
| 69359 | ** Finish with a read transaction. All this does is release the | ||||
| 69360 | ** read-lock. | ||||
| 69361 | */ | ||||
| 69362 | SQLITE_PRIVATEstatic void sqlite3WalEndReadTransaction(Wal *pWal){ | ||||
| 69363 | #ifndef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 69364 | assert( pWal->writeLock==0 || pWal->readLock<0 )((void) (0)); | ||||
| 69365 | #endif | ||||
| 69366 | if( pWal->readLock>=0 ){ | ||||
| 69367 | sqlite3WalEndWriteTransaction(pWal); | ||||
| 69368 | walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)(3+(pWal->readLock))); | ||||
| 69369 | pWal->readLock = -1; | ||||
| 69370 | } | ||||
| 69371 | } | ||||
| 69372 | |||||
| 69373 | /* | ||||
| 69374 | ** Search the wal file for page pgno. If found, set *piRead to the frame that | ||||
| 69375 | ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead | ||||
| 69376 | ** to zero. | ||||
| 69377 | ** | ||||
| 69378 | ** Return SQLITE_OK if successful, or an error code if an error occurs. If an | ||||
| 69379 | ** error does occur, the final value of *piRead is undefined. | ||||
| 69380 | */ | ||||
| 69381 | static int walFindFrame( | ||||
| 69382 | Wal *pWal, /* WAL handle */ | ||||
| 69383 | Pgno pgno, /* Database page number to read data for */ | ||||
| 69384 | u32 *piRead /* OUT: Frame number (or zero) */ | ||||
| 69385 | ){ | ||||
| 69386 | u32 iRead = 0; /* If !=0, WAL frame to return data from */ | ||||
| 69387 | u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */ | ||||
| 69388 | int iHash; /* Used to loop through N hash tables */ | ||||
| 69389 | int iMinHash; | ||||
| 69390 | |||||
| 69391 | /* This routine is only be called from within a read transaction. */ | ||||
| 69392 | assert( pWal->readLock>=0 || pWal->lockError )((void) (0)); | ||||
| 69393 | |||||
| 69394 | /* If the "last page" field of the wal-index header snapshot is 0, then | ||||
| 69395 | ** no data will be read from the wal under any circumstances. Return early | ||||
| 69396 | ** in this case as an optimization. Likewise, if pWal->readLock==0, | ||||
| 69397 | ** then the WAL is ignored by the reader so return early, as if the | ||||
| 69398 | ** WAL were empty. | ||||
| 69399 | */ | ||||
| 69400 | if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){ | ||||
| 69401 | *piRead = 0; | ||||
| 69402 | return SQLITE_OK0; | ||||
| 69403 | } | ||||
| 69404 | |||||
| 69405 | /* Search the hash table or tables for an entry matching page number | ||||
| 69406 | ** pgno. Each iteration of the following for() loop searches one | ||||
| 69407 | ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames). | ||||
| 69408 | ** | ||||
| 69409 | ** This code might run concurrently to the code in walIndexAppend() | ||||
| 69410 | ** that adds entries to the wal-index (and possibly to this hash | ||||
| 69411 | ** table). This means the value just read from the hash | ||||
| 69412 | ** slot (aHash[iKey]) may have been added before or after the | ||||
| 69413 | ** current read transaction was opened. Values added after the | ||||
| 69414 | ** read transaction was opened may have been written incorrectly - | ||||
| 69415 | ** i.e. these slots may contain garbage data. However, we assume | ||||
| 69416 | ** that any slots written before the current read transaction was | ||||
| 69417 | ** opened remain unmodified. | ||||
| 69418 | ** | ||||
| 69419 | ** For the reasons above, the if(...) condition featured in the inner | ||||
| 69420 | ** loop of the following block is more stringent that would be required | ||||
| 69421 | ** if we had exclusive access to the hash-table: | ||||
| 69422 | ** | ||||
| 69423 | ** (aPgno[iFrame]==pgno): | ||||
| 69424 | ** This condition filters out normal hash-table collisions. | ||||
| 69425 | ** | ||||
| 69426 | ** (iFrame<=iLast): | ||||
| 69427 | ** This condition filters out entries that were added to the hash | ||||
| 69428 | ** table after the current read-transaction had started. | ||||
| 69429 | */ | ||||
| 69430 | iMinHash = walFramePage(pWal->minFrame); | ||||
| 69431 | for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){ | ||||
| 69432 | WalHashLoc sLoc; /* Hash table location */ | ||||
| 69433 | int iKey; /* Hash slot index */ | ||||
| 69434 | int nCollide; /* Number of hash collisions remaining */ | ||||
| 69435 | int rc; /* Error code */ | ||||
| 69436 | u32 iH; | ||||
| 69437 | |||||
| 69438 | rc = walHashGet(pWal, iHash, &sLoc); | ||||
| 69439 | if( rc!=SQLITE_OK0 ){ | ||||
| 69440 | return rc; | ||||
| 69441 | } | ||||
| 69442 | nCollide = HASHTABLE_NSLOT(4096*2); | ||||
| 69443 | iKey = walHash(pgno); | ||||
| 69444 | SEH_INJECT_FAULT((void) (0));; | ||||
| 69445 | while( (iH = AtomicLoad(&sLoc.aHash[iKey])__atomic_load_n((&sLoc.aHash[iKey]),0))!=0 ){ | ||||
| 69446 | u32 iFrame = iH + sLoc.iZero; | ||||
| 69447 | if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){ | ||||
| 69448 | assert( iFrame>iRead || CORRUPT_DB )((void) (0)); | ||||
| 69449 | iRead = iFrame; | ||||
| 69450 | } | ||||
| 69451 | if( (nCollide--)==0 ){ | ||||
| 69452 | *piRead = 0; | ||||
| 69453 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(69453); | ||||
| 69454 | } | ||||
| 69455 | iKey = walNextHash(iKey); | ||||
| 69456 | } | ||||
| 69457 | if( iRead ) break; | ||||
| 69458 | } | ||||
| 69459 | |||||
| 69460 | #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT | ||||
| 69461 | /* If expensive assert() statements are available, do a linear search | ||||
| 69462 | ** of the wal-index file content. Make sure the results agree with the | ||||
| 69463 | ** result obtained using the hash indexes above. */ | ||||
| 69464 | { | ||||
| 69465 | u32 iRead2 = 0; | ||||
| 69466 | u32 iTest; | ||||
| 69467 | assert( pWal->bShmUnreliable || pWal->minFrame>0 )((void) (0)); | ||||
| 69468 | for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){ | ||||
| 69469 | if( walFramePgno(pWal, iTest)==pgno ){ | ||||
| 69470 | iRead2 = iTest; | ||||
| 69471 | break; | ||||
| 69472 | } | ||||
| 69473 | } | ||||
| 69474 | assert( iRead==iRead2 )((void) (0)); | ||||
| 69475 | } | ||||
| 69476 | #endif | ||||
| 69477 | |||||
| 69478 | *piRead = iRead; | ||||
| 69479 | return SQLITE_OK0; | ||||
| 69480 | } | ||||
| 69481 | |||||
| 69482 | /* | ||||
| 69483 | ** Search the wal file for page pgno. If found, set *piRead to the frame that | ||||
| 69484 | ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead | ||||
| 69485 | ** to zero. | ||||
| 69486 | ** | ||||
| 69487 | ** Return SQLITE_OK if successful, or an error code if an error occurs. If an | ||||
| 69488 | ** error does occur, the final value of *piRead is undefined. | ||||
| 69489 | ** | ||||
| 69490 | ** The difference between this function and walFindFrame() is that this | ||||
| 69491 | ** function wraps walFindFrame() in an SEH_TRY{...} block. | ||||
| 69492 | */ | ||||
| 69493 | SQLITE_PRIVATEstatic int sqlite3WalFindFrame( | ||||
| 69494 | Wal *pWal, /* WAL handle */ | ||||
| 69495 | Pgno pgno, /* Database page number to read data for */ | ||||
| 69496 | u32 *piRead /* OUT: Frame number (or zero) */ | ||||
| 69497 | ){ | ||||
| 69498 | int rc; | ||||
| 69499 | SEH_TRY; { | ||||
| 69500 | rc = walFindFrame(pWal, pgno, piRead); | ||||
| 69501 | } | ||||
| 69502 | SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; ); ((void) (0)); | ||||
| 69503 | return rc; | ||||
| 69504 | } | ||||
| 69505 | |||||
| 69506 | /* | ||||
| 69507 | ** Read the contents of frame iRead from the wal file into buffer pOut | ||||
| 69508 | ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an | ||||
| 69509 | ** error code otherwise. | ||||
| 69510 | */ | ||||
| 69511 | SQLITE_PRIVATEstatic int sqlite3WalReadFrame( | ||||
| 69512 | Wal *pWal, /* WAL handle */ | ||||
| 69513 | u32 iRead, /* Frame to read */ | ||||
| 69514 | int nOut, /* Size of buffer pOut in bytes */ | ||||
| 69515 | u8 *pOut /* Buffer to write page data to */ | ||||
| 69516 | ){ | ||||
| 69517 | int sz; | ||||
| 69518 | i64 iOffset; | ||||
| 69519 | sz = pWal->hdr.szPage; | ||||
| 69520 | sz = (sz&0xfe00) + ((sz&0x0001)<<16); | ||||
| 69521 | testcase( sz<=32768 ); | ||||
| 69522 | testcase( sz>=65536 ); | ||||
| 69523 | iOffset = walFrameOffset(iRead, sz)( 32 + ((iRead)-1)*(i64)((sz)+24) ) + WAL_FRAME_HDRSIZE24; | ||||
| 69524 | /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ | ||||
| 69525 | return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); | ||||
| 69526 | } | ||||
| 69527 | |||||
| 69528 | /* | ||||
| 69529 | ** Return the size of the database in pages (or zero, if unknown). | ||||
| 69530 | */ | ||||
| 69531 | SQLITE_PRIVATEstatic Pgno sqlite3WalDbsize(Wal *pWal){ | ||||
| 69532 | if( pWal && ALWAYS(pWal->readLock>=0)(pWal->readLock>=0) ){ | ||||
| 69533 | return pWal->hdr.nPage; | ||||
| 69534 | } | ||||
| 69535 | return 0; | ||||
| 69536 | } | ||||
| 69537 | |||||
| 69538 | |||||
| 69539 | /* | ||||
| 69540 | ** This function starts a write transaction on the WAL. | ||||
| 69541 | ** | ||||
| 69542 | ** A read transaction must have already been started by a prior call | ||||
| 69543 | ** to sqlite3WalBeginReadTransaction(). | ||||
| 69544 | ** | ||||
| 69545 | ** If another thread or process has written into the database since | ||||
| 69546 | ** the read transaction was started, then it is not possible for this | ||||
| 69547 | ** thread to write as doing so would cause a fork. So this routine | ||||
| 69548 | ** returns SQLITE_BUSY in that case and no write transaction is started. | ||||
| 69549 | ** | ||||
| 69550 | ** There can only be a single writer active at a time. | ||||
| 69551 | */ | ||||
| 69552 | SQLITE_PRIVATEstatic int sqlite3WalBeginWriteTransaction(Wal *pWal){ | ||||
| 69553 | int rc; | ||||
| 69554 | |||||
| 69555 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 69556 | /* If the write-lock is already held, then it was obtained before the | ||||
| 69557 | ** read-transaction was even opened, making this call a no-op. | ||||
| 69558 | ** Return early. */ | ||||
| 69559 | if( pWal->writeLock ){ | ||||
| 69560 | assert( !memcmp(&pWal->hdr,(void*)pWal->apWiData[0],sizeof(WalIndexHdr)) )((void) (0)); | ||||
| 69561 | return SQLITE_OK0; | ||||
| 69562 | } | ||||
| 69563 | #endif | ||||
| 69564 | |||||
| 69565 | /* Cannot start a write transaction without first holding a read | ||||
| 69566 | ** transaction. */ | ||||
| 69567 | assert( pWal->readLock>=0 )((void) (0)); | ||||
| 69568 | assert( pWal->writeLock==0 && pWal->iReCksum==0 )((void) (0)); | ||||
| 69569 | |||||
| 69570 | if( pWal->readOnly ){ | ||||
| 69571 | return SQLITE_READONLY8; | ||||
| 69572 | } | ||||
| 69573 | |||||
| 69574 | /* Only one writer allowed at a time. Get the write lock. Return | ||||
| 69575 | ** SQLITE_BUSY if unable. | ||||
| 69576 | */ | ||||
| 69577 | rc = walLockExclusive(pWal, WAL_WRITE_LOCK0, 1); | ||||
| 69578 | if( rc ){ | ||||
| 69579 | return rc; | ||||
| 69580 | } | ||||
| 69581 | pWal->writeLock = 1; | ||||
| 69582 | |||||
| 69583 | /* If another connection has written to the database file since the | ||||
| 69584 | ** time the read transaction on this connection was started, then | ||||
| 69585 | ** the write is disallowed. | ||||
| 69586 | */ | ||||
| 69587 | SEH_TRY; { | ||||
| 69588 | if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){ | ||||
| 69589 | rc = SQLITE_BUSY_SNAPSHOT(5 | (2<<8)); | ||||
| 69590 | } | ||||
| 69591 | } | ||||
| 69592 | SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; ); ((void) (0)); | ||||
| 69593 | |||||
| 69594 | if( rc!=SQLITE_OK0 ){ | ||||
| 69595 | walUnlockExclusive(pWal, WAL_WRITE_LOCK0, 1); | ||||
| 69596 | pWal->writeLock = 0; | ||||
| 69597 | } | ||||
| 69598 | return rc; | ||||
| 69599 | } | ||||
| 69600 | |||||
| 69601 | /* | ||||
| 69602 | ** End a write transaction. The commit has already been done. This | ||||
| 69603 | ** routine merely releases the lock. | ||||
| 69604 | */ | ||||
| 69605 | SQLITE_PRIVATEstatic int sqlite3WalEndWriteTransaction(Wal *pWal){ | ||||
| 69606 | if( pWal->writeLock ){ | ||||
| 69607 | walUnlockExclusive(pWal, WAL_WRITE_LOCK0, 1); | ||||
| 69608 | pWal->writeLock = 0; | ||||
| 69609 | pWal->iReCksum = 0; | ||||
| 69610 | pWal->truncateOnCommit = 0; | ||||
| 69611 | } | ||||
| 69612 | return SQLITE_OK0; | ||||
| 69613 | } | ||||
| 69614 | |||||
| 69615 | /* | ||||
| 69616 | ** If any data has been written (but not committed) to the log file, this | ||||
| 69617 | ** function moves the write-pointer back to the start of the transaction. | ||||
| 69618 | ** | ||||
| 69619 | ** Additionally, the callback function is invoked for each frame written | ||||
| 69620 | ** to the WAL since the start of the transaction. If the callback returns | ||||
| 69621 | ** other than SQLITE_OK, it is not invoked again and the error code is | ||||
| 69622 | ** returned to the caller. | ||||
| 69623 | ** | ||||
| 69624 | ** Otherwise, if the callback function does not return an error, this | ||||
| 69625 | ** function returns SQLITE_OK. | ||||
| 69626 | */ | ||||
| 69627 | SQLITE_PRIVATEstatic int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ | ||||
| 69628 | int rc = SQLITE_OK0; | ||||
| 69629 | if( ALWAYS(pWal->writeLock)(pWal->writeLock) ){ | ||||
| 69630 | Pgno iMax = pWal->hdr.mxFrame; | ||||
| 69631 | Pgno iFrame; | ||||
| 69632 | |||||
| 69633 | SEH_TRY; { | ||||
| 69634 | /* Restore the clients cache of the wal-index header to the state it | ||||
| 69635 | ** was in before the client began writing to the database. | ||||
| 69636 | */ | ||||
| 69637 | memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); | ||||
| 69638 | |||||
| 69639 | for(iFrame=pWal->hdr.mxFrame+1; | ||||
| 69640 | ALWAYS(rc==SQLITE_OK)(rc==0) && iFrame<=iMax; | ||||
| 69641 | iFrame++ | ||||
| 69642 | ){ | ||||
| 69643 | /* This call cannot fail. Unless the page for which the page number | ||||
| 69644 | ** is passed as the second argument is (a) in the cache and | ||||
| 69645 | ** (b) has an outstanding reference, then xUndo is either a no-op | ||||
| 69646 | ** (if (a) is false) or simply expels the page from the cache (if (b) | ||||
| 69647 | ** is false). | ||||
| 69648 | ** | ||||
| 69649 | ** If the upper layer is doing a rollback, it is guaranteed that there | ||||
| 69650 | ** are no outstanding references to any page other than page 1. And | ||||
| 69651 | ** page 1 is never written to the log until the transaction is | ||||
| 69652 | ** committed. As a result, the call to xUndo may not fail. | ||||
| 69653 | */ | ||||
| 69654 | assert( walFramePgno(pWal, iFrame)!=1 )((void) (0)); | ||||
| 69655 | rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame)); | ||||
| 69656 | } | ||||
| 69657 | if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal); | ||||
| 69658 | } | ||||
| 69659 | SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; ); ((void) (0)); | ||||
| 69660 | pWal->iReCksum = 0; | ||||
| 69661 | } | ||||
| 69662 | return rc; | ||||
| 69663 | } | ||||
| 69664 | |||||
| 69665 | /* | ||||
| 69666 | ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 | ||||
| 69667 | ** values. This function populates the array with values required to | ||||
| 69668 | ** "rollback" the write position of the WAL handle back to the current | ||||
| 69669 | ** point in the event of a savepoint rollback (via WalSavepointUndo()). | ||||
| 69670 | */ | ||||
| 69671 | SQLITE_PRIVATEstatic void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ | ||||
| 69672 | assert( pWal->writeLock )((void) (0)); | ||||
| 69673 | aWalData[0] = pWal->hdr.mxFrame; | ||||
| 69674 | aWalData[1] = pWal->hdr.aFrameCksum[0]; | ||||
| 69675 | aWalData[2] = pWal->hdr.aFrameCksum[1]; | ||||
| 69676 | aWalData[3] = pWal->nCkpt; | ||||
| 69677 | } | ||||
| 69678 | |||||
| 69679 | /* | ||||
| 69680 | ** Move the write position of the WAL back to the point identified by | ||||
| 69681 | ** the values in the aWalData[] array. aWalData must point to an array | ||||
| 69682 | ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated | ||||
| 69683 | ** by a call to WalSavepoint(). | ||||
| 69684 | */ | ||||
| 69685 | SQLITE_PRIVATEstatic int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ | ||||
| 69686 | int rc = SQLITE_OK0; | ||||
| 69687 | |||||
| 69688 | assert( pWal->writeLock )((void) (0)); | ||||
| 69689 | assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame )((void) (0)); | ||||
| 69690 | |||||
| 69691 | if( aWalData[3]!=pWal->nCkpt ){ | ||||
| 69692 | /* This savepoint was opened immediately after the write-transaction | ||||
| 69693 | ** was started. Right after that, the writer decided to wrap around | ||||
| 69694 | ** to the start of the log. Update the savepoint values to match. | ||||
| 69695 | */ | ||||
| 69696 | aWalData[0] = 0; | ||||
| 69697 | aWalData[3] = pWal->nCkpt; | ||||
| 69698 | } | ||||
| 69699 | |||||
| 69700 | if( aWalData[0]<pWal->hdr.mxFrame ){ | ||||
| 69701 | pWal->hdr.mxFrame = aWalData[0]; | ||||
| 69702 | pWal->hdr.aFrameCksum[0] = aWalData[1]; | ||||
| 69703 | pWal->hdr.aFrameCksum[1] = aWalData[2]; | ||||
| 69704 | SEH_TRY; { | ||||
| 69705 | walCleanupHash(pWal); | ||||
| 69706 | } | ||||
| 69707 | SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; ); ((void) (0)); | ||||
| 69708 | if( pWal->iReCksum>pWal->hdr.mxFrame ){ | ||||
| 69709 | pWal->iReCksum = 0; | ||||
| 69710 | } | ||||
| 69711 | } | ||||
| 69712 | |||||
| 69713 | return rc; | ||||
| 69714 | } | ||||
| 69715 | |||||
| 69716 | /* | ||||
| 69717 | ** This function is called just before writing a set of frames to the log | ||||
| 69718 | ** file (see sqlite3WalFrames()). It checks to see if, instead of appending | ||||
| 69719 | ** to the current log file, it is possible to overwrite the start of the | ||||
| 69720 | ** existing log file with the new frames (i.e. "reset" the log). If so, | ||||
| 69721 | ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left | ||||
| 69722 | ** unchanged. | ||||
| 69723 | ** | ||||
| 69724 | ** SQLITE_OK is returned if no error is encountered (regardless of whether | ||||
| 69725 | ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned | ||||
| 69726 | ** if an error occurs. | ||||
| 69727 | */ | ||||
| 69728 | static int walRestartLog(Wal *pWal){ | ||||
| 69729 | int rc = SQLITE_OK0; | ||||
| 69730 | int cnt; | ||||
| 69731 | |||||
| 69732 | if( pWal->readLock==0 ){ | ||||
| 69733 | volatile WalCkptInfo *pInfo = walCkptInfo(pWal); | ||||
| 69734 | assert( pInfo->nBackfill==pWal->hdr.mxFrame )((void) (0)); | ||||
| 69735 | if( pInfo->nBackfill>0 ){ | ||||
| 69736 | u32 salt1; | ||||
| 69737 | sqlite3_randomness(4, &salt1); | ||||
| 69738 | rc = walLockExclusive(pWal, WAL_READ_LOCK(1)(3+(1)), WAL_NREADER(8 -3)-1); | ||||
| 69739 | if( rc==SQLITE_OK0 ){ | ||||
| 69740 | /* If all readers are using WAL_READ_LOCK(0) (in other words if no | ||||
| 69741 | ** readers are currently using the WAL), then the transactions | ||||
| 69742 | ** frames will overwrite the start of the existing log. Update the | ||||
| 69743 | ** wal-index header to reflect this. | ||||
| 69744 | ** | ||||
| 69745 | ** In theory it would be Ok to update the cache of the header only | ||||
| 69746 | ** at this point. But updating the actual wal-index header is also | ||||
| 69747 | ** safe and means there is no special case for sqlite3WalUndo() | ||||
| 69748 | ** to handle if this transaction is rolled back. */ | ||||
| 69749 | walRestartHdr(pWal, salt1); | ||||
| 69750 | walUnlockExclusive(pWal, WAL_READ_LOCK(1)(3+(1)), WAL_NREADER(8 -3)-1); | ||||
| 69751 | }else if( rc!=SQLITE_BUSY5 ){ | ||||
| 69752 | return rc; | ||||
| 69753 | } | ||||
| 69754 | } | ||||
| 69755 | walUnlockShared(pWal, WAL_READ_LOCK(0)(3+(0))); | ||||
| 69756 | pWal->readLock = -1; | ||||
| 69757 | cnt = 0; | ||||
| 69758 | do{ | ||||
| 69759 | int notUsed; | ||||
| 69760 | rc = walTryBeginRead(pWal, ¬Used, 1, &cnt); | ||||
| 69761 | }while( rc==WAL_RETRY(-1) ); | ||||
| 69762 | assert( (rc&0xff)!=SQLITE_BUSY )((void) (0)); /* BUSY not possible when useWal==1 */ | ||||
| 69763 | testcase( (rc&0xff)==SQLITE_IOERR ); | ||||
| 69764 | testcase( rc==SQLITE_PROTOCOL ); | ||||
| 69765 | testcase( rc==SQLITE_OK ); | ||||
| 69766 | } | ||||
| 69767 | return rc; | ||||
| 69768 | } | ||||
| 69769 | |||||
| 69770 | /* | ||||
| 69771 | ** Information about the current state of the WAL file and where | ||||
| 69772 | ** the next fsync should occur - passed from sqlite3WalFrames() into | ||||
| 69773 | ** walWriteToLog(). | ||||
| 69774 | */ | ||||
| 69775 | typedef struct WalWriter { | ||||
| 69776 | Wal *pWal; /* The complete WAL information */ | ||||
| 69777 | sqlite3_file *pFd; /* The WAL file to which we write */ | ||||
| 69778 | sqlite3_int64 iSyncPoint; /* Fsync at this offset */ | ||||
| 69779 | int syncFlags; /* Flags for the fsync */ | ||||
| 69780 | int szPage; /* Size of one page */ | ||||
| 69781 | } WalWriter; | ||||
| 69782 | |||||
| 69783 | /* | ||||
| 69784 | ** Write iAmt bytes of content into the WAL file beginning at iOffset. | ||||
| 69785 | ** Do a sync when crossing the p->iSyncPoint boundary. | ||||
| 69786 | ** | ||||
| 69787 | ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt, | ||||
| 69788 | ** first write the part before iSyncPoint, then sync, then write the | ||||
| 69789 | ** rest. | ||||
| 69790 | */ | ||||
| 69791 | static int walWriteToLog( | ||||
| 69792 | WalWriter *p, /* WAL to write to */ | ||||
| 69793 | void *pContent, /* Content to be written */ | ||||
| 69794 | int iAmt, /* Number of bytes to write */ | ||||
| 69795 | sqlite3_int64 iOffset /* Start writing at this offset */ | ||||
| 69796 | ){ | ||||
| 69797 | int rc; | ||||
| 69798 | if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){ | ||||
| 69799 | int iFirstAmt = (int)(p->iSyncPoint - iOffset); | ||||
| 69800 | rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); | ||||
| 69801 | if( rc ) return rc; | ||||
| 69802 | iOffset += iFirstAmt; | ||||
| 69803 | iAmt -= iFirstAmt; | ||||
| 69804 | pContent = (void*)(iFirstAmt + (char*)pContent); | ||||
| 69805 | assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 )((void) (0)); | ||||
| 69806 | rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags)((p->syncFlags)&0x03)); | ||||
| 69807 | if( iAmt==0 || rc ) return rc; | ||||
| 69808 | } | ||||
| 69809 | rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); | ||||
| 69810 | return rc; | ||||
| 69811 | } | ||||
| 69812 | |||||
| 69813 | /* | ||||
| 69814 | ** Write out a single frame of the WAL | ||||
| 69815 | */ | ||||
| 69816 | static int walWriteOneFrame( | ||||
| 69817 | WalWriter *p, /* Where to write the frame */ | ||||
| 69818 | PgHdr *pPage, /* The page of the frame to be written */ | ||||
| 69819 | int nTruncate, /* The commit flag. Usually 0. >0 for commit */ | ||||
| 69820 | sqlite3_int64 iOffset /* Byte offset at which to write */ | ||||
| 69821 | ){ | ||||
| 69822 | int rc; /* Result code from subfunctions */ | ||||
| 69823 | void *pData; /* Data actually written */ | ||||
| 69824 | u8 aFrame[WAL_FRAME_HDRSIZE24]; /* Buffer to assemble frame-header in */ | ||||
| 69825 | pData = pPage->pData; | ||||
| 69826 | walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame); | ||||
| 69827 | rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset); | ||||
| 69828 | if( rc ) return rc; | ||||
| 69829 | /* Write the page data */ | ||||
| 69830 | rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame)); | ||||
| 69831 | return rc; | ||||
| 69832 | } | ||||
| 69833 | |||||
| 69834 | /* | ||||
| 69835 | ** This function is called as part of committing a transaction within which | ||||
| 69836 | ** one or more frames have been overwritten. It updates the checksums for | ||||
| 69837 | ** all frames written to the wal file by the current transaction starting | ||||
| 69838 | ** with the earliest to have been overwritten. | ||||
| 69839 | ** | ||||
| 69840 | ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. | ||||
| 69841 | */ | ||||
| 69842 | static int walRewriteChecksums(Wal *pWal, u32 iLast){ | ||||
| 69843 | const int szPage = pWal->szPage;/* Database page size */ | ||||
| 69844 | int rc = SQLITE_OK0; /* Return code */ | ||||
| 69845 | u8 *aBuf; /* Buffer to load data from wal file into */ | ||||
| 69846 | u8 aFrame[WAL_FRAME_HDRSIZE24]; /* Buffer to assemble frame-headers in */ | ||||
| 69847 | u32 iRead; /* Next frame to read from wal file */ | ||||
| 69848 | i64 iCksumOff; | ||||
| 69849 | |||||
| 69850 | aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE24); | ||||
| 69851 | if( aBuf==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 69852 | |||||
| 69853 | /* Find the checksum values to use as input for the recalculating the | ||||
| 69854 | ** first checksum. If the first frame is frame 1 (implying that the current | ||||
| 69855 | ** transaction restarted the wal file), these values must be read from the | ||||
| 69856 | ** wal-file header. Otherwise, read them from the frame header of the | ||||
| 69857 | ** previous frame. */ | ||||
| 69858 | assert( pWal->iReCksum>0 )((void) (0)); | ||||
| 69859 | if( pWal->iReCksum==1 ){ | ||||
| 69860 | iCksumOff = 24; | ||||
| 69861 | }else{ | ||||
| 69862 | iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage)( 32 + ((pWal->iReCksum-1)-1)*(i64)((szPage)+24) ) + 16; | ||||
| 69863 | } | ||||
| 69864 | rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff); | ||||
| 69865 | pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf); | ||||
| 69866 | pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]); | ||||
| 69867 | |||||
| 69868 | iRead = pWal->iReCksum; | ||||
| 69869 | pWal->iReCksum = 0; | ||||
| 69870 | for(; rc==SQLITE_OK0 && iRead<=iLast; iRead++){ | ||||
| 69871 | i64 iOff = walFrameOffset(iRead, szPage)( 32 + ((iRead)-1)*(i64)((szPage)+24) ); | ||||
| 69872 | rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE24, iOff); | ||||
| 69873 | if( rc==SQLITE_OK0 ){ | ||||
| 69874 | u32 iPgno, nDbSize; | ||||
| 69875 | iPgno = sqlite3Get4byte(aBuf); | ||||
| 69876 | nDbSize = sqlite3Get4byte(&aBuf[4]); | ||||
| 69877 | |||||
| 69878 | walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE24], aFrame); | ||||
| 69879 | rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff); | ||||
| 69880 | } | ||||
| 69881 | } | ||||
| 69882 | |||||
| 69883 | sqlite3_free(aBuf); | ||||
| 69884 | return rc; | ||||
| 69885 | } | ||||
| 69886 | |||||
| 69887 | /* | ||||
| 69888 | ** Write a set of frames to the log. The caller must hold the write-lock | ||||
| 69889 | ** on the log file (obtained using sqlite3WalBeginWriteTransaction()). | ||||
| 69890 | */ | ||||
| 69891 | static int walFrames( | ||||
| 69892 | Wal *pWal, /* Wal handle to write to */ | ||||
| 69893 | int szPage, /* Database page-size in bytes */ | ||||
| 69894 | PgHdr *pList, /* List of dirty pages to write */ | ||||
| 69895 | Pgno nTruncate, /* Database size after this commit */ | ||||
| 69896 | int isCommit, /* True if this is a commit */ | ||||
| 69897 | int sync_flags /* Flags to pass to OsSync() (or 0) */ | ||||
| 69898 | ){ | ||||
| 69899 | int rc; /* Used to catch return codes */ | ||||
| 69900 | u32 iFrame; /* Next frame address */ | ||||
| 69901 | PgHdr *p; /* Iterator to run through pList with. */ | ||||
| 69902 | PgHdr *pLast = 0; /* Last frame in list */ | ||||
| 69903 | int nExtra = 0; /* Number of extra copies of last page */ | ||||
| 69904 | int szFrame; /* The size of a single frame */ | ||||
| 69905 | i64 iOffset; /* Next byte to write in WAL file */ | ||||
| 69906 | WalWriter w; /* The writer */ | ||||
| 69907 | u32 iFirst = 0; /* First frame that may be overwritten */ | ||||
| 69908 | WalIndexHdr *pLive; /* Pointer to shared header */ | ||||
| 69909 | |||||
| 69910 | assert( pList )((void) (0)); | ||||
| 69911 | assert( pWal->writeLock )((void) (0)); | ||||
| 69912 | |||||
| 69913 | /* If this frame set completes a transaction, then nTruncate>0. If | ||||
| 69914 | ** nTruncate==0 then this frame set does not complete the transaction. */ | ||||
| 69915 | assert( (isCommit!=0)==(nTruncate!=0) )((void) (0)); | ||||
| 69916 | |||||
| 69917 | #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) | ||||
| 69918 | { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){} | ||||
| 69919 | WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n", | ||||
| 69920 | pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill")); | ||||
| 69921 | } | ||||
| 69922 | #endif | ||||
| 69923 | |||||
| 69924 | pLive = (WalIndexHdr*)walIndexHdr(pWal); | ||||
| 69925 | if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){ | ||||
| 69926 | iFirst = pLive->mxFrame+1; | ||||
| 69927 | } | ||||
| 69928 | |||||
| 69929 | /* See if it is possible to write these frames into the start of the | ||||
| 69930 | ** log file, instead of appending to it at pWal->hdr.mxFrame. | ||||
| 69931 | */ | ||||
| 69932 | if( SQLITE_OK0!=(rc = walRestartLog(pWal)) ){ | ||||
| 69933 | return rc; | ||||
| 69934 | } | ||||
| 69935 | |||||
| 69936 | /* If this is the first frame written into the log, write the WAL | ||||
| 69937 | ** header to the start of the WAL file. See comments at the top of | ||||
| 69938 | ** this source file for a description of the WAL header format. | ||||
| 69939 | */ | ||||
| 69940 | iFrame = pWal->hdr.mxFrame; | ||||
| 69941 | if( iFrame==0 ){ | ||||
| 69942 | u8 aWalHdr[WAL_HDRSIZE32]; /* Buffer to assemble wal-header in */ | ||||
| 69943 | u32 aCksum[2]; /* Checksum for wal-header */ | ||||
| 69944 | |||||
| 69945 | sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC0x377f0682 | SQLITE_BIGENDIAN0)); | ||||
| 69946 | sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION3007000); | ||||
| 69947 | sqlite3Put4byte(&aWalHdr[8], szPage); | ||||
| 69948 | sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); | ||||
| 69949 | if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); | ||||
| 69950 | memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); | ||||
| 69951 | walChecksumBytes(1, aWalHdr, WAL_HDRSIZE32-2*4, 0, aCksum); | ||||
| 69952 | sqlite3Put4byte(&aWalHdr[24], aCksum[0]); | ||||
| 69953 | sqlite3Put4byte(&aWalHdr[28], aCksum[1]); | ||||
| 69954 | |||||
| 69955 | pWal->szPage = szPage; | ||||
| 69956 | pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN0; | ||||
| 69957 | pWal->hdr.aFrameCksum[0] = aCksum[0]; | ||||
| 69958 | pWal->hdr.aFrameCksum[1] = aCksum[1]; | ||||
| 69959 | pWal->truncateOnCommit = 1; | ||||
| 69960 | |||||
| 69961 | rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); | ||||
| 69962 | WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok")); | ||||
| 69963 | if( rc!=SQLITE_OK0 ){ | ||||
| 69964 | return rc; | ||||
| 69965 | } | ||||
| 69966 | |||||
| 69967 | /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless | ||||
| 69968 | ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise | ||||
| 69969 | ** an out-of-order write following a WAL restart could result in | ||||
| 69970 | ** database corruption. See the ticket: | ||||
| 69971 | ** | ||||
| 69972 | ** https://sqlite.org/src/info/ff5be73dee | ||||
| 69973 | */ | ||||
| 69974 | if( pWal->syncHeader ){ | ||||
| 69975 | rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)(((sync_flags)>>2)&0x03)); | ||||
| 69976 | if( rc ) return rc; | ||||
| 69977 | } | ||||
| 69978 | } | ||||
| 69979 | if( (int)pWal->szPage!=szPage ){ | ||||
| 69980 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(69980); /* TH3 test case: cov1/corrupt155.test */ | ||||
| 69981 | } | ||||
| 69982 | |||||
| 69983 | /* Setup information needed to write frames into the WAL */ | ||||
| 69984 | w.pWal = pWal; | ||||
| 69985 | w.pFd = pWal->pWalFd; | ||||
| 69986 | w.iSyncPoint = 0; | ||||
| 69987 | w.syncFlags = sync_flags; | ||||
| 69988 | w.szPage = szPage; | ||||
| 69989 | iOffset = walFrameOffset(iFrame+1, szPage)( 32 + ((iFrame+1)-1)*(i64)((szPage)+24) ); | ||||
| 69990 | szFrame = szPage + WAL_FRAME_HDRSIZE24; | ||||
| 69991 | |||||
| 69992 | /* Write all frames into the log file exactly once */ | ||||
| 69993 | for(p=pList; p; p=p->pDirty){ | ||||
| 69994 | int nDbSize; /* 0 normally. Positive == commit flag */ | ||||
| 69995 | |||||
| 69996 | /* Check if this page has already been written into the wal file by | ||||
| 69997 | ** the current transaction. If so, overwrite the existing frame and | ||||
| 69998 | ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that | ||||
| 69999 | ** checksums must be recomputed when the transaction is committed. */ | ||||
| 70000 | if( iFirst && (p->pDirty || isCommit==0) ){ | ||||
| 70001 | u32 iWrite = 0; | ||||
| 70002 | VVA_ONLY(rc =) walFindFrame(pWal, p->pgno, &iWrite); | ||||
| 70003 | assert( rc==SQLITE_OK || iWrite==0 )((void) (0)); | ||||
| 70004 | if( iWrite>=iFirst ){ | ||||
| 70005 | i64 iOff = walFrameOffset(iWrite, szPage)( 32 + ((iWrite)-1)*(i64)((szPage)+24) ) + WAL_FRAME_HDRSIZE24; | ||||
| 70006 | void *pData; | ||||
| 70007 | if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){ | ||||
| 70008 | pWal->iReCksum = iWrite; | ||||
| 70009 | } | ||||
| 70010 | pData = p->pData; | ||||
| 70011 | rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff); | ||||
| 70012 | if( rc ) return rc; | ||||
| 70013 | p->flags &= ~PGHDR_WAL_APPEND0x040; | ||||
| 70014 | continue; | ||||
| 70015 | } | ||||
| 70016 | } | ||||
| 70017 | |||||
| 70018 | iFrame++; | ||||
| 70019 | assert( iOffset==walFrameOffset(iFrame, szPage) )((void) (0)); | ||||
| 70020 | nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0; | ||||
| 70021 | rc = walWriteOneFrame(&w, p, nDbSize, iOffset); | ||||
| 70022 | if( rc ) return rc; | ||||
| 70023 | pLast = p; | ||||
| 70024 | iOffset += szFrame; | ||||
| 70025 | p->flags |= PGHDR_WAL_APPEND0x040; | ||||
| 70026 | } | ||||
| 70027 | |||||
| 70028 | /* Recalculate checksums within the wal file if required. */ | ||||
| 70029 | if( isCommit && pWal->iReCksum ){ | ||||
| 70030 | rc = walRewriteChecksums(pWal, iFrame); | ||||
| 70031 | if( rc ) return rc; | ||||
| 70032 | } | ||||
| 70033 | |||||
| 70034 | /* If this is the end of a transaction, then we might need to pad | ||||
| 70035 | ** the transaction and/or sync the WAL file. | ||||
| 70036 | ** | ||||
| 70037 | ** Padding and syncing only occur if this set of frames complete a | ||||
| 70038 | ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL | ||||
| 70039 | ** or synchronous==OFF, then no padding or syncing are needed. | ||||
| 70040 | ** | ||||
| 70041 | ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not | ||||
| 70042 | ** needed and only the sync is done. If padding is needed, then the | ||||
| 70043 | ** final frame is repeated (with its commit mark) until the next sector | ||||
| 70044 | ** boundary is crossed. Only the part of the WAL prior to the last | ||||
| 70045 | ** sector boundary is synced; the part of the last frame that extends | ||||
| 70046 | ** past the sector boundary is written after the sync. | ||||
| 70047 | */ | ||||
| 70048 | if( isCommit && WAL_SYNC_FLAGS(sync_flags)((sync_flags)&0x03)!=0 ){ | ||||
| 70049 | int bSync = 1; | ||||
| 70050 | if( pWal->padToSectorBoundary ){ | ||||
| 70051 | int sectorSize = sqlite3SectorSize(pWal->pWalFd); | ||||
| 70052 | w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize; | ||||
| 70053 | bSync = (w.iSyncPoint==iOffset); | ||||
| 70054 | testcase( bSync ); | ||||
| 70055 | while( iOffset<w.iSyncPoint ){ | ||||
| 70056 | rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset); | ||||
| 70057 | if( rc ) return rc; | ||||
| 70058 | iOffset += szFrame; | ||||
| 70059 | nExtra++; | ||||
| 70060 | assert( pLast!=0 )((void) (0)); | ||||
| 70061 | } | ||||
| 70062 | } | ||||
| 70063 | if( bSync ){ | ||||
| 70064 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 70065 | rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags)((sync_flags)&0x03)); | ||||
| 70066 | } | ||||
| 70067 | } | ||||
| 70068 | |||||
| 70069 | /* If this frame set completes the first transaction in the WAL and | ||||
| 70070 | ** if PRAGMA journal_size_limit is set, then truncate the WAL to the | ||||
| 70071 | ** journal size limit, if possible. | ||||
| 70072 | */ | ||||
| 70073 | if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){ | ||||
| 70074 | i64 sz = pWal->mxWalSize; | ||||
| 70075 | if( walFrameOffset(iFrame+nExtra+1, szPage)( 32 + ((iFrame+nExtra+1)-1)*(i64)((szPage)+24) )>pWal->mxWalSize ){ | ||||
| 70076 | sz = walFrameOffset(iFrame+nExtra+1, szPage)( 32 + ((iFrame+nExtra+1)-1)*(i64)((szPage)+24) ); | ||||
| 70077 | } | ||||
| 70078 | walLimitSize(pWal, sz); | ||||
| 70079 | pWal->truncateOnCommit = 0; | ||||
| 70080 | } | ||||
| 70081 | |||||
| 70082 | /* Append data to the wal-index. It is not necessary to lock the | ||||
| 70083 | ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index | ||||
| 70084 | ** guarantees that there are no other writers, and no data that may | ||||
| 70085 | ** be in use by existing readers is being overwritten. | ||||
| 70086 | */ | ||||
| 70087 | iFrame = pWal->hdr.mxFrame; | ||||
| 70088 | for(p=pList; p && rc==SQLITE_OK0; p=p->pDirty){ | ||||
| 70089 | if( (p->flags & PGHDR_WAL_APPEND0x040)==0 ) continue; | ||||
| 70090 | iFrame++; | ||||
| 70091 | rc = walIndexAppend(pWal, iFrame, p->pgno); | ||||
| 70092 | } | ||||
| 70093 | assert( pLast!=0 || nExtra==0 )((void) (0)); | ||||
| 70094 | while( rc==SQLITE_OK0 && nExtra>0 ){ | ||||
| 70095 | iFrame++; | ||||
| 70096 | nExtra--; | ||||
| 70097 | rc = walIndexAppend(pWal, iFrame, pLast->pgno); | ||||
| 70098 | } | ||||
| 70099 | |||||
| 70100 | if( rc==SQLITE_OK0 ){ | ||||
| 70101 | /* Update the private copy of the header. */ | ||||
| 70102 | pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); | ||||
| 70103 | testcase( szPage<=32768 ); | ||||
| 70104 | testcase( szPage>=65536 ); | ||||
| 70105 | pWal->hdr.mxFrame = iFrame; | ||||
| 70106 | if( isCommit ){ | ||||
| 70107 | pWal->hdr.iChange++; | ||||
| 70108 | pWal->hdr.nPage = nTruncate; | ||||
| 70109 | } | ||||
| 70110 | /* If this is a commit, update the wal-index header too. */ | ||||
| 70111 | if( isCommit ){ | ||||
| 70112 | walIndexWriteHdr(pWal); | ||||
| 70113 | pWal->iCallback = iFrame; | ||||
| 70114 | } | ||||
| 70115 | } | ||||
| 70116 | |||||
| 70117 | WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok")); | ||||
| 70118 | return rc; | ||||
| 70119 | } | ||||
| 70120 | |||||
| 70121 | /* | ||||
| 70122 | ** Write a set of frames to the log. The caller must hold the write-lock | ||||
| 70123 | ** on the log file (obtained using sqlite3WalBeginWriteTransaction()). | ||||
| 70124 | ** | ||||
| 70125 | ** The difference between this function and walFrames() is that this | ||||
| 70126 | ** function wraps walFrames() in an SEH_TRY{...} block. | ||||
| 70127 | */ | ||||
| 70128 | SQLITE_PRIVATEstatic int sqlite3WalFrames( | ||||
| 70129 | Wal *pWal, /* Wal handle to write to */ | ||||
| 70130 | int szPage, /* Database page-size in bytes */ | ||||
| 70131 | PgHdr *pList, /* List of dirty pages to write */ | ||||
| 70132 | Pgno nTruncate, /* Database size after this commit */ | ||||
| 70133 | int isCommit, /* True if this is a commit */ | ||||
| 70134 | int sync_flags /* Flags to pass to OsSync() (or 0) */ | ||||
| 70135 | ){ | ||||
| 70136 | int rc; | ||||
| 70137 | SEH_TRY; { | ||||
| 70138 | rc = walFrames(pWal, szPage, pList, nTruncate, isCommit, sync_flags); | ||||
| 70139 | } | ||||
| 70140 | SEH_EXCEPT( rc = walHandleException(pWal); ); ((void) (0)); | ||||
| 70141 | return rc; | ||||
| 70142 | } | ||||
| 70143 | |||||
| 70144 | /* | ||||
| 70145 | ** This routine is called to implement sqlite3_wal_checkpoint() and | ||||
| 70146 | ** related interfaces. | ||||
| 70147 | ** | ||||
| 70148 | ** Obtain a CHECKPOINT lock and then backfill as much information as | ||||
| 70149 | ** we can from WAL into the database. | ||||
| 70150 | ** | ||||
| 70151 | ** If parameter xBusy is not NULL, it is a pointer to a busy-handler | ||||
| 70152 | ** callback. In this case this function runs a blocking checkpoint. | ||||
| 70153 | */ | ||||
| 70154 | SQLITE_PRIVATEstatic int sqlite3WalCheckpoint( | ||||
| 70155 | Wal *pWal, /* Wal connection */ | ||||
| 70156 | sqlite3 *db, /* Check this handle's interrupt flag */ | ||||
| 70157 | int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */ | ||||
| 70158 | int (*xBusy)(void*), /* Function to call when busy */ | ||||
| 70159 | void *pBusyArg, /* Context argument for xBusyHandler */ | ||||
| 70160 | int sync_flags, /* Flags to sync db file with (or 0) */ | ||||
| 70161 | int nBuf, /* Size of temporary buffer */ | ||||
| 70162 | u8 *zBuf, /* Temporary buffer to use */ | ||||
| 70163 | int *pnLog, /* OUT: Number of frames in WAL */ | ||||
| 70164 | int *pnCkpt /* OUT: Number of backfilled frames in WAL */ | ||||
| 70165 | ){ | ||||
| 70166 | int rc; /* Return code */ | ||||
| 70167 | int isChanged = 0; /* True if a new wal-index header is loaded */ | ||||
| 70168 | int eMode2 = eMode; /* Mode to pass to walCheckpoint() */ | ||||
| 70169 | int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */ | ||||
| 70170 | |||||
| 70171 | assert( pWal->ckptLock==0 )((void) (0)); | ||||
| 70172 | assert( pWal->writeLock==0 )((void) (0)); | ||||
| 70173 | |||||
| 70174 | /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked | ||||
| 70175 | ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ | ||||
| 70176 | assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 )((void) (0)); | ||||
| 70177 | |||||
| 70178 | if( pWal->readOnly ) return SQLITE_READONLY8; | ||||
| 70179 | WALTRACE(("WAL%p: checkpoint begins\n", pWal)); | ||||
| 70180 | |||||
| 70181 | /* Enable blocking locks, if possible. */ | ||||
| 70182 | sqlite3WalDb(pWal, db); | ||||
| 70183 | if( xBusy2 ) (void)walEnableBlocking(pWal)0; | ||||
| 70184 | |||||
| 70185 | /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive | ||||
| 70186 | ** "checkpoint" lock on the database file. | ||||
| 70187 | ** EVIDENCE-OF: R-10421-19736 If any other process is running a | ||||
| 70188 | ** checkpoint operation at the same time, the lock cannot be obtained and | ||||
| 70189 | ** SQLITE_BUSY is returned. | ||||
| 70190 | ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured, | ||||
| 70191 | ** it will not be invoked in this case. | ||||
| 70192 | */ | ||||
| 70193 | rc = walLockExclusive(pWal, WAL_CKPT_LOCK1, 1); | ||||
| 70194 | testcase( rc==SQLITE_BUSY ); | ||||
| 70195 | testcase( rc!=SQLITE_OK && xBusy2!=0 ); | ||||
| 70196 | if( rc==SQLITE_OK0 ){ | ||||
| 70197 | pWal->ckptLock = 1; | ||||
| 70198 | |||||
| 70199 | /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and | ||||
| 70200 | ** TRUNCATE modes also obtain the exclusive "writer" lock on the database | ||||
| 70201 | ** file. | ||||
| 70202 | ** | ||||
| 70203 | ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained | ||||
| 70204 | ** immediately, and a busy-handler is configured, it is invoked and the | ||||
| 70205 | ** writer lock retried until either the busy-handler returns 0 or the | ||||
| 70206 | ** lock is successfully obtained. | ||||
| 70207 | */ | ||||
| 70208 | if( eMode!=SQLITE_CHECKPOINT_PASSIVE0 ){ | ||||
| 70209 | rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK0, 1); | ||||
| 70210 | if( rc==SQLITE_OK0 ){ | ||||
| 70211 | pWal->writeLock = 1; | ||||
| 70212 | }else if( rc==SQLITE_BUSY5 ){ | ||||
| 70213 | eMode2 = SQLITE_CHECKPOINT_PASSIVE0; | ||||
| 70214 | xBusy2 = 0; | ||||
| 70215 | rc = SQLITE_OK0; | ||||
| 70216 | } | ||||
| 70217 | } | ||||
| 70218 | } | ||||
| 70219 | |||||
| 70220 | |||||
| 70221 | /* Read the wal-index header. */ | ||||
| 70222 | SEH_TRY; { | ||||
| 70223 | if( rc==SQLITE_OK0 ){ | ||||
| 70224 | /* For a passive checkpoint, do not re-enable blocking locks after | ||||
| 70225 | ** reading the wal-index header. A passive checkpoint should not block | ||||
| 70226 | ** or invoke the busy handler. The only lock such a checkpoint may | ||||
| 70227 | ** attempt to obtain is a lock on a read-slot, and it should give up | ||||
| 70228 | ** immediately and do a partial checkpoint if it cannot obtain it. */ | ||||
| 70229 | walDisableBlocking(pWal); | ||||
| 70230 | rc = walIndexReadHdr(pWal, &isChanged); | ||||
| 70231 | if( eMode2!=SQLITE_CHECKPOINT_PASSIVE0 ) (void)walEnableBlocking(pWal)0; | ||||
| 70232 | if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ | ||||
| 70233 | sqlite3OsUnfetch(pWal->pDbFd, 0, 0); | ||||
| 70234 | } | ||||
| 70235 | } | ||||
| 70236 | |||||
| 70237 | /* Copy data from the log to the database file. */ | ||||
| 70238 | if( rc==SQLITE_OK0 ){ | ||||
| 70239 | if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ | ||||
| 70240 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(70240); | ||||
| 70241 | }else{ | ||||
| 70242 | rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags,zBuf); | ||||
| 70243 | } | ||||
| 70244 | |||||
| 70245 | /* If no error occurred, set the output variables. */ | ||||
| 70246 | if( rc==SQLITE_OK0 || rc==SQLITE_BUSY5 ){ | ||||
| 70247 | if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame; | ||||
| 70248 | SEH_INJECT_FAULT((void) (0));; | ||||
| 70249 | if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill); | ||||
| 70250 | } | ||||
| 70251 | } | ||||
| 70252 | } | ||||
| 70253 | SEH_EXCEPT( rc = walHandleException(pWal); ); ((void) (0)); | ||||
| 70254 | |||||
| 70255 | if( isChanged ){ | ||||
| 70256 | /* If a new wal-index header was loaded before the checkpoint was | ||||
| 70257 | ** performed, then the pager-cache associated with pWal is now | ||||
| 70258 | ** out of date. So zero the cached wal-index header to ensure that | ||||
| 70259 | ** next time the pager opens a snapshot on this database it knows that | ||||
| 70260 | ** the cache needs to be reset. | ||||
| 70261 | */ | ||||
| 70262 | memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); | ||||
| 70263 | } | ||||
| 70264 | |||||
| 70265 | walDisableBlocking(pWal); | ||||
| 70266 | sqlite3WalDb(pWal, 0); | ||||
| 70267 | |||||
| 70268 | /* Release the locks. */ | ||||
| 70269 | sqlite3WalEndWriteTransaction(pWal); | ||||
| 70270 | if( pWal->ckptLock ){ | ||||
| 70271 | walUnlockExclusive(pWal, WAL_CKPT_LOCK1, 1); | ||||
| 70272 | pWal->ckptLock = 0; | ||||
| 70273 | } | ||||
| 70274 | WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); | ||||
| 70275 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 70276 | if( rc==SQLITE_BUSY_TIMEOUT(5 | (3<<8)) ) rc = SQLITE_BUSY5; | ||||
| 70277 | #endif | ||||
| 70278 | return (rc==SQLITE_OK0 && eMode!=eMode2 ? SQLITE_BUSY5 : rc); | ||||
| 70279 | } | ||||
| 70280 | |||||
| 70281 | /* Return the value to pass to a sqlite3_wal_hook callback, the | ||||
| 70282 | ** number of frames in the WAL at the point of the last commit since | ||||
| 70283 | ** sqlite3WalCallback() was called. If no commits have occurred since | ||||
| 70284 | ** the last call, then return 0. | ||||
| 70285 | */ | ||||
| 70286 | SQLITE_PRIVATEstatic int sqlite3WalCallback(Wal *pWal){ | ||||
| 70287 | u32 ret = 0; | ||||
| 70288 | if( pWal ){ | ||||
| 70289 | ret = pWal->iCallback; | ||||
| 70290 | pWal->iCallback = 0; | ||||
| 70291 | } | ||||
| 70292 | return (int)ret; | ||||
| 70293 | } | ||||
| 70294 | |||||
| 70295 | /* | ||||
| 70296 | ** This function is called to change the WAL subsystem into or out | ||||
| 70297 | ** of locking_mode=EXCLUSIVE. | ||||
| 70298 | ** | ||||
| 70299 | ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE | ||||
| 70300 | ** into locking_mode=NORMAL. This means that we must acquire a lock | ||||
| 70301 | ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL | ||||
| 70302 | ** or if the acquisition of the lock fails, then return 0. If the | ||||
| 70303 | ** transition out of exclusive-mode is successful, return 1. This | ||||
| 70304 | ** operation must occur while the pager is still holding the exclusive | ||||
| 70305 | ** lock on the main database file. | ||||
| 70306 | ** | ||||
| 70307 | ** If op is one, then change from locking_mode=NORMAL into | ||||
| 70308 | ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must | ||||
| 70309 | ** be released. Return 1 if the transition is made and 0 if the | ||||
| 70310 | ** WAL is already in exclusive-locking mode - meaning that this | ||||
| 70311 | ** routine is a no-op. The pager must already hold the exclusive lock | ||||
| 70312 | ** on the main database file before invoking this operation. | ||||
| 70313 | ** | ||||
| 70314 | ** If op is negative, then do a dry-run of the op==1 case but do | ||||
| 70315 | ** not actually change anything. The pager uses this to see if it | ||||
| 70316 | ** should acquire the database exclusive lock prior to invoking | ||||
| 70317 | ** the op==1 case. | ||||
| 70318 | */ | ||||
| 70319 | SQLITE_PRIVATEstatic int sqlite3WalExclusiveMode(Wal *pWal, int op){ | ||||
| 70320 | int rc; | ||||
| 70321 | assert( pWal->writeLock==0 )((void) (0)); | ||||
| 70322 | assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 )((void) (0)); | ||||
| 70323 | |||||
| 70324 | /* pWal->readLock is usually set, but might be -1 if there was a | ||||
| 70325 | ** prior error while attempting to acquire are read-lock. This cannot | ||||
| 70326 | ** happen if the connection is actually in exclusive mode (as no xShmLock | ||||
| 70327 | ** locks are taken in this case). Nor should the pager attempt to | ||||
| 70328 | ** upgrade to exclusive-mode following such an error. | ||||
| 70329 | */ | ||||
| 70330 | #ifndef SQLITE_USE_SEH | ||||
| 70331 | assert( pWal->readLock>=0 || pWal->lockError )((void) (0)); | ||||
| 70332 | #endif | ||||
| 70333 | assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) )((void) (0)); | ||||
| 70334 | |||||
| 70335 | if( op==0 ){ | ||||
| 70336 | if( pWal->exclusiveMode!=WAL_NORMAL_MODE0 ){ | ||||
| 70337 | pWal->exclusiveMode = WAL_NORMAL_MODE0; | ||||
| 70338 | if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock)(3+(pWal->readLock)))!=SQLITE_OK0 ){ | ||||
| 70339 | pWal->exclusiveMode = WAL_EXCLUSIVE_MODE1; | ||||
| 70340 | } | ||||
| 70341 | rc = pWal->exclusiveMode==WAL_NORMAL_MODE0; | ||||
| 70342 | }else{ | ||||
| 70343 | /* Already in locking_mode=NORMAL */ | ||||
| 70344 | rc = 0; | ||||
| 70345 | } | ||||
| 70346 | }else if( op>0 ){ | ||||
| 70347 | assert( pWal->exclusiveMode==WAL_NORMAL_MODE )((void) (0)); | ||||
| 70348 | assert( pWal->readLock>=0 )((void) (0)); | ||||
| 70349 | walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)(3+(pWal->readLock))); | ||||
| 70350 | pWal->exclusiveMode = WAL_EXCLUSIVE_MODE1; | ||||
| 70351 | rc = 1; | ||||
| 70352 | }else{ | ||||
| 70353 | rc = pWal->exclusiveMode==WAL_NORMAL_MODE0; | ||||
| 70354 | } | ||||
| 70355 | return rc; | ||||
| 70356 | } | ||||
| 70357 | |||||
| 70358 | /* | ||||
| 70359 | ** Return true if the argument is non-NULL and the WAL module is using | ||||
| 70360 | ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the | ||||
| 70361 | ** WAL module is using shared-memory, return false. | ||||
| 70362 | */ | ||||
| 70363 | SQLITE_PRIVATEstatic int sqlite3WalHeapMemory(Wal *pWal){ | ||||
| 70364 | return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE2 ); | ||||
| 70365 | } | ||||
| 70366 | |||||
| 70367 | #ifdef SQLITE_ENABLE_SNAPSHOT1 | ||||
| 70368 | /* Create a snapshot object. The content of a snapshot is opaque to | ||||
| 70369 | ** every other subsystem, so the WAL module can put whatever it needs | ||||
| 70370 | ** in the object. | ||||
| 70371 | */ | ||||
| 70372 | SQLITE_PRIVATEstatic int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){ | ||||
| 70373 | int rc = SQLITE_OK0; | ||||
| 70374 | WalIndexHdr *pRet; | ||||
| 70375 | static const u32 aZero[4] = { 0, 0, 0, 0 }; | ||||
| 70376 | |||||
| 70377 | assert( pWal->readLock>=0 && pWal->writeLock==0 )((void) (0)); | ||||
| 70378 | |||||
| 70379 | if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){ | ||||
| 70380 | *ppSnapshot = 0; | ||||
| 70381 | return SQLITE_ERROR1; | ||||
| 70382 | } | ||||
| 70383 | pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr)); | ||||
| 70384 | if( pRet==0 ){ | ||||
| 70385 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 70386 | }else{ | ||||
| 70387 | memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr)); | ||||
| 70388 | *ppSnapshot = (sqlite3_snapshot*)pRet; | ||||
| 70389 | } | ||||
| 70390 | |||||
| 70391 | return rc; | ||||
| 70392 | } | ||||
| 70393 | |||||
| 70394 | /* Try to open on pSnapshot when the next read-transaction starts | ||||
| 70395 | */ | ||||
| 70396 | SQLITE_PRIVATEstatic void sqlite3WalSnapshotOpen( | ||||
| 70397 | Wal *pWal, | ||||
| 70398 | sqlite3_snapshot *pSnapshot | ||||
| 70399 | ){ | ||||
| 70400 | if( pSnapshot && ((WalIndexHdr*)pSnapshot)->iVersion==0 ){ | ||||
| 70401 | /* iVersion==0 means that this is a call to sqlite3_snapshot_get(). In | ||||
| 70402 | ** this case set the bGetSnapshot flag so that if the call to | ||||
| 70403 | ** sqlite3_snapshot_get() is about to read transaction on this wal | ||||
| 70404 | ** file, it does not take read-lock 0 if the wal file has been completely | ||||
| 70405 | ** checkpointed. Taking read-lock 0 would work, but then it would be | ||||
| 70406 | ** possible for a subsequent writer to destroy the snapshot even while | ||||
| 70407 | ** this connection is holding its read-transaction open. This is contrary | ||||
| 70408 | ** to user expectations, so we avoid it by not taking read-lock 0. */ | ||||
| 70409 | pWal->bGetSnapshot = 1; | ||||
| 70410 | }else{ | ||||
| 70411 | pWal->pSnapshot = (WalIndexHdr*)pSnapshot; | ||||
| 70412 | pWal->bGetSnapshot = 0; | ||||
| 70413 | } | ||||
| 70414 | } | ||||
| 70415 | |||||
| 70416 | /* | ||||
| 70417 | ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if | ||||
| 70418 | ** p1 is older than p2 and zero if p1 and p2 are the same snapshot. | ||||
| 70419 | */ | ||||
| 70420 | SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){ | ||||
| 70421 | WalIndexHdr *pHdr1 = (WalIndexHdr*)p1; | ||||
| 70422 | WalIndexHdr *pHdr2 = (WalIndexHdr*)p2; | ||||
| 70423 | |||||
| 70424 | /* aSalt[0] is a copy of the value stored in the wal file header. It | ||||
| 70425 | ** is incremented each time the wal file is restarted. */ | ||||
| 70426 | if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1; | ||||
| 70427 | if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1; | ||||
| 70428 | if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1; | ||||
| 70429 | if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1; | ||||
| 70430 | return 0; | ||||
| 70431 | } | ||||
| 70432 | |||||
| 70433 | /* | ||||
| 70434 | ** The caller currently has a read transaction open on the database. | ||||
| 70435 | ** This function takes a SHARED lock on the CHECKPOINTER slot and then | ||||
| 70436 | ** checks if the snapshot passed as the second argument is still | ||||
| 70437 | ** available. If so, SQLITE_OK is returned. | ||||
| 70438 | ** | ||||
| 70439 | ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if | ||||
| 70440 | ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error | ||||
| 70441 | ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER | ||||
| 70442 | ** lock is released before returning. | ||||
| 70443 | */ | ||||
| 70444 | SQLITE_PRIVATEstatic int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){ | ||||
| 70445 | int rc; | ||||
| 70446 | SEH_TRY; { | ||||
| 70447 | rc = walLockShared(pWal, WAL_CKPT_LOCK1); | ||||
| 70448 | if( rc==SQLITE_OK0 ){ | ||||
| 70449 | WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot; | ||||
| 70450 | if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) | ||||
| 70451 | || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted | ||||
| 70452 | ){ | ||||
| 70453 | rc = SQLITE_ERROR_SNAPSHOT(1 | (3<<8)); | ||||
| 70454 | walUnlockShared(pWal, WAL_CKPT_LOCK1); | ||||
| 70455 | } | ||||
| 70456 | } | ||||
| 70457 | } | ||||
| 70458 | SEH_EXCEPT( rc = walHandleException(pWal); ); ((void) (0)); | ||||
| 70459 | return rc; | ||||
| 70460 | } | ||||
| 70461 | |||||
| 70462 | /* | ||||
| 70463 | ** Release a lock obtained by an earlier successful call to | ||||
| 70464 | ** sqlite3WalSnapshotCheck(). | ||||
| 70465 | */ | ||||
| 70466 | SQLITE_PRIVATEstatic void sqlite3WalSnapshotUnlock(Wal *pWal){ | ||||
| 70467 | assert( pWal )((void) (0)); | ||||
| 70468 | walUnlockShared(pWal, WAL_CKPT_LOCK1); | ||||
| 70469 | } | ||||
| 70470 | |||||
| 70471 | |||||
| 70472 | #endif /* SQLITE_ENABLE_SNAPSHOT */ | ||||
| 70473 | |||||
| 70474 | #ifdef SQLITE_ENABLE_ZIPVFS | ||||
| 70475 | /* | ||||
| 70476 | ** If the argument is not NULL, it points to a Wal object that holds a | ||||
| 70477 | ** read-lock. This function returns the database page-size if it is known, | ||||
| 70478 | ** or zero if it is not (or if pWal is NULL). | ||||
| 70479 | */ | ||||
| 70480 | SQLITE_PRIVATEstatic int sqlite3WalFramesize(Wal *pWal){ | ||||
| 70481 | assert( pWal==0 || pWal->readLock>=0 )((void) (0)); | ||||
| 70482 | return (pWal ? pWal->szPage : 0); | ||||
| 70483 | } | ||||
| 70484 | #endif | ||||
| 70485 | |||||
| 70486 | /* Return the sqlite3_file object for the WAL file | ||||
| 70487 | */ | ||||
| 70488 | SQLITE_PRIVATEstatic sqlite3_file *sqlite3WalFile(Wal *pWal){ | ||||
| 70489 | return pWal->pWalFd; | ||||
| 70490 | } | ||||
| 70491 | |||||
| 70492 | #endif /* #ifndef SQLITE_OMIT_WAL */ | ||||
| 70493 | |||||
| 70494 | /************** End of wal.c *************************************************/ | ||||
| 70495 | /************** Begin file btmutex.c *****************************************/ | ||||
| 70496 | /* | ||||
| 70497 | ** 2007 August 27 | ||||
| 70498 | ** | ||||
| 70499 | ** The author disclaims copyright to this source code. In place of | ||||
| 70500 | ** a legal notice, here is a blessing: | ||||
| 70501 | ** | ||||
| 70502 | ** May you do good and not evil. | ||||
| 70503 | ** May you find forgiveness for yourself and forgive others. | ||||
| 70504 | ** May you share freely, never taking more than you give. | ||||
| 70505 | ** | ||||
| 70506 | ************************************************************************* | ||||
| 70507 | ** | ||||
| 70508 | ** This file contains code used to implement mutexes on Btree objects. | ||||
| 70509 | ** This code really belongs in btree.c. But btree.c is getting too | ||||
| 70510 | ** big and we want to break it down some. This packaged seemed like | ||||
| 70511 | ** a good breakout. | ||||
| 70512 | */ | ||||
| 70513 | /************** Include btreeInt.h in the middle of btmutex.c ****************/ | ||||
| 70514 | /************** Begin file btreeInt.h ****************************************/ | ||||
| 70515 | /* | ||||
| 70516 | ** 2004 April 6 | ||||
| 70517 | ** | ||||
| 70518 | ** The author disclaims copyright to this source code. In place of | ||||
| 70519 | ** a legal notice, here is a blessing: | ||||
| 70520 | ** | ||||
| 70521 | ** May you do good and not evil. | ||||
| 70522 | ** May you find forgiveness for yourself and forgive others. | ||||
| 70523 | ** May you share freely, never taking more than you give. | ||||
| 70524 | ** | ||||
| 70525 | ************************************************************************* | ||||
| 70526 | ** This file implements an external (disk-based) database using BTrees. | ||||
| 70527 | ** For a detailed discussion of BTrees, refer to | ||||
| 70528 | ** | ||||
| 70529 | ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: | ||||
| 70530 | ** "Sorting And Searching", pages 473-480. Addison-Wesley | ||||
| 70531 | ** Publishing Company, Reading, Massachusetts. | ||||
| 70532 | ** | ||||
| 70533 | ** The basic idea is that each page of the file contains N database | ||||
| 70534 | ** entries and N+1 pointers to subpages. | ||||
| 70535 | ** | ||||
| 70536 | ** ---------------------------------------------------------------- | ||||
| 70537 | ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | | ||||
| 70538 | ** ---------------------------------------------------------------- | ||||
| 70539 | ** | ||||
| 70540 | ** All of the keys on the page that Ptr(0) points to have values less | ||||
| 70541 | ** than Key(0). All of the keys on page Ptr(1) and its subpages have | ||||
| 70542 | ** values greater than Key(0) and less than Key(1). All of the keys | ||||
| 70543 | ** on Ptr(N) and its subpages have values greater than Key(N-1). And | ||||
| 70544 | ** so forth. | ||||
| 70545 | ** | ||||
| 70546 | ** Finding a particular key requires reading O(log(M)) pages from the | ||||
| 70547 | ** disk where M is the number of entries in the tree. | ||||
| 70548 | ** | ||||
| 70549 | ** In this implementation, a single file can hold one or more separate | ||||
| 70550 | ** BTrees. Each BTree is identified by the index of its root page. The | ||||
| 70551 | ** key and data for any entry are combined to form the "payload". A | ||||
| 70552 | ** fixed amount of payload can be carried directly on the database | ||||
| 70553 | ** page. If the payload is larger than the preset amount then surplus | ||||
| 70554 | ** bytes are stored on overflow pages. The payload for an entry | ||||
| 70555 | ** and the preceding pointer are combined to form a "Cell". Each | ||||
| 70556 | ** page has a small header which contains the Ptr(N) pointer and other | ||||
| 70557 | ** information such as the size of key and data. | ||||
| 70558 | ** | ||||
| 70559 | ** FORMAT DETAILS | ||||
| 70560 | ** | ||||
| 70561 | ** The file is divided into pages. The first page is called page 1, | ||||
| 70562 | ** the second is page 2, and so forth. A page number of zero indicates | ||||
| 70563 | ** "no such page". The page size can be any power of 2 between 512 and 65536. | ||||
| 70564 | ** Each page can be either a btree page, a freelist page, an overflow | ||||
| 70565 | ** page, or a pointer-map page. | ||||
| 70566 | ** | ||||
| 70567 | ** The first page is always a btree page. The first 100 bytes of the first | ||||
| 70568 | ** page contain a special header (the "file header") that describes the file. | ||||
| 70569 | ** The format of the file header is as follows: | ||||
| 70570 | ** | ||||
| 70571 | ** OFFSET SIZE DESCRIPTION | ||||
| 70572 | ** 0 16 Header string: "SQLite format 3\000" | ||||
| 70573 | ** 16 2 Page size in bytes. (1 means 65536) | ||||
| 70574 | ** 18 1 File format write version | ||||
| 70575 | ** 19 1 File format read version | ||||
| 70576 | ** 20 1 Bytes of unused space at the end of each page | ||||
| 70577 | ** 21 1 Max embedded payload fraction (must be 64) | ||||
| 70578 | ** 22 1 Min embedded payload fraction (must be 32) | ||||
| 70579 | ** 23 1 Min leaf payload fraction (must be 32) | ||||
| 70580 | ** 24 4 File change counter | ||||
| 70581 | ** 28 4 The size of the database in pages | ||||
| 70582 | ** 32 4 First freelist page | ||||
| 70583 | ** 36 4 Number of freelist pages in the file | ||||
| 70584 | ** 40 60 15 4-byte meta values passed to higher layers | ||||
| 70585 | ** | ||||
| 70586 | ** 40 4 Schema cookie | ||||
| 70587 | ** 44 4 File format of schema layer | ||||
| 70588 | ** 48 4 Size of page cache | ||||
| 70589 | ** 52 4 Largest root-page (auto/incr_vacuum) | ||||
| 70590 | ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be | ||||
| 70591 | ** 60 4 User version | ||||
| 70592 | ** 64 4 Incremental vacuum mode | ||||
| 70593 | ** 68 4 Application-ID | ||||
| 70594 | ** 72 20 unused | ||||
| 70595 | ** 92 4 The version-valid-for number | ||||
| 70596 | ** 96 4 SQLITE_VERSION_NUMBER | ||||
| 70597 | ** | ||||
| 70598 | ** All of the integer values are big-endian (most significant byte first). | ||||
| 70599 | ** | ||||
| 70600 | ** The file change counter is incremented when the database is changed | ||||
| 70601 | ** This counter allows other processes to know when the file has changed | ||||
| 70602 | ** and thus when they need to flush their cache. | ||||
| 70603 | ** | ||||
| 70604 | ** The max embedded payload fraction is the amount of the total usable | ||||
| 70605 | ** space in a page that can be consumed by a single cell for standard | ||||
| 70606 | ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default | ||||
| 70607 | ** is to limit the maximum cell size so that at least 4 cells will fit | ||||
| 70608 | ** on one page. Thus the default max embedded payload fraction is 64. | ||||
| 70609 | ** | ||||
| 70610 | ** If the payload for a cell is larger than the max payload, then extra | ||||
| 70611 | ** payload is spilled to overflow pages. Once an overflow page is allocated, | ||||
| 70612 | ** as many bytes as possible are moved into the overflow pages without letting | ||||
| 70613 | ** the cell size drop below the min embedded payload fraction. | ||||
| 70614 | ** | ||||
| 70615 | ** The min leaf payload fraction is like the min embedded payload fraction | ||||
| 70616 | ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum | ||||
| 70617 | ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it | ||||
| 70618 | ** not specified in the header. | ||||
| 70619 | ** | ||||
| 70620 | ** Each btree pages is divided into three sections: The header, the | ||||
| 70621 | ** cell pointer array, and the cell content area. Page 1 also has a 100-byte | ||||
| 70622 | ** file header that occurs before the page header. | ||||
| 70623 | ** | ||||
| 70624 | ** |----------------| | ||||
| 70625 | ** | file header | 100 bytes. Page 1 only. | ||||
| 70626 | ** |----------------| | ||||
| 70627 | ** | page header | 8 bytes for leaves. 12 bytes for interior nodes | ||||
| 70628 | ** |----------------| | ||||
| 70629 | ** | cell pointer | | 2 bytes per cell. Sorted order. | ||||
| 70630 | ** | array | | Grows downward | ||||
| 70631 | ** | | v | ||||
| 70632 | ** |----------------| | ||||
| 70633 | ** | unallocated | | ||||
| 70634 | ** | space | | ||||
| 70635 | ** |----------------| ^ Grows upwards | ||||
| 70636 | ** | cell content | | Arbitrary order interspersed with freeblocks. | ||||
| 70637 | ** | area | | and free space fragments. | ||||
| 70638 | ** |----------------| | ||||
| 70639 | ** | ||||
| 70640 | ** The page headers looks like this: | ||||
| 70641 | ** | ||||
| 70642 | ** OFFSET SIZE DESCRIPTION | ||||
| 70643 | ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf | ||||
| 70644 | ** 1 2 byte offset to the first freeblock | ||||
| 70645 | ** 3 2 number of cells on this page | ||||
| 70646 | ** 5 2 first byte of the cell content area | ||||
| 70647 | ** 7 1 number of fragmented free bytes | ||||
| 70648 | ** 8 4 Right child (the Ptr(N) value). Omitted on leaves. | ||||
| 70649 | ** | ||||
| 70650 | ** The flags define the format of this btree page. The leaf flag means that | ||||
| 70651 | ** this page has no children. The zerodata flag means that this page carries | ||||
| 70652 | ** only keys and no data. The intkey flag means that the key is an integer | ||||
| 70653 | ** which is stored in the key size entry of the cell header rather than in | ||||
| 70654 | ** the payload area. | ||||
| 70655 | ** | ||||
| 70656 | ** The cell pointer array begins on the first byte after the page header. | ||||
| 70657 | ** The cell pointer array contains zero or more 2-byte numbers which are | ||||
| 70658 | ** offsets from the beginning of the page to the cell content in the cell | ||||
| 70659 | ** content area. The cell pointers occur in sorted order. The system strives | ||||
| 70660 | ** to keep free space after the last cell pointer so that new cells can | ||||
| 70661 | ** be easily added without having to defragment the page. | ||||
| 70662 | ** | ||||
| 70663 | ** Cell content is stored at the very end of the page and grows toward the | ||||
| 70664 | ** beginning of the page. | ||||
| 70665 | ** | ||||
| 70666 | ** Unused space within the cell content area is collected into a linked list of | ||||
| 70667 | ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset | ||||
| 70668 | ** to the first freeblock is given in the header. Freeblocks occur in | ||||
| 70669 | ** increasing order. Because a freeblock must be at least 4 bytes in size, | ||||
| 70670 | ** any group of 3 or fewer unused bytes in the cell content area cannot | ||||
| 70671 | ** exist on the freeblock chain. A group of 3 or fewer free bytes is called | ||||
| 70672 | ** a fragment. The total number of bytes in all fragments is recorded. | ||||
| 70673 | ** in the page header at offset 7. | ||||
| 70674 | ** | ||||
| 70675 | ** SIZE DESCRIPTION | ||||
| 70676 | ** 2 Byte offset of the next freeblock | ||||
| 70677 | ** 2 Bytes in this freeblock | ||||
| 70678 | ** | ||||
| 70679 | ** Cells are of variable length. Cells are stored in the cell content area at | ||||
| 70680 | ** the end of the page. Pointers to the cells are in the cell pointer array | ||||
| 70681 | ** that immediately follows the page header. Cells is not necessarily | ||||
| 70682 | ** contiguous or in order, but cell pointers are contiguous and in order. | ||||
| 70683 | ** | ||||
| 70684 | ** Cell content makes use of variable length integers. A variable | ||||
| 70685 | ** length integer is 1 to 9 bytes where the lower 7 bits of each | ||||
| 70686 | ** byte are used. The integer consists of all bytes that have bit 8 set and | ||||
| 70687 | ** the first byte with bit 8 clear. The most significant byte of the integer | ||||
| 70688 | ** appears first. A variable-length integer may not be more than 9 bytes long. | ||||
| 70689 | ** As a special case, all 8 bits of the 9th byte are used as data. This | ||||
| 70690 | ** allows a 64-bit integer to be encoded in 9 bytes. | ||||
| 70691 | ** | ||||
| 70692 | ** 0x00 becomes 0x00000000 | ||||
| 70693 | ** 0x7f becomes 0x0000007f | ||||
| 70694 | ** 0x81 0x00 becomes 0x00000080 | ||||
| 70695 | ** 0x82 0x00 becomes 0x00000100 | ||||
| 70696 | ** 0x80 0x7f becomes 0x0000007f | ||||
| 70697 | ** 0x81 0x91 0xd1 0xac 0x78 becomes 0x12345678 | ||||
| 70698 | ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 | ||||
| 70699 | ** | ||||
| 70700 | ** Variable length integers are used for rowids and to hold the number of | ||||
| 70701 | ** bytes of key and data in a btree cell. | ||||
| 70702 | ** | ||||
| 70703 | ** The content of a cell looks like this: | ||||
| 70704 | ** | ||||
| 70705 | ** SIZE DESCRIPTION | ||||
| 70706 | ** 4 Page number of the left child. Omitted if leaf flag is set. | ||||
| 70707 | ** var Number of bytes of data. Omitted if the zerodata flag is set. | ||||
| 70708 | ** var Number of bytes of key. Or the key itself if intkey flag is set. | ||||
| 70709 | ** * Payload | ||||
| 70710 | ** 4 First page of the overflow chain. Omitted if no overflow | ||||
| 70711 | ** | ||||
| 70712 | ** Overflow pages form a linked list. Each page except the last is completely | ||||
| 70713 | ** filled with data (pagesize - 4 bytes). The last page can have as little | ||||
| 70714 | ** as 1 byte of data. | ||||
| 70715 | ** | ||||
| 70716 | ** SIZE DESCRIPTION | ||||
| 70717 | ** 4 Page number of next overflow page | ||||
| 70718 | ** * Data | ||||
| 70719 | ** | ||||
| 70720 | ** Freelist pages come in two subtypes: trunk pages and leaf pages. The | ||||
| 70721 | ** file header points to the first in a linked list of trunk page. Each trunk | ||||
| 70722 | ** page points to multiple leaf pages. The content of a leaf page is | ||||
| 70723 | ** unspecified. A trunk page looks like this: | ||||
| 70724 | ** | ||||
| 70725 | ** SIZE DESCRIPTION | ||||
| 70726 | ** 4 Page number of next trunk page | ||||
| 70727 | ** 4 Number of leaf pointers on this page | ||||
| 70728 | ** * zero or more pages numbers of leaves | ||||
| 70729 | */ | ||||
| 70730 | /* #include "sqliteInt.h" */ | ||||
| 70731 | |||||
| 70732 | |||||
| 70733 | /* The following value is the maximum cell size assuming a maximum page | ||||
| 70734 | ** size give above. | ||||
| 70735 | */ | ||||
| 70736 | #define MX_CELL_SIZE(pBt)((int)(pBt->pageSize-8)) ((int)(pBt->pageSize-8)) | ||||
| 70737 | |||||
| 70738 | /* The maximum number of cells on a single page of the database. This | ||||
| 70739 | ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself | ||||
| 70740 | ** plus 2 bytes for the index to the cell in the page header). Such | ||||
| 70741 | ** small cells will be rare, but they are possible. | ||||
| 70742 | */ | ||||
| 70743 | #define MX_CELL(pBt)((pBt->pageSize-8)/6) ((pBt->pageSize-8)/6) | ||||
| 70744 | |||||
| 70745 | /* Forward declarations */ | ||||
| 70746 | typedef struct MemPage MemPage; | ||||
| 70747 | typedef struct BtLock BtLock; | ||||
| 70748 | typedef struct CellInfo CellInfo; | ||||
| 70749 | |||||
| 70750 | /* | ||||
| 70751 | ** This is a magic string that appears at the beginning of every | ||||
| 70752 | ** SQLite database in order to identify the file as a real database. | ||||
| 70753 | ** | ||||
| 70754 | ** You can change this value at compile-time by specifying a | ||||
| 70755 | ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The | ||||
| 70756 | ** header must be exactly 16 bytes including the zero-terminator so | ||||
| 70757 | ** the string itself should be 15 characters long. If you change | ||||
| 70758 | ** the header, then your custom library will not be able to read | ||||
| 70759 | ** databases generated by the standard tools and the standard tools | ||||
| 70760 | ** will not be able to read databases created by your custom library. | ||||
| 70761 | */ | ||||
| 70762 | #ifndef SQLITE_FILE_HEADER"SQLite format 3" /* 123456789 123456 */ | ||||
| 70763 | # define SQLITE_FILE_HEADER"SQLite format 3" "SQLite format 3" | ||||
| 70764 | #endif | ||||
| 70765 | |||||
| 70766 | /* | ||||
| 70767 | ** Page type flags. An ORed combination of these flags appear as the | ||||
| 70768 | ** first byte of on-disk image of every BTree page. | ||||
| 70769 | */ | ||||
| 70770 | #define PTF_INTKEY0x01 0x01 | ||||
| 70771 | #define PTF_ZERODATA0x02 0x02 | ||||
| 70772 | #define PTF_LEAFDATA0x04 0x04 | ||||
| 70773 | #define PTF_LEAF0x08 0x08 | ||||
| 70774 | |||||
| 70775 | /* | ||||
| 70776 | ** An instance of this object stores information about each a single database | ||||
| 70777 | ** page that has been loaded into memory. The information in this object | ||||
| 70778 | ** is derived from the raw on-disk page content. | ||||
| 70779 | ** | ||||
| 70780 | ** As each database page is loaded into memory, the pager allocates an | ||||
| 70781 | ** instance of this object and zeros the first 8 bytes. (This is the | ||||
| 70782 | ** "extra" information associated with each page of the pager.) | ||||
| 70783 | ** | ||||
| 70784 | ** Access to all fields of this structure is controlled by the mutex | ||||
| 70785 | ** stored in MemPage.pBt->mutex. | ||||
| 70786 | */ | ||||
| 70787 | struct MemPage { | ||||
| 70788 | u8 isInit; /* True if previously initialized. MUST BE FIRST! */ | ||||
| 70789 | u8 intKey; /* True if table b-trees. False for index b-trees */ | ||||
| 70790 | u8 intKeyLeaf; /* True if the leaf of an intKey table */ | ||||
| 70791 | Pgno pgno; /* Page number for this page */ | ||||
| 70792 | /* Only the first 8 bytes (above) are zeroed by pager.c when a new page | ||||
| 70793 | ** is allocated. All fields that follow must be initialized before use */ | ||||
| 70794 | u8 leaf; /* True if a leaf page */ | ||||
| 70795 | u8 hdrOffset; /* 100 for page 1. 0 otherwise */ | ||||
| 70796 | u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ | ||||
| 70797 | u8 max1bytePayload; /* min(maxLocal,127) */ | ||||
| 70798 | u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ | ||||
| 70799 | u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ | ||||
| 70800 | u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ | ||||
| 70801 | u16 cellOffset; /* Index in aData of first cell pointer */ | ||||
| 70802 | int nFree; /* Number of free bytes on the page. -1 for unknown */ | ||||
| 70803 | u16 nCell; /* Number of cells on this page, local and ovfl */ | ||||
| 70804 | u16 maskPage; /* Mask for page offset */ | ||||
| 70805 | u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th | ||||
| 70806 | ** non-overflow cell */ | ||||
| 70807 | u8 *apOvfl[4]; /* Pointers to the body of overflow cells */ | ||||
| 70808 | BtShared *pBt; /* Pointer to BtShared that this page is part of */ | ||||
| 70809 | u8 *aData; /* Pointer to disk image of the page data */ | ||||
| 70810 | u8 *aDataEnd; /* One byte past the end of the entire page - not just | ||||
| 70811 | ** the usable space, the entire page. Used to prevent | ||||
| 70812 | ** corruption-induced buffer overflow. */ | ||||
| 70813 | u8 *aCellIdx; /* The cell index area */ | ||||
| 70814 | u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */ | ||||
| 70815 | DbPage *pDbPage; /* Pager page handle */ | ||||
| 70816 | u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */ | ||||
| 70817 | void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */ | ||||
| 70818 | }; | ||||
| 70819 | |||||
| 70820 | /* | ||||
| 70821 | ** A linked list of the following structures is stored at BtShared.pLock. | ||||
| 70822 | ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor | ||||
| 70823 | ** is opened on the table with root page BtShared.iTable. Locks are removed | ||||
| 70824 | ** from this list when a transaction is committed or rolled back, or when | ||||
| 70825 | ** a btree handle is closed. | ||||
| 70826 | */ | ||||
| 70827 | struct BtLock { | ||||
| 70828 | Btree *pBtree; /* Btree handle holding this lock */ | ||||
| 70829 | Pgno iTable; /* Root page of table */ | ||||
| 70830 | u8 eLock; /* READ_LOCK or WRITE_LOCK */ | ||||
| 70831 | BtLock *pNext; /* Next in BtShared.pLock list */ | ||||
| 70832 | }; | ||||
| 70833 | |||||
| 70834 | /* Candidate values for BtLock.eLock */ | ||||
| 70835 | #define READ_LOCK1 1 | ||||
| 70836 | #define WRITE_LOCK2 2 | ||||
| 70837 | |||||
| 70838 | /* A Btree handle | ||||
| 70839 | ** | ||||
| 70840 | ** A database connection contains a pointer to an instance of | ||||
| 70841 | ** this object for every database file that it has open. This structure | ||||
| 70842 | ** is opaque to the database connection. The database connection cannot | ||||
| 70843 | ** see the internals of this structure and only deals with pointers to | ||||
| 70844 | ** this structure. | ||||
| 70845 | ** | ||||
| 70846 | ** For some database files, the same underlying database cache might be | ||||
| 70847 | ** shared between multiple connections. In that case, each connection | ||||
| 70848 | ** has it own instance of this object. But each instance of this object | ||||
| 70849 | ** points to the same BtShared object. The database cache and the | ||||
| 70850 | ** schema associated with the database file are all contained within | ||||
| 70851 | ** the BtShared object. | ||||
| 70852 | ** | ||||
| 70853 | ** All fields in this structure are accessed under sqlite3.mutex. | ||||
| 70854 | ** The pBt pointer itself may not be changed while there exists cursors | ||||
| 70855 | ** in the referenced BtShared that point back to this Btree since those | ||||
| 70856 | ** cursors have to go through this Btree to find their BtShared and | ||||
| 70857 | ** they often do so without holding sqlite3.mutex. | ||||
| 70858 | */ | ||||
| 70859 | struct Btree { | ||||
| 70860 | sqlite3 *db; /* The database connection holding this btree */ | ||||
| 70861 | BtShared *pBt; /* Sharable content of this btree */ | ||||
| 70862 | u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ | ||||
| 70863 | u8 sharable; /* True if we can share pBt with another db */ | ||||
| 70864 | u8 locked; /* True if db currently has pBt locked */ | ||||
| 70865 | u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */ | ||||
| 70866 | int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ | ||||
| 70867 | int nBackup; /* Number of backup operations reading this btree */ | ||||
| 70868 | u32 iBDataVersion; /* Combines with pBt->pPager->iDataVersion */ | ||||
| 70869 | Btree *pNext; /* List of other sharable Btrees from the same db */ | ||||
| 70870 | Btree *pPrev; /* Back pointer of the same list */ | ||||
| 70871 | #ifdef SQLITE_DEBUG | ||||
| 70872 | u64 nSeek; /* Calls to sqlite3BtreeMovetoUnpacked() */ | ||||
| 70873 | #endif | ||||
| 70874 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 70875 | BtLock lock; /* Object used to lock page 1 */ | ||||
| 70876 | #endif | ||||
| 70877 | }; | ||||
| 70878 | |||||
| 70879 | /* | ||||
| 70880 | ** Btree.inTrans may take one of the following values. | ||||
| 70881 | ** | ||||
| 70882 | ** If the shared-data extension is enabled, there may be multiple users | ||||
| 70883 | ** of the Btree structure. At most one of these may open a write transaction, | ||||
| 70884 | ** but any number may have active read transactions. | ||||
| 70885 | ** | ||||
| 70886 | ** These values must match SQLITE_TXN_NONE, SQLITE_TXN_READ, and | ||||
| 70887 | ** SQLITE_TXN_WRITE | ||||
| 70888 | */ | ||||
| 70889 | #define TRANS_NONE0 0 | ||||
| 70890 | #define TRANS_READ1 1 | ||||
| 70891 | #define TRANS_WRITE2 2 | ||||
| 70892 | |||||
| 70893 | #if TRANS_NONE0!=SQLITE_TXN_NONE0 | ||||
| 70894 | # error wrong numeric code for no-transaction | ||||
| 70895 | #endif | ||||
| 70896 | #if TRANS_READ1!=SQLITE_TXN_READ1 | ||||
| 70897 | # error wrong numeric code for read-transaction | ||||
| 70898 | #endif | ||||
| 70899 | #if TRANS_WRITE2!=SQLITE_TXN_WRITE2 | ||||
| 70900 | # error wrong numeric code for write-transaction | ||||
| 70901 | #endif | ||||
| 70902 | |||||
| 70903 | |||||
| 70904 | /* | ||||
| 70905 | ** An instance of this object represents a single database file. | ||||
| 70906 | ** | ||||
| 70907 | ** A single database file can be in use at the same time by two | ||||
| 70908 | ** or more database connections. When two or more connections are | ||||
| 70909 | ** sharing the same database file, each connection has it own | ||||
| 70910 | ** private Btree object for the file and each of those Btrees points | ||||
| 70911 | ** to this one BtShared object. BtShared.nRef is the number of | ||||
| 70912 | ** connections currently sharing this database file. | ||||
| 70913 | ** | ||||
| 70914 | ** Fields in this structure are accessed under the BtShared.mutex | ||||
| 70915 | ** mutex, except for nRef and pNext which are accessed under the | ||||
| 70916 | ** global SQLITE_MUTEX_STATIC_MAIN mutex. The pPager field | ||||
| 70917 | ** may not be modified once it is initially set as long as nRef>0. | ||||
| 70918 | ** The pSchema field may be set once under BtShared.mutex and | ||||
| 70919 | ** thereafter is unchanged as long as nRef>0. | ||||
| 70920 | ** | ||||
| 70921 | ** isPending: | ||||
| 70922 | ** | ||||
| 70923 | ** If a BtShared client fails to obtain a write-lock on a database | ||||
| 70924 | ** table (because there exists one or more read-locks on the table), | ||||
| 70925 | ** the shared-cache enters 'pending-lock' state and isPending is | ||||
| 70926 | ** set to true. | ||||
| 70927 | ** | ||||
| 70928 | ** The shared-cache leaves the 'pending lock' state when either of | ||||
| 70929 | ** the following occur: | ||||
| 70930 | ** | ||||
| 70931 | ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR | ||||
| 70932 | ** 2) The number of locks held by other connections drops to zero. | ||||
| 70933 | ** | ||||
| 70934 | ** while in the 'pending-lock' state, no connection may start a new | ||||
| 70935 | ** transaction. | ||||
| 70936 | ** | ||||
| 70937 | ** This feature is included to help prevent writer-starvation. | ||||
| 70938 | */ | ||||
| 70939 | struct BtShared { | ||||
| 70940 | Pager *pPager; /* The page cache */ | ||||
| 70941 | sqlite3 *db; /* Database connection currently using this Btree */ | ||||
| 70942 | BtCursor *pCursor; /* A list of all open cursors */ | ||||
| 70943 | MemPage *pPage1; /* First page of the database */ | ||||
| 70944 | u8 openFlags; /* Flags to sqlite3BtreeOpen() */ | ||||
| 70945 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 70946 | u8 autoVacuum; /* True if auto-vacuum is enabled */ | ||||
| 70947 | u8 incrVacuum; /* True if incr-vacuum is enabled */ | ||||
| 70948 | u8 bDoTruncate; /* True to truncate db on commit */ | ||||
| 70949 | #endif | ||||
| 70950 | u8 inTransaction; /* Transaction state */ | ||||
| 70951 | u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */ | ||||
| 70952 | u8 nReserveWanted; /* Desired number of extra bytes per page */ | ||||
| 70953 | u16 btsFlags; /* Boolean parameters. See BTS_* macros below */ | ||||
| 70954 | u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ | ||||
| 70955 | u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ | ||||
| 70956 | u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ | ||||
| 70957 | u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ | ||||
| 70958 | u32 pageSize; /* Total number of bytes on a page */ | ||||
| 70959 | u32 usableSize; /* Number of usable bytes on each page */ | ||||
| 70960 | int nTransaction; /* Number of open transactions (read + write) */ | ||||
| 70961 | u32 nPage; /* Number of pages in the database */ | ||||
| 70962 | void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ | ||||
| 70963 | void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ | ||||
| 70964 | sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ | ||||
| 70965 | Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */ | ||||
| 70966 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 70967 | int nRef; /* Number of references to this structure */ | ||||
| 70968 | BtShared *pNext; /* Next on a list of sharable BtShared structs */ | ||||
| 70969 | BtLock *pLock; /* List of locks held on this shared-btree struct */ | ||||
| 70970 | Btree *pWriter; /* Btree with currently open write transaction */ | ||||
| 70971 | #endif | ||||
| 70972 | u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */ | ||||
| 70973 | int nPreformatSize; /* Size of last cell written by TransferRow() */ | ||||
| 70974 | }; | ||||
| 70975 | |||||
| 70976 | /* | ||||
| 70977 | ** Allowed values for BtShared.btsFlags | ||||
| 70978 | */ | ||||
| 70979 | #define BTS_READ_ONLY0x0001 0x0001 /* Underlying file is readonly */ | ||||
| 70980 | #define BTS_PAGESIZE_FIXED0x0002 0x0002 /* Page size can no longer be changed */ | ||||
| 70981 | #define BTS_SECURE_DELETE0x0004 0x0004 /* PRAGMA secure_delete is enabled */ | ||||
| 70982 | #define BTS_OVERWRITE0x0008 0x0008 /* Overwrite deleted content with zeros */ | ||||
| 70983 | #define BTS_FAST_SECURE0x000c 0x000c /* Combination of the previous two */ | ||||
| 70984 | #define BTS_INITIALLY_EMPTY0x0010 0x0010 /* Database was empty at trans start */ | ||||
| 70985 | #define BTS_NO_WAL0x0020 0x0020 /* Do not open write-ahead-log files */ | ||||
| 70986 | #define BTS_EXCLUSIVE0x0040 0x0040 /* pWriter has an exclusive lock */ | ||||
| 70987 | #define BTS_PENDING0x0080 0x0080 /* Waiting for read-locks to clear */ | ||||
| 70988 | |||||
| 70989 | /* | ||||
| 70990 | ** An instance of the following structure is used to hold information | ||||
| 70991 | ** about a cell. The parseCellPtr() function fills in this structure | ||||
| 70992 | ** based on information extract from the raw disk page. | ||||
| 70993 | */ | ||||
| 70994 | struct CellInfo { | ||||
| 70995 | i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */ | ||||
| 70996 | u8 *pPayload; /* Pointer to the start of payload */ | ||||
| 70997 | u32 nPayload; /* Bytes of payload */ | ||||
| 70998 | u16 nLocal; /* Amount of payload held locally, not on overflow */ | ||||
| 70999 | u16 nSize; /* Size of the cell content on the main b-tree page */ | ||||
| 71000 | }; | ||||
| 71001 | |||||
| 71002 | /* | ||||
| 71003 | ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than | ||||
| 71004 | ** this will be declared corrupt. This value is calculated based on a | ||||
| 71005 | ** maximum database size of 2^31 pages a minimum fanout of 2 for a | ||||
| 71006 | ** root-node and 3 for all other internal nodes. | ||||
| 71007 | ** | ||||
| 71008 | ** If a tree that appears to be taller than this is encountered, it is | ||||
| 71009 | ** assumed that the database is corrupt. | ||||
| 71010 | */ | ||||
| 71011 | #define BTCURSOR_MAX_DEPTH20 20 | ||||
| 71012 | |||||
| 71013 | /* | ||||
| 71014 | ** Maximum amount of storage local to a database page, regardless of | ||||
| 71015 | ** page size. | ||||
| 71016 | */ | ||||
| 71017 | #define BT_MAX_LOCAL65501 65501 /* 65536 - 35 */ | ||||
| 71018 | |||||
| 71019 | /* | ||||
| 71020 | ** A cursor is a pointer to a particular entry within a particular | ||||
| 71021 | ** b-tree within a database file. | ||||
| 71022 | ** | ||||
| 71023 | ** The entry is identified by its MemPage and the index in | ||||
| 71024 | ** MemPage.aCell[] of the entry. | ||||
| 71025 | ** | ||||
| 71026 | ** A single database file can be shared by two more database connections, | ||||
| 71027 | ** but cursors cannot be shared. Each cursor is associated with a | ||||
| 71028 | ** particular database connection identified BtCursor.pBtree.db. | ||||
| 71029 | ** | ||||
| 71030 | ** Fields in this structure are accessed under the BtShared.mutex | ||||
| 71031 | ** found at self->pBt->mutex. | ||||
| 71032 | ** | ||||
| 71033 | ** skipNext meaning: | ||||
| 71034 | ** The meaning of skipNext depends on the value of eState: | ||||
| 71035 | ** | ||||
| 71036 | ** eState Meaning of skipNext | ||||
| 71037 | ** VALID skipNext is meaningless and is ignored | ||||
| 71038 | ** INVALID skipNext is meaningless and is ignored | ||||
| 71039 | ** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and | ||||
| 71040 | ** sqlite3BtreePrevious() is no-op if skipNext<0. | ||||
| 71041 | ** REQUIRESEEK restoreCursorPosition() restores the cursor to | ||||
| 71042 | ** eState=SKIPNEXT if skipNext!=0 | ||||
| 71043 | ** FAULT skipNext holds the cursor fault error code. | ||||
| 71044 | */ | ||||
| 71045 | struct BtCursor { | ||||
| 71046 | u8 eState; /* One of the CURSOR_XXX constants (see below) */ | ||||
| 71047 | u8 curFlags; /* zero or more BTCF_* flags defined below */ | ||||
| 71048 | u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */ | ||||
| 71049 | u8 hints; /* As configured by CursorSetHints() */ | ||||
| 71050 | int skipNext; /* Prev() is noop if negative. Next() is noop if positive. | ||||
| 71051 | ** Error code if eState==CURSOR_FAULT */ | ||||
| 71052 | Btree *pBtree; /* The Btree to which this cursor belongs */ | ||||
| 71053 | Pgno *aOverflow; /* Cache of overflow page locations */ | ||||
| 71054 | void *pKey; /* Saved key that was cursor last known position */ | ||||
| 71055 | /* All fields above are zeroed when the cursor is allocated. See | ||||
| 71056 | ** sqlite3BtreeCursorZero(). Fields that follow must be manually | ||||
| 71057 | ** initialized. */ | ||||
| 71058 | #define BTCURSOR_FIRST_UNINITpBt pBt /* Name of first uninitialized field */ | ||||
| 71059 | BtShared *pBt; /* The BtShared this cursor points to */ | ||||
| 71060 | BtCursor *pNext; /* Forms a linked list of all cursors */ | ||||
| 71061 | CellInfo info; /* A parse of the cell we are pointing at */ | ||||
| 71062 | i64 nKey; /* Size of pKey, or last integer key */ | ||||
| 71063 | Pgno pgnoRoot; /* The root page of this tree */ | ||||
| 71064 | i8 iPage; /* Index of current page in apPage */ | ||||
| 71065 | u8 curIntKey; /* Value of apPage[0]->intKey */ | ||||
| 71066 | u16 ix; /* Current index for apPage[iPage] */ | ||||
| 71067 | u16 aiIdx[BTCURSOR_MAX_DEPTH20-1]; /* Current index in apPage[i] */ | ||||
| 71068 | struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */ | ||||
| 71069 | MemPage *pPage; /* Current page */ | ||||
| 71070 | MemPage *apPage[BTCURSOR_MAX_DEPTH20-1]; /* Stack of parents of current page */ | ||||
| 71071 | }; | ||||
| 71072 | |||||
| 71073 | /* | ||||
| 71074 | ** Legal values for BtCursor.curFlags | ||||
| 71075 | */ | ||||
| 71076 | #define BTCF_WriteFlag0x01 0x01 /* True if a write cursor */ | ||||
| 71077 | #define BTCF_ValidNKey0x02 0x02 /* True if info.nKey is valid */ | ||||
| 71078 | #define BTCF_ValidOvfl0x04 0x04 /* True if aOverflow is valid */ | ||||
| 71079 | #define BTCF_AtLast0x08 0x08 /* Cursor is pointing to the last entry */ | ||||
| 71080 | #define BTCF_Incrblob0x10 0x10 /* True if an incremental I/O handle */ | ||||
| 71081 | #define BTCF_Multiple0x20 0x20 /* Maybe another cursor on the same btree */ | ||||
| 71082 | #define BTCF_Pinned0x40 0x40 /* Cursor is busy and cannot be moved */ | ||||
| 71083 | |||||
| 71084 | /* | ||||
| 71085 | ** Potential values for BtCursor.eState. | ||||
| 71086 | ** | ||||
| 71087 | ** CURSOR_INVALID: | ||||
| 71088 | ** Cursor does not point to a valid entry. This can happen (for example) | ||||
| 71089 | ** because the table is empty or because BtreeCursorFirst() has not been | ||||
| 71090 | ** called. | ||||
| 71091 | ** | ||||
| 71092 | ** CURSOR_VALID: | ||||
| 71093 | ** Cursor points to a valid entry. getPayload() etc. may be called. | ||||
| 71094 | ** | ||||
| 71095 | ** CURSOR_SKIPNEXT: | ||||
| 71096 | ** Cursor is valid except that the Cursor.skipNext field is non-zero | ||||
| 71097 | ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious() | ||||
| 71098 | ** operation should be a no-op. | ||||
| 71099 | ** | ||||
| 71100 | ** CURSOR_REQUIRESEEK: | ||||
| 71101 | ** The table that this cursor was opened on still exists, but has been | ||||
| 71102 | ** modified since the cursor was last used. The cursor position is saved | ||||
| 71103 | ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in | ||||
| 71104 | ** this state, restoreCursorPosition() can be called to attempt to | ||||
| 71105 | ** seek the cursor to the saved position. | ||||
| 71106 | ** | ||||
| 71107 | ** CURSOR_FAULT: | ||||
| 71108 | ** An unrecoverable error (an I/O error or a malloc failure) has occurred | ||||
| 71109 | ** on a different connection that shares the BtShared cache with this | ||||
| 71110 | ** cursor. The error has left the cache in an inconsistent state. | ||||
| 71111 | ** Do nothing else with this cursor. Any attempt to use the cursor | ||||
| 71112 | ** should return the error code stored in BtCursor.skipNext | ||||
| 71113 | */ | ||||
| 71114 | #define CURSOR_VALID0 0 | ||||
| 71115 | #define CURSOR_INVALID1 1 | ||||
| 71116 | #define CURSOR_SKIPNEXT2 2 | ||||
| 71117 | #define CURSOR_REQUIRESEEK3 3 | ||||
| 71118 | #define CURSOR_FAULT4 4 | ||||
| 71119 | |||||
| 71120 | /* | ||||
| 71121 | ** The database page the PENDING_BYTE occupies. This page is never used. | ||||
| 71122 | */ | ||||
| 71123 | #define PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ((Pgno)((PENDING_BYTEsqlite3PendingByte/((pBt)->pageSize))+1)) | ||||
| 71124 | |||||
| 71125 | /* | ||||
| 71126 | ** These macros define the location of the pointer-map entry for a | ||||
| 71127 | ** database page. The first argument to each is the number of usable | ||||
| 71128 | ** bytes on each page of the database (often 1024). The second is the | ||||
| 71129 | ** page number to look up in the pointer map. | ||||
| 71130 | ** | ||||
| 71131 | ** PTRMAP_PAGENO returns the database page number of the pointer-map | ||||
| 71132 | ** page that stores the required pointer. PTRMAP_PTROFFSET returns | ||||
| 71133 | ** the offset of the requested map entry. | ||||
| 71134 | ** | ||||
| 71135 | ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, | ||||
| 71136 | ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be | ||||
| 71137 | ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements | ||||
| 71138 | ** this test. | ||||
| 71139 | */ | ||||
| 71140 | #define PTRMAP_PAGENO(pBt, pgno)ptrmapPageno(pBt, pgno) ptrmapPageno(pBt, pgno) | ||||
| 71141 | #define PTRMAP_PTROFFSET(pgptrmap, pgno)(5*(pgno-pgptrmap-1)) (5*(pgno-pgptrmap-1)) | ||||
| 71142 | #define PTRMAP_ISPAGE(pBt, pgno)(ptrmapPageno((pBt), (pgno))==(pgno)) (PTRMAP_PAGENO((pBt),(pgno))ptrmapPageno((pBt), (pgno))==(pgno)) | ||||
| 71143 | |||||
| 71144 | /* | ||||
| 71145 | ** The pointer map is a lookup table that identifies the parent page for | ||||
| 71146 | ** each child page in the database file. The parent page is the page that | ||||
| 71147 | ** contains a pointer to the child. Every page in the database contains | ||||
| 71148 | ** 0 or 1 parent pages. (In this context 'database page' refers | ||||
| 71149 | ** to any page that is not part of the pointer map itself.) Each pointer map | ||||
| 71150 | ** entry consists of a single byte 'type' and a 4 byte parent page number. | ||||
| 71151 | ** The PTRMAP_XXX identifiers below are the valid types. | ||||
| 71152 | ** | ||||
| 71153 | ** The purpose of the pointer map is to facility moving pages from one | ||||
| 71154 | ** position in the file to another as part of autovacuum. When a page | ||||
| 71155 | ** is moved, the pointer in its parent must be updated to point to the | ||||
| 71156 | ** new location. The pointer map is used to locate the parent page quickly. | ||||
| 71157 | ** | ||||
| 71158 | ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not | ||||
| 71159 | ** used in this case. | ||||
| 71160 | ** | ||||
| 71161 | ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number | ||||
| 71162 | ** is not used in this case. | ||||
| 71163 | ** | ||||
| 71164 | ** PTRMAP_OVERFLOW1: The database page is the first page in a list of | ||||
| 71165 | ** overflow pages. The page number identifies the page that | ||||
| 71166 | ** contains the cell with a pointer to this overflow page. | ||||
| 71167 | ** | ||||
| 71168 | ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of | ||||
| 71169 | ** overflow pages. The page-number identifies the previous | ||||
| 71170 | ** page in the overflow page list. | ||||
| 71171 | ** | ||||
| 71172 | ** PTRMAP_BTREE: The database page is a non-root btree page. The page number | ||||
| 71173 | ** identifies the parent page in the btree. | ||||
| 71174 | */ | ||||
| 71175 | #define PTRMAP_ROOTPAGE1 1 | ||||
| 71176 | #define PTRMAP_FREEPAGE2 2 | ||||
| 71177 | #define PTRMAP_OVERFLOW13 3 | ||||
| 71178 | #define PTRMAP_OVERFLOW24 4 | ||||
| 71179 | #define PTRMAP_BTREE5 5 | ||||
| 71180 | |||||
| 71181 | /* A bunch of assert() statements to check the transaction state variables | ||||
| 71182 | ** of handle p (type Btree*) are internally consistent. | ||||
| 71183 | */ | ||||
| 71184 | #define btreeIntegrity(p)((void) (0)); ((void) (0)); \ | ||||
| 71185 | assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 )((void) (0)); \ | ||||
| 71186 | assert( p->pBt->inTransaction>=p->inTrans )((void) (0)); | ||||
| 71187 | |||||
| 71188 | |||||
| 71189 | /* | ||||
| 71190 | ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine | ||||
| 71191 | ** if the database supports auto-vacuum or not. Because it is used | ||||
| 71192 | ** within an expression that is an argument to another macro | ||||
| 71193 | ** (sqliteMallocRaw), it is not possible to use conditional compilation. | ||||
| 71194 | ** So, this macro is defined instead. | ||||
| 71195 | */ | ||||
| 71196 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 71197 | #define ISAUTOVACUUM(pBt)(pBt->autoVacuum) (pBt->autoVacuum) | ||||
| 71198 | #else | ||||
| 71199 | #define ISAUTOVACUUM(pBt)(pBt->autoVacuum) 0 | ||||
| 71200 | #endif | ||||
| 71201 | |||||
| 71202 | |||||
| 71203 | /* | ||||
| 71204 | ** This structure is passed around through all the PRAGMA integrity_check | ||||
| 71205 | ** checking routines in order to keep track of some global state information. | ||||
| 71206 | ** | ||||
| 71207 | ** The aRef[] array is allocated so that there is 1 bit for each page in | ||||
| 71208 | ** the database. As the integrity-check proceeds, for each page used in | ||||
| 71209 | ** the database the corresponding bit is set. This allows integrity-check to | ||||
| 71210 | ** detect pages that are used twice and orphaned pages (both of which | ||||
| 71211 | ** indicate corruption). | ||||
| 71212 | */ | ||||
| 71213 | typedef struct IntegrityCk IntegrityCk; | ||||
| 71214 | struct IntegrityCk { | ||||
| 71215 | BtShared *pBt; /* The tree being checked out */ | ||||
| 71216 | Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */ | ||||
| 71217 | u8 *aPgRef; /* 1 bit per page in the db (see above) */ | ||||
| 71218 | Pgno nCkPage; /* Pages in the database. 0 for partial check */ | ||||
| 71219 | int mxErr; /* Stop accumulating errors when this reaches zero */ | ||||
| 71220 | int nErr; /* Number of messages written to zErrMsg so far */ | ||||
| 71221 | int rc; /* SQLITE_OK, SQLITE_NOMEM, or SQLITE_INTERRUPT */ | ||||
| 71222 | u32 nStep; /* Number of steps into the integrity_check process */ | ||||
| 71223 | const char *zPfx; /* Error message prefix */ | ||||
| 71224 | Pgno v0; /* Value for first %u substitution in zPfx (root page) */ | ||||
| 71225 | Pgno v1; /* Value for second %u substitution in zPfx (current pg) */ | ||||
| 71226 | int v2; /* Value for third %d substitution in zPfx */ | ||||
| 71227 | StrAccum errMsg; /* Accumulate the error message text here */ | ||||
| 71228 | u32 *heap; /* Min-heap used for analyzing cell coverage */ | ||||
| 71229 | sqlite3 *db; /* Database connection running the check */ | ||||
| 71230 | i64 nRow; /* Number of rows visited in current tree */ | ||||
| 71231 | }; | ||||
| 71232 | |||||
| 71233 | /* | ||||
| 71234 | ** Routines to read or write a two- and four-byte big-endian integer values. | ||||
| 71235 | */ | ||||
| 71236 | #define get2byte(x)((x)[0]<<8 | (x)[1]) ((x)[0]<<8 | (x)[1]) | ||||
| 71237 | #define put2byte(p,v)((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) | ||||
| 71238 | #define get4bytesqlite3Get4byte sqlite3Get4byte | ||||
| 71239 | #define put4bytesqlite3Put4byte sqlite3Put4byte | ||||
| 71240 | |||||
| 71241 | /* | ||||
| 71242 | ** get2byteAligned(), unlike get2byte(), requires that its argument point to a | ||||
| 71243 | ** two-byte aligned address. get2byteAligned() is only used for accessing the | ||||
| 71244 | ** cell addresses in a btree header. | ||||
| 71245 | */ | ||||
| 71246 | #if SQLITE_BYTEORDER1234==4321 | ||||
| 71247 | # define get2byteAligned(x)((x)[0]<<8 | (x)[1]) (*(u16*)(x)) | ||||
| 71248 | #elif SQLITE_BYTEORDER1234==1234 && GCC_VERSION(4*1000000+2*1000+1)>=4008000 | ||||
| 71249 | # define get2byteAligned(x)((x)[0]<<8 | (x)[1]) __builtin_bswap16(*(u16*)(x)) | ||||
| 71250 | #elif SQLITE_BYTEORDER1234==1234 && MSVC_VERSION0>=1300 | ||||
| 71251 | # define get2byteAligned(x)((x)[0]<<8 | (x)[1]) _byteswap_ushort(*(u16*)(x)) | ||||
| 71252 | #else | ||||
| 71253 | # define get2byteAligned(x)((x)[0]<<8 | (x)[1]) ((x)[0]<<8 | (x)[1]) | ||||
| 71254 | #endif | ||||
| 71255 | |||||
| 71256 | /************** End of btreeInt.h ********************************************/ | ||||
| 71257 | /************** Continuing where we left off in btmutex.c ********************/ | ||||
| 71258 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 71259 | #if SQLITE_THREADSAFE2 | ||||
| 71260 | |||||
| 71261 | /* | ||||
| 71262 | ** Obtain the BtShared mutex associated with B-Tree handle p. Also, | ||||
| 71263 | ** set BtShared.db to the database handle associated with p and the | ||||
| 71264 | ** p->locked boolean to true. | ||||
| 71265 | */ | ||||
| 71266 | static void lockBtreeMutex(Btree *p){ | ||||
| 71267 | assert( p->locked==0 )((void) (0)); | ||||
| 71268 | assert( sqlite3_mutex_notheld(p->pBt->mutex) )((void) (0)); | ||||
| 71269 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 71270 | |||||
| 71271 | sqlite3_mutex_enter(p->pBt->mutex); | ||||
| 71272 | p->pBt->db = p->db; | ||||
| 71273 | p->locked = 1; | ||||
| 71274 | } | ||||
| 71275 | |||||
| 71276 | /* | ||||
| 71277 | ** Release the BtShared mutex associated with B-Tree handle p and | ||||
| 71278 | ** clear the p->locked boolean. | ||||
| 71279 | */ | ||||
| 71280 | static void SQLITE_NOINLINE__attribute__((noinline)) unlockBtreeMutex(Btree *p){ | ||||
| 71281 | BtShared *pBt = p->pBt; | ||||
| 71282 | assert( p->locked==1 )((void) (0)); | ||||
| 71283 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 71284 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 71285 | assert( p->db==pBt->db )((void) (0)); | ||||
| 71286 | |||||
| 71287 | sqlite3_mutex_leave(pBt->mutex); | ||||
| 71288 | p->locked = 0; | ||||
| 71289 | } | ||||
| 71290 | |||||
| 71291 | /* Forward reference */ | ||||
| 71292 | static void SQLITE_NOINLINE__attribute__((noinline)) btreeLockCarefully(Btree *p); | ||||
| 71293 | |||||
| 71294 | /* | ||||
| 71295 | ** Enter a mutex on the given BTree object. | ||||
| 71296 | ** | ||||
| 71297 | ** If the object is not sharable, then no mutex is ever required | ||||
| 71298 | ** and this routine is a no-op. The underlying mutex is non-recursive. | ||||
| 71299 | ** But we keep a reference count in Btree.wantToLock so the behavior | ||||
| 71300 | ** of this interface is recursive. | ||||
| 71301 | ** | ||||
| 71302 | ** To avoid deadlocks, multiple Btrees are locked in the same order | ||||
| 71303 | ** by all database connections. The p->pNext is a list of other | ||||
| 71304 | ** Btrees belonging to the same database connection as the p Btree | ||||
| 71305 | ** which need to be locked after p. If we cannot get a lock on | ||||
| 71306 | ** p, then first unlock all of the others on p->pNext, then wait | ||||
| 71307 | ** for the lock to become available on p, then relock all of the | ||||
| 71308 | ** subsequent Btrees that desire a lock. | ||||
| 71309 | */ | ||||
| 71310 | SQLITE_PRIVATEstatic void sqlite3BtreeEnter(Btree *p){ | ||||
| 71311 | /* Some basic sanity checking on the Btree. The list of Btrees | ||||
| 71312 | ** connected by pNext and pPrev should be in sorted order by | ||||
| 71313 | ** Btree.pBt value. All elements of the list should belong to | ||||
| 71314 | ** the same connection. Only shared Btrees are on the list. */ | ||||
| 71315 | assert( p->pNext==0 || p->pNext->pBt>p->pBt )((void) (0)); | ||||
| 71316 | assert( p->pPrev==0 || p->pPrev->pBt<p->pBt )((void) (0)); | ||||
| 71317 | assert( p->pNext==0 || p->pNext->db==p->db )((void) (0)); | ||||
| 71318 | assert( p->pPrev==0 || p->pPrev->db==p->db )((void) (0)); | ||||
| 71319 | assert( p->sharable || (p->pNext==0 && p->pPrev==0) )((void) (0)); | ||||
| 71320 | |||||
| 71321 | /* Check for locking consistency */ | ||||
| 71322 | assert( !p->locked || p->wantToLock>0 )((void) (0)); | ||||
| 71323 | assert( p->sharable || p->wantToLock==0 )((void) (0)); | ||||
| 71324 | |||||
| 71325 | /* We should already hold a lock on the database connection */ | ||||
| 71326 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 71327 | |||||
| 71328 | /* Unless the database is sharable and unlocked, then BtShared.db | ||||
| 71329 | ** should already be set correctly. */ | ||||
| 71330 | assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db )((void) (0)); | ||||
| 71331 | |||||
| 71332 | if( !p->sharable ) return; | ||||
| 71333 | p->wantToLock++; | ||||
| 71334 | if( p->locked ) return; | ||||
| 71335 | btreeLockCarefully(p); | ||||
| 71336 | } | ||||
| 71337 | |||||
| 71338 | /* This is a helper function for sqlite3BtreeLock(). By moving | ||||
| 71339 | ** complex, but seldom used logic, out of sqlite3BtreeLock() and | ||||
| 71340 | ** into this routine, we avoid unnecessary stack pointer changes | ||||
| 71341 | ** and thus help the sqlite3BtreeLock() routine to run much faster | ||||
| 71342 | ** in the common case. | ||||
| 71343 | */ | ||||
| 71344 | static void SQLITE_NOINLINE__attribute__((noinline)) btreeLockCarefully(Btree *p){ | ||||
| 71345 | Btree *pLater; | ||||
| 71346 | |||||
| 71347 | /* In most cases, we should be able to acquire the lock we | ||||
| 71348 | ** want without having to go through the ascending lock | ||||
| 71349 | ** procedure that follows. Just be sure not to block. | ||||
| 71350 | */ | ||||
| 71351 | if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK0 ){ | ||||
| 71352 | p->pBt->db = p->db; | ||||
| 71353 | p->locked = 1; | ||||
| 71354 | return; | ||||
| 71355 | } | ||||
| 71356 | |||||
| 71357 | /* To avoid deadlock, first release all locks with a larger | ||||
| 71358 | ** BtShared address. Then acquire our lock. Then reacquire | ||||
| 71359 | ** the other BtShared locks that we used to hold in ascending | ||||
| 71360 | ** order. | ||||
| 71361 | */ | ||||
| 71362 | for(pLater=p->pNext; pLater; pLater=pLater->pNext){ | ||||
| 71363 | assert( pLater->sharable )((void) (0)); | ||||
| 71364 | assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt )((void) (0)); | ||||
| 71365 | assert( !pLater->locked || pLater->wantToLock>0 )((void) (0)); | ||||
| 71366 | if( pLater->locked ){ | ||||
| 71367 | unlockBtreeMutex(pLater); | ||||
| 71368 | } | ||||
| 71369 | } | ||||
| 71370 | lockBtreeMutex(p); | ||||
| 71371 | for(pLater=p->pNext; pLater; pLater=pLater->pNext){ | ||||
| 71372 | if( pLater->wantToLock ){ | ||||
| 71373 | lockBtreeMutex(pLater); | ||||
| 71374 | } | ||||
| 71375 | } | ||||
| 71376 | } | ||||
| 71377 | |||||
| 71378 | |||||
| 71379 | /* | ||||
| 71380 | ** Exit the recursive mutex on a Btree. | ||||
| 71381 | */ | ||||
| 71382 | SQLITE_PRIVATEstatic void sqlite3BtreeLeave(Btree *p){ | ||||
| 71383 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 71384 | if( p->sharable ){ | ||||
| 71385 | assert( p->wantToLock>0 )((void) (0)); | ||||
| 71386 | p->wantToLock--; | ||||
| 71387 | if( p->wantToLock==0 ){ | ||||
| 71388 | unlockBtreeMutex(p); | ||||
| 71389 | } | ||||
| 71390 | } | ||||
| 71391 | } | ||||
| 71392 | |||||
| 71393 | #ifndef NDEBUG1 | ||||
| 71394 | /* | ||||
| 71395 | ** Return true if the BtShared mutex is held on the btree, or if the | ||||
| 71396 | ** B-Tree is not marked as sharable. | ||||
| 71397 | ** | ||||
| 71398 | ** This routine is used only from within assert() statements. | ||||
| 71399 | */ | ||||
| 71400 | SQLITE_PRIVATEstatic int sqlite3BtreeHoldsMutex(Btree *p){ | ||||
| 71401 | assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 )((void) (0)); | ||||
| 71402 | assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db )((void) (0)); | ||||
| 71403 | assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) )((void) (0)); | ||||
| 71404 | assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 71405 | |||||
| 71406 | return (p->sharable==0 || p->locked); | ||||
| 71407 | } | ||||
| 71408 | #endif | ||||
| 71409 | |||||
| 71410 | |||||
| 71411 | /* | ||||
| 71412 | ** Enter the mutex on every Btree associated with a database | ||||
| 71413 | ** connection. This is needed (for example) prior to parsing | ||||
| 71414 | ** a statement since we will be comparing table and column names | ||||
| 71415 | ** against all schemas and we do not want those schemas being | ||||
| 71416 | ** reset out from under us. | ||||
| 71417 | ** | ||||
| 71418 | ** There is a corresponding leave-all procedures. | ||||
| 71419 | ** | ||||
| 71420 | ** Enter the mutexes in ascending order by BtShared pointer address | ||||
| 71421 | ** to avoid the possibility of deadlock when two threads with | ||||
| 71422 | ** two or more btrees in common both try to lock all their btrees | ||||
| 71423 | ** at the same instant. | ||||
| 71424 | */ | ||||
| 71425 | static void SQLITE_NOINLINE__attribute__((noinline)) btreeEnterAll(sqlite3 *db){ | ||||
| 71426 | int i; | ||||
| 71427 | u8 skipOk = 1; | ||||
| 71428 | Btree *p; | ||||
| 71429 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 71430 | for(i=0; i<db->nDb; i++){ | ||||
| 71431 | p = db->aDb[i].pBt; | ||||
| 71432 | if( p && p->sharable ){ | ||||
| 71433 | sqlite3BtreeEnter(p); | ||||
| 71434 | skipOk = 0; | ||||
| 71435 | } | ||||
| 71436 | } | ||||
| 71437 | db->noSharedCache = skipOk; | ||||
| 71438 | } | ||||
| 71439 | SQLITE_PRIVATEstatic void sqlite3BtreeEnterAll(sqlite3 *db){ | ||||
| 71440 | if( db->noSharedCache==0 ) btreeEnterAll(db); | ||||
| 71441 | } | ||||
| 71442 | static void SQLITE_NOINLINE__attribute__((noinline)) btreeLeaveAll(sqlite3 *db){ | ||||
| 71443 | int i; | ||||
| 71444 | Btree *p; | ||||
| 71445 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 71446 | for(i=0; i<db->nDb; i++){ | ||||
| 71447 | p = db->aDb[i].pBt; | ||||
| 71448 | if( p ) sqlite3BtreeLeave(p); | ||||
| 71449 | } | ||||
| 71450 | } | ||||
| 71451 | SQLITE_PRIVATEstatic void sqlite3BtreeLeaveAll(sqlite3 *db){ | ||||
| 71452 | if( db->noSharedCache==0 ) btreeLeaveAll(db); | ||||
| 71453 | } | ||||
| 71454 | |||||
| 71455 | #ifndef NDEBUG1 | ||||
| 71456 | /* | ||||
| 71457 | ** Return true if the current thread holds the database connection | ||||
| 71458 | ** mutex and all required BtShared mutexes. | ||||
| 71459 | ** | ||||
| 71460 | ** This routine is used inside assert() statements only. | ||||
| 71461 | */ | ||||
| 71462 | SQLITE_PRIVATEstatic int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ | ||||
| 71463 | int i; | ||||
| 71464 | if( !sqlite3_mutex_held(db->mutex) ){ | ||||
| 71465 | return 0; | ||||
| 71466 | } | ||||
| 71467 | for(i=0; i<db->nDb; i++){ | ||||
| 71468 | Btree *p; | ||||
| 71469 | p = db->aDb[i].pBt; | ||||
| 71470 | if( p && p->sharable && | ||||
| 71471 | (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ | ||||
| 71472 | return 0; | ||||
| 71473 | } | ||||
| 71474 | } | ||||
| 71475 | return 1; | ||||
| 71476 | } | ||||
| 71477 | #endif /* NDEBUG */ | ||||
| 71478 | |||||
| 71479 | #ifndef NDEBUG1 | ||||
| 71480 | /* | ||||
| 71481 | ** Return true if the correct mutexes are held for accessing the | ||||
| 71482 | ** db->aDb[iDb].pSchema structure. The mutexes required for schema | ||||
| 71483 | ** access are: | ||||
| 71484 | ** | ||||
| 71485 | ** (1) The mutex on db | ||||
| 71486 | ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. | ||||
| 71487 | ** | ||||
| 71488 | ** If pSchema is not NULL, then iDb is computed from pSchema and | ||||
| 71489 | ** db using sqlite3SchemaToIndex(). | ||||
| 71490 | */ | ||||
| 71491 | SQLITE_PRIVATEstatic int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ | ||||
| 71492 | Btree *p; | ||||
| 71493 | assert( db!=0 )((void) (0)); | ||||
| 71494 | if( db->pVfs==0 && db->nDb==0 ) return 1; | ||||
| 71495 | if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); | ||||
| 71496 | assert( iDb>=0 && iDb<db->nDb )((void) (0)); | ||||
| 71497 | if( !sqlite3_mutex_held(db->mutex) ) return 0; | ||||
| 71498 | if( iDb==1 ) return 1; | ||||
| 71499 | p = db->aDb[iDb].pBt; | ||||
| 71500 | assert( p!=0 )((void) (0)); | ||||
| 71501 | return p->sharable==0 || p->locked==1; | ||||
| 71502 | } | ||||
| 71503 | #endif /* NDEBUG */ | ||||
| 71504 | |||||
| 71505 | #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ | ||||
| 71506 | /* | ||||
| 71507 | ** The following are special cases for mutex enter routines for use | ||||
| 71508 | ** in single threaded applications that use shared cache. Except for | ||||
| 71509 | ** these two routines, all mutex operations are no-ops in that case and | ||||
| 71510 | ** are null #defines in btree.h. | ||||
| 71511 | ** | ||||
| 71512 | ** If shared cache is disabled, then all btree mutex routines, including | ||||
| 71513 | ** the ones below, are no-ops and are null #defines in btree.h. | ||||
| 71514 | */ | ||||
| 71515 | |||||
| 71516 | SQLITE_PRIVATEstatic void sqlite3BtreeEnter(Btree *p){ | ||||
| 71517 | p->pBt->db = p->db; | ||||
| 71518 | } | ||||
| 71519 | SQLITE_PRIVATEstatic void sqlite3BtreeEnterAll(sqlite3 *db){ | ||||
| 71520 | int i; | ||||
| 71521 | for(i=0; i<db->nDb; i++){ | ||||
| 71522 | Btree *p = db->aDb[i].pBt; | ||||
| 71523 | if( p ){ | ||||
| 71524 | p->pBt->db = p->db; | ||||
| 71525 | } | ||||
| 71526 | } | ||||
| 71527 | } | ||||
| 71528 | #endif /* if SQLITE_THREADSAFE */ | ||||
| 71529 | |||||
| 71530 | #ifndef SQLITE_OMIT_INCRBLOB | ||||
| 71531 | /* | ||||
| 71532 | ** Enter a mutex on a Btree given a cursor owned by that Btree. | ||||
| 71533 | ** | ||||
| 71534 | ** These entry points are used by incremental I/O only. Enter() is required | ||||
| 71535 | ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not | ||||
| 71536 | ** the build is threadsafe. Leave() is only required by threadsafe builds. | ||||
| 71537 | */ | ||||
| 71538 | SQLITE_PRIVATEstatic void sqlite3BtreeEnterCursor(BtCursor *pCur){ | ||||
| 71539 | sqlite3BtreeEnter(pCur->pBtree); | ||||
| 71540 | } | ||||
| 71541 | # if SQLITE_THREADSAFE2 | ||||
| 71542 | SQLITE_PRIVATEstatic void sqlite3BtreeLeaveCursor(BtCursor *pCur){ | ||||
| 71543 | sqlite3BtreeLeave(pCur->pBtree); | ||||
| 71544 | } | ||||
| 71545 | # endif | ||||
| 71546 | #endif /* ifndef SQLITE_OMIT_INCRBLOB */ | ||||
| 71547 | |||||
| 71548 | #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */ | ||||
| 71549 | |||||
| 71550 | /************** End of btmutex.c *********************************************/ | ||||
| 71551 | /************** Begin file btree.c *******************************************/ | ||||
| 71552 | /* | ||||
| 71553 | ** 2004 April 6 | ||||
| 71554 | ** | ||||
| 71555 | ** The author disclaims copyright to this source code. In place of | ||||
| 71556 | ** a legal notice, here is a blessing: | ||||
| 71557 | ** | ||||
| 71558 | ** May you do good and not evil. | ||||
| 71559 | ** May you find forgiveness for yourself and forgive others. | ||||
| 71560 | ** May you share freely, never taking more than you give. | ||||
| 71561 | ** | ||||
| 71562 | ************************************************************************* | ||||
| 71563 | ** This file implements an external (disk-based) database using BTrees. | ||||
| 71564 | ** See the header comment on "btreeInt.h" for additional information. | ||||
| 71565 | ** Including a description of file format and an overview of operation. | ||||
| 71566 | */ | ||||
| 71567 | /* #include "btreeInt.h" */ | ||||
| 71568 | |||||
| 71569 | /* | ||||
| 71570 | ** The header string that appears at the beginning of every | ||||
| 71571 | ** SQLite database. | ||||
| 71572 | */ | ||||
| 71573 | static const char zMagicHeader[] = SQLITE_FILE_HEADER"SQLite format 3"; | ||||
| 71574 | |||||
| 71575 | /* | ||||
| 71576 | ** Set this global variable to 1 to enable tracing using the TRACE | ||||
| 71577 | ** macro. | ||||
| 71578 | */ | ||||
| 71579 | #if 0 | ||||
| 71580 | int sqlite3BtreeTrace=1; /* True to enable tracing */ | ||||
| 71581 | # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdoutstdout);} | ||||
| 71582 | #else | ||||
| 71583 | # define TRACE(X) | ||||
| 71584 | #endif | ||||
| 71585 | |||||
| 71586 | /* | ||||
| 71587 | ** Extract a 2-byte big-endian integer from an array of unsigned bytes. | ||||
| 71588 | ** But if the value is zero, make it 65536. | ||||
| 71589 | ** | ||||
| 71590 | ** This routine is used to extract the "offset to cell content area" value | ||||
| 71591 | ** from the header of a btree page. If the page size is 65536 and the page | ||||
| 71592 | ** is empty, the offset should be 65536, but the 2-byte value stores zero. | ||||
| 71593 | ** This routine makes the necessary adjustment to 65536. | ||||
| 71594 | */ | ||||
| 71595 | #define get2byteNotZero(X)(((((int)((X)[0]<<8 | (X)[1]))-1)&0xffff)+1) (((((int)get2byte(X)((X)[0]<<8 | (X)[1]))-1)&0xffff)+1) | ||||
| 71596 | |||||
| 71597 | /* | ||||
| 71598 | ** Values passed as the 5th argument to allocateBtreePage() | ||||
| 71599 | */ | ||||
| 71600 | #define BTALLOC_ANY0 0 /* Allocate any page */ | ||||
| 71601 | #define BTALLOC_EXACT1 1 /* Allocate exact page if possible */ | ||||
| 71602 | #define BTALLOC_LE2 2 /* Allocate any page <= the parameter */ | ||||
| 71603 | |||||
| 71604 | /* | ||||
| 71605 | ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not | ||||
| 71606 | ** defined, or 0 if it is. For example: | ||||
| 71607 | ** | ||||
| 71608 | ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); | ||||
| 71609 | */ | ||||
| 71610 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 71611 | #define IfNotOmitAV(expr)(expr) (expr) | ||||
| 71612 | #else | ||||
| 71613 | #define IfNotOmitAV(expr)(expr) 0 | ||||
| 71614 | #endif | ||||
| 71615 | |||||
| 71616 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 71617 | /* | ||||
| 71618 | ** A list of BtShared objects that are eligible for participation | ||||
| 71619 | ** in shared cache. This variable has file scope during normal builds, | ||||
| 71620 | ** but the test harness needs to access it so we make it global for | ||||
| 71621 | ** test builds. | ||||
| 71622 | ** | ||||
| 71623 | ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN. | ||||
| 71624 | */ | ||||
| 71625 | #ifdef SQLITE_TEST | ||||
| 71626 | SQLITE_PRIVATEstatic BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; | ||||
| 71627 | #else | ||||
| 71628 | static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; | ||||
| 71629 | #endif | ||||
| 71630 | #endif /* SQLITE_OMIT_SHARED_CACHE */ | ||||
| 71631 | |||||
| 71632 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 71633 | /* | ||||
| 71634 | ** Enable or disable the shared pager and schema features. | ||||
| 71635 | ** | ||||
| 71636 | ** This routine has no effect on existing database connections. | ||||
| 71637 | ** The shared cache setting effects only future calls to | ||||
| 71638 | ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). | ||||
| 71639 | */ | ||||
| 71640 | SQLITE_API int sqlite3_enable_shared_cache(int enable){ | ||||
| 71641 | sqlite3GlobalConfigsqlite3Config.sharedCacheEnabled = enable; | ||||
| 71642 | return SQLITE_OK0; | ||||
| 71643 | } | ||||
| 71644 | #endif | ||||
| 71645 | |||||
| 71646 | |||||
| 71647 | |||||
| 71648 | #ifdef SQLITE_OMIT_SHARED_CACHE | ||||
| 71649 | /* | ||||
| 71650 | ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), | ||||
| 71651 | ** and clearAllSharedCacheTableLocks() | ||||
| 71652 | ** manipulate entries in the BtShared.pLock linked list used to store | ||||
| 71653 | ** shared-cache table level locks. If the library is compiled with the | ||||
| 71654 | ** shared-cache feature disabled, then there is only ever one user | ||||
| 71655 | ** of each BtShared structure and so this locking is not necessary. | ||||
| 71656 | ** So define the lock related functions as no-ops. | ||||
| 71657 | */ | ||||
| 71658 | #define querySharedCacheTableLock(a,b,c) SQLITE_OK0 | ||||
| 71659 | #define setSharedCacheTableLock(a,b,c) SQLITE_OK0 | ||||
| 71660 | #define clearAllSharedCacheTableLocks(a) | ||||
| 71661 | #define downgradeAllSharedCacheTableLocks(a) | ||||
| 71662 | #define hasSharedCacheTableLock(a,b,c,d) 1 | ||||
| 71663 | #define hasReadConflicts(a, b) 0 | ||||
| 71664 | #endif | ||||
| 71665 | |||||
| 71666 | #ifdef SQLITE_DEBUG | ||||
| 71667 | /* | ||||
| 71668 | ** Return and reset the seek counter for a Btree object. | ||||
| 71669 | */ | ||||
| 71670 | SQLITE_PRIVATEstatic sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt)0{ | ||||
| 71671 | u64 n = pBt->nSeek; | ||||
| 71672 | pBt->nSeek = 0; | ||||
| 71673 | return n; | ||||
| 71674 | } | ||||
| 71675 | #endif | ||||
| 71676 | |||||
| 71677 | /* | ||||
| 71678 | ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single | ||||
| 71679 | ** (MemPage*) as an argument. The (MemPage*) must not be NULL. | ||||
| 71680 | ** | ||||
| 71681 | ** If SQLITE_DEBUG is not defined, then this macro is equivalent to | ||||
| 71682 | ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message | ||||
| 71683 | ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented | ||||
| 71684 | ** with the page number and filename associated with the (MemPage*). | ||||
| 71685 | */ | ||||
| 71686 | #ifdef SQLITE_DEBUG | ||||
| 71687 | int corruptPageError(int lineno, MemPage *p){ | ||||
| 71688 | char *zMsg; | ||||
| 71689 | sqlite3BeginBenignMalloc(); | ||||
| 71690 | zMsg = sqlite3_mprintf("database corruption page %u of %s", | ||||
| 71691 | p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0) | ||||
| 71692 | ); | ||||
| 71693 | sqlite3EndBenignMalloc(); | ||||
| 71694 | if( zMsg ){ | ||||
| 71695 | sqlite3ReportError(SQLITE_CORRUPT11, lineno, zMsg); | ||||
| 71696 | } | ||||
| 71697 | sqlite3_free(zMsg); | ||||
| 71698 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(71698); | ||||
| 71699 | } | ||||
| 71700 | # define SQLITE_CORRUPT_PAGE(pMemPage)sqlite3CorruptError(71700) corruptPageError(__LINE__71700, pMemPage) | ||||
| 71701 | #else | ||||
| 71702 | # define SQLITE_CORRUPT_PAGE(pMemPage)sqlite3CorruptError(71702) SQLITE_CORRUPT_PGNO(pMemPage->pgno)sqlite3CorruptError(71702) | ||||
| 71703 | #endif | ||||
| 71704 | |||||
| 71705 | /* Default value for SHARED_LOCK_TRACE macro if shared-cache is disabled | ||||
| 71706 | ** or if the lock tracking is disabled. This is always the value for | ||||
| 71707 | ** release builds. | ||||
| 71708 | */ | ||||
| 71709 | #define SHARED_LOCK_TRACE(X,MSG,TAB,TYPE) /*no-op*/ | ||||
| 71710 | |||||
| 71711 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 71712 | |||||
| 71713 | #if 0 | ||||
| 71714 | /* ^---- Change to 1 and recompile to enable shared-lock tracing | ||||
| 71715 | ** for debugging purposes. | ||||
| 71716 | ** | ||||
| 71717 | ** Print all shared-cache locks on a BtShared. Debugging use only. | ||||
| 71718 | */ | ||||
| 71719 | static void sharedLockTrace( | ||||
| 71720 | BtShared *pBt, | ||||
| 71721 | const char *zMsg, | ||||
| 71722 | int iRoot, | ||||
| 71723 | int eLockType | ||||
| 71724 | ){ | ||||
| 71725 | BtLock *pLock; | ||||
| 71726 | if( iRoot>0 ){ | ||||
| 71727 | printf("%s-%p %u%s:", zMsg, pBt, iRoot, eLockType==READ_LOCK1?"R":"W"); | ||||
| 71728 | }else{ | ||||
| 71729 | printf("%s-%p:", zMsg, pBt); | ||||
| 71730 | } | ||||
| 71731 | for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ | ||||
| 71732 | printf(" %p/%u%s", pLock->pBtree, pLock->iTable, | ||||
| 71733 | pLock->eLock==READ_LOCK1 ? "R" : "W"); | ||||
| 71734 | while( pLock->pNext && pLock->pBtree==pLock->pNext->pBtree ){ | ||||
| 71735 | pLock = pLock->pNext; | ||||
| 71736 | printf(",%u%s", pLock->iTable, pLock->eLock==READ_LOCK1 ? "R" : "W"); | ||||
| 71737 | } | ||||
| 71738 | } | ||||
| 71739 | printf("\n"); | ||||
| 71740 | fflush(stdoutstdout); | ||||
| 71741 | } | ||||
| 71742 | #undef SHARED_LOCK_TRACE | ||||
| 71743 | #define SHARED_LOCK_TRACE(X,MSG,TAB,TYPE) sharedLockTrace(X,MSG,TAB,TYPE) | ||||
| 71744 | #endif /* Shared-lock tracing */ | ||||
| 71745 | |||||
| 71746 | #ifdef SQLITE_DEBUG | ||||
| 71747 | /* | ||||
| 71748 | **** This function is only used as part of an assert() statement. *** | ||||
| 71749 | ** | ||||
| 71750 | ** Check to see if pBtree holds the required locks to read or write to the | ||||
| 71751 | ** table with root page iRoot. Return 1 if it does and 0 if not. | ||||
| 71752 | ** | ||||
| 71753 | ** For example, when writing to a table with root-page iRoot via | ||||
| 71754 | ** Btree connection pBtree: | ||||
| 71755 | ** | ||||
| 71756 | ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); | ||||
| 71757 | ** | ||||
| 71758 | ** When writing to an index that resides in a sharable database, the | ||||
| 71759 | ** caller should have first obtained a lock specifying the root page of | ||||
| 71760 | ** the corresponding table. This makes things a bit more complicated, | ||||
| 71761 | ** as this module treats each table as a separate structure. To determine | ||||
| 71762 | ** the table corresponding to the index being written, this | ||||
| 71763 | ** function has to search through the database schema. | ||||
| 71764 | ** | ||||
| 71765 | ** Instead of a lock on the table/index rooted at page iRoot, the caller may | ||||
| 71766 | ** hold a write-lock on the schema table (root page 1). This is also | ||||
| 71767 | ** acceptable. | ||||
| 71768 | */ | ||||
| 71769 | static int hasSharedCacheTableLock( | ||||
| 71770 | Btree *pBtree, /* Handle that must hold lock */ | ||||
| 71771 | Pgno iRoot, /* Root page of b-tree */ | ||||
| 71772 | int isIndex, /* True if iRoot is the root of an index b-tree */ | ||||
| 71773 | int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ | ||||
| 71774 | ){ | ||||
| 71775 | Schema *pSchema = (Schema *)pBtree->pBt->pSchema; | ||||
| 71776 | Pgno iTab = 0; | ||||
| 71777 | BtLock *pLock; | ||||
| 71778 | |||||
| 71779 | /* If this database is not shareable, or if the client is reading | ||||
| 71780 | ** and has the read-uncommitted flag set, then no lock is required. | ||||
| 71781 | ** Return true immediately. | ||||
| 71782 | */ | ||||
| 71783 | if( (pBtree->sharable==0) | ||||
| 71784 | || (eLockType==READ_LOCK1 && (pBtree->db->flags & SQLITE_ReadUncommit((u64)(0x00004)<<32))) | ||||
| 71785 | ){ | ||||
| 71786 | return 1; | ||||
| 71787 | } | ||||
| 71788 | |||||
| 71789 | /* If the client is reading or writing an index and the schema is | ||||
| 71790 | ** not loaded, then it is too difficult to actually check to see if | ||||
| 71791 | ** the correct locks are held. So do not bother - just return true. | ||||
| 71792 | ** This case does not come up very often anyhow. | ||||
| 71793 | */ | ||||
| 71794 | if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded0x0001)==0) ){ | ||||
| 71795 | return 1; | ||||
| 71796 | } | ||||
| 71797 | |||||
| 71798 | /* Figure out the root-page that the lock should be held on. For table | ||||
| 71799 | ** b-trees, this is just the root page of the b-tree being read or | ||||
| 71800 | ** written. For index b-trees, it is the root page of the associated | ||||
| 71801 | ** table. */ | ||||
| 71802 | if( isIndex ){ | ||||
| 71803 | HashElem *p; | ||||
| 71804 | int bSeen = 0; | ||||
| 71805 | for(p=sqliteHashFirst(&pSchema->idxHash)((&pSchema->idxHash)->first); p; p=sqliteHashNext(p)((p)->next)){ | ||||
| 71806 | Index *pIdx = (Index *)sqliteHashData(p)((p)->data); | ||||
| 71807 | if( pIdx->tnum==iRoot ){ | ||||
| 71808 | if( bSeen ){ | ||||
| 71809 | /* Two or more indexes share the same root page. There must | ||||
| 71810 | ** be imposter tables. So just return true. The assert is not | ||||
| 71811 | ** useful in that case. */ | ||||
| 71812 | return 1; | ||||
| 71813 | } | ||||
| 71814 | iTab = pIdx->pTable->tnum; | ||||
| 71815 | bSeen = 1; | ||||
| 71816 | } | ||||
| 71817 | } | ||||
| 71818 | }else{ | ||||
| 71819 | iTab = iRoot; | ||||
| 71820 | } | ||||
| 71821 | |||||
| 71822 | SHARED_LOCK_TRACE(pBtree->pBt,"hasLock",iRoot,eLockType); | ||||
| 71823 | |||||
| 71824 | /* Search for the required lock. Either a write-lock on root-page iTab, a | ||||
| 71825 | ** write-lock on the schema table, or (if the client is reading) a | ||||
| 71826 | ** read-lock on iTab will suffice. Return 1 if any of these are found. */ | ||||
| 71827 | for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ | ||||
| 71828 | if( pLock->pBtree==pBtree | ||||
| 71829 | && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK2 && pLock->iTable==1)) | ||||
| 71830 | && pLock->eLock>=eLockType | ||||
| 71831 | ){ | ||||
| 71832 | return 1; | ||||
| 71833 | } | ||||
| 71834 | } | ||||
| 71835 | |||||
| 71836 | /* Failed to find the required lock. */ | ||||
| 71837 | return 0; | ||||
| 71838 | } | ||||
| 71839 | #endif /* SQLITE_DEBUG */ | ||||
| 71840 | |||||
| 71841 | #ifdef SQLITE_DEBUG | ||||
| 71842 | /* | ||||
| 71843 | **** This function may be used as part of assert() statements only. **** | ||||
| 71844 | ** | ||||
| 71845 | ** Return true if it would be illegal for pBtree to write into the | ||||
| 71846 | ** table or index rooted at iRoot because other shared connections are | ||||
| 71847 | ** simultaneously reading that same table or index. | ||||
| 71848 | ** | ||||
| 71849 | ** It is illegal for pBtree to write if some other Btree object that | ||||
| 71850 | ** shares the same BtShared object is currently reading or writing | ||||
| 71851 | ** the iRoot table. Except, if the other Btree object has the | ||||
| 71852 | ** read-uncommitted flag set, then it is OK for the other object to | ||||
| 71853 | ** have a read cursor. | ||||
| 71854 | ** | ||||
| 71855 | ** For example, before writing to any part of the table or index | ||||
| 71856 | ** rooted at page iRoot, one should call: | ||||
| 71857 | ** | ||||
| 71858 | ** assert( !hasReadConflicts(pBtree, iRoot) ); | ||||
| 71859 | */ | ||||
| 71860 | static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ | ||||
| 71861 | BtCursor *p; | ||||
| 71862 | for(p=pBtree->pBt->pCursor; p; p=p->pNext){ | ||||
| 71863 | if( p->pgnoRoot==iRoot | ||||
| 71864 | && p->pBtree!=pBtree | ||||
| 71865 | && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit((u64)(0x00004)<<32)) | ||||
| 71866 | ){ | ||||
| 71867 | return 1; | ||||
| 71868 | } | ||||
| 71869 | } | ||||
| 71870 | return 0; | ||||
| 71871 | } | ||||
| 71872 | #endif /* #ifdef SQLITE_DEBUG */ | ||||
| 71873 | |||||
| 71874 | /* | ||||
| 71875 | ** Query to see if Btree handle p may obtain a lock of type eLock | ||||
| 71876 | ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return | ||||
| 71877 | ** SQLITE_OK if the lock may be obtained (by calling | ||||
| 71878 | ** setSharedCacheTableLock()), or SQLITE_LOCKED if not. | ||||
| 71879 | */ | ||||
| 71880 | static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ | ||||
| 71881 | BtShared *pBt = p->pBt; | ||||
| 71882 | BtLock *pIter; | ||||
| 71883 | |||||
| 71884 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 71885 | assert( eLock==READ_LOCK || eLock==WRITE_LOCK )((void) (0)); | ||||
| 71886 | assert( p->db!=0 )((void) (0)); | ||||
| 71887 | assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 )((void) (0)); | ||||
| 71888 | |||||
| 71889 | /* If requesting a write-lock, then the Btree must have an open write | ||||
| 71890 | ** transaction on this file. And, obviously, for this to be so there | ||||
| 71891 | ** must be an open write transaction on the file itself. | ||||
| 71892 | */ | ||||
| 71893 | assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) )((void) (0)); | ||||
| 71894 | assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE )((void) (0)); | ||||
| 71895 | |||||
| 71896 | /* This routine is a no-op if the shared-cache is not enabled */ | ||||
| 71897 | if( !p->sharable ){ | ||||
| 71898 | return SQLITE_OK0; | ||||
| 71899 | } | ||||
| 71900 | |||||
| 71901 | /* If some other connection is holding an exclusive lock, the | ||||
| 71902 | ** requested lock may not be obtained. | ||||
| 71903 | */ | ||||
| 71904 | if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE0x0040)!=0 ){ | ||||
| 71905 | sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); | ||||
| 71906 | return SQLITE_LOCKED_SHAREDCACHE(6 | (1<<8)); | ||||
| 71907 | } | ||||
| 71908 | |||||
| 71909 | for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ | ||||
| 71910 | /* The condition (pIter->eLock!=eLock) in the following if(...) | ||||
| 71911 | ** statement is a simplification of: | ||||
| 71912 | ** | ||||
| 71913 | ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) | ||||
| 71914 | ** | ||||
| 71915 | ** since we know that if eLock==WRITE_LOCK, then no other connection | ||||
| 71916 | ** may hold a WRITE_LOCK on any table in this file (since there can | ||||
| 71917 | ** only be a single writer). | ||||
| 71918 | */ | ||||
| 71919 | assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK )((void) (0)); | ||||
| 71920 | assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK)((void) (0)); | ||||
| 71921 | if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ | ||||
| 71922 | sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); | ||||
| 71923 | if( eLock==WRITE_LOCK2 ){ | ||||
| 71924 | assert( p==pBt->pWriter )((void) (0)); | ||||
| 71925 | pBt->btsFlags |= BTS_PENDING0x0080; | ||||
| 71926 | } | ||||
| 71927 | return SQLITE_LOCKED_SHAREDCACHE(6 | (1<<8)); | ||||
| 71928 | } | ||||
| 71929 | } | ||||
| 71930 | return SQLITE_OK0; | ||||
| 71931 | } | ||||
| 71932 | #endif /* !SQLITE_OMIT_SHARED_CACHE */ | ||||
| 71933 | |||||
| 71934 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 71935 | /* | ||||
| 71936 | ** Add a lock on the table with root-page iTable to the shared-btree used | ||||
| 71937 | ** by Btree handle p. Parameter eLock must be either READ_LOCK or | ||||
| 71938 | ** WRITE_LOCK. | ||||
| 71939 | ** | ||||
| 71940 | ** This function assumes the following: | ||||
| 71941 | ** | ||||
| 71942 | ** (a) The specified Btree object p is connected to a sharable | ||||
| 71943 | ** database (one with the BtShared.sharable flag set), and | ||||
| 71944 | ** | ||||
| 71945 | ** (b) No other Btree objects hold a lock that conflicts | ||||
| 71946 | ** with the requested lock (i.e. querySharedCacheTableLock() has | ||||
| 71947 | ** already been called and returned SQLITE_OK). | ||||
| 71948 | ** | ||||
| 71949 | ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM | ||||
| 71950 | ** is returned if a malloc attempt fails. | ||||
| 71951 | */ | ||||
| 71952 | static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ | ||||
| 71953 | BtShared *pBt = p->pBt; | ||||
| 71954 | BtLock *pLock = 0; | ||||
| 71955 | BtLock *pIter; | ||||
| 71956 | |||||
| 71957 | SHARED_LOCK_TRACE(pBt,"setLock", iTable, eLock); | ||||
| 71958 | |||||
| 71959 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 71960 | assert( eLock==READ_LOCK || eLock==WRITE_LOCK )((void) (0)); | ||||
| 71961 | assert( p->db!=0 )((void) (0)); | ||||
| 71962 | |||||
| 71963 | /* A connection with the read-uncommitted flag set will never try to | ||||
| 71964 | ** obtain a read-lock using this function. The only read-lock obtained | ||||
| 71965 | ** by a connection in read-uncommitted mode is on the sqlite_schema | ||||
| 71966 | ** table, and that lock is obtained in BtreeBeginTrans(). */ | ||||
| 71967 | assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK )((void) (0)); | ||||
| 71968 | |||||
| 71969 | /* This function should only be called on a sharable b-tree after it | ||||
| 71970 | ** has been determined that no other b-tree holds a conflicting lock. */ | ||||
| 71971 | assert( p->sharable )((void) (0)); | ||||
| 71972 | assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) )((void) (0)); | ||||
| 71973 | |||||
| 71974 | /* First search the list for an existing lock on this table. */ | ||||
| 71975 | for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ | ||||
| 71976 | if( pIter->iTable==iTable && pIter->pBtree==p ){ | ||||
| 71977 | pLock = pIter; | ||||
| 71978 | break; | ||||
| 71979 | } | ||||
| 71980 | } | ||||
| 71981 | |||||
| 71982 | /* If the above search did not find a BtLock struct associating Btree p | ||||
| 71983 | ** with table iTable, allocate one and link it into the list. | ||||
| 71984 | */ | ||||
| 71985 | if( !pLock ){ | ||||
| 71986 | pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); | ||||
| 71987 | if( !pLock ){ | ||||
| 71988 | return SQLITE_NOMEM_BKPT7; | ||||
| 71989 | } | ||||
| 71990 | pLock->iTable = iTable; | ||||
| 71991 | pLock->pBtree = p; | ||||
| 71992 | pLock->pNext = pBt->pLock; | ||||
| 71993 | pBt->pLock = pLock; | ||||
| 71994 | } | ||||
| 71995 | |||||
| 71996 | /* Set the BtLock.eLock variable to the maximum of the current lock | ||||
| 71997 | ** and the requested lock. This means if a write-lock was already held | ||||
| 71998 | ** and a read-lock requested, we don't incorrectly downgrade the lock. | ||||
| 71999 | */ | ||||
| 72000 | assert( WRITE_LOCK>READ_LOCK )((void) (0)); | ||||
| 72001 | if( eLock>pLock->eLock ){ | ||||
| 72002 | pLock->eLock = eLock; | ||||
| 72003 | } | ||||
| 72004 | |||||
| 72005 | return SQLITE_OK0; | ||||
| 72006 | } | ||||
| 72007 | #endif /* !SQLITE_OMIT_SHARED_CACHE */ | ||||
| 72008 | |||||
| 72009 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 72010 | /* | ||||
| 72011 | ** Release all the table locks (locks obtained via calls to | ||||
| 72012 | ** the setSharedCacheTableLock() procedure) held by Btree object p. | ||||
| 72013 | ** | ||||
| 72014 | ** This function assumes that Btree p has an open read or write | ||||
| 72015 | ** transaction. If it does not, then the BTS_PENDING flag | ||||
| 72016 | ** may be incorrectly cleared. | ||||
| 72017 | */ | ||||
| 72018 | static void clearAllSharedCacheTableLocks(Btree *p){ | ||||
| 72019 | BtShared *pBt = p->pBt; | ||||
| 72020 | BtLock **ppIter = &pBt->pLock; | ||||
| 72021 | |||||
| 72022 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 72023 | assert( p->sharable || 0==*ppIter )((void) (0)); | ||||
| 72024 | assert( p->inTrans>0 )((void) (0)); | ||||
| 72025 | |||||
| 72026 | SHARED_LOCK_TRACE(pBt, "clearAllLocks", 0, 0); | ||||
| 72027 | |||||
| 72028 | while( *ppIter ){ | ||||
| 72029 | BtLock *pLock = *ppIter; | ||||
| 72030 | assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree )((void) (0)); | ||||
| 72031 | assert( pLock->pBtree->inTrans>=pLock->eLock )((void) (0)); | ||||
| 72032 | if( pLock->pBtree==p ){ | ||||
| 72033 | *ppIter = pLock->pNext; | ||||
| 72034 | assert( pLock->iTable!=1 || pLock==&p->lock )((void) (0)); | ||||
| 72035 | if( pLock->iTable!=1 ){ | ||||
| 72036 | sqlite3_free(pLock); | ||||
| 72037 | } | ||||
| 72038 | }else{ | ||||
| 72039 | ppIter = &pLock->pNext; | ||||
| 72040 | } | ||||
| 72041 | } | ||||
| 72042 | |||||
| 72043 | assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter )((void) (0)); | ||||
| 72044 | if( pBt->pWriter==p ){ | ||||
| 72045 | pBt->pWriter = 0; | ||||
| 72046 | pBt->btsFlags &= ~(BTS_EXCLUSIVE0x0040|BTS_PENDING0x0080); | ||||
| 72047 | }else if( pBt->nTransaction==2 ){ | ||||
| 72048 | /* This function is called when Btree p is concluding its | ||||
| 72049 | ** transaction. If there currently exists a writer, and p is not | ||||
| 72050 | ** that writer, then the number of locks held by connections other | ||||
| 72051 | ** than the writer must be about to drop to zero. In this case | ||||
| 72052 | ** set the BTS_PENDING flag to 0. | ||||
| 72053 | ** | ||||
| 72054 | ** If there is not currently a writer, then BTS_PENDING must | ||||
| 72055 | ** be zero already. So this next line is harmless in that case. | ||||
| 72056 | */ | ||||
| 72057 | pBt->btsFlags &= ~BTS_PENDING0x0080; | ||||
| 72058 | } | ||||
| 72059 | } | ||||
| 72060 | |||||
| 72061 | /* | ||||
| 72062 | ** This function changes all write-locks held by Btree p into read-locks. | ||||
| 72063 | */ | ||||
| 72064 | static void downgradeAllSharedCacheTableLocks(Btree *p){ | ||||
| 72065 | BtShared *pBt = p->pBt; | ||||
| 72066 | |||||
| 72067 | SHARED_LOCK_TRACE(pBt, "downgradeLocks", 0, 0); | ||||
| 72068 | |||||
| 72069 | if( pBt->pWriter==p ){ | ||||
| 72070 | BtLock *pLock; | ||||
| 72071 | pBt->pWriter = 0; | ||||
| 72072 | pBt->btsFlags &= ~(BTS_EXCLUSIVE0x0040|BTS_PENDING0x0080); | ||||
| 72073 | for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ | ||||
| 72074 | assert( pLock->eLock==READ_LOCK || pLock->pBtree==p )((void) (0)); | ||||
| 72075 | pLock->eLock = READ_LOCK1; | ||||
| 72076 | } | ||||
| 72077 | } | ||||
| 72078 | } | ||||
| 72079 | |||||
| 72080 | #endif /* SQLITE_OMIT_SHARED_CACHE */ | ||||
| 72081 | |||||
| 72082 | static void releasePage(MemPage *pPage); /* Forward reference */ | ||||
| 72083 | static void releasePageOne(MemPage *pPage); /* Forward reference */ | ||||
| 72084 | static void releasePageNotNull(MemPage *pPage); /* Forward reference */ | ||||
| 72085 | |||||
| 72086 | /* | ||||
| 72087 | ***** This routine is used inside of assert() only **** | ||||
| 72088 | ** | ||||
| 72089 | ** Verify that the cursor holds the mutex on its BtShared | ||||
| 72090 | */ | ||||
| 72091 | #ifdef SQLITE_DEBUG | ||||
| 72092 | static int cursorHoldsMutex(BtCursor *p){ | ||||
| 72093 | return sqlite3_mutex_held(p->pBt->mutex); | ||||
| 72094 | } | ||||
| 72095 | |||||
| 72096 | /* Verify that the cursor and the BtShared agree about what is the current | ||||
| 72097 | ** database connetion. This is important in shared-cache mode. If the database | ||||
| 72098 | ** connection pointers get out-of-sync, it is possible for routines like | ||||
| 72099 | ** btreeInitPage() to reference an stale connection pointer that references a | ||||
| 72100 | ** a connection that has already closed. This routine is used inside assert() | ||||
| 72101 | ** statements only and for the purpose of double-checking that the btree code | ||||
| 72102 | ** does keep the database connection pointers up-to-date. | ||||
| 72103 | */ | ||||
| 72104 | static int cursorOwnsBtShared(BtCursor *p){ | ||||
| 72105 | assert( cursorHoldsMutex(p) )((void) (0)); | ||||
| 72106 | return (p->pBtree->db==p->pBt->db); | ||||
| 72107 | } | ||||
| 72108 | #endif | ||||
| 72109 | |||||
| 72110 | /* | ||||
| 72111 | ** Invalidate the overflow cache of the cursor passed as the first argument. | ||||
| 72112 | ** on the shared btree structure pBt. | ||||
| 72113 | */ | ||||
| 72114 | #define invalidateOverflowCache(pCur)(pCur->curFlags &= ~0x04) (pCur->curFlags &= ~BTCF_ValidOvfl0x04) | ||||
| 72115 | |||||
| 72116 | /* | ||||
| 72117 | ** Invalidate the overflow page-list cache for all cursors opened | ||||
| 72118 | ** on the shared btree structure pBt. | ||||
| 72119 | */ | ||||
| 72120 | static void invalidateAllOverflowCache(BtShared *pBt){ | ||||
| 72121 | BtCursor *p; | ||||
| 72122 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 72123 | for(p=pBt->pCursor; p; p=p->pNext){ | ||||
| 72124 | invalidateOverflowCache(p)(p->curFlags &= ~0x04); | ||||
| 72125 | } | ||||
| 72126 | } | ||||
| 72127 | |||||
| 72128 | #ifndef SQLITE_OMIT_INCRBLOB | ||||
| 72129 | /* | ||||
| 72130 | ** This function is called before modifying the contents of a table | ||||
| 72131 | ** to invalidate any incrblob cursors that are open on the | ||||
| 72132 | ** row or one of the rows being modified. | ||||
| 72133 | ** | ||||
| 72134 | ** If argument isClearTable is true, then the entire contents of the | ||||
| 72135 | ** table is about to be deleted. In this case invalidate all incrblob | ||||
| 72136 | ** cursors open on any row within the table with root-page pgnoRoot. | ||||
| 72137 | ** | ||||
| 72138 | ** Otherwise, if argument isClearTable is false, then the row with | ||||
| 72139 | ** rowid iRow is being replaced or deleted. In this case invalidate | ||||
| 72140 | ** only those incrblob cursors open on that specific row. | ||||
| 72141 | */ | ||||
| 72142 | static void invalidateIncrblobCursors( | ||||
| 72143 | Btree *pBtree, /* The database file to check */ | ||||
| 72144 | Pgno pgnoRoot, /* The table that might be changing */ | ||||
| 72145 | i64 iRow, /* The rowid that might be changing */ | ||||
| 72146 | int isClearTable /* True if all rows are being deleted */ | ||||
| 72147 | ){ | ||||
| 72148 | BtCursor *p; | ||||
| 72149 | assert( pBtree->hasIncrblobCur )((void) (0)); | ||||
| 72150 | assert( sqlite3BtreeHoldsMutex(pBtree) )((void) (0)); | ||||
| 72151 | pBtree->hasIncrblobCur = 0; | ||||
| 72152 | for(p=pBtree->pBt->pCursor; p; p=p->pNext){ | ||||
| 72153 | if( (p->curFlags & BTCF_Incrblob0x10)!=0 ){ | ||||
| 72154 | pBtree->hasIncrblobCur = 1; | ||||
| 72155 | if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){ | ||||
| 72156 | p->eState = CURSOR_INVALID1; | ||||
| 72157 | } | ||||
| 72158 | } | ||||
| 72159 | } | ||||
| 72160 | } | ||||
| 72161 | |||||
| 72162 | #else | ||||
| 72163 | /* Stub function when INCRBLOB is omitted */ | ||||
| 72164 | #define invalidateIncrblobCursors(w,x,y,z) | ||||
| 72165 | #endif /* SQLITE_OMIT_INCRBLOB */ | ||||
| 72166 | |||||
| 72167 | /* | ||||
| 72168 | ** Set bit pgno of the BtShared.pHasContent bitvec. This is called | ||||
| 72169 | ** when a page that previously contained data becomes a free-list leaf | ||||
| 72170 | ** page. | ||||
| 72171 | ** | ||||
| 72172 | ** The BtShared.pHasContent bitvec exists to work around an obscure | ||||
| 72173 | ** bug caused by the interaction of two useful IO optimizations surrounding | ||||
| 72174 | ** free-list leaf pages: | ||||
| 72175 | ** | ||||
| 72176 | ** 1) When all data is deleted from a page and the page becomes | ||||
| 72177 | ** a free-list leaf page, the page is not written to the database | ||||
| 72178 | ** (as free-list leaf pages contain no meaningful data). Sometimes | ||||
| 72179 | ** such a page is not even journalled (as it will not be modified, | ||||
| 72180 | ** why bother journalling it?). | ||||
| 72181 | ** | ||||
| 72182 | ** 2) When a free-list leaf page is reused, its content is not read | ||||
| 72183 | ** from the database or written to the journal file (why should it | ||||
| 72184 | ** be, if it is not at all meaningful?). | ||||
| 72185 | ** | ||||
| 72186 | ** By themselves, these optimizations work fine and provide a handy | ||||
| 72187 | ** performance boost to bulk delete or insert operations. However, if | ||||
| 72188 | ** a page is moved to the free-list and then reused within the same | ||||
| 72189 | ** transaction, a problem comes up. If the page is not journalled when | ||||
| 72190 | ** it is moved to the free-list and it is also not journalled when it | ||||
| 72191 | ** is extracted from the free-list and reused, then the original data | ||||
| 72192 | ** may be lost. In the event of a rollback, it may not be possible | ||||
| 72193 | ** to restore the database to its original configuration. | ||||
| 72194 | ** | ||||
| 72195 | ** The solution is the BtShared.pHasContent bitvec. Whenever a page is | ||||
| 72196 | ** moved to become a free-list leaf page, the corresponding bit is | ||||
| 72197 | ** set in the bitvec. Whenever a leaf page is extracted from the free-list, | ||||
| 72198 | ** optimization 2 above is omitted if the corresponding bit is already | ||||
| 72199 | ** set in BtShared.pHasContent. The contents of the bitvec are cleared | ||||
| 72200 | ** at the end of every transaction. | ||||
| 72201 | */ | ||||
| 72202 | static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ | ||||
| 72203 | int rc = SQLITE_OK0; | ||||
| 72204 | if( !pBt->pHasContent ){ | ||||
| 72205 | assert( pgno<=pBt->nPage )((void) (0)); | ||||
| 72206 | pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); | ||||
| 72207 | if( !pBt->pHasContent ){ | ||||
| 72208 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 72209 | } | ||||
| 72210 | } | ||||
| 72211 | if( rc==SQLITE_OK0 && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ | ||||
| 72212 | rc = sqlite3BitvecSet(pBt->pHasContent, pgno); | ||||
| 72213 | } | ||||
| 72214 | return rc; | ||||
| 72215 | } | ||||
| 72216 | |||||
| 72217 | /* | ||||
| 72218 | ** Query the BtShared.pHasContent vector. | ||||
| 72219 | ** | ||||
| 72220 | ** This function is called when a free-list leaf page is removed from the | ||||
| 72221 | ** free-list for reuse. It returns false if it is safe to retrieve the | ||||
| 72222 | ** page from the pager layer with the 'no-content' flag set. True otherwise. | ||||
| 72223 | */ | ||||
| 72224 | static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ | ||||
| 72225 | Bitvec *p = pBt->pHasContent; | ||||
| 72226 | return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno)); | ||||
| 72227 | } | ||||
| 72228 | |||||
| 72229 | /* | ||||
| 72230 | ** Clear (destroy) the BtShared.pHasContent bitvec. This should be | ||||
| 72231 | ** invoked at the conclusion of each write-transaction. | ||||
| 72232 | */ | ||||
| 72233 | static void btreeClearHasContent(BtShared *pBt){ | ||||
| 72234 | sqlite3BitvecDestroy(pBt->pHasContent); | ||||
| 72235 | pBt->pHasContent = 0; | ||||
| 72236 | } | ||||
| 72237 | |||||
| 72238 | /* | ||||
| 72239 | ** Release all of the apPage[] pages for a cursor. | ||||
| 72240 | */ | ||||
| 72241 | static void btreeReleaseAllCursorPages(BtCursor *pCur){ | ||||
| 72242 | int i; | ||||
| 72243 | if( pCur->iPage>=0 ){ | ||||
| 72244 | for(i=0; i<pCur->iPage; i++){ | ||||
| 72245 | releasePageNotNull(pCur->apPage[i]); | ||||
| 72246 | } | ||||
| 72247 | releasePageNotNull(pCur->pPage); | ||||
| 72248 | pCur->iPage = -1; | ||||
| 72249 | } | ||||
| 72250 | } | ||||
| 72251 | |||||
| 72252 | /* | ||||
| 72253 | ** The cursor passed as the only argument must point to a valid entry | ||||
| 72254 | ** when this function is called (i.e. have eState==CURSOR_VALID). This | ||||
| 72255 | ** function saves the current cursor key in variables pCur->nKey and | ||||
| 72256 | ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error | ||||
| 72257 | ** code otherwise. | ||||
| 72258 | ** | ||||
| 72259 | ** If the cursor is open on an intkey table, then the integer key | ||||
| 72260 | ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to | ||||
| 72261 | ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is | ||||
| 72262 | ** set to point to a malloced buffer pCur->nKey bytes in size containing | ||||
| 72263 | ** the key. | ||||
| 72264 | */ | ||||
| 72265 | static int saveCursorKey(BtCursor *pCur){ | ||||
| 72266 | int rc = SQLITE_OK0; | ||||
| 72267 | assert( CURSOR_VALID==pCur->eState )((void) (0)); | ||||
| 72268 | assert( 0==pCur->pKey )((void) (0)); | ||||
| 72269 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 72270 | |||||
| 72271 | if( pCur->curIntKey ){ | ||||
| 72272 | /* Only the rowid is required for a table btree */ | ||||
| 72273 | pCur->nKey = sqlite3BtreeIntegerKey(pCur); | ||||
| 72274 | }else{ | ||||
| 72275 | /* For an index btree, save the complete key content. It is possible | ||||
| 72276 | ** that the current key is corrupt. In that case, it is possible that | ||||
| 72277 | ** the sqlite3VdbeRecordUnpack() function may overread the buffer by | ||||
| 72278 | ** up to the size of 1 varint plus 1 8-byte value when the cursor | ||||
| 72279 | ** position is restored. Hence the 17 bytes of padding allocated | ||||
| 72280 | ** below. */ | ||||
| 72281 | void *pKey; | ||||
| 72282 | pCur->nKey = sqlite3BtreePayloadSize(pCur); | ||||
| 72283 | pKey = sqlite3Malloc( ((i64)pCur->nKey) + 9 + 8 ); | ||||
| 72284 | if( pKey ){ | ||||
| 72285 | rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); | ||||
| 72286 | if( rc==SQLITE_OK0 ){ | ||||
| 72287 | memset(((u8*)pKey)+pCur->nKey, 0, 9+8); | ||||
| 72288 | pCur->pKey = pKey; | ||||
| 72289 | }else{ | ||||
| 72290 | sqlite3_free(pKey); | ||||
| 72291 | } | ||||
| 72292 | }else{ | ||||
| 72293 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 72294 | } | ||||
| 72295 | } | ||||
| 72296 | assert( !pCur->curIntKey || !pCur->pKey )((void) (0)); | ||||
| 72297 | return rc; | ||||
| 72298 | } | ||||
| 72299 | |||||
| 72300 | /* | ||||
| 72301 | ** Save the current cursor position in the variables BtCursor.nKey | ||||
| 72302 | ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. | ||||
| 72303 | ** | ||||
| 72304 | ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) | ||||
| 72305 | ** prior to calling this routine. | ||||
| 72306 | */ | ||||
| 72307 | static int saveCursorPosition(BtCursor *pCur){ | ||||
| 72308 | int rc; | ||||
| 72309 | |||||
| 72310 | assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState )((void) (0)); | ||||
| 72311 | assert( 0==pCur->pKey )((void) (0)); | ||||
| 72312 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 72313 | |||||
| 72314 | if( pCur->curFlags & BTCF_Pinned0x40 ){ | ||||
| 72315 | return SQLITE_CONSTRAINT_PINNED(19 |(11<<8)); | ||||
| 72316 | } | ||||
| 72317 | if( pCur->eState==CURSOR_SKIPNEXT2 ){ | ||||
| 72318 | pCur->eState = CURSOR_VALID0; | ||||
| 72319 | }else{ | ||||
| 72320 | pCur->skipNext = 0; | ||||
| 72321 | } | ||||
| 72322 | |||||
| 72323 | rc = saveCursorKey(pCur); | ||||
| 72324 | if( rc==SQLITE_OK0 ){ | ||||
| 72325 | btreeReleaseAllCursorPages(pCur); | ||||
| 72326 | pCur->eState = CURSOR_REQUIRESEEK3; | ||||
| 72327 | } | ||||
| 72328 | |||||
| 72329 | pCur->curFlags &= ~(BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04|BTCF_AtLast0x08); | ||||
| 72330 | return rc; | ||||
| 72331 | } | ||||
| 72332 | |||||
| 72333 | /* Forward reference */ | ||||
| 72334 | static int SQLITE_NOINLINE__attribute__((noinline)) saveCursorsOnList(BtCursor*,Pgno,BtCursor*); | ||||
| 72335 | |||||
| 72336 | /* | ||||
| 72337 | ** Save the positions of all cursors (except pExcept) that are open on | ||||
| 72338 | ** the table with root-page iRoot. "Saving the cursor position" means that | ||||
| 72339 | ** the location in the btree is remembered in such a way that it can be | ||||
| 72340 | ** moved back to the same spot after the btree has been modified. This | ||||
| 72341 | ** routine is called just before cursor pExcept is used to modify the | ||||
| 72342 | ** table, for example in BtreeDelete() or BtreeInsert(). | ||||
| 72343 | ** | ||||
| 72344 | ** If there are two or more cursors on the same btree, then all such | ||||
| 72345 | ** cursors should have their BTCF_Multiple flag set. The btreeCursor() | ||||
| 72346 | ** routine enforces that rule. This routine only needs to be called in | ||||
| 72347 | ** the uncommon case when pExpect has the BTCF_Multiple flag set. | ||||
| 72348 | ** | ||||
| 72349 | ** If pExpect!=NULL and if no other cursors are found on the same root-page, | ||||
| 72350 | ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another | ||||
| 72351 | ** pointless call to this routine. | ||||
| 72352 | ** | ||||
| 72353 | ** Implementation note: This routine merely checks to see if any cursors | ||||
| 72354 | ** need to be saved. It calls out to saveCursorsOnList() in the (unusual) | ||||
| 72355 | ** event that cursors are in need to being saved. | ||||
| 72356 | */ | ||||
| 72357 | static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ | ||||
| 72358 | BtCursor *p; | ||||
| 72359 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 72360 | assert( pExcept==0 || pExcept->pBt==pBt )((void) (0)); | ||||
| 72361 | for(p=pBt->pCursor; p; p=p->pNext){ | ||||
| 72362 | if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; | ||||
| 72363 | } | ||||
| 72364 | if( p ) return saveCursorsOnList(p, iRoot, pExcept); | ||||
| 72365 | if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple0x20; | ||||
| 72366 | return SQLITE_OK0; | ||||
| 72367 | } | ||||
| 72368 | |||||
| 72369 | /* This helper routine to saveAllCursors does the actual work of saving | ||||
| 72370 | ** the cursors if and when a cursor is found that actually requires saving. | ||||
| 72371 | ** The common case is that no cursors need to be saved, so this routine is | ||||
| 72372 | ** broken out from its caller to avoid unnecessary stack pointer movement. | ||||
| 72373 | */ | ||||
| 72374 | static int SQLITE_NOINLINE__attribute__((noinline)) saveCursorsOnList( | ||||
| 72375 | BtCursor *p, /* The first cursor that needs saving */ | ||||
| 72376 | Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ | ||||
| 72377 | BtCursor *pExcept /* Do not save this cursor */ | ||||
| 72378 | ){ | ||||
| 72379 | do{ | ||||
| 72380 | if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ | ||||
| 72381 | if( p->eState==CURSOR_VALID0 || p->eState==CURSOR_SKIPNEXT2 ){ | ||||
| 72382 | int rc = saveCursorPosition(p); | ||||
| 72383 | if( SQLITE_OK0!=rc ){ | ||||
| 72384 | return rc; | ||||
| 72385 | } | ||||
| 72386 | }else{ | ||||
| 72387 | testcase( p->iPage>=0 ); | ||||
| 72388 | btreeReleaseAllCursorPages(p); | ||||
| 72389 | } | ||||
| 72390 | } | ||||
| 72391 | p = p->pNext; | ||||
| 72392 | }while( p ); | ||||
| 72393 | return SQLITE_OK0; | ||||
| 72394 | } | ||||
| 72395 | |||||
| 72396 | /* | ||||
| 72397 | ** Clear the current cursor position. | ||||
| 72398 | */ | ||||
| 72399 | SQLITE_PRIVATEstatic void sqlite3BtreeClearCursor(BtCursor *pCur){ | ||||
| 72400 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 72401 | sqlite3_free(pCur->pKey); | ||||
| 72402 | pCur->pKey = 0; | ||||
| 72403 | pCur->eState = CURSOR_INVALID1; | ||||
| 72404 | } | ||||
| 72405 | |||||
| 72406 | /* | ||||
| 72407 | ** In this version of BtreeMoveto, pKey is a packed index record | ||||
| 72408 | ** such as is generated by the OP_MakeRecord opcode. Unpack the | ||||
| 72409 | ** record and then call sqlite3BtreeIndexMoveto() to do the work. | ||||
| 72410 | */ | ||||
| 72411 | static int btreeMoveto( | ||||
| 72412 | BtCursor *pCur, /* Cursor open on the btree to be searched */ | ||||
| 72413 | const void *pKey, /* Packed key if the btree is an index */ | ||||
| 72414 | i64 nKey, /* Integer key for tables. Size of pKey for indices */ | ||||
| 72415 | int bias, /* Bias search to the high end */ | ||||
| 72416 | int *pRes /* Write search results here */ | ||||
| 72417 | ){ | ||||
| 72418 | int rc; /* Status code */ | ||||
| 72419 | UnpackedRecord *pIdxKey; /* Unpacked index key */ | ||||
| 72420 | |||||
| 72421 | if( pKey ){ | ||||
| 72422 | KeyInfo *pKeyInfo = pCur->pKeyInfo; | ||||
| 72423 | assert( nKey==(i64)(int)nKey )((void) (0)); | ||||
| 72424 | pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); | ||||
| 72425 | if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT7; | ||||
| 72426 | sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey); | ||||
| 72427 | if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){ | ||||
| 72428 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(72428); | ||||
| 72429 | }else{ | ||||
| 72430 | rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes); | ||||
| 72431 | } | ||||
| 72432 | sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey); | ||||
| 72433 | }else{ | ||||
| 72434 | pIdxKey = 0; | ||||
| 72435 | rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes); | ||||
| 72436 | } | ||||
| 72437 | return rc; | ||||
| 72438 | } | ||||
| 72439 | |||||
| 72440 | /* | ||||
| 72441 | ** Restore the cursor to the position it was in (or as close to as possible) | ||||
| 72442 | ** when saveCursorPosition() was called. Note that this call deletes the | ||||
| 72443 | ** saved position info stored by saveCursorPosition(), so there can be | ||||
| 72444 | ** at most one effective restoreCursorPosition() call after each | ||||
| 72445 | ** saveCursorPosition(). | ||||
| 72446 | */ | ||||
| 72447 | static int btreeRestoreCursorPosition(BtCursor *pCur){ | ||||
| 72448 | int rc; | ||||
| 72449 | int skipNext = 0; | ||||
| 72450 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 72451 | assert( pCur->eState>=CURSOR_REQUIRESEEK )((void) (0)); | ||||
| 72452 | if( pCur->eState==CURSOR_FAULT4 ){ | ||||
| 72453 | return pCur->skipNext; | ||||
| 72454 | } | ||||
| 72455 | pCur->eState = CURSOR_INVALID1; | ||||
| 72456 | if( sqlite3FaultSim(410) ){ | ||||
| 72457 | rc = SQLITE_IOERR10; | ||||
| 72458 | }else{ | ||||
| 72459 | rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); | ||||
| 72460 | } | ||||
| 72461 | if( rc==SQLITE_OK0 ){ | ||||
| 72462 | sqlite3_free(pCur->pKey); | ||||
| 72463 | pCur->pKey = 0; | ||||
| 72464 | assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID )((void) (0)); | ||||
| 72465 | if( skipNext ) pCur->skipNext = skipNext; | ||||
| 72466 | if( pCur->skipNext && pCur->eState==CURSOR_VALID0 ){ | ||||
| 72467 | pCur->eState = CURSOR_SKIPNEXT2; | ||||
| 72468 | } | ||||
| 72469 | } | ||||
| 72470 | return rc; | ||||
| 72471 | } | ||||
| 72472 | |||||
| 72473 | #define restoreCursorPosition(p)(p->eState>=3 ? btreeRestoreCursorPosition(p) : 0) \ | ||||
| 72474 | (p->eState>=CURSOR_REQUIRESEEK3 ? \ | ||||
| 72475 | btreeRestoreCursorPosition(p) : \ | ||||
| 72476 | SQLITE_OK0) | ||||
| 72477 | |||||
| 72478 | /* | ||||
| 72479 | ** Determine whether or not a cursor has moved from the position where | ||||
| 72480 | ** it was last placed, or has been invalidated for any other reason. | ||||
| 72481 | ** Cursors can move when the row they are pointing at is deleted out | ||||
| 72482 | ** from under them, for example. Cursor might also move if a btree | ||||
| 72483 | ** is rebalanced. | ||||
| 72484 | ** | ||||
| 72485 | ** Calling this routine with a NULL cursor pointer returns false. | ||||
| 72486 | ** | ||||
| 72487 | ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor | ||||
| 72488 | ** back to where it ought to be if this routine returns true. | ||||
| 72489 | */ | ||||
| 72490 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ | ||||
| 72491 | assert( EIGHT_BYTE_ALIGNMENT(pCur)((void) (0)) | ||||
| 72492 | || pCur==sqlite3BtreeFakeValidCursor() )((void) (0)); | ||||
| 72493 | assert( offsetof(BtCursor, eState)==0 )((void) (0)); | ||||
| 72494 | assert( sizeof(pCur->eState)==1 )((void) (0)); | ||||
| 72495 | return CURSOR_VALID0 != *(u8*)pCur; | ||||
| 72496 | } | ||||
| 72497 | |||||
| 72498 | /* | ||||
| 72499 | ** Return a pointer to a fake BtCursor object that will always answer | ||||
| 72500 | ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake | ||||
| 72501 | ** cursor returned must not be used with any other Btree interface. | ||||
| 72502 | */ | ||||
| 72503 | SQLITE_PRIVATEstatic BtCursor *sqlite3BtreeFakeValidCursor(void){ | ||||
| 72504 | static u8 fakeCursor = CURSOR_VALID0; | ||||
| 72505 | assert( offsetof(BtCursor, eState)==0 )((void) (0)); | ||||
| 72506 | return (BtCursor*)&fakeCursor; | ||||
| 72507 | } | ||||
| 72508 | |||||
| 72509 | /* | ||||
| 72510 | ** This routine restores a cursor back to its original position after it | ||||
| 72511 | ** has been moved by some outside activity (such as a btree rebalance or | ||||
| 72512 | ** a row having been deleted out from under the cursor). | ||||
| 72513 | ** | ||||
| 72514 | ** On success, the *pDifferentRow parameter is false if the cursor is left | ||||
| 72515 | ** pointing at exactly the same row. *pDifferntRow is the row the cursor | ||||
| 72516 | ** was pointing to has been deleted, forcing the cursor to point to some | ||||
| 72517 | ** nearby row. | ||||
| 72518 | ** | ||||
| 72519 | ** This routine should only be called for a cursor that just returned | ||||
| 72520 | ** TRUE from sqlite3BtreeCursorHasMoved(). | ||||
| 72521 | */ | ||||
| 72522 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ | ||||
| 72523 | int rc; | ||||
| 72524 | |||||
| 72525 | assert( pCur!=0 )((void) (0)); | ||||
| 72526 | assert( pCur->eState!=CURSOR_VALID )((void) (0)); | ||||
| 72527 | rc = restoreCursorPosition(pCur)(pCur->eState>=3 ? btreeRestoreCursorPosition(pCur) : 0 ); | ||||
| 72528 | if( rc ){ | ||||
| 72529 | *pDifferentRow = 1; | ||||
| 72530 | return rc; | ||||
| 72531 | } | ||||
| 72532 | if( pCur->eState!=CURSOR_VALID0 ){ | ||||
| 72533 | *pDifferentRow = 1; | ||||
| 72534 | }else{ | ||||
| 72535 | *pDifferentRow = 0; | ||||
| 72536 | } | ||||
| 72537 | return SQLITE_OK0; | ||||
| 72538 | } | ||||
| 72539 | |||||
| 72540 | #ifdef SQLITE_ENABLE_CURSOR_HINTS | ||||
| 72541 | /* | ||||
| 72542 | ** Provide hints to the cursor. The particular hint given (and the type | ||||
| 72543 | ** and number of the varargs parameters) is determined by the eHintType | ||||
| 72544 | ** parameter. See the definitions of the BTREE_HINT_* macros for details. | ||||
| 72545 | */ | ||||
| 72546 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ | ||||
| 72547 | /* Used only by system that substitute their own storage engine */ | ||||
| 72548 | #ifdef SQLITE_DEBUG | ||||
| 72549 | if( ALWAYS(eHintType==BTREE_HINT_RANGE)(eHintType==0) ){ | ||||
| 72550 | va_list ap; | ||||
| 72551 | Expr *pExpr; | ||||
| 72552 | Walker w; | ||||
| 72553 | memset(&w, 0, sizeof(w)); | ||||
| 72554 | w.xExprCallback = sqlite3CursorRangeHintExprCheck; | ||||
| 72555 | va_start(ap, eHintType)__builtin_va_start(ap, eHintType); | ||||
| 72556 | pExpr = va_arg(ap, Expr*)__builtin_va_arg(ap, Expr*); | ||||
| 72557 | w.u.aMem = va_arg(ap, Mem*)__builtin_va_arg(ap, Mem*); | ||||
| 72558 | va_end(ap)__builtin_va_end(ap); | ||||
| 72559 | assert( pExpr!=0 )((void) (0)); | ||||
| 72560 | assert( w.u.aMem!=0 )((void) (0)); | ||||
| 72561 | sqlite3WalkExpr(&w, pExpr); | ||||
| 72562 | } | ||||
| 72563 | #endif /* SQLITE_DEBUG */ | ||||
| 72564 | } | ||||
| 72565 | #endif /* SQLITE_ENABLE_CURSOR_HINTS */ | ||||
| 72566 | |||||
| 72567 | |||||
| 72568 | /* | ||||
| 72569 | ** Provide flag hints to the cursor. | ||||
| 72570 | */ | ||||
| 72571 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ | ||||
| 72572 | assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 )((void) (0)); | ||||
| 72573 | pCur->hints = (u8)x; | ||||
| 72574 | } | ||||
| 72575 | |||||
| 72576 | |||||
| 72577 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 72578 | /* | ||||
| 72579 | ** Given a page number of a regular database page, return the page | ||||
| 72580 | ** number for the pointer-map page that contains the entry for the | ||||
| 72581 | ** input page number. | ||||
| 72582 | ** | ||||
| 72583 | ** Return 0 (not a valid page) for pgno==1 since there is | ||||
| 72584 | ** no pointer map associated with page 1. The integrity_check logic | ||||
| 72585 | ** requires that ptrmapPageno(*,1)!=1. | ||||
| 72586 | */ | ||||
| 72587 | static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ | ||||
| 72588 | int nPagesPerMapPage; | ||||
| 72589 | Pgno iPtrMap, ret; | ||||
| 72590 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 72591 | if( pgno<2 ) return 0; | ||||
| 72592 | nPagesPerMapPage = (pBt->usableSize/5)+1; | ||||
| 72593 | iPtrMap = (pgno-2)/nPagesPerMapPage; | ||||
| 72594 | ret = (iPtrMap*nPagesPerMapPage) + 2; | ||||
| 72595 | if( ret==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ | ||||
| 72596 | ret++; | ||||
| 72597 | } | ||||
| 72598 | return ret; | ||||
| 72599 | } | ||||
| 72600 | |||||
| 72601 | /* | ||||
| 72602 | ** Write an entry into the pointer map. | ||||
| 72603 | ** | ||||
| 72604 | ** This routine updates the pointer map entry for page number 'key' | ||||
| 72605 | ** so that it maps to type 'eType' and parent page number 'pgno'. | ||||
| 72606 | ** | ||||
| 72607 | ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is | ||||
| 72608 | ** a no-op. If an error occurs, the appropriate error code is written | ||||
| 72609 | ** into *pRC. | ||||
| 72610 | */ | ||||
| 72611 | static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ | ||||
| 72612 | DbPage *pDbPage; /* The pointer map page */ | ||||
| 72613 | u8 *pPtrmap; /* The pointer map data */ | ||||
| 72614 | Pgno iPtrmap; /* The pointer map page number */ | ||||
| 72615 | int offset; /* Offset in pointer map page */ | ||||
| 72616 | int rc; /* Return code from subfunctions */ | ||||
| 72617 | |||||
| 72618 | if( *pRC ) return; | ||||
| 72619 | |||||
| 72620 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 72621 | /* The super-journal page number must never be used as a pointer map page */ | ||||
| 72622 | assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) )((void) (0)); | ||||
| 72623 | |||||
| 72624 | assert( pBt->autoVacuum )((void) (0)); | ||||
| 72625 | if( key==0 ){ | ||||
| 72626 | *pRC = SQLITE_CORRUPT_BKPTsqlite3CorruptError(72626); | ||||
| 72627 | return; | ||||
| 72628 | } | ||||
| 72629 | iPtrmap = PTRMAP_PAGENO(pBt, key)ptrmapPageno(pBt, key); | ||||
| 72630 | rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); | ||||
| 72631 | if( rc!=SQLITE_OK0 ){ | ||||
| 72632 | *pRC = rc; | ||||
| 72633 | return; | ||||
| 72634 | } | ||||
| 72635 | if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){ | ||||
| 72636 | /* The first byte of the extra data is the MemPage.isInit byte. | ||||
| 72637 | ** If that byte is set, it means this page is also being used | ||||
| 72638 | ** as a btree page. */ | ||||
| 72639 | *pRC = SQLITE_CORRUPT_BKPTsqlite3CorruptError(72639); | ||||
| 72640 | goto ptrmap_exit; | ||||
| 72641 | } | ||||
| 72642 | offset = PTRMAP_PTROFFSET(iPtrmap, key)(5*(key-iPtrmap-1)); | ||||
| 72643 | if( offset<0 ){ | ||||
| 72644 | *pRC = SQLITE_CORRUPT_BKPTsqlite3CorruptError(72644); | ||||
| 72645 | goto ptrmap_exit; | ||||
| 72646 | } | ||||
| 72647 | assert( offset <= (int)pBt->usableSize-5 )((void) (0)); | ||||
| 72648 | pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); | ||||
| 72649 | |||||
| 72650 | if( eType!=pPtrmap[offset] || get4bytesqlite3Get4byte(&pPtrmap[offset+1])!=parent ){ | ||||
| 72651 | TRACE(("PTRMAP_UPDATE: %u->(%u,%u)\n", key, eType, parent)); | ||||
| 72652 | *pRC= rc = sqlite3PagerWrite(pDbPage); | ||||
| 72653 | if( rc==SQLITE_OK0 ){ | ||||
| 72654 | pPtrmap[offset] = eType; | ||||
| 72655 | put4bytesqlite3Put4byte(&pPtrmap[offset+1], parent); | ||||
| 72656 | } | ||||
| 72657 | } | ||||
| 72658 | |||||
| 72659 | ptrmap_exit: | ||||
| 72660 | sqlite3PagerUnref(pDbPage); | ||||
| 72661 | } | ||||
| 72662 | |||||
| 72663 | /* | ||||
| 72664 | ** Read an entry from the pointer map. | ||||
| 72665 | ** | ||||
| 72666 | ** This routine retrieves the pointer map entry for page 'key', writing | ||||
| 72667 | ** the type and parent page number to *pEType and *pPgno respectively. | ||||
| 72668 | ** An error code is returned if something goes wrong, otherwise SQLITE_OK. | ||||
| 72669 | */ | ||||
| 72670 | static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ | ||||
| 72671 | DbPage *pDbPage; /* The pointer map page */ | ||||
| 72672 | int iPtrmap; /* Pointer map page index */ | ||||
| 72673 | u8 *pPtrmap; /* Pointer map page data */ | ||||
| 72674 | int offset; /* Offset of entry in pointer map */ | ||||
| 72675 | int rc; | ||||
| 72676 | |||||
| 72677 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 72678 | |||||
| 72679 | iPtrmap = PTRMAP_PAGENO(pBt, key)ptrmapPageno(pBt, key); | ||||
| 72680 | rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); | ||||
| 72681 | if( rc!=0 ){ | ||||
| 72682 | return rc; | ||||
| 72683 | } | ||||
| 72684 | pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); | ||||
| 72685 | |||||
| 72686 | offset = PTRMAP_PTROFFSET(iPtrmap, key)(5*(key-iPtrmap-1)); | ||||
| 72687 | if( offset<0 ){ | ||||
| 72688 | sqlite3PagerUnref(pDbPage); | ||||
| 72689 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(72689); | ||||
| 72690 | } | ||||
| 72691 | assert( offset <= (int)pBt->usableSize-5 )((void) (0)); | ||||
| 72692 | assert( pEType!=0 )((void) (0)); | ||||
| 72693 | *pEType = pPtrmap[offset]; | ||||
| 72694 | if( pPgno ) *pPgno = get4bytesqlite3Get4byte(&pPtrmap[offset+1]); | ||||
| 72695 | |||||
| 72696 | sqlite3PagerUnref(pDbPage); | ||||
| 72697 | if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap)sqlite3CorruptError(72697); | ||||
| 72698 | return SQLITE_OK0; | ||||
| 72699 | } | ||||
| 72700 | |||||
| 72701 | #else /* if defined SQLITE_OMIT_AUTOVACUUM */ | ||||
| 72702 | #define ptrmapPut(w,x,y,z,rc) | ||||
| 72703 | #define ptrmapGet(w,x,y,z) SQLITE_OK0 | ||||
| 72704 | #define ptrmapPutOvflPtr(x, y, z, rc) | ||||
| 72705 | #endif | ||||
| 72706 | |||||
| 72707 | /* | ||||
| 72708 | ** Given a btree page and a cell index (0 means the first cell on | ||||
| 72709 | ** the page, 1 means the second cell, and so forth) return a pointer | ||||
| 72710 | ** to the cell content. | ||||
| 72711 | ** | ||||
| 72712 | ** findCellPastPtr() does the same except it skips past the initial | ||||
| 72713 | ** 4-byte child pointer found on interior pages, if there is one. | ||||
| 72714 | ** | ||||
| 72715 | ** This routine works only for pages that do not contain overflow cells. | ||||
| 72716 | */ | ||||
| 72717 | #define findCell(P,I)((P)->aData + ((P)->maskPage & ((&(P)->aCellIdx [2*(I)])[0]<<8 | (&(P)->aCellIdx[2*(I)])[1]))) \ | ||||
| 72718 | ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])((&(P)->aCellIdx[2*(I)])[0]<<8 | (&(P)->aCellIdx [2*(I)])[1]))) | ||||
| 72719 | #define findCellPastPtr(P,I)((P)->aDataOfst + ((P)->maskPage & ((&(P)->aCellIdx [2*(I)])[0]<<8 | (&(P)->aCellIdx[2*(I)])[1]))) \ | ||||
| 72720 | ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])((&(P)->aCellIdx[2*(I)])[0]<<8 | (&(P)->aCellIdx [2*(I)])[1]))) | ||||
| 72721 | |||||
| 72722 | |||||
| 72723 | /* | ||||
| 72724 | ** This is common tail processing for btreeParseCellPtr() and | ||||
| 72725 | ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely | ||||
| 72726 | ** on a single B-tree page. Make necessary adjustments to the CellInfo | ||||
| 72727 | ** structure. | ||||
| 72728 | */ | ||||
| 72729 | static SQLITE_NOINLINE__attribute__((noinline)) void btreeParseCellAdjustSizeForOverflow( | ||||
| 72730 | MemPage *pPage, /* Page containing the cell */ | ||||
| 72731 | u8 *pCell, /* Pointer to the cell text. */ | ||||
| 72732 | CellInfo *pInfo /* Fill in this structure */ | ||||
| 72733 | ){ | ||||
| 72734 | /* If the payload will not fit completely on the local page, we have | ||||
| 72735 | ** to decide how much to store locally and how much to spill onto | ||||
| 72736 | ** overflow pages. The strategy is to minimize the amount of unused | ||||
| 72737 | ** space on overflow pages while keeping the amount of local storage | ||||
| 72738 | ** in between minLocal and maxLocal. | ||||
| 72739 | ** | ||||
| 72740 | ** Warning: changing the way overflow payload is distributed in any | ||||
| 72741 | ** way will result in an incompatible file format. | ||||
| 72742 | */ | ||||
| 72743 | int minLocal; /* Minimum amount of payload held locally */ | ||||
| 72744 | int maxLocal; /* Maximum amount of payload held locally */ | ||||
| 72745 | int surplus; /* Overflow payload available for local storage */ | ||||
| 72746 | |||||
| 72747 | minLocal = pPage->minLocal; | ||||
| 72748 | maxLocal = pPage->maxLocal; | ||||
| 72749 | surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4); | ||||
| 72750 | testcase( surplus==maxLocal ); | ||||
| 72751 | testcase( surplus==maxLocal+1 ); | ||||
| 72752 | if( surplus <= maxLocal ){ | ||||
| 72753 | pInfo->nLocal = (u16)surplus; | ||||
| 72754 | }else{ | ||||
| 72755 | pInfo->nLocal = (u16)minLocal; | ||||
| 72756 | } | ||||
| 72757 | pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4; | ||||
| 72758 | } | ||||
| 72759 | |||||
| 72760 | /* | ||||
| 72761 | ** Given a record with nPayload bytes of payload stored within btree | ||||
| 72762 | ** page pPage, return the number of bytes of payload stored locally. | ||||
| 72763 | */ | ||||
| 72764 | static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){ | ||||
| 72765 | int maxLocal; /* Maximum amount of payload held locally */ | ||||
| 72766 | maxLocal = pPage->maxLocal; | ||||
| 72767 | assert( nPayload>=0 )((void) (0)); | ||||
| 72768 | if( nPayload<=maxLocal ){ | ||||
| 72769 | return (int)nPayload; | ||||
| 72770 | }else{ | ||||
| 72771 | int minLocal; /* Minimum amount of payload held locally */ | ||||
| 72772 | int surplus; /* Overflow payload available for local storage */ | ||||
| 72773 | minLocal = pPage->minLocal; | ||||
| 72774 | surplus = (int)(minLocal +(nPayload - minLocal)%(pPage->pBt->usableSize-4)); | ||||
| 72775 | return (surplus <= maxLocal) ? surplus : minLocal; | ||||
| 72776 | } | ||||
| 72777 | } | ||||
| 72778 | |||||
| 72779 | /* | ||||
| 72780 | ** The following routines are implementations of the MemPage.xParseCell() | ||||
| 72781 | ** method. | ||||
| 72782 | ** | ||||
| 72783 | ** Parse a cell content block and fill in the CellInfo structure. | ||||
| 72784 | ** | ||||
| 72785 | ** btreeParseCellPtr() => table btree leaf nodes | ||||
| 72786 | ** btreeParseCellNoPayload() => table btree internal nodes | ||||
| 72787 | ** btreeParseCellPtrIndex() => index btree nodes | ||||
| 72788 | ** | ||||
| 72789 | ** There is also a wrapper function btreeParseCell() that works for | ||||
| 72790 | ** all MemPage types and that references the cell by index rather than | ||||
| 72791 | ** by pointer. | ||||
| 72792 | */ | ||||
| 72793 | static void btreeParseCellPtrNoPayload( | ||||
| 72794 | MemPage *pPage, /* Page containing the cell */ | ||||
| 72795 | u8 *pCell, /* Pointer to the cell text. */ | ||||
| 72796 | CellInfo *pInfo /* Fill in this structure */ | ||||
| 72797 | ){ | ||||
| 72798 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 72799 | assert( pPage->leaf==0 )((void) (0)); | ||||
| 72800 | assert( pPage->childPtrSize==4 )((void) (0)); | ||||
| 72801 | #ifndef SQLITE_DEBUG | ||||
| 72802 | UNUSED_PARAMETER(pPage)(void)(pPage); | ||||
| 72803 | #endif | ||||
| 72804 | pInfo->nSize = 4 + getVarintsqlite3GetVarint(&pCell[4], (u64*)&pInfo->nKey); | ||||
| 72805 | pInfo->nPayload = 0; | ||||
| 72806 | pInfo->nLocal = 0; | ||||
| 72807 | pInfo->pPayload = 0; | ||||
| 72808 | return; | ||||
| 72809 | } | ||||
| 72810 | static void btreeParseCellPtr( | ||||
| 72811 | MemPage *pPage, /* Page containing the cell */ | ||||
| 72812 | u8 *pCell, /* Pointer to the cell text. */ | ||||
| 72813 | CellInfo *pInfo /* Fill in this structure */ | ||||
| 72814 | ){ | ||||
| 72815 | u8 *pIter; /* For scanning through pCell */ | ||||
| 72816 | u32 nPayload; /* Number of bytes of cell payload */ | ||||
| 72817 | u64 iKey; /* Extracted Key value */ | ||||
| 72818 | |||||
| 72819 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 72820 | assert( pPage->leaf==0 || pPage->leaf==1 )((void) (0)); | ||||
| 72821 | assert( pPage->intKeyLeaf )((void) (0)); | ||||
| 72822 | assert( pPage->childPtrSize==0 )((void) (0)); | ||||
| 72823 | pIter = pCell; | ||||
| 72824 | |||||
| 72825 | /* The next block of code is equivalent to: | ||||
| 72826 | ** | ||||
| 72827 | ** pIter += getVarint32(pIter, nPayload); | ||||
| 72828 | ** | ||||
| 72829 | ** The code is inlined to avoid a function call. | ||||
| 72830 | */ | ||||
| 72831 | nPayload = *pIter; | ||||
| 72832 | if( nPayload>=0x80 ){ | ||||
| 72833 | u8 *pEnd = &pIter[8]; | ||||
| 72834 | nPayload &= 0x7f; | ||||
| 72835 | do{ | ||||
| 72836 | nPayload = (nPayload<<7) | (*++pIter & 0x7f); | ||||
| 72837 | }while( (*pIter)>=0x80 && pIter<pEnd ); | ||||
| 72838 | } | ||||
| 72839 | pIter++; | ||||
| 72840 | |||||
| 72841 | /* The next block of code is equivalent to: | ||||
| 72842 | ** | ||||
| 72843 | ** pIter += getVarint(pIter, (u64*)&pInfo->nKey); | ||||
| 72844 | ** | ||||
| 72845 | ** The code is inlined and the loop is unrolled for performance. | ||||
| 72846 | ** This routine is a high-runner. | ||||
| 72847 | */ | ||||
| 72848 | iKey = *pIter; | ||||
| 72849 | if( iKey>=0x80 ){ | ||||
| 72850 | u8 x; | ||||
| 72851 | iKey = (iKey<<7) ^ (x = *++pIter); | ||||
| 72852 | if( x>=0x80 ){ | ||||
| 72853 | iKey = (iKey<<7) ^ (x = *++pIter); | ||||
| 72854 | if( x>=0x80 ){ | ||||
| 72855 | iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++pIter); | ||||
| 72856 | if( x>=0x80 ){ | ||||
| 72857 | iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter); | ||||
| 72858 | if( x>=0x80 ){ | ||||
| 72859 | iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter); | ||||
| 72860 | if( x>=0x80 ){ | ||||
| 72861 | iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter); | ||||
| 72862 | if( x>=0x80 ){ | ||||
| 72863 | iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter); | ||||
| 72864 | if( x>=0x80 ){ | ||||
| 72865 | iKey = (iKey<<8) ^ 0x8000 ^ (*++pIter); | ||||
| 72866 | } | ||||
| 72867 | } | ||||
| 72868 | } | ||||
| 72869 | } | ||||
| 72870 | } | ||||
| 72871 | }else{ | ||||
| 72872 | iKey ^= 0x204000; | ||||
| 72873 | } | ||||
| 72874 | }else{ | ||||
| 72875 | iKey ^= 0x4000; | ||||
| 72876 | } | ||||
| 72877 | } | ||||
| 72878 | pIter++; | ||||
| 72879 | |||||
| 72880 | pInfo->nKey = *(i64*)&iKey; | ||||
| 72881 | pInfo->nPayload = nPayload; | ||||
| 72882 | pInfo->pPayload = pIter; | ||||
| 72883 | testcase( nPayload==pPage->maxLocal ); | ||||
| 72884 | testcase( nPayload==(u32)pPage->maxLocal+1 ); | ||||
| 72885 | assert( nPayload>=0 )((void) (0)); | ||||
| 72886 | assert( pPage->maxLocal <= BT_MAX_LOCAL )((void) (0)); | ||||
| 72887 | if( nPayload<=pPage->maxLocal ){ | ||||
| 72888 | /* This is the (easy) common case where the entire payload fits | ||||
| 72889 | ** on the local page. No overflow is required. | ||||
| 72890 | */ | ||||
| 72891 | pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell); | ||||
| 72892 | if( pInfo->nSize<4 ) pInfo->nSize = 4; | ||||
| 72893 | pInfo->nLocal = (u16)nPayload; | ||||
| 72894 | }else{ | ||||
| 72895 | btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); | ||||
| 72896 | } | ||||
| 72897 | } | ||||
| 72898 | static void btreeParseCellPtrIndex( | ||||
| 72899 | MemPage *pPage, /* Page containing the cell */ | ||||
| 72900 | u8 *pCell, /* Pointer to the cell text. */ | ||||
| 72901 | CellInfo *pInfo /* Fill in this structure */ | ||||
| 72902 | ){ | ||||
| 72903 | u8 *pIter; /* For scanning through pCell */ | ||||
| 72904 | u32 nPayload; /* Number of bytes of cell payload */ | ||||
| 72905 | |||||
| 72906 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 72907 | assert( pPage->leaf==0 || pPage->leaf==1 )((void) (0)); | ||||
| 72908 | assert( pPage->intKeyLeaf==0 )((void) (0)); | ||||
| 72909 | pIter = pCell + pPage->childPtrSize; | ||||
| 72910 | nPayload = *pIter; | ||||
| 72911 | if( nPayload>=0x80 ){ | ||||
| 72912 | u8 *pEnd = &pIter[8]; | ||||
| 72913 | nPayload &= 0x7f; | ||||
| 72914 | do{ | ||||
| 72915 | nPayload = (nPayload<<7) | (*++pIter & 0x7f); | ||||
| 72916 | }while( *(pIter)>=0x80 && pIter<pEnd ); | ||||
| 72917 | } | ||||
| 72918 | pIter++; | ||||
| 72919 | pInfo->nKey = nPayload; | ||||
| 72920 | pInfo->nPayload = nPayload; | ||||
| 72921 | pInfo->pPayload = pIter; | ||||
| 72922 | testcase( nPayload==pPage->maxLocal ); | ||||
| 72923 | testcase( nPayload==(u32)pPage->maxLocal+1 ); | ||||
| 72924 | assert( nPayload>=0 )((void) (0)); | ||||
| 72925 | assert( pPage->maxLocal <= BT_MAX_LOCAL )((void) (0)); | ||||
| 72926 | if( nPayload<=pPage->maxLocal ){ | ||||
| 72927 | /* This is the (easy) common case where the entire payload fits | ||||
| 72928 | ** on the local page. No overflow is required. | ||||
| 72929 | */ | ||||
| 72930 | pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell); | ||||
| 72931 | if( pInfo->nSize<4 ) pInfo->nSize = 4; | ||||
| 72932 | pInfo->nLocal = (u16)nPayload; | ||||
| 72933 | }else{ | ||||
| 72934 | btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); | ||||
| 72935 | } | ||||
| 72936 | } | ||||
| 72937 | static void btreeParseCell( | ||||
| 72938 | MemPage *pPage, /* Page containing the cell */ | ||||
| 72939 | int iCell, /* The cell index. First cell is 0 */ | ||||
| 72940 | CellInfo *pInfo /* Fill in this structure */ | ||||
| 72941 | ){ | ||||
| 72942 | pPage->xParseCell(pPage, findCell(pPage, iCell)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(iCell)])[0]<<8 | (&(pPage)->aCellIdx [2*(iCell)])[1]))), pInfo); | ||||
| 72943 | } | ||||
| 72944 | |||||
| 72945 | /* | ||||
| 72946 | ** The following routines are implementations of the MemPage.xCellSize | ||||
| 72947 | ** method. | ||||
| 72948 | ** | ||||
| 72949 | ** Compute the total number of bytes that a Cell needs in the cell | ||||
| 72950 | ** data area of the btree-page. The return number includes the cell | ||||
| 72951 | ** data header and the local payload, but not any overflow page or | ||||
| 72952 | ** the space used by the cell pointer. | ||||
| 72953 | ** | ||||
| 72954 | ** cellSizePtrNoPayload() => table internal nodes | ||||
| 72955 | ** cellSizePtrTableLeaf() => table leaf nodes | ||||
| 72956 | ** cellSizePtr() => index internal nodes | ||||
| 72957 | ** cellSizeIdxLeaf() => index leaf nodes | ||||
| 72958 | */ | ||||
| 72959 | static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ | ||||
| 72960 | u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ | ||||
| 72961 | u8 *pEnd; /* End mark for a varint */ | ||||
| 72962 | u32 nSize; /* Size value to return */ | ||||
| 72963 | |||||
| 72964 | #ifdef SQLITE_DEBUG | ||||
| 72965 | /* The value returned by this function should always be the same as | ||||
| 72966 | ** the (CellInfo.nSize) value found by doing a full parse of the | ||||
| 72967 | ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of | ||||
| 72968 | ** this function verifies that this invariant is not violated. */ | ||||
| 72969 | CellInfo debuginfo; | ||||
| 72970 | pPage->xParseCell(pPage, pCell, &debuginfo); | ||||
| 72971 | #endif | ||||
| 72972 | |||||
| 72973 | assert( pPage->childPtrSize==4 )((void) (0)); | ||||
| 72974 | nSize = *pIter; | ||||
| 72975 | if( nSize>=0x80 ){ | ||||
| 72976 | pEnd = &pIter[8]; | ||||
| 72977 | nSize &= 0x7f; | ||||
| 72978 | do{ | ||||
| 72979 | nSize = (nSize<<7) | (*++pIter & 0x7f); | ||||
| 72980 | }while( *(pIter)>=0x80 && pIter<pEnd ); | ||||
| 72981 | } | ||||
| 72982 | pIter++; | ||||
| 72983 | testcase( nSize==pPage->maxLocal ); | ||||
| 72984 | testcase( nSize==(u32)pPage->maxLocal+1 ); | ||||
| 72985 | if( nSize<=pPage->maxLocal ){ | ||||
| 72986 | nSize += (u32)(pIter - pCell); | ||||
| 72987 | assert( nSize>4 )((void) (0)); | ||||
| 72988 | }else{ | ||||
| 72989 | int minLocal = pPage->minLocal; | ||||
| 72990 | nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); | ||||
| 72991 | testcase( nSize==pPage->maxLocal ); | ||||
| 72992 | testcase( nSize==(u32)pPage->maxLocal+1 ); | ||||
| 72993 | if( nSize>pPage->maxLocal ){ | ||||
| 72994 | nSize = minLocal; | ||||
| 72995 | } | ||||
| 72996 | nSize += 4 + (u16)(pIter - pCell); | ||||
| 72997 | } | ||||
| 72998 | assert( nSize==debuginfo.nSize || CORRUPT_DB )((void) (0)); | ||||
| 72999 | return (u16)nSize; | ||||
| 73000 | } | ||||
| 73001 | static u16 cellSizePtrIdxLeaf(MemPage *pPage, u8 *pCell){ | ||||
| 73002 | u8 *pIter = pCell; /* For looping over bytes of pCell */ | ||||
| 73003 | u8 *pEnd; /* End mark for a varint */ | ||||
| 73004 | u32 nSize; /* Size value to return */ | ||||
| 73005 | |||||
| 73006 | #ifdef SQLITE_DEBUG | ||||
| 73007 | /* The value returned by this function should always be the same as | ||||
| 73008 | ** the (CellInfo.nSize) value found by doing a full parse of the | ||||
| 73009 | ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of | ||||
| 73010 | ** this function verifies that this invariant is not violated. */ | ||||
| 73011 | CellInfo debuginfo; | ||||
| 73012 | pPage->xParseCell(pPage, pCell, &debuginfo); | ||||
| 73013 | #endif | ||||
| 73014 | |||||
| 73015 | assert( pPage->childPtrSize==0 )((void) (0)); | ||||
| 73016 | nSize = *pIter; | ||||
| 73017 | if( nSize>=0x80 ){ | ||||
| 73018 | pEnd = &pIter[8]; | ||||
| 73019 | nSize &= 0x7f; | ||||
| 73020 | do{ | ||||
| 73021 | nSize = (nSize<<7) | (*++pIter & 0x7f); | ||||
| 73022 | }while( *(pIter)>=0x80 && pIter<pEnd ); | ||||
| 73023 | } | ||||
| 73024 | pIter++; | ||||
| 73025 | testcase( nSize==pPage->maxLocal ); | ||||
| 73026 | testcase( nSize==(u32)pPage->maxLocal+1 ); | ||||
| 73027 | if( nSize<=pPage->maxLocal ){ | ||||
| 73028 | nSize += (u32)(pIter - pCell); | ||||
| 73029 | if( nSize<4 ) nSize = 4; | ||||
| 73030 | }else{ | ||||
| 73031 | int minLocal = pPage->minLocal; | ||||
| 73032 | nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); | ||||
| 73033 | testcase( nSize==pPage->maxLocal ); | ||||
| 73034 | testcase( nSize==(u32)pPage->maxLocal+1 ); | ||||
| 73035 | if( nSize>pPage->maxLocal ){ | ||||
| 73036 | nSize = minLocal; | ||||
| 73037 | } | ||||
| 73038 | nSize += 4 + (u16)(pIter - pCell); | ||||
| 73039 | } | ||||
| 73040 | assert( nSize==debuginfo.nSize || CORRUPT_DB )((void) (0)); | ||||
| 73041 | return (u16)nSize; | ||||
| 73042 | } | ||||
| 73043 | static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ | ||||
| 73044 | u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ | ||||
| 73045 | u8 *pEnd; /* End mark for a varint */ | ||||
| 73046 | |||||
| 73047 | #ifdef SQLITE_DEBUG | ||||
| 73048 | /* The value returned by this function should always be the same as | ||||
| 73049 | ** the (CellInfo.nSize) value found by doing a full parse of the | ||||
| 73050 | ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of | ||||
| 73051 | ** this function verifies that this invariant is not violated. */ | ||||
| 73052 | CellInfo debuginfo; | ||||
| 73053 | pPage->xParseCell(pPage, pCell, &debuginfo); | ||||
| 73054 | #else | ||||
| 73055 | UNUSED_PARAMETER(pPage)(void)(pPage); | ||||
| 73056 | #endif | ||||
| 73057 | |||||
| 73058 | assert( pPage->childPtrSize==4 )((void) (0)); | ||||
| 73059 | pEnd = pIter + 9; | ||||
| 73060 | while( (*pIter++)&0x80 && pIter<pEnd ); | ||||
| 73061 | assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB )((void) (0)); | ||||
| 73062 | return (u16)(pIter - pCell); | ||||
| 73063 | } | ||||
| 73064 | static u16 cellSizePtrTableLeaf(MemPage *pPage, u8 *pCell){ | ||||
| 73065 | u8 *pIter = pCell; /* For looping over bytes of pCell */ | ||||
| 73066 | u8 *pEnd; /* End mark for a varint */ | ||||
| 73067 | u32 nSize; /* Size value to return */ | ||||
| 73068 | |||||
| 73069 | #ifdef SQLITE_DEBUG | ||||
| 73070 | /* The value returned by this function should always be the same as | ||||
| 73071 | ** the (CellInfo.nSize) value found by doing a full parse of the | ||||
| 73072 | ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of | ||||
| 73073 | ** this function verifies that this invariant is not violated. */ | ||||
| 73074 | CellInfo debuginfo; | ||||
| 73075 | pPage->xParseCell(pPage, pCell, &debuginfo); | ||||
| 73076 | #endif | ||||
| 73077 | |||||
| 73078 | nSize = *pIter; | ||||
| 73079 | if( nSize>=0x80 ){ | ||||
| 73080 | pEnd = &pIter[8]; | ||||
| 73081 | nSize &= 0x7f; | ||||
| 73082 | do{ | ||||
| 73083 | nSize = (nSize<<7) | (*++pIter & 0x7f); | ||||
| 73084 | }while( *(pIter)>=0x80 && pIter<pEnd ); | ||||
| 73085 | } | ||||
| 73086 | pIter++; | ||||
| 73087 | /* pIter now points at the 64-bit integer key value, a variable length | ||||
| 73088 | ** integer. The following block moves pIter to point at the first byte | ||||
| 73089 | ** past the end of the key value. */ | ||||
| 73090 | if( (*pIter++)&0x80 | ||||
| 73091 | && (*pIter++)&0x80 | ||||
| 73092 | && (*pIter++)&0x80 | ||||
| 73093 | && (*pIter++)&0x80 | ||||
| 73094 | && (*pIter++)&0x80 | ||||
| 73095 | && (*pIter++)&0x80 | ||||
| 73096 | && (*pIter++)&0x80 | ||||
| 73097 | && (*pIter++)&0x80 ){ pIter++; } | ||||
| 73098 | testcase( nSize==pPage->maxLocal ); | ||||
| 73099 | testcase( nSize==(u32)pPage->maxLocal+1 ); | ||||
| 73100 | if( nSize<=pPage->maxLocal ){ | ||||
| 73101 | nSize += (u32)(pIter - pCell); | ||||
| 73102 | if( nSize<4 ) nSize = 4; | ||||
| 73103 | }else{ | ||||
| 73104 | int minLocal = pPage->minLocal; | ||||
| 73105 | nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); | ||||
| 73106 | testcase( nSize==pPage->maxLocal ); | ||||
| 73107 | testcase( nSize==(u32)pPage->maxLocal+1 ); | ||||
| 73108 | if( nSize>pPage->maxLocal ){ | ||||
| 73109 | nSize = minLocal; | ||||
| 73110 | } | ||||
| 73111 | nSize += 4 + (u16)(pIter - pCell); | ||||
| 73112 | } | ||||
| 73113 | assert( nSize==debuginfo.nSize || CORRUPT_DB )((void) (0)); | ||||
| 73114 | return (u16)nSize; | ||||
| 73115 | } | ||||
| 73116 | |||||
| 73117 | |||||
| 73118 | #ifdef SQLITE_DEBUG | ||||
| 73119 | /* This variation on cellSizePtr() is used inside of assert() statements | ||||
| 73120 | ** only. */ | ||||
| 73121 | static u16 cellSize(MemPage *pPage, int iCell){ | ||||
| 73122 | return pPage->xCellSize(pPage, findCell(pPage, iCell)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(iCell)])[0]<<8 | (&(pPage)->aCellIdx [2*(iCell)])[1])))); | ||||
| 73123 | } | ||||
| 73124 | #endif | ||||
| 73125 | |||||
| 73126 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 73127 | /* | ||||
| 73128 | ** The cell pCell is currently part of page pSrc but will ultimately be part | ||||
| 73129 | ** of pPage. (pSrc and pPage are often the same.) If pCell contains a | ||||
| 73130 | ** pointer to an overflow page, insert an entry into the pointer-map for | ||||
| 73131 | ** the overflow page that will be valid after pCell has been moved to pPage. | ||||
| 73132 | */ | ||||
| 73133 | static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){ | ||||
| 73134 | CellInfo info; | ||||
| 73135 | if( *pRC ) return; | ||||
| 73136 | assert( pCell!=0 )((void) (0)); | ||||
| 73137 | pPage->xParseCell(pPage, pCell, &info); | ||||
| 73138 | if( info.nLocal<info.nPayload ){ | ||||
| 73139 | Pgno ovfl; | ||||
| 73140 | if( SQLITE_OVERFLOW(pSrc->aDataEnd, pCell, pCell+info.nLocal)(((uptr)(pCell)<(uptr)(pSrc->aDataEnd))&&((uptr )(pCell+info.nLocal)>(uptr)(pSrc->aDataEnd))) ){ | ||||
| 73141 | testcase( pSrc!=pPage ); | ||||
| 73142 | *pRC = SQLITE_CORRUPT_BKPTsqlite3CorruptError(73142); | ||||
| 73143 | return; | ||||
| 73144 | } | ||||
| 73145 | ovfl = get4bytesqlite3Get4byte(&pCell[info.nSize-4]); | ||||
| 73146 | ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW13, pPage->pgno, pRC); | ||||
| 73147 | } | ||||
| 73148 | } | ||||
| 73149 | #endif | ||||
| 73150 | |||||
| 73151 | |||||
| 73152 | /* | ||||
| 73153 | ** Defragment the page given. This routine reorganizes cells within the | ||||
| 73154 | ** page so that there are no free-blocks on the free-block list. | ||||
| 73155 | ** | ||||
| 73156 | ** Parameter nMaxFrag is the maximum amount of fragmented space that may be | ||||
| 73157 | ** present in the page after this routine returns. | ||||
| 73158 | ** | ||||
| 73159 | ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a | ||||
| 73160 | ** b-tree page so that there are no freeblocks or fragment bytes, all | ||||
| 73161 | ** unused bytes are contained in the unallocated space region, and all | ||||
| 73162 | ** cells are packed tightly at the end of the page. | ||||
| 73163 | */ | ||||
| 73164 | static int defragmentPage(MemPage *pPage, int nMaxFrag){ | ||||
| 73165 | int i; /* Loop counter */ | ||||
| 73166 | int pc; /* Address of the i-th cell */ | ||||
| 73167 | int hdr; /* Offset to the page header */ | ||||
| 73168 | int size; /* Size of a cell */ | ||||
| 73169 | int usableSize; /* Number of usable bytes on a page */ | ||||
| 73170 | int cellOffset; /* Offset to the cell pointer array */ | ||||
| 73171 | int cbrk; /* Offset to the cell content area */ | ||||
| 73172 | int nCell; /* Number of cells on the page */ | ||||
| 73173 | unsigned char *data; /* The page data */ | ||||
| 73174 | unsigned char *temp; /* Temp area for cell content */ | ||||
| 73175 | unsigned char *src; /* Source of content */ | ||||
| 73176 | int iCellFirst; /* First allowable cell index */ | ||||
| 73177 | int iCellLast; /* Last possible cell index */ | ||||
| 73178 | int iCellStart; /* First cell offset in input */ | ||||
| 73179 | |||||
| 73180 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 73181 | assert( pPage->pBt!=0 )((void) (0)); | ||||
| 73182 | assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE )((void) (0)); | ||||
| 73183 | assert( pPage->nOverflow==0 )((void) (0)); | ||||
| 73184 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73185 | data = pPage->aData; | ||||
| 73186 | hdr = pPage->hdrOffset; | ||||
| 73187 | cellOffset = pPage->cellOffset; | ||||
| 73188 | nCell = pPage->nCell; | ||||
| 73189 | assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB )((void) (0)); | ||||
| 73190 | iCellFirst = cellOffset + 2*nCell; | ||||
| 73191 | usableSize = pPage->pBt->usableSize; | ||||
| 73192 | |||||
| 73193 | /* This block handles pages with two or fewer free blocks and nMaxFrag | ||||
| 73194 | ** or fewer fragmented bytes. In this case it is faster to move the | ||||
| 73195 | ** two (or one) blocks of cells using memmove() and add the required | ||||
| 73196 | ** offsets to each pointer in the cell-pointer array than it is to | ||||
| 73197 | ** reconstruct the entire page. */ | ||||
| 73198 | if( (int)data[hdr+7]<=nMaxFrag ){ | ||||
| 73199 | int iFree = get2byte(&data[hdr+1])((&data[hdr+1])[0]<<8 | (&data[hdr+1])[1]); | ||||
| 73200 | if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73200); | ||||
| 73201 | if( iFree ){ | ||||
| 73202 | int iFree2 = get2byte(&data[iFree])((&data[iFree])[0]<<8 | (&data[iFree])[1]); | ||||
| 73203 | if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73203); | ||||
| 73204 | if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){ | ||||
| 73205 | u8 *pEnd = &data[cellOffset + nCell*2]; | ||||
| 73206 | u8 *pAddr; | ||||
| 73207 | int sz2 = 0; | ||||
| 73208 | int sz = get2byte(&data[iFree+2])((&data[iFree+2])[0]<<8 | (&data[iFree+2])[1]); | ||||
| 73209 | int top = get2byte(&data[hdr+5])((&data[hdr+5])[0]<<8 | (&data[hdr+5])[1]); | ||||
| 73210 | if( top>=iFree ){ | ||||
| 73211 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73211); | ||||
| 73212 | } | ||||
| 73213 | if( iFree2 ){ | ||||
| 73214 | if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73214); | ||||
| 73215 | sz2 = get2byte(&data[iFree2+2])((&data[iFree2+2])[0]<<8 | (&data[iFree2+2])[1] ); | ||||
| 73216 | if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73216); | ||||
| 73217 | memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz)); | ||||
| 73218 | sz += sz2; | ||||
| 73219 | }else if( iFree+sz>usableSize ){ | ||||
| 73220 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73220); | ||||
| 73221 | } | ||||
| 73222 | |||||
| 73223 | cbrk = top+sz; | ||||
| 73224 | assert( cbrk+(iFree-top) <= usableSize )((void) (0)); | ||||
| 73225 | memmove(&data[cbrk], &data[top], iFree-top); | ||||
| 73226 | for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){ | ||||
| 73227 | pc = get2byte(pAddr)((pAddr)[0]<<8 | (pAddr)[1]); | ||||
| 73228 | if( pc<iFree ){ put2byte(pAddr, pc+sz)((pAddr)[0] = (u8)((pc+sz)>>8), (pAddr)[1] = (u8)(pc+sz )); } | ||||
| 73229 | else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2)((pAddr)[0] = (u8)((pc+sz2)>>8), (pAddr)[1] = (u8)(pc+sz2 )); } | ||||
| 73230 | } | ||||
| 73231 | goto defragment_out; | ||||
| 73232 | } | ||||
| 73233 | } | ||||
| 73234 | } | ||||
| 73235 | |||||
| 73236 | cbrk = usableSize; | ||||
| 73237 | iCellLast = usableSize - 4; | ||||
| 73238 | iCellStart = get2byte(&data[hdr+5])((&data[hdr+5])[0]<<8 | (&data[hdr+5])[1]); | ||||
| 73239 | if( nCell>0 ){ | ||||
| 73240 | temp = sqlite3PagerTempSpace(pPage->pBt->pPager); | ||||
| 73241 | memcpy(temp, data, usableSize); | ||||
| 73242 | src = temp; | ||||
| 73243 | for(i=0; i<nCell; i++){ | ||||
| 73244 | u8 *pAddr; /* The i-th cell pointer */ | ||||
| 73245 | pAddr = &data[cellOffset + i*2]; | ||||
| 73246 | pc = get2byte(pAddr)((pAddr)[0]<<8 | (pAddr)[1]); | ||||
| 73247 | testcase( pc==iCellFirst ); | ||||
| 73248 | testcase( pc==iCellLast ); | ||||
| 73249 | /* These conditions have already been verified in btreeInitPage() | ||||
| 73250 | ** if PRAGMA cell_size_check=ON. | ||||
| 73251 | */ | ||||
| 73252 | if( pc>iCellLast ){ | ||||
| 73253 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73253); | ||||
| 73254 | } | ||||
| 73255 | assert( pc>=0 && pc<=iCellLast )((void) (0)); | ||||
| 73256 | size = pPage->xCellSize(pPage, &src[pc]); | ||||
| 73257 | cbrk -= size; | ||||
| 73258 | if( cbrk<iCellStart || pc+size>usableSize ){ | ||||
| 73259 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73259); | ||||
| 73260 | } | ||||
| 73261 | assert( cbrk+size<=usableSize && cbrk>=iCellStart )((void) (0)); | ||||
| 73262 | testcase( cbrk+size==usableSize ); | ||||
| 73263 | testcase( pc+size==usableSize ); | ||||
| 73264 | put2byte(pAddr, cbrk)((pAddr)[0] = (u8)((cbrk)>>8), (pAddr)[1] = (u8)(cbrk)); | ||||
| 73265 | memcpy(&data[cbrk], &src[pc], size); | ||||
| 73266 | } | ||||
| 73267 | } | ||||
| 73268 | data[hdr+7] = 0; | ||||
| 73269 | |||||
| 73270 | defragment_out: | ||||
| 73271 | assert( pPage->nFree>=0 )((void) (0)); | ||||
| 73272 | if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){ | ||||
| 73273 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73273); | ||||
| 73274 | } | ||||
| 73275 | assert( cbrk>=iCellFirst )((void) (0)); | ||||
| 73276 | put2byte(&data[hdr+5], cbrk)((&data[hdr+5])[0] = (u8)((cbrk)>>8), (&data[hdr +5])[1] = (u8)(cbrk)); | ||||
| 73277 | data[hdr+1] = 0; | ||||
| 73278 | data[hdr+2] = 0; | ||||
| 73279 | memset(&data[iCellFirst], 0, cbrk-iCellFirst); | ||||
| 73280 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 73281 | return SQLITE_OK0; | ||||
| 73282 | } | ||||
| 73283 | |||||
| 73284 | /* | ||||
| 73285 | ** Search the free-list on page pPg for space to store a cell nByte bytes in | ||||
| 73286 | ** size. If one can be found, return a pointer to the space and remove it | ||||
| 73287 | ** from the free-list. | ||||
| 73288 | ** | ||||
| 73289 | ** If no suitable space can be found on the free-list, return NULL. | ||||
| 73290 | ** | ||||
| 73291 | ** This function may detect corruption within pPg. If corruption is | ||||
| 73292 | ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned. | ||||
| 73293 | ** | ||||
| 73294 | ** Slots on the free list that are between 1 and 3 bytes larger than nByte | ||||
| 73295 | ** will be ignored if adding the extra space to the fragmentation count | ||||
| 73296 | ** causes the fragmentation count to exceed 60. | ||||
| 73297 | */ | ||||
| 73298 | static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ | ||||
| 73299 | const int hdr = pPg->hdrOffset; /* Offset to page header */ | ||||
| 73300 | u8 * const aData = pPg->aData; /* Page data */ | ||||
| 73301 | int iAddr = hdr + 1; /* Address of ptr to pc */ | ||||
| 73302 | u8 *pTmp = &aData[iAddr]; /* Temporary ptr into aData[] */ | ||||
| 73303 | int pc = get2byte(pTmp)((pTmp)[0]<<8 | (pTmp)[1]); /* Address of a free slot */ | ||||
| 73304 | int x; /* Excess size of the slot */ | ||||
| 73305 | int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */ | ||||
| 73306 | int size; /* Size of the free slot */ | ||||
| 73307 | |||||
| 73308 | assert( pc>0 )((void) (0)); | ||||
| 73309 | while( pc<=maxPC ){ | ||||
| 73310 | /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each | ||||
| 73311 | ** freeblock form a big-endian integer which is the size of the freeblock | ||||
| 73312 | ** in bytes, including the 4-byte header. */ | ||||
| 73313 | pTmp = &aData[pc+2]; | ||||
| 73314 | size = get2byte(pTmp)((pTmp)[0]<<8 | (pTmp)[1]); | ||||
| 73315 | if( (x = size - nByte)>=0 ){ | ||||
| 73316 | testcase( x==4 ); | ||||
| 73317 | testcase( x==3 ); | ||||
| 73318 | if( x<4 ){ | ||||
| 73319 | /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total | ||||
| 73320 | ** number of bytes in fragments may not exceed 60. */ | ||||
| 73321 | if( aData[hdr+7]>57 ) return 0; | ||||
| 73322 | |||||
| 73323 | /* Remove the slot from the free-list. Update the number of | ||||
| 73324 | ** fragmented bytes within the page. */ | ||||
| 73325 | memcpy(&aData[iAddr], &aData[pc], 2); | ||||
| 73326 | aData[hdr+7] += (u8)x; | ||||
| 73327 | return &aData[pc]; | ||||
| 73328 | }else if( x+pc > maxPC ){ | ||||
| 73329 | /* This slot extends off the end of the usable part of the page */ | ||||
| 73330 | *pRc = SQLITE_CORRUPT_PAGE(pPg)sqlite3CorruptError(73330); | ||||
| 73331 | return 0; | ||||
| 73332 | }else{ | ||||
| 73333 | /* The slot remains on the free-list. Reduce its size to account | ||||
| 73334 | ** for the portion used by the new allocation. */ | ||||
| 73335 | put2byte(&aData[pc+2], x)((&aData[pc+2])[0] = (u8)((x)>>8), (&aData[pc+2 ])[1] = (u8)(x)); | ||||
| 73336 | } | ||||
| 73337 | return &aData[pc + x]; | ||||
| 73338 | } | ||||
| 73339 | iAddr = pc; | ||||
| 73340 | pTmp = &aData[pc]; | ||||
| 73341 | pc = get2byte(pTmp)((pTmp)[0]<<8 | (pTmp)[1]); | ||||
| 73342 | if( pc<=iAddr ){ | ||||
| 73343 | if( pc ){ | ||||
| 73344 | /* The next slot in the chain comes before the current slot */ | ||||
| 73345 | *pRc = SQLITE_CORRUPT_PAGE(pPg)sqlite3CorruptError(73345); | ||||
| 73346 | } | ||||
| 73347 | return 0; | ||||
| 73348 | } | ||||
| 73349 | } | ||||
| 73350 | if( pc>maxPC+nByte-4 ){ | ||||
| 73351 | /* The free slot chain extends off the end of the page */ | ||||
| 73352 | *pRc = SQLITE_CORRUPT_PAGE(pPg)sqlite3CorruptError(73352); | ||||
| 73353 | } | ||||
| 73354 | return 0; | ||||
| 73355 | } | ||||
| 73356 | |||||
| 73357 | /* | ||||
| 73358 | ** Allocate nByte bytes of space from within the B-Tree page passed | ||||
| 73359 | ** as the first argument. Write into *pIdx the index into pPage->aData[] | ||||
| 73360 | ** of the first byte of allocated space. Return either SQLITE_OK or | ||||
| 73361 | ** an error code (usually SQLITE_CORRUPT). | ||||
| 73362 | ** | ||||
| 73363 | ** The caller guarantees that there is sufficient space to make the | ||||
| 73364 | ** allocation. This routine might need to defragment in order to bring | ||||
| 73365 | ** all the space together, however. This routine will avoid using | ||||
| 73366 | ** the first two bytes past the cell pointer area since presumably this | ||||
| 73367 | ** allocation is being made in order to insert a new cell, so we will | ||||
| 73368 | ** also end up needing a new cell pointer. | ||||
| 73369 | */ | ||||
| 73370 | static SQLITE_INLINE__attribute__((always_inline)) inline int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ | ||||
| 73371 | const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ | ||||
| 73372 | u8 * const data = pPage->aData; /* Local cache of pPage->aData */ | ||||
| 73373 | int top; /* First byte of cell content area */ | ||||
| 73374 | int rc = SQLITE_OK0; /* Integer return code */ | ||||
| 73375 | u8 *pTmp; /* Temp ptr into data[] */ | ||||
| 73376 | int gap; /* First byte of gap between cell pointers and cell content */ | ||||
| 73377 | |||||
| 73378 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 73379 | assert( pPage->pBt )((void) (0)); | ||||
| 73380 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73381 | assert( nByte>=0 )((void) (0)); /* Minimum cell size is 4 */ | ||||
| 73382 | assert( pPage->nFree>=nByte )((void) (0)); | ||||
| 73383 | assert( pPage->nOverflow==0 )((void) (0)); | ||||
| 73384 | assert( nByte < (int)(pPage->pBt->usableSize-8) )((void) (0)); | ||||
| 73385 | |||||
| 73386 | assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf )((void) (0)); | ||||
| 73387 | gap = pPage->cellOffset + 2*pPage->nCell; | ||||
| 73388 | assert( gap<=65536 )((void) (0)); | ||||
| 73389 | /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size | ||||
| 73390 | ** and the reserved space is zero (the usual value for reserved space) | ||||
| 73391 | ** then the cell content offset of an empty page wants to be 65536. | ||||
| 73392 | ** However, that integer is too large to be stored in a 2-byte unsigned | ||||
| 73393 | ** integer, so a value of 0 is used in its place. */ | ||||
| 73394 | pTmp = &data[hdr+5]; | ||||
| 73395 | top = get2byte(pTmp)((pTmp)[0]<<8 | (pTmp)[1]); | ||||
| 73396 | if( gap>top ){ | ||||
| 73397 | if( top==0 && pPage->pBt->usableSize==65536 ){ | ||||
| 73398 | top = 65536; | ||||
| 73399 | }else{ | ||||
| 73400 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73400); | ||||
| 73401 | } | ||||
| 73402 | }else if( top>(int)pPage->pBt->usableSize ){ | ||||
| 73403 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73403); | ||||
| 73404 | } | ||||
| 73405 | |||||
| 73406 | /* If there is enough space between gap and top for one more cell pointer, | ||||
| 73407 | ** and if the freelist is not empty, then search the | ||||
| 73408 | ** freelist looking for a slot big enough to satisfy the request. | ||||
| 73409 | */ | ||||
| 73410 | testcase( gap+2==top ); | ||||
| 73411 | testcase( gap+1==top ); | ||||
| 73412 | testcase( gap==top ); | ||||
| 73413 | if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ | ||||
| 73414 | u8 *pSpace = pageFindSlot(pPage, nByte, &rc); | ||||
| 73415 | if( pSpace ){ | ||||
| 73416 | int g2; | ||||
| 73417 | assert( pSpace+nByte<=data+pPage->pBt->usableSize )((void) (0)); | ||||
| 73418 | *pIdx = g2 = (int)(pSpace-data); | ||||
| 73419 | if( g2<=gap ){ | ||||
| 73420 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73420); | ||||
| 73421 | }else{ | ||||
| 73422 | return SQLITE_OK0; | ||||
| 73423 | } | ||||
| 73424 | }else if( rc ){ | ||||
| 73425 | return rc; | ||||
| 73426 | } | ||||
| 73427 | } | ||||
| 73428 | |||||
| 73429 | /* The request could not be fulfilled using a freelist slot. Check | ||||
| 73430 | ** to see if defragmentation is necessary. | ||||
| 73431 | */ | ||||
| 73432 | testcase( gap+2+nByte==top ); | ||||
| 73433 | if( gap+2+nByte>top ){ | ||||
| 73434 | assert( pPage->nCell>0 || CORRUPT_DB )((void) (0)); | ||||
| 73435 | assert( pPage->nFree>=0 )((void) (0)); | ||||
| 73436 | rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte))((4)<(pPage->nFree - (2+nByte))?(4):(pPage->nFree - ( 2+nByte)))); | ||||
| 73437 | if( rc ) return rc; | ||||
| 73438 | top = get2byteNotZero(&data[hdr+5])(((((int)((&data[hdr+5])[0]<<8 | (&data[hdr+5]) [1]))-1)&0xffff)+1); | ||||
| 73439 | assert( gap+2+nByte<=top )((void) (0)); | ||||
| 73440 | } | ||||
| 73441 | |||||
| 73442 | |||||
| 73443 | /* Allocate memory from the gap in between the cell pointer array | ||||
| 73444 | ** and the cell content area. The btreeComputeFreeSpace() call has already | ||||
| 73445 | ** validated the freelist. Given that the freelist is valid, there | ||||
| 73446 | ** is no way that the allocation can extend off the end of the page. | ||||
| 73447 | ** The assert() below verifies the previous sentence. | ||||
| 73448 | */ | ||||
| 73449 | top -= nByte; | ||||
| 73450 | put2byte(&data[hdr+5], top)((&data[hdr+5])[0] = (u8)((top)>>8), (&data[hdr +5])[1] = (u8)(top)); | ||||
| 73451 | assert( top+nByte <= (int)pPage->pBt->usableSize )((void) (0)); | ||||
| 73452 | *pIdx = top; | ||||
| 73453 | return SQLITE_OK0; | ||||
| 73454 | } | ||||
| 73455 | |||||
| 73456 | /* | ||||
| 73457 | ** Return a section of the pPage->aData to the freelist. | ||||
| 73458 | ** The first byte of the new free block is pPage->aData[iStart] | ||||
| 73459 | ** and the size of the block is iSize bytes. | ||||
| 73460 | ** | ||||
| 73461 | ** Adjacent freeblocks are coalesced. | ||||
| 73462 | ** | ||||
| 73463 | ** Even though the freeblock list was checked by btreeComputeFreeSpace(), | ||||
| 73464 | ** that routine will not detect overlap between cells or freeblocks. Nor | ||||
| 73465 | ** does it detect cells or freeblocks that encroach into the reserved bytes | ||||
| 73466 | ** at the end of the page. So do additional corruption checks inside this | ||||
| 73467 | ** routine and return SQLITE_CORRUPT if any problems are found. | ||||
| 73468 | */ | ||||
| 73469 | static int freeSpace(MemPage *pPage, int iStart, int iSize){ | ||||
| 73470 | int iPtr; /* Address of ptr to next freeblock */ | ||||
| 73471 | int iFreeBlk; /* Address of the next freeblock */ | ||||
| 73472 | u8 hdr; /* Page header size. 0 or 100 */ | ||||
| 73473 | int nFrag = 0; /* Reduction in fragmentation */ | ||||
| 73474 | int iOrigSize = iSize; /* Original value of iSize */ | ||||
| 73475 | int x; /* Offset to cell content area */ | ||||
| 73476 | int iEnd = iStart + iSize; /* First byte past the iStart buffer */ | ||||
| 73477 | unsigned char *data = pPage->aData; /* Page content */ | ||||
| 73478 | u8 *pTmp; /* Temporary ptr into data[] */ | ||||
| 73479 | |||||
| 73480 | assert( pPage->pBt!=0 )((void) (0)); | ||||
| 73481 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 73482 | assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize )((void) (0)); | ||||
| 73483 | assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize )((void) (0)); | ||||
| 73484 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73485 | assert( iSize>=4 )((void) (0)); /* Minimum cell size is 4 */ | ||||
| 73486 | assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 )((void) (0)); | ||||
| 73487 | |||||
| 73488 | /* The list of freeblocks must be in ascending order. Find the | ||||
| 73489 | ** spot on the list where iStart should be inserted. | ||||
| 73490 | */ | ||||
| 73491 | hdr = pPage->hdrOffset; | ||||
| 73492 | iPtr = hdr + 1; | ||||
| 73493 | if( data[iPtr+1]==0 && data[iPtr]==0 ){ | ||||
| 73494 | iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ | ||||
| 73495 | }else{ | ||||
| 73496 | while( (iFreeBlk = get2byte(&data[iPtr])((&data[iPtr])[0]<<8 | (&data[iPtr])[1]))<iStart ){ | ||||
| 73497 | if( iFreeBlk<=iPtr ){ | ||||
| 73498 | if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */ | ||||
| 73499 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73499); | ||||
| 73500 | } | ||||
| 73501 | iPtr = iFreeBlk; | ||||
| 73502 | } | ||||
| 73503 | if( iFreeBlk>(int)pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */ | ||||
| 73504 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73504); | ||||
| 73505 | } | ||||
| 73506 | assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB )((void) (0)); | ||||
| 73507 | |||||
| 73508 | /* At this point: | ||||
| 73509 | ** iFreeBlk: First freeblock after iStart, or zero if none | ||||
| 73510 | ** iPtr: The address of a pointer to iFreeBlk | ||||
| 73511 | ** | ||||
| 73512 | ** Check to see if iFreeBlk should be coalesced onto the end of iStart. | ||||
| 73513 | */ | ||||
| 73514 | if( iFreeBlk && iEnd+3>=iFreeBlk ){ | ||||
| 73515 | nFrag = iFreeBlk - iEnd; | ||||
| 73516 | if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73516); | ||||
| 73517 | iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2])((&data[iFreeBlk+2])[0]<<8 | (&data[iFreeBlk+2] )[1]); | ||||
| 73518 | if( iEnd > (int)pPage->pBt->usableSize ){ | ||||
| 73519 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73519); | ||||
| 73520 | } | ||||
| 73521 | iSize = iEnd - iStart; | ||||
| 73522 | iFreeBlk = get2byte(&data[iFreeBlk])((&data[iFreeBlk])[0]<<8 | (&data[iFreeBlk])[1] ); | ||||
| 73523 | } | ||||
| 73524 | |||||
| 73525 | /* If iPtr is another freeblock (that is, if iPtr is not the freelist | ||||
| 73526 | ** pointer in the page header) then check to see if iStart should be | ||||
| 73527 | ** coalesced onto the end of iPtr. | ||||
| 73528 | */ | ||||
| 73529 | if( iPtr>hdr+1 ){ | ||||
| 73530 | int iPtrEnd = iPtr + get2byte(&data[iPtr+2])((&data[iPtr+2])[0]<<8 | (&data[iPtr+2])[1]); | ||||
| 73531 | if( iPtrEnd+3>=iStart ){ | ||||
| 73532 | if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73532); | ||||
| 73533 | nFrag += iStart - iPtrEnd; | ||||
| 73534 | iSize = iEnd - iPtr; | ||||
| 73535 | iStart = iPtr; | ||||
| 73536 | } | ||||
| 73537 | } | ||||
| 73538 | if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73538); | ||||
| 73539 | data[hdr+7] -= (u8)nFrag; | ||||
| 73540 | } | ||||
| 73541 | pTmp = &data[hdr+5]; | ||||
| 73542 | x = get2byte(pTmp)((pTmp)[0]<<8 | (pTmp)[1]); | ||||
| 73543 | if( pPage->pBt->btsFlags & BTS_FAST_SECURE0x000c ){ | ||||
| 73544 | /* Overwrite deleted information with zeros when the secure_delete | ||||
| 73545 | ** option is enabled */ | ||||
| 73546 | memset(&data[iStart], 0, iSize); | ||||
| 73547 | } | ||||
| 73548 | if( iStart<=x ){ | ||||
| 73549 | /* The new freeblock is at the beginning of the cell content area, | ||||
| 73550 | ** so just extend the cell content area rather than create another | ||||
| 73551 | ** freelist entry */ | ||||
| 73552 | if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73552); | ||||
| 73553 | if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73553); | ||||
| 73554 | put2byte(&data[hdr+1], iFreeBlk)((&data[hdr+1])[0] = (u8)((iFreeBlk)>>8), (&data [hdr+1])[1] = (u8)(iFreeBlk)); | ||||
| 73555 | put2byte(&data[hdr+5], iEnd)((&data[hdr+5])[0] = (u8)((iEnd)>>8), (&data[hdr +5])[1] = (u8)(iEnd)); | ||||
| 73556 | }else{ | ||||
| 73557 | /* Insert the new freeblock into the freelist */ | ||||
| 73558 | put2byte(&data[iPtr], iStart)((&data[iPtr])[0] = (u8)((iStart)>>8), (&data[iPtr ])[1] = (u8)(iStart)); | ||||
| 73559 | put2byte(&data[iStart], iFreeBlk)((&data[iStart])[0] = (u8)((iFreeBlk)>>8), (&data [iStart])[1] = (u8)(iFreeBlk)); | ||||
| 73560 | assert( iSize>=0 && iSize<=0xffff )((void) (0)); | ||||
| 73561 | put2byte(&data[iStart+2], (u16)iSize)((&data[iStart+2])[0] = (u8)(((u16)iSize)>>8), (& data[iStart+2])[1] = (u8)((u16)iSize)); | ||||
| 73562 | } | ||||
| 73563 | pPage->nFree += iOrigSize; | ||||
| 73564 | return SQLITE_OK0; | ||||
| 73565 | } | ||||
| 73566 | |||||
| 73567 | /* | ||||
| 73568 | ** Decode the flags byte (the first byte of the header) for a page | ||||
| 73569 | ** and initialize fields of the MemPage structure accordingly. | ||||
| 73570 | ** | ||||
| 73571 | ** Only the following combinations are supported. Anything different | ||||
| 73572 | ** indicates a corrupt database files: | ||||
| 73573 | ** | ||||
| 73574 | ** PTF_ZERODATA (0x02, 2) | ||||
| 73575 | ** PTF_LEAFDATA | PTF_INTKEY (0x05, 5) | ||||
| 73576 | ** PTF_ZERODATA | PTF_LEAF (0x0a, 10) | ||||
| 73577 | ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF (0x0d, 13) | ||||
| 73578 | */ | ||||
| 73579 | static int decodeFlags(MemPage *pPage, int flagByte){ | ||||
| 73580 | BtShared *pBt; /* A copy of pPage->pBt */ | ||||
| 73581 | |||||
| 73582 | assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) )((void) (0)); | ||||
| 73583 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73584 | pBt = pPage->pBt; | ||||
| 73585 | pPage->max1bytePayload = pBt->max1bytePayload; | ||||
| 73586 | if( flagByte>=(PTF_ZERODATA0x02 | PTF_LEAF0x08) ){ | ||||
| 73587 | pPage->childPtrSize = 0; | ||||
| 73588 | pPage->leaf = 1; | ||||
| 73589 | if( flagByte==(PTF_LEAFDATA0x04 | PTF_INTKEY0x01 | PTF_LEAF0x08) ){ | ||||
| 73590 | pPage->intKeyLeaf = 1; | ||||
| 73591 | pPage->xCellSize = cellSizePtrTableLeaf; | ||||
| 73592 | pPage->xParseCell = btreeParseCellPtr; | ||||
| 73593 | pPage->intKey = 1; | ||||
| 73594 | pPage->maxLocal = pBt->maxLeaf; | ||||
| 73595 | pPage->minLocal = pBt->minLeaf; | ||||
| 73596 | }else if( flagByte==(PTF_ZERODATA0x02 | PTF_LEAF0x08) ){ | ||||
| 73597 | pPage->intKey = 0; | ||||
| 73598 | pPage->intKeyLeaf = 0; | ||||
| 73599 | pPage->xCellSize = cellSizePtrIdxLeaf; | ||||
| 73600 | pPage->xParseCell = btreeParseCellPtrIndex; | ||||
| 73601 | pPage->maxLocal = pBt->maxLocal; | ||||
| 73602 | pPage->minLocal = pBt->minLocal; | ||||
| 73603 | }else{ | ||||
| 73604 | pPage->intKey = 0; | ||||
| 73605 | pPage->intKeyLeaf = 0; | ||||
| 73606 | pPage->xCellSize = cellSizePtrIdxLeaf; | ||||
| 73607 | pPage->xParseCell = btreeParseCellPtrIndex; | ||||
| 73608 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73608); | ||||
| 73609 | } | ||||
| 73610 | }else{ | ||||
| 73611 | pPage->childPtrSize = 4; | ||||
| 73612 | pPage->leaf = 0; | ||||
| 73613 | if( flagByte==(PTF_ZERODATA0x02) ){ | ||||
| 73614 | pPage->intKey = 0; | ||||
| 73615 | pPage->intKeyLeaf = 0; | ||||
| 73616 | pPage->xCellSize = cellSizePtr; | ||||
| 73617 | pPage->xParseCell = btreeParseCellPtrIndex; | ||||
| 73618 | pPage->maxLocal = pBt->maxLocal; | ||||
| 73619 | pPage->minLocal = pBt->minLocal; | ||||
| 73620 | }else if( flagByte==(PTF_LEAFDATA0x04 | PTF_INTKEY0x01) ){ | ||||
| 73621 | pPage->intKeyLeaf = 0; | ||||
| 73622 | pPage->xCellSize = cellSizePtrNoPayload; | ||||
| 73623 | pPage->xParseCell = btreeParseCellPtrNoPayload; | ||||
| 73624 | pPage->intKey = 1; | ||||
| 73625 | pPage->maxLocal = pBt->maxLeaf; | ||||
| 73626 | pPage->minLocal = pBt->minLeaf; | ||||
| 73627 | }else{ | ||||
| 73628 | pPage->intKey = 0; | ||||
| 73629 | pPage->intKeyLeaf = 0; | ||||
| 73630 | pPage->xCellSize = cellSizePtr; | ||||
| 73631 | pPage->xParseCell = btreeParseCellPtrIndex; | ||||
| 73632 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73632); | ||||
| 73633 | } | ||||
| 73634 | } | ||||
| 73635 | return SQLITE_OK0; | ||||
| 73636 | } | ||||
| 73637 | |||||
| 73638 | /* | ||||
| 73639 | ** Compute the amount of freespace on the page. In other words, fill | ||||
| 73640 | ** in the pPage->nFree field. | ||||
| 73641 | */ | ||||
| 73642 | static int btreeComputeFreeSpace(MemPage *pPage){ | ||||
| 73643 | int pc; /* Address of a freeblock within pPage->aData[] */ | ||||
| 73644 | u8 hdr; /* Offset to beginning of page header */ | ||||
| 73645 | u8 *data; /* Equal to pPage->aData */ | ||||
| 73646 | int usableSize; /* Amount of usable space on each page */ | ||||
| 73647 | int nFree; /* Number of unused bytes on the page */ | ||||
| 73648 | int top; /* First byte of the cell content area */ | ||||
| 73649 | int iCellFirst; /* First allowable cell or freeblock offset */ | ||||
| 73650 | int iCellLast; /* Last possible cell or freeblock offset */ | ||||
| 73651 | |||||
| 73652 | assert( pPage->pBt!=0 )((void) (0)); | ||||
| 73653 | assert( pPage->pBt->db!=0 )((void) (0)); | ||||
| 73654 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73655 | assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) )((void) (0)); | ||||
| 73656 | assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) )((void) (0)); | ||||
| 73657 | assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) )((void) (0)); | ||||
| 73658 | assert( pPage->isInit==1 )((void) (0)); | ||||
| 73659 | assert( pPage->nFree<0 )((void) (0)); | ||||
| 73660 | |||||
| 73661 | usableSize = pPage->pBt->usableSize; | ||||
| 73662 | hdr = pPage->hdrOffset; | ||||
| 73663 | data = pPage->aData; | ||||
| 73664 | /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates | ||||
| 73665 | ** the start of the cell content area. A zero value for this integer is | ||||
| 73666 | ** interpreted as 65536. */ | ||||
| 73667 | top = get2byteNotZero(&data[hdr+5])(((((int)((&data[hdr+5])[0]<<8 | (&data[hdr+5]) [1]))-1)&0xffff)+1); | ||||
| 73668 | iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell; | ||||
| 73669 | iCellLast = usableSize - 4; | ||||
| 73670 | |||||
| 73671 | /* Compute the total free space on the page | ||||
| 73672 | ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the | ||||
| 73673 | ** start of the first freeblock on the page, or is zero if there are no | ||||
| 73674 | ** freeblocks. */ | ||||
| 73675 | pc = get2byte(&data[hdr+1])((&data[hdr+1])[0]<<8 | (&data[hdr+1])[1]); | ||||
| 73676 | nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ | ||||
| 73677 | if( pc>0 ){ | ||||
| 73678 | u32 next, size; | ||||
| 73679 | if( pc<top ){ | ||||
| 73680 | /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will | ||||
| 73681 | ** always be at least one cell before the first freeblock. | ||||
| 73682 | */ | ||||
| 73683 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73683); | ||||
| 73684 | } | ||||
| 73685 | while( 1 ){ | ||||
| 73686 | if( pc>iCellLast ){ | ||||
| 73687 | /* Freeblock off the end of the page */ | ||||
| 73688 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73688); | ||||
| 73689 | } | ||||
| 73690 | next = get2byte(&data[pc])((&data[pc])[0]<<8 | (&data[pc])[1]); | ||||
| 73691 | size = get2byte(&data[pc+2])((&data[pc+2])[0]<<8 | (&data[pc+2])[1]); | ||||
| 73692 | nFree = nFree + size; | ||||
| 73693 | if( next<=pc+size+3 ) break; | ||||
| 73694 | pc = next; | ||||
| 73695 | } | ||||
| 73696 | if( next>0 ){ | ||||
| 73697 | /* Freeblock not in ascending order */ | ||||
| 73698 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73698); | ||||
| 73699 | } | ||||
| 73700 | if( pc+size>(unsigned int)usableSize ){ | ||||
| 73701 | /* Last freeblock extends past page end */ | ||||
| 73702 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73702); | ||||
| 73703 | } | ||||
| 73704 | } | ||||
| 73705 | |||||
| 73706 | /* At this point, nFree contains the sum of the offset to the start | ||||
| 73707 | ** of the cell-content area plus the number of free bytes within | ||||
| 73708 | ** the cell-content area. If this is greater than the usable-size | ||||
| 73709 | ** of the page, then the page must be corrupted. This check also | ||||
| 73710 | ** serves to verify that the offset to the start of the cell-content | ||||
| 73711 | ** area, according to the page header, lies within the page. | ||||
| 73712 | */ | ||||
| 73713 | if( nFree>usableSize || nFree<iCellFirst ){ | ||||
| 73714 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73714); | ||||
| 73715 | } | ||||
| 73716 | pPage->nFree = (u16)(nFree - iCellFirst); | ||||
| 73717 | return SQLITE_OK0; | ||||
| 73718 | } | ||||
| 73719 | |||||
| 73720 | /* | ||||
| 73721 | ** Do additional sanity check after btreeInitPage() if | ||||
| 73722 | ** PRAGMA cell_size_check=ON | ||||
| 73723 | */ | ||||
| 73724 | static SQLITE_NOINLINE__attribute__((noinline)) int btreeCellSizeCheck(MemPage *pPage){ | ||||
| 73725 | int iCellFirst; /* First allowable cell or freeblock offset */ | ||||
| 73726 | int iCellLast; /* Last possible cell or freeblock offset */ | ||||
| 73727 | int i; /* Index into the cell pointer array */ | ||||
| 73728 | int sz; /* Size of a cell */ | ||||
| 73729 | int pc; /* Address of a freeblock within pPage->aData[] */ | ||||
| 73730 | u8 *data; /* Equal to pPage->aData */ | ||||
| 73731 | int usableSize; /* Maximum usable space on the page */ | ||||
| 73732 | int cellOffset; /* Start of cell content area */ | ||||
| 73733 | |||||
| 73734 | iCellFirst = pPage->cellOffset + 2*pPage->nCell; | ||||
| 73735 | usableSize = pPage->pBt->usableSize; | ||||
| 73736 | iCellLast = usableSize - 4; | ||||
| 73737 | data = pPage->aData; | ||||
| 73738 | cellOffset = pPage->cellOffset; | ||||
| 73739 | if( !pPage->leaf ) iCellLast--; | ||||
| 73740 | for(i=0; i<pPage->nCell; i++){ | ||||
| 73741 | pc = get2byteAligned(&data[cellOffset+i*2])((&data[cellOffset+i*2])[0]<<8 | (&data[cellOffset +i*2])[1]); | ||||
| 73742 | testcase( pc==iCellFirst ); | ||||
| 73743 | testcase( pc==iCellLast ); | ||||
| 73744 | if( pc<iCellFirst || pc>iCellLast ){ | ||||
| 73745 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73745); | ||||
| 73746 | } | ||||
| 73747 | sz = pPage->xCellSize(pPage, &data[pc]); | ||||
| 73748 | testcase( pc+sz==usableSize ); | ||||
| 73749 | if( pc+sz>usableSize ){ | ||||
| 73750 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73750); | ||||
| 73751 | } | ||||
| 73752 | } | ||||
| 73753 | return SQLITE_OK0; | ||||
| 73754 | } | ||||
| 73755 | |||||
| 73756 | /* | ||||
| 73757 | ** Initialize the auxiliary information for a disk block. | ||||
| 73758 | ** | ||||
| 73759 | ** Return SQLITE_OK on success. If we see that the page does | ||||
| 73760 | ** not contain a well-formed database page, then return | ||||
| 73761 | ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not | ||||
| 73762 | ** guarantee that the page is well-formed. It only shows that | ||||
| 73763 | ** we failed to detect any corruption. | ||||
| 73764 | */ | ||||
| 73765 | static int btreeInitPage(MemPage *pPage){ | ||||
| 73766 | u8 *data; /* Equal to pPage->aData */ | ||||
| 73767 | BtShared *pBt; /* The main btree structure */ | ||||
| 73768 | |||||
| 73769 | assert( pPage->pBt!=0 )((void) (0)); | ||||
| 73770 | assert( pPage->pBt->db!=0 )((void) (0)); | ||||
| 73771 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73772 | assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) )((void) (0)); | ||||
| 73773 | assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) )((void) (0)); | ||||
| 73774 | assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) )((void) (0)); | ||||
| 73775 | assert( pPage->isInit==0 )((void) (0)); | ||||
| 73776 | |||||
| 73777 | pBt = pPage->pBt; | ||||
| 73778 | data = pPage->aData + pPage->hdrOffset; | ||||
| 73779 | /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating | ||||
| 73780 | ** the b-tree page type. */ | ||||
| 73781 | if( decodeFlags(pPage, data[0]) ){ | ||||
| 73782 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73782); | ||||
| 73783 | } | ||||
| 73784 | assert( pBt->pageSize>=512 && pBt->pageSize<=65536 )((void) (0)); | ||||
| 73785 | pPage->maskPage = (u16)(pBt->pageSize - 1); | ||||
| 73786 | pPage->nOverflow = 0; | ||||
| 73787 | pPage->cellOffset = (u16)(pPage->hdrOffset + 8 + pPage->childPtrSize); | ||||
| 73788 | pPage->aCellIdx = data + pPage->childPtrSize + 8; | ||||
| 73789 | pPage->aDataEnd = pPage->aData + pBt->pageSize; | ||||
| 73790 | pPage->aDataOfst = pPage->aData + pPage->childPtrSize; | ||||
| 73791 | /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the | ||||
| 73792 | ** number of cells on the page. */ | ||||
| 73793 | pPage->nCell = get2byte(&data[3])((&data[3])[0]<<8 | (&data[3])[1]); | ||||
| 73794 | if( pPage->nCell>MX_CELL(pBt)((pBt->pageSize-8)/6) ){ | ||||
| 73795 | /* To many cells for a single page. The page must be corrupt */ | ||||
| 73796 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(73796); | ||||
| 73797 | } | ||||
| 73798 | testcase( pPage->nCell==MX_CELL(pBt) ); | ||||
| 73799 | /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only | ||||
| 73800 | ** possible for a root page of a table that contains no rows) then the | ||||
| 73801 | ** offset to the cell content area will equal the page size minus the | ||||
| 73802 | ** bytes of reserved space. */ | ||||
| 73803 | assert( pPage->nCell>0((void) (0)) | ||||
| 73804 | || get2byteNotZero(&data[5])==(int)pBt->usableSize((void) (0)) | ||||
| 73805 | || CORRUPT_DB )((void) (0)); | ||||
| 73806 | pPage->nFree = -1; /* Indicate that this value is yet uncomputed */ | ||||
| 73807 | pPage->isInit = 1; | ||||
| 73808 | if( pBt->db->flags & SQLITE_CellSizeCk0x00200000 ){ | ||||
| 73809 | return btreeCellSizeCheck(pPage); | ||||
| 73810 | } | ||||
| 73811 | return SQLITE_OK0; | ||||
| 73812 | } | ||||
| 73813 | |||||
| 73814 | /* | ||||
| 73815 | ** Set up a raw page so that it looks like a database page holding | ||||
| 73816 | ** no entries. | ||||
| 73817 | */ | ||||
| 73818 | static void zeroPage(MemPage *pPage, int flags){ | ||||
| 73819 | unsigned char *data = pPage->aData; | ||||
| 73820 | BtShared *pBt = pPage->pBt; | ||||
| 73821 | int hdr = pPage->hdrOffset; | ||||
| 73822 | int first; | ||||
| 73823 | |||||
| 73824 | assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB )((void) (0)); | ||||
| 73825 | assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage )((void) (0)); | ||||
| 73826 | assert( sqlite3PagerGetData(pPage->pDbPage) == data )((void) (0)); | ||||
| 73827 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 73828 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 73829 | if( pBt->btsFlags & BTS_FAST_SECURE0x000c ){ | ||||
| 73830 | memset(&data[hdr], 0, pBt->usableSize - hdr); | ||||
| 73831 | } | ||||
| 73832 | data[hdr] = (char)flags; | ||||
| 73833 | first = hdr + ((flags&PTF_LEAF0x08)==0 ? 12 : 8); | ||||
| 73834 | memset(&data[hdr+1], 0, 4); | ||||
| 73835 | data[hdr+7] = 0; | ||||
| 73836 | put2byte(&data[hdr+5], pBt->usableSize)((&data[hdr+5])[0] = (u8)((pBt->usableSize)>>8), (&data[hdr+5])[1] = (u8)(pBt->usableSize)); | ||||
| 73837 | pPage->nFree = (u16)(pBt->usableSize - first); | ||||
| 73838 | decodeFlags(pPage, flags); | ||||
| 73839 | pPage->cellOffset = (u16)first; | ||||
| 73840 | pPage->aDataEnd = &data[pBt->pageSize]; | ||||
| 73841 | pPage->aCellIdx = &data[first]; | ||||
| 73842 | pPage->aDataOfst = &data[pPage->childPtrSize]; | ||||
| 73843 | pPage->nOverflow = 0; | ||||
| 73844 | assert( pBt->pageSize>=512 && pBt->pageSize<=65536 )((void) (0)); | ||||
| 73845 | pPage->maskPage = (u16)(pBt->pageSize - 1); | ||||
| 73846 | pPage->nCell = 0; | ||||
| 73847 | pPage->isInit = 1; | ||||
| 73848 | } | ||||
| 73849 | |||||
| 73850 | |||||
| 73851 | /* | ||||
| 73852 | ** Convert a DbPage obtained from the pager into a MemPage used by | ||||
| 73853 | ** the btree layer. | ||||
| 73854 | */ | ||||
| 73855 | static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ | ||||
| 73856 | MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); | ||||
| 73857 | if( pgno!=pPage->pgno ){ | ||||
| 73858 | pPage->aData = sqlite3PagerGetData(pDbPage); | ||||
| 73859 | pPage->pDbPage = pDbPage; | ||||
| 73860 | pPage->pBt = pBt; | ||||
| 73861 | pPage->pgno = pgno; | ||||
| 73862 | pPage->hdrOffset = pgno==1 ? 100 : 0; | ||||
| 73863 | } | ||||
| 73864 | assert( pPage->aData==sqlite3PagerGetData(pDbPage) )((void) (0)); | ||||
| 73865 | return pPage; | ||||
| 73866 | } | ||||
| 73867 | |||||
| 73868 | /* | ||||
| 73869 | ** Get a page from the pager. Initialize the MemPage.pBt and | ||||
| 73870 | ** MemPage.aData elements if needed. See also: btreeGetUnusedPage(). | ||||
| 73871 | ** | ||||
| 73872 | ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care | ||||
| 73873 | ** about the content of the page at this time. So do not go to the disk | ||||
| 73874 | ** to fetch the content. Just fill in the content with zeros for now. | ||||
| 73875 | ** If in the future we call sqlite3PagerWrite() on this page, that | ||||
| 73876 | ** means we have started to be concerned about content and the disk | ||||
| 73877 | ** read should occur at that point. | ||||
| 73878 | */ | ||||
| 73879 | static int btreeGetPage( | ||||
| 73880 | BtShared *pBt, /* The btree */ | ||||
| 73881 | Pgno pgno, /* Number of the page to fetch */ | ||||
| 73882 | MemPage **ppPage, /* Return the page in this parameter */ | ||||
| 73883 | int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ | ||||
| 73884 | ){ | ||||
| 73885 | int rc; | ||||
| 73886 | DbPage *pDbPage; | ||||
| 73887 | |||||
| 73888 | assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY )((void) (0)); | ||||
| 73889 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 73890 | rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); | ||||
| 73891 | if( rc ) return rc; | ||||
| 73892 | *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); | ||||
| 73893 | return SQLITE_OK0; | ||||
| 73894 | } | ||||
| 73895 | |||||
| 73896 | /* | ||||
| 73897 | ** Retrieve a page from the pager cache. If the requested page is not | ||||
| 73898 | ** already in the pager cache return NULL. Initialize the MemPage.pBt and | ||||
| 73899 | ** MemPage.aData elements if needed. | ||||
| 73900 | */ | ||||
| 73901 | static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ | ||||
| 73902 | DbPage *pDbPage; | ||||
| 73903 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 73904 | pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); | ||||
| 73905 | if( pDbPage ){ | ||||
| 73906 | return btreePageFromDbPage(pDbPage, pgno, pBt); | ||||
| 73907 | } | ||||
| 73908 | return 0; | ||||
| 73909 | } | ||||
| 73910 | |||||
| 73911 | /* | ||||
| 73912 | ** Return the size of the database file in pages. If there is any kind of | ||||
| 73913 | ** error, return ((unsigned int)-1). | ||||
| 73914 | */ | ||||
| 73915 | static Pgno btreePagecount(BtShared *pBt){ | ||||
| 73916 | return pBt->nPage; | ||||
| 73917 | } | ||||
| 73918 | SQLITE_PRIVATEstatic Pgno sqlite3BtreeLastPage(Btree *p){ | ||||
| 73919 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 73920 | return btreePagecount(p->pBt); | ||||
| 73921 | } | ||||
| 73922 | |||||
| 73923 | /* | ||||
| 73924 | ** Get a page from the pager and initialize it. | ||||
| 73925 | */ | ||||
| 73926 | static int getAndInitPage( | ||||
| 73927 | BtShared *pBt, /* The database file */ | ||||
| 73928 | Pgno pgno, /* Number of the page to get */ | ||||
| 73929 | MemPage **ppPage, /* Write the page pointer here */ | ||||
| 73930 | int bReadOnly /* True for a read-only page */ | ||||
| 73931 | ){ | ||||
| 73932 | int rc; | ||||
| 73933 | DbPage *pDbPage; | ||||
| 73934 | MemPage *pPage; | ||||
| 73935 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 73936 | |||||
| 73937 | if( pgno>btreePagecount(pBt) ){ | ||||
| 73938 | *ppPage = 0; | ||||
| 73939 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(73939); | ||||
| 73940 | } | ||||
| 73941 | rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); | ||||
| 73942 | if( rc ){ | ||||
| 73943 | *ppPage = 0; | ||||
| 73944 | return rc; | ||||
| 73945 | } | ||||
| 73946 | pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); | ||||
| 73947 | if( pPage->isInit==0 ){ | ||||
| 73948 | btreePageFromDbPage(pDbPage, pgno, pBt); | ||||
| 73949 | rc = btreeInitPage(pPage); | ||||
| 73950 | if( rc!=SQLITE_OK0 ){ | ||||
| 73951 | releasePage(pPage); | ||||
| 73952 | *ppPage = 0; | ||||
| 73953 | return rc; | ||||
| 73954 | } | ||||
| 73955 | } | ||||
| 73956 | assert( pPage->pgno==pgno || CORRUPT_DB )((void) (0)); | ||||
| 73957 | assert( pPage->aData==sqlite3PagerGetData(pDbPage) )((void) (0)); | ||||
| 73958 | *ppPage = pPage; | ||||
| 73959 | return SQLITE_OK0; | ||||
| 73960 | } | ||||
| 73961 | |||||
| 73962 | /* | ||||
| 73963 | ** Release a MemPage. This should be called once for each prior | ||||
| 73964 | ** call to btreeGetPage. | ||||
| 73965 | ** | ||||
| 73966 | ** Page1 is a special case and must be released using releasePageOne(). | ||||
| 73967 | */ | ||||
| 73968 | static void releasePageNotNull(MemPage *pPage){ | ||||
| 73969 | assert( pPage->aData )((void) (0)); | ||||
| 73970 | assert( pPage->pBt )((void) (0)); | ||||
| 73971 | assert( pPage->pDbPage!=0 )((void) (0)); | ||||
| 73972 | assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage )((void) (0)); | ||||
| 73973 | assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData )((void) (0)); | ||||
| 73974 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73975 | sqlite3PagerUnrefNotNull(pPage->pDbPage); | ||||
| 73976 | } | ||||
| 73977 | static void releasePage(MemPage *pPage){ | ||||
| 73978 | if( pPage ) releasePageNotNull(pPage); | ||||
| 73979 | } | ||||
| 73980 | static void releasePageOne(MemPage *pPage){ | ||||
| 73981 | assert( pPage!=0 )((void) (0)); | ||||
| 73982 | assert( pPage->aData )((void) (0)); | ||||
| 73983 | assert( pPage->pBt )((void) (0)); | ||||
| 73984 | assert( pPage->pDbPage!=0 )((void) (0)); | ||||
| 73985 | assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage )((void) (0)); | ||||
| 73986 | assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData )((void) (0)); | ||||
| 73987 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 73988 | sqlite3PagerUnrefPageOne(pPage->pDbPage); | ||||
| 73989 | } | ||||
| 73990 | |||||
| 73991 | /* | ||||
| 73992 | ** Get an unused page. | ||||
| 73993 | ** | ||||
| 73994 | ** This works just like btreeGetPage() with the addition: | ||||
| 73995 | ** | ||||
| 73996 | ** * If the page is already in use for some other purpose, immediately | ||||
| 73997 | ** release it and return an SQLITE_CURRUPT error. | ||||
| 73998 | ** * Make sure the isInit flag is clear | ||||
| 73999 | */ | ||||
| 74000 | static int btreeGetUnusedPage( | ||||
| 74001 | BtShared *pBt, /* The btree */ | ||||
| 74002 | Pgno pgno, /* Number of the page to fetch */ | ||||
| 74003 | MemPage **ppPage, /* Return the page in this parameter */ | ||||
| 74004 | int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ | ||||
| 74005 | ){ | ||||
| 74006 | int rc = btreeGetPage(pBt, pgno, ppPage, flags); | ||||
| 74007 | if( rc==SQLITE_OK0 ){ | ||||
| 74008 | if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ | ||||
| 74009 | releasePage(*ppPage); | ||||
| 74010 | *ppPage = 0; | ||||
| 74011 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(74011); | ||||
| 74012 | } | ||||
| 74013 | (*ppPage)->isInit = 0; | ||||
| 74014 | }else{ | ||||
| 74015 | *ppPage = 0; | ||||
| 74016 | } | ||||
| 74017 | return rc; | ||||
| 74018 | } | ||||
| 74019 | |||||
| 74020 | |||||
| 74021 | /* | ||||
| 74022 | ** During a rollback, when the pager reloads information into the cache | ||||
| 74023 | ** so that the cache is restored to its original state at the start of | ||||
| 74024 | ** the transaction, for each page restored this routine is called. | ||||
| 74025 | ** | ||||
| 74026 | ** This routine needs to reset the extra data section at the end of the | ||||
| 74027 | ** page to agree with the restored data. | ||||
| 74028 | */ | ||||
| 74029 | static void pageReinit(DbPage *pData){ | ||||
| 74030 | MemPage *pPage; | ||||
| 74031 | pPage = (MemPage *)sqlite3PagerGetExtra(pData); | ||||
| 74032 | assert( sqlite3PagerPageRefcount(pData)>0 )((void) (0)); | ||||
| 74033 | if( pPage->isInit ){ | ||||
| 74034 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 74035 | pPage->isInit = 0; | ||||
| 74036 | if( sqlite3PagerPageRefcount(pData)>1 ){ | ||||
| 74037 | /* pPage might not be a btree page; it might be an overflow page | ||||
| 74038 | ** or ptrmap page or a free page. In those cases, the following | ||||
| 74039 | ** call to btreeInitPage() will likely return SQLITE_CORRUPT. | ||||
| 74040 | ** But no harm is done by this. And it is very important that | ||||
| 74041 | ** btreeInitPage() be called on every btree page so we make | ||||
| 74042 | ** the call for every page that comes in for re-initializing. */ | ||||
| 74043 | btreeInitPage(pPage); | ||||
| 74044 | } | ||||
| 74045 | } | ||||
| 74046 | } | ||||
| 74047 | |||||
| 74048 | /* | ||||
| 74049 | ** Invoke the busy handler for a btree. | ||||
| 74050 | */ | ||||
| 74051 | static int btreeInvokeBusyHandler(void *pArg){ | ||||
| 74052 | BtShared *pBt = (BtShared*)pArg; | ||||
| 74053 | assert( pBt->db )((void) (0)); | ||||
| 74054 | assert( sqlite3_mutex_held(pBt->db->mutex) )((void) (0)); | ||||
| 74055 | return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); | ||||
| 74056 | } | ||||
| 74057 | |||||
| 74058 | /* | ||||
| 74059 | ** Open a database file. | ||||
| 74060 | ** | ||||
| 74061 | ** zFilename is the name of the database file. If zFilename is NULL | ||||
| 74062 | ** then an ephemeral database is created. The ephemeral database might | ||||
| 74063 | ** be exclusively in memory, or it might use a disk-based memory cache. | ||||
| 74064 | ** Either way, the ephemeral database will be automatically deleted | ||||
| 74065 | ** when sqlite3BtreeClose() is called. | ||||
| 74066 | ** | ||||
| 74067 | ** If zFilename is ":memory:" then an in-memory database is created | ||||
| 74068 | ** that is automatically destroyed when it is closed. | ||||
| 74069 | ** | ||||
| 74070 | ** The "flags" parameter is a bitmask that might contain bits like | ||||
| 74071 | ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. | ||||
| 74072 | ** | ||||
| 74073 | ** If the database is already opened in the same database connection | ||||
| 74074 | ** and we are in shared cache mode, then the open will fail with an | ||||
| 74075 | ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared | ||||
| 74076 | ** objects in the same database connection since doing so will lead | ||||
| 74077 | ** to problems with locking. | ||||
| 74078 | */ | ||||
| 74079 | SQLITE_PRIVATEstatic int sqlite3BtreeOpen( | ||||
| 74080 | sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ | ||||
| 74081 | const char *zFilename, /* Name of the file containing the BTree database */ | ||||
| 74082 | sqlite3 *db, /* Associated database handle */ | ||||
| 74083 | Btree **ppBtree, /* Pointer to new Btree object written here */ | ||||
| 74084 | int flags, /* Options */ | ||||
| 74085 | int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ | ||||
| 74086 | ){ | ||||
| 74087 | BtShared *pBt = 0; /* Shared part of btree structure */ | ||||
| 74088 | Btree *p; /* Handle to return */ | ||||
| 74089 | sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ | ||||
| 74090 | int rc = SQLITE_OK0; /* Result code from this function */ | ||||
| 74091 | u8 nReserve; /* Byte of unused space on each page */ | ||||
| 74092 | unsigned char zDbHeader[100]; /* Database header content */ | ||||
| 74093 | |||||
| 74094 | /* True if opening an ephemeral, temporary database */ | ||||
| 74095 | const int isTempDb = zFilename==0 || zFilename[0]==0; | ||||
| 74096 | |||||
| 74097 | /* Set the variable isMemdb to true for an in-memory database, or | ||||
| 74098 | ** false for a file-based database. | ||||
| 74099 | */ | ||||
| 74100 | #ifdef SQLITE_OMIT_MEMORYDB | ||||
| 74101 | const int isMemdb = 0; | ||||
| 74102 | #else | ||||
| 74103 | const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) | ||||
| 74104 | || (isTempDb && sqlite3TempInMemory(db)) | ||||
| 74105 | || (vfsFlags & SQLITE_OPEN_MEMORY0x00000080)!=0; | ||||
| 74106 | #endif | ||||
| 74107 | |||||
| 74108 | assert( db!=0 )((void) (0)); | ||||
| 74109 | assert( pVfs!=0 )((void) (0)); | ||||
| 74110 | assert( sqlite3_mutex_held(db->mutex) )((void) (0)); | ||||
| 74111 | assert( (flags&0xff)==flags )((void) (0)); /* flags fit in 8 bits */ | ||||
| 74112 | |||||
| 74113 | /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ | ||||
| 74114 | assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 )((void) (0)); | ||||
| 74115 | |||||
| 74116 | /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ | ||||
| 74117 | assert( (flags & BTREE_SINGLE)==0 || isTempDb )((void) (0)); | ||||
| 74118 | |||||
| 74119 | if( isMemdb ){ | ||||
| 74120 | flags |= BTREE_MEMORY2; | ||||
| 74121 | } | ||||
| 74122 | if( (vfsFlags & SQLITE_OPEN_MAIN_DB0x00000100)!=0 && (isMemdb || isTempDb) ){ | ||||
| 74123 | vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB0x00000100) | SQLITE_OPEN_TEMP_DB0x00000200; | ||||
| 74124 | } | ||||
| 74125 | p = sqlite3MallocZero(sizeof(Btree)); | ||||
| 74126 | if( !p ){ | ||||
| 74127 | return SQLITE_NOMEM_BKPT7; | ||||
| 74128 | } | ||||
| 74129 | p->inTrans = TRANS_NONE0; | ||||
| 74130 | p->db = db; | ||||
| 74131 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 74132 | p->lock.pBtree = p; | ||||
| 74133 | p->lock.iTable = 1; | ||||
| 74134 | #endif | ||||
| 74135 | |||||
| 74136 | #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) | ||||
| 74137 | /* | ||||
| 74138 | ** If this Btree is a candidate for shared cache, try to find an | ||||
| 74139 | ** existing BtShared object that we can share with | ||||
| 74140 | */ | ||||
| 74141 | if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI0x00000040)!=0) ){ | ||||
| 74142 | if( vfsFlags & SQLITE_OPEN_SHAREDCACHE0x00020000 ){ | ||||
| 74143 | int nFilename = sqlite3Strlen30(zFilename)+1; | ||||
| 74144 | int nFullPathname = pVfs->mxPathname+1; | ||||
| 74145 | char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)((nFullPathname)>(nFilename)?(nFullPathname):(nFilename))); | ||||
| 74146 | MUTEX_LOGIC( sqlite3_mutex *mutexShared; )sqlite3_mutex *mutexShared; | ||||
| 74147 | |||||
| 74148 | p->sharable = 1; | ||||
| 74149 | if( !zFullPathname ){ | ||||
| 74150 | sqlite3_free(p); | ||||
| 74151 | return SQLITE_NOMEM_BKPT7; | ||||
| 74152 | } | ||||
| 74153 | if( isMemdb ){ | ||||
| 74154 | memcpy(zFullPathname, zFilename, nFilename); | ||||
| 74155 | }else{ | ||||
| 74156 | rc = sqlite3OsFullPathname(pVfs, zFilename, | ||||
| 74157 | nFullPathname, zFullPathname); | ||||
| 74158 | if( rc ){ | ||||
| 74159 | if( rc==SQLITE_OK_SYMLINK(0 | (2<<8)) ){ | ||||
| 74160 | rc = SQLITE_OK0; | ||||
| 74161 | }else{ | ||||
| 74162 | sqlite3_free(zFullPathname); | ||||
| 74163 | sqlite3_free(p); | ||||
| 74164 | return rc; | ||||
| 74165 | } | ||||
| 74166 | } | ||||
| 74167 | } | ||||
| 74168 | #if SQLITE_THREADSAFE2 | ||||
| 74169 | mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN4); | ||||
| 74170 | sqlite3_mutex_enter(mutexOpen); | ||||
| 74171 | mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN2); | ||||
| 74172 | sqlite3_mutex_enter(mutexShared); | ||||
| 74173 | #endif | ||||
| 74174 | for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList)sqlite3SharedCacheList; pBt; pBt=pBt->pNext){ | ||||
| 74175 | assert( pBt->nRef>0 )((void) (0)); | ||||
| 74176 | if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) | ||||
| 74177 | && sqlite3PagerVfs(pBt->pPager)==pVfs ){ | ||||
| 74178 | int iDb; | ||||
| 74179 | for(iDb=db->nDb-1; iDb>=0; iDb--){ | ||||
| 74180 | Btree *pExisting = db->aDb[iDb].pBt; | ||||
| 74181 | if( pExisting && pExisting->pBt==pBt ){ | ||||
| 74182 | sqlite3_mutex_leave(mutexShared); | ||||
| 74183 | sqlite3_mutex_leave(mutexOpen); | ||||
| 74184 | sqlite3_free(zFullPathname); | ||||
| 74185 | sqlite3_free(p); | ||||
| 74186 | return SQLITE_CONSTRAINT19; | ||||
| 74187 | } | ||||
| 74188 | } | ||||
| 74189 | p->pBt = pBt; | ||||
| 74190 | pBt->nRef++; | ||||
| 74191 | break; | ||||
| 74192 | } | ||||
| 74193 | } | ||||
| 74194 | sqlite3_mutex_leave(mutexShared); | ||||
| 74195 | sqlite3_free(zFullPathname); | ||||
| 74196 | } | ||||
| 74197 | #ifdef SQLITE_DEBUG | ||||
| 74198 | else{ | ||||
| 74199 | /* In debug mode, we mark all persistent databases as sharable | ||||
| 74200 | ** even when they are not. This exercises the locking code and | ||||
| 74201 | ** gives more opportunity for asserts(sqlite3_mutex_held()) | ||||
| 74202 | ** statements to find locking problems. | ||||
| 74203 | */ | ||||
| 74204 | p->sharable = 1; | ||||
| 74205 | } | ||||
| 74206 | #endif | ||||
| 74207 | } | ||||
| 74208 | #endif | ||||
| 74209 | if( pBt==0 ){ | ||||
| 74210 | /* | ||||
| 74211 | ** The following asserts make sure that structures used by the btree are | ||||
| 74212 | ** the right size. This is to guard against size changes that result | ||||
| 74213 | ** when compiling on a different architecture. | ||||
| 74214 | */ | ||||
| 74215 | assert( sizeof(i64)==8 )((void) (0)); | ||||
| 74216 | assert( sizeof(u64)==8 )((void) (0)); | ||||
| 74217 | assert( sizeof(u32)==4 )((void) (0)); | ||||
| 74218 | assert( sizeof(u16)==2 )((void) (0)); | ||||
| 74219 | assert( sizeof(Pgno)==4 )((void) (0)); | ||||
| 74220 | |||||
| 74221 | /* Suppress false-positive compiler warning from PVS-Studio */ | ||||
| 74222 | memset(&zDbHeader[16], 0, 8); | ||||
| 74223 | |||||
| 74224 | pBt = sqlite3MallocZero( sizeof(*pBt) ); | ||||
| 74225 | if( pBt==0 ){ | ||||
| 74226 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 74227 | goto btree_open_out; | ||||
| 74228 | } | ||||
| 74229 | rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, | ||||
| 74230 | sizeof(MemPage), flags, vfsFlags, pageReinit); | ||||
| 74231 | if( rc==SQLITE_OK0 ){ | ||||
| 74232 | sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); | ||||
| 74233 | rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); | ||||
| 74234 | } | ||||
| 74235 | if( rc!=SQLITE_OK0 ){ | ||||
| 74236 | goto btree_open_out; | ||||
| 74237 | } | ||||
| 74238 | pBt->openFlags = (u8)flags; | ||||
| 74239 | pBt->db = db; | ||||
| 74240 | sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt); | ||||
| 74241 | p->pBt = pBt; | ||||
| 74242 | |||||
| 74243 | pBt->pCursor = 0; | ||||
| 74244 | pBt->pPage1 = 0; | ||||
| 74245 | if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY0x0001; | ||||
| 74246 | #if defined(SQLITE_SECURE_DELETE) | ||||
| 74247 | pBt->btsFlags |= BTS_SECURE_DELETE0x0004; | ||||
| 74248 | #elif defined(SQLITE_FAST_SECURE_DELETE) | ||||
| 74249 | pBt->btsFlags |= BTS_OVERWRITE0x0008; | ||||
| 74250 | #endif | ||||
| 74251 | /* EVIDENCE-OF: R-51873-39618 The page size for a database file is | ||||
| 74252 | ** determined by the 2-byte integer located at an offset of 16 bytes from | ||||
| 74253 | ** the beginning of the database file. */ | ||||
| 74254 | pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); | ||||
| 74255 | if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE65536 | ||||
| 74256 | || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ | ||||
| 74257 | pBt->pageSize = 0; | ||||
| 74258 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 74259 | /* If the magic name ":memory:" will create an in-memory database, then | ||||
| 74260 | ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if | ||||
| 74261 | ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if | ||||
| 74262 | ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a | ||||
| 74263 | ** regular file-name. In this case the auto-vacuum applies as per normal. | ||||
| 74264 | */ | ||||
| 74265 | if( zFilename && !isMemdb ){ | ||||
| 74266 | pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM0 ? 1 : 0); | ||||
| 74267 | pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM0==2 ? 1 : 0); | ||||
| 74268 | } | ||||
| 74269 | #endif | ||||
| 74270 | nReserve = 0; | ||||
| 74271 | }else{ | ||||
| 74272 | /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is | ||||
| 74273 | ** determined by the one-byte unsigned integer found at an offset of 20 | ||||
| 74274 | ** into the database file header. */ | ||||
| 74275 | nReserve = zDbHeader[20]; | ||||
| 74276 | pBt->btsFlags |= BTS_PAGESIZE_FIXED0x0002; | ||||
| 74277 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 74278 | pBt->autoVacuum = (get4bytesqlite3Get4byte(&zDbHeader[36 + 4*4])?1:0); | ||||
| 74279 | pBt->incrVacuum = (get4bytesqlite3Get4byte(&zDbHeader[36 + 7*4])?1:0); | ||||
| 74280 | #endif | ||||
| 74281 | } | ||||
| 74282 | rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); | ||||
| 74283 | if( rc ) goto btree_open_out; | ||||
| 74284 | pBt->usableSize = pBt->pageSize - nReserve; | ||||
| 74285 | assert( (pBt->pageSize & 7)==0 )((void) (0)); /* 8-byte alignment of pageSize */ | ||||
| 74286 | |||||
| 74287 | #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) | ||||
| 74288 | /* Add the new BtShared object to the linked list sharable BtShareds. | ||||
| 74289 | */ | ||||
| 74290 | pBt->nRef = 1; | ||||
| 74291 | if( p->sharable ){ | ||||
| 74292 | MUTEX_LOGIC( sqlite3_mutex *mutexShared; )sqlite3_mutex *mutexShared; | ||||
| 74293 | MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)mutexShared = sqlite3MutexAlloc(2); | ||||
| 74294 | if( SQLITE_THREADSAFE2 && sqlite3GlobalConfigsqlite3Config.bCoreMutex ){ | ||||
| 74295 | pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST0); | ||||
| 74296 | if( pBt->mutex==0 ){ | ||||
| 74297 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 74298 | goto btree_open_out; | ||||
| 74299 | } | ||||
| 74300 | } | ||||
| 74301 | sqlite3_mutex_enter(mutexShared); | ||||
| 74302 | pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList)sqlite3SharedCacheList; | ||||
| 74303 | GLOBAL(BtShared*,sqlite3SharedCacheList)sqlite3SharedCacheList = pBt; | ||||
| 74304 | sqlite3_mutex_leave(mutexShared); | ||||
| 74305 | } | ||||
| 74306 | #endif | ||||
| 74307 | } | ||||
| 74308 | |||||
| 74309 | #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) | ||||
| 74310 | /* If the new Btree uses a sharable pBtShared, then link the new | ||||
| 74311 | ** Btree into the list of all sharable Btrees for the same connection. | ||||
| 74312 | ** The list is kept in ascending order by pBt address. | ||||
| 74313 | */ | ||||
| 74314 | if( p->sharable ){ | ||||
| 74315 | int i; | ||||
| 74316 | Btree *pSib; | ||||
| 74317 | for(i=0; i<db->nDb; i++){ | ||||
| 74318 | if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ | ||||
| 74319 | while( pSib->pPrev ){ pSib = pSib->pPrev; } | ||||
| 74320 | if( (uptr)p->pBt<(uptr)pSib->pBt ){ | ||||
| 74321 | p->pNext = pSib; | ||||
| 74322 | p->pPrev = 0; | ||||
| 74323 | pSib->pPrev = p; | ||||
| 74324 | }else{ | ||||
| 74325 | while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){ | ||||
| 74326 | pSib = pSib->pNext; | ||||
| 74327 | } | ||||
| 74328 | p->pNext = pSib->pNext; | ||||
| 74329 | p->pPrev = pSib; | ||||
| 74330 | if( p->pNext ){ | ||||
| 74331 | p->pNext->pPrev = p; | ||||
| 74332 | } | ||||
| 74333 | pSib->pNext = p; | ||||
| 74334 | } | ||||
| 74335 | break; | ||||
| 74336 | } | ||||
| 74337 | } | ||||
| 74338 | } | ||||
| 74339 | #endif | ||||
| 74340 | *ppBtree = p; | ||||
| 74341 | |||||
| 74342 | btree_open_out: | ||||
| 74343 | if( rc!=SQLITE_OK0 ){ | ||||
| 74344 | if( pBt && pBt->pPager ){ | ||||
| 74345 | sqlite3PagerClose(pBt->pPager, 0); | ||||
| 74346 | } | ||||
| 74347 | sqlite3_free(pBt); | ||||
| 74348 | sqlite3_free(p); | ||||
| 74349 | *ppBtree = 0; | ||||
| 74350 | }else{ | ||||
| 74351 | sqlite3_file *pFile; | ||||
| 74352 | |||||
| 74353 | /* If the B-Tree was successfully opened, set the pager-cache size to the | ||||
| 74354 | ** default value. Except, when opening on an existing shared pager-cache, | ||||
| 74355 | ** do not change the pager-cache size. | ||||
| 74356 | */ | ||||
| 74357 | if( sqlite3BtreeSchema(p, 0, 0)==0 ){ | ||||
| 74358 | sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE128); | ||||
| 74359 | } | ||||
| 74360 | |||||
| 74361 | pFile = sqlite3PagerFile(pBt->pPager); | ||||
| 74362 | if( pFile->pMethods ){ | ||||
| 74363 | sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB30, (void*)&pBt->db); | ||||
| 74364 | } | ||||
| 74365 | } | ||||
| 74366 | if( mutexOpen ){ | ||||
| 74367 | assert( sqlite3_mutex_held(mutexOpen) )((void) (0)); | ||||
| 74368 | sqlite3_mutex_leave(mutexOpen); | ||||
| 74369 | } | ||||
| 74370 | assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 )((void) (0)); | ||||
| 74371 | return rc; | ||||
| 74372 | } | ||||
| 74373 | |||||
| 74374 | /* | ||||
| 74375 | ** Decrement the BtShared.nRef counter. When it reaches zero, | ||||
| 74376 | ** remove the BtShared structure from the sharing list. Return | ||||
| 74377 | ** true if the BtShared.nRef counter reaches zero and return | ||||
| 74378 | ** false if it is still positive. | ||||
| 74379 | */ | ||||
| 74380 | static int removeFromSharingList(BtShared *pBt){ | ||||
| 74381 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 74382 | MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )sqlite3_mutex *pMainMtx; | ||||
| 74383 | BtShared *pList; | ||||
| 74384 | int removed = 0; | ||||
| 74385 | |||||
| 74386 | assert( sqlite3_mutex_notheld(pBt->mutex) )((void) (0)); | ||||
| 74387 | MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )pMainMtx = sqlite3MutexAlloc(2); | ||||
| 74388 | sqlite3_mutex_enter(pMainMtx); | ||||
| 74389 | pBt->nRef--; | ||||
| 74390 | if( pBt->nRef<=0 ){ | ||||
| 74391 | if( GLOBAL(BtShared*,sqlite3SharedCacheList)sqlite3SharedCacheList==pBt ){ | ||||
| 74392 | GLOBAL(BtShared*,sqlite3SharedCacheList)sqlite3SharedCacheList = pBt->pNext; | ||||
| 74393 | }else{ | ||||
| 74394 | pList = GLOBAL(BtShared*,sqlite3SharedCacheList)sqlite3SharedCacheList; | ||||
| 74395 | while( ALWAYS(pList)(pList) && pList->pNext!=pBt ){ | ||||
| 74396 | pList=pList->pNext; | ||||
| 74397 | } | ||||
| 74398 | if( ALWAYS(pList)(pList) ){ | ||||
| 74399 | pList->pNext = pBt->pNext; | ||||
| 74400 | } | ||||
| 74401 | } | ||||
| 74402 | if( SQLITE_THREADSAFE2 ){ | ||||
| 74403 | sqlite3_mutex_free(pBt->mutex); | ||||
| 74404 | } | ||||
| 74405 | removed = 1; | ||||
| 74406 | } | ||||
| 74407 | sqlite3_mutex_leave(pMainMtx); | ||||
| 74408 | return removed; | ||||
| 74409 | #else | ||||
| 74410 | return 1; | ||||
| 74411 | #endif | ||||
| 74412 | } | ||||
| 74413 | |||||
| 74414 | /* | ||||
| 74415 | ** Make sure pBt->pTmpSpace points to an allocation of | ||||
| 74416 | ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child | ||||
| 74417 | ** pointer. | ||||
| 74418 | */ | ||||
| 74419 | static SQLITE_NOINLINE__attribute__((noinline)) int allocateTempSpace(BtShared *pBt){ | ||||
| 74420 | assert( pBt!=0 )((void) (0)); | ||||
| 74421 | assert( pBt->pTmpSpace==0 )((void) (0)); | ||||
| 74422 | /* This routine is called only by btreeCursor() when allocating the | ||||
| 74423 | ** first write cursor for the BtShared object */ | ||||
| 74424 | assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 )((void) (0)); | ||||
| 74425 | pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); | ||||
| 74426 | if( pBt->pTmpSpace==0 ){ | ||||
| 74427 | BtCursor *pCur = pBt->pCursor; | ||||
| 74428 | pBt->pCursor = pCur->pNext; /* Unlink the cursor */ | ||||
| 74429 | memset(pCur, 0, sizeof(*pCur)); | ||||
| 74430 | return SQLITE_NOMEM_BKPT7; | ||||
| 74431 | } | ||||
| 74432 | |||||
| 74433 | /* One of the uses of pBt->pTmpSpace is to format cells before | ||||
| 74434 | ** inserting them into a leaf page (function fillInCell()). If | ||||
| 74435 | ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes | ||||
| 74436 | ** by the various routines that manipulate binary cells. Which | ||||
| 74437 | ** can mean that fillInCell() only initializes the first 2 or 3 | ||||
| 74438 | ** bytes of pTmpSpace, but that the first 4 bytes are copied from | ||||
| 74439 | ** it into a database page. This is not actually a problem, but it | ||||
| 74440 | ** does cause a valgrind error when the 1 or 2 bytes of uninitialized | ||||
| 74441 | ** data is passed to system call write(). So to avoid this error, | ||||
| 74442 | ** zero the first 4 bytes of temp space here. | ||||
| 74443 | ** | ||||
| 74444 | ** Also: Provide four bytes of initialized space before the | ||||
| 74445 | ** beginning of pTmpSpace as an area available to prepend the | ||||
| 74446 | ** left-child pointer to the beginning of a cell. | ||||
| 74447 | */ | ||||
| 74448 | memset(pBt->pTmpSpace, 0, 8); | ||||
| 74449 | pBt->pTmpSpace += 4; | ||||
| 74450 | return SQLITE_OK0; | ||||
| 74451 | } | ||||
| 74452 | |||||
| 74453 | /* | ||||
| 74454 | ** Free the pBt->pTmpSpace allocation | ||||
| 74455 | */ | ||||
| 74456 | static void freeTempSpace(BtShared *pBt){ | ||||
| 74457 | if( pBt->pTmpSpace ){ | ||||
| 74458 | pBt->pTmpSpace -= 4; | ||||
| 74459 | sqlite3PageFree(pBt->pTmpSpace); | ||||
| 74460 | pBt->pTmpSpace = 0; | ||||
| 74461 | } | ||||
| 74462 | } | ||||
| 74463 | |||||
| 74464 | /* | ||||
| 74465 | ** Close an open database and invalidate all cursors. | ||||
| 74466 | */ | ||||
| 74467 | SQLITE_PRIVATEstatic int sqlite3BtreeClose(Btree *p){ | ||||
| 74468 | BtShared *pBt = p->pBt; | ||||
| 74469 | |||||
| 74470 | /* Close all cursors opened via this handle. */ | ||||
| 74471 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 74472 | sqlite3BtreeEnter(p); | ||||
| 74473 | |||||
| 74474 | /* Verify that no other cursors have this Btree open */ | ||||
| 74475 | #ifdef SQLITE_DEBUG | ||||
| 74476 | { | ||||
| 74477 | BtCursor *pCur = pBt->pCursor; | ||||
| 74478 | while( pCur ){ | ||||
| 74479 | BtCursor *pTmp = pCur; | ||||
| 74480 | pCur = pCur->pNext; | ||||
| 74481 | assert( pTmp->pBtree!=p )((void) (0)); | ||||
| 74482 | |||||
| 74483 | } | ||||
| 74484 | } | ||||
| 74485 | #endif | ||||
| 74486 | |||||
| 74487 | /* Rollback any active transaction and free the handle structure. | ||||
| 74488 | ** The call to sqlite3BtreeRollback() drops any table-locks held by | ||||
| 74489 | ** this handle. | ||||
| 74490 | */ | ||||
| 74491 | sqlite3BtreeRollback(p, SQLITE_OK0, 0); | ||||
| 74492 | sqlite3BtreeLeave(p); | ||||
| 74493 | |||||
| 74494 | /* If there are still other outstanding references to the shared-btree | ||||
| 74495 | ** structure, return now. The remainder of this procedure cleans | ||||
| 74496 | ** up the shared-btree. | ||||
| 74497 | */ | ||||
| 74498 | assert( p->wantToLock==0 && p->locked==0 )((void) (0)); | ||||
| 74499 | if( !p->sharable || removeFromSharingList(pBt) ){ | ||||
| 74500 | /* The pBt is no longer on the sharing list, so we can access | ||||
| 74501 | ** it without having to hold the mutex. | ||||
| 74502 | ** | ||||
| 74503 | ** Clean out and delete the BtShared object. | ||||
| 74504 | */ | ||||
| 74505 | assert( !pBt->pCursor )((void) (0)); | ||||
| 74506 | sqlite3PagerClose(pBt->pPager, p->db); | ||||
| 74507 | if( pBt->xFreeSchema && pBt->pSchema ){ | ||||
| 74508 | pBt->xFreeSchema(pBt->pSchema); | ||||
| 74509 | } | ||||
| 74510 | sqlite3DbFree(0, pBt->pSchema); | ||||
| 74511 | freeTempSpace(pBt); | ||||
| 74512 | sqlite3_free(pBt); | ||||
| 74513 | } | ||||
| 74514 | |||||
| 74515 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 74516 | assert( p->wantToLock==0 )((void) (0)); | ||||
| 74517 | assert( p->locked==0 )((void) (0)); | ||||
| 74518 | if( p->pPrev ) p->pPrev->pNext = p->pNext; | ||||
| 74519 | if( p->pNext ) p->pNext->pPrev = p->pPrev; | ||||
| 74520 | #endif | ||||
| 74521 | |||||
| 74522 | sqlite3_free(p); | ||||
| 74523 | return SQLITE_OK0; | ||||
| 74524 | } | ||||
| 74525 | |||||
| 74526 | /* | ||||
| 74527 | ** Change the "soft" limit on the number of pages in the cache. | ||||
| 74528 | ** Unused and unmodified pages will be recycled when the number of | ||||
| 74529 | ** pages in the cache exceeds this soft limit. But the size of the | ||||
| 74530 | ** cache is allowed to grow larger than this limit if it contains | ||||
| 74531 | ** dirty pages or pages still in active use. | ||||
| 74532 | */ | ||||
| 74533 | SQLITE_PRIVATEstatic int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ | ||||
| 74534 | BtShared *pBt = p->pBt; | ||||
| 74535 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 74536 | sqlite3BtreeEnter(p); | ||||
| 74537 | sqlite3PagerSetCachesize(pBt->pPager, mxPage); | ||||
| 74538 | sqlite3BtreeLeave(p); | ||||
| 74539 | return SQLITE_OK0; | ||||
| 74540 | } | ||||
| 74541 | |||||
| 74542 | /* | ||||
| 74543 | ** Change the "spill" limit on the number of pages in the cache. | ||||
| 74544 | ** If the number of pages exceeds this limit during a write transaction, | ||||
| 74545 | ** the pager might attempt to "spill" pages to the journal early in | ||||
| 74546 | ** order to free up memory. | ||||
| 74547 | ** | ||||
| 74548 | ** The value returned is the current spill size. If zero is passed | ||||
| 74549 | ** as an argument, no changes are made to the spill size setting, so | ||||
| 74550 | ** using mxPage of 0 is a way to query the current spill size. | ||||
| 74551 | */ | ||||
| 74552 | SQLITE_PRIVATEstatic int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ | ||||
| 74553 | BtShared *pBt = p->pBt; | ||||
| 74554 | int res; | ||||
| 74555 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 74556 | sqlite3BtreeEnter(p); | ||||
| 74557 | res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage); | ||||
| 74558 | sqlite3BtreeLeave(p); | ||||
| 74559 | return res; | ||||
| 74560 | } | ||||
| 74561 | |||||
| 74562 | #if SQLITE_MAX_MMAP_SIZE20971520>0 | ||||
| 74563 | /* | ||||
| 74564 | ** Change the limit on the amount of the database file that may be | ||||
| 74565 | ** memory mapped. | ||||
| 74566 | */ | ||||
| 74567 | SQLITE_PRIVATEstatic int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ | ||||
| 74568 | BtShared *pBt = p->pBt; | ||||
| 74569 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 74570 | sqlite3BtreeEnter(p); | ||||
| 74571 | sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); | ||||
| 74572 | sqlite3BtreeLeave(p); | ||||
| 74573 | return SQLITE_OK0; | ||||
| 74574 | } | ||||
| 74575 | #endif /* SQLITE_MAX_MMAP_SIZE>0 */ | ||||
| 74576 | |||||
| 74577 | /* | ||||
| 74578 | ** Change the way data is synced to disk in order to increase or decrease | ||||
| 74579 | ** how well the database resists damage due to OS crashes and power | ||||
| 74580 | ** failures. Level 1 is the same as asynchronous (no syncs() occur and | ||||
| 74581 | ** there is a high probability of damage) Level 2 is the default. There | ||||
| 74582 | ** is a very low but non-zero probability of damage. Level 3 reduces the | ||||
| 74583 | ** probability of damage to near zero but with a write performance reduction. | ||||
| 74584 | */ | ||||
| 74585 | #ifndef SQLITE_OMIT_PAGER_PRAGMAS | ||||
| 74586 | SQLITE_PRIVATEstatic int sqlite3BtreeSetPagerFlags( | ||||
| 74587 | Btree *p, /* The btree to set the safety level on */ | ||||
| 74588 | unsigned pgFlags /* Various PAGER_* flags */ | ||||
| 74589 | ){ | ||||
| 74590 | BtShared *pBt = p->pBt; | ||||
| 74591 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 74592 | sqlite3BtreeEnter(p); | ||||
| 74593 | sqlite3PagerSetFlags(pBt->pPager, pgFlags); | ||||
| 74594 | sqlite3BtreeLeave(p); | ||||
| 74595 | return SQLITE_OK0; | ||||
| 74596 | } | ||||
| 74597 | #endif | ||||
| 74598 | |||||
| 74599 | /* | ||||
| 74600 | ** Change the default pages size and the number of reserved bytes per page. | ||||
| 74601 | ** Or, if the page size has already been fixed, return SQLITE_READONLY | ||||
| 74602 | ** without changing anything. | ||||
| 74603 | ** | ||||
| 74604 | ** The page size must be a power of 2 between 512 and 65536. If the page | ||||
| 74605 | ** size supplied does not meet this constraint then the page size is not | ||||
| 74606 | ** changed. | ||||
| 74607 | ** | ||||
| 74608 | ** Page sizes are constrained to be a power of two so that the region | ||||
| 74609 | ** of the database file used for locking (beginning at PENDING_BYTE, | ||||
| 74610 | ** the first byte past the 1GB boundary, 0x40000000) needs to occur | ||||
| 74611 | ** at the beginning of a page. | ||||
| 74612 | ** | ||||
| 74613 | ** If parameter nReserve is less than zero, then the number of reserved | ||||
| 74614 | ** bytes per page is left unchanged. | ||||
| 74615 | ** | ||||
| 74616 | ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size | ||||
| 74617 | ** and autovacuum mode can no longer be changed. | ||||
| 74618 | */ | ||||
| 74619 | SQLITE_PRIVATEstatic int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ | ||||
| 74620 | int rc = SQLITE_OK0; | ||||
| 74621 | int x; | ||||
| 74622 | BtShared *pBt = p->pBt; | ||||
| 74623 | assert( nReserve>=0 && nReserve<=255 )((void) (0)); | ||||
| 74624 | sqlite3BtreeEnter(p); | ||||
| 74625 | pBt->nReserveWanted = (u8)nReserve; | ||||
| 74626 | x = pBt->pageSize - pBt->usableSize; | ||||
| 74627 | if( nReserve<x ) nReserve = x; | ||||
| 74628 | if( pBt->btsFlags & BTS_PAGESIZE_FIXED0x0002 ){ | ||||
| 74629 | sqlite3BtreeLeave(p); | ||||
| 74630 | return SQLITE_READONLY8; | ||||
| 74631 | } | ||||
| 74632 | assert( nReserve>=0 && nReserve<=255 )((void) (0)); | ||||
| 74633 | if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE65536 && | ||||
| 74634 | ((pageSize-1)&pageSize)==0 ){ | ||||
| 74635 | assert( (pageSize & 7)==0 )((void) (0)); | ||||
| 74636 | assert( !pBt->pCursor )((void) (0)); | ||||
| 74637 | if( nReserve>32 && pageSize==512 ) pageSize = 1024; | ||||
| 74638 | pBt->pageSize = (u32)pageSize; | ||||
| 74639 | freeTempSpace(pBt); | ||||
| 74640 | } | ||||
| 74641 | rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); | ||||
| 74642 | pBt->usableSize = pBt->pageSize - (u16)nReserve; | ||||
| 74643 | if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED0x0002; | ||||
| 74644 | sqlite3BtreeLeave(p); | ||||
| 74645 | return rc; | ||||
| 74646 | } | ||||
| 74647 | |||||
| 74648 | /* | ||||
| 74649 | ** Return the currently defined page size | ||||
| 74650 | */ | ||||
| 74651 | SQLITE_PRIVATEstatic int sqlite3BtreeGetPageSize(Btree *p){ | ||||
| 74652 | return p->pBt->pageSize; | ||||
| 74653 | } | ||||
| 74654 | |||||
| 74655 | /* | ||||
| 74656 | ** This function is similar to sqlite3BtreeGetReserve(), except that it | ||||
| 74657 | ** may only be called if it is guaranteed that the b-tree mutex is already | ||||
| 74658 | ** held. | ||||
| 74659 | ** | ||||
| 74660 | ** This is useful in one special case in the backup API code where it is | ||||
| 74661 | ** known that the shared b-tree mutex is held, but the mutex on the | ||||
| 74662 | ** database handle that owns *p is not. In this case if sqlite3BtreeEnter() | ||||
| 74663 | ** were to be called, it might collide with some other operation on the | ||||
| 74664 | ** database handle that owns *p, causing undefined behavior. | ||||
| 74665 | */ | ||||
| 74666 | SQLITE_PRIVATEstatic int sqlite3BtreeGetReserveNoMutex(Btree *p){ | ||||
| 74667 | int n; | ||||
| 74668 | assert( sqlite3_mutex_held(p->pBt->mutex) )((void) (0)); | ||||
| 74669 | n = p->pBt->pageSize - p->pBt->usableSize; | ||||
| 74670 | return n; | ||||
| 74671 | } | ||||
| 74672 | |||||
| 74673 | /* | ||||
| 74674 | ** Return the number of bytes of space at the end of every page that | ||||
| 74675 | ** are intentionally left unused. This is the "reserved" space that is | ||||
| 74676 | ** sometimes used by extensions. | ||||
| 74677 | ** | ||||
| 74678 | ** The value returned is the larger of the current reserve size and | ||||
| 74679 | ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES. | ||||
| 74680 | ** The amount of reserve can only grow - never shrink. | ||||
| 74681 | */ | ||||
| 74682 | SQLITE_PRIVATEstatic int sqlite3BtreeGetRequestedReserve(Btree *p){ | ||||
| 74683 | int n1, n2; | ||||
| 74684 | sqlite3BtreeEnter(p); | ||||
| 74685 | n1 = (int)p->pBt->nReserveWanted; | ||||
| 74686 | n2 = sqlite3BtreeGetReserveNoMutex(p); | ||||
| 74687 | sqlite3BtreeLeave(p); | ||||
| 74688 | return n1>n2 ? n1 : n2; | ||||
| 74689 | } | ||||
| 74690 | |||||
| 74691 | |||||
| 74692 | /* | ||||
| 74693 | ** Set the maximum page count for a database if mxPage is positive. | ||||
| 74694 | ** No changes are made if mxPage is 0 or negative. | ||||
| 74695 | ** Regardless of the value of mxPage, return the maximum page count. | ||||
| 74696 | */ | ||||
| 74697 | SQLITE_PRIVATEstatic Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){ | ||||
| 74698 | Pgno n; | ||||
| 74699 | sqlite3BtreeEnter(p); | ||||
| 74700 | n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); | ||||
| 74701 | sqlite3BtreeLeave(p); | ||||
| 74702 | return n; | ||||
| 74703 | } | ||||
| 74704 | |||||
| 74705 | /* | ||||
| 74706 | ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags: | ||||
| 74707 | ** | ||||
| 74708 | ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared | ||||
| 74709 | ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared | ||||
| 74710 | ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set | ||||
| 74711 | ** newFlag==(-1) No changes | ||||
| 74712 | ** | ||||
| 74713 | ** This routine acts as a query if newFlag is less than zero | ||||
| 74714 | ** | ||||
| 74715 | ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but | ||||
| 74716 | ** freelist leaf pages are not written back to the database. Thus in-page | ||||
| 74717 | ** deleted content is cleared, but freelist deleted content is not. | ||||
| 74718 | ** | ||||
| 74719 | ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition | ||||
| 74720 | ** that freelist leaf pages are written back into the database, increasing | ||||
| 74721 | ** the amount of disk I/O. | ||||
| 74722 | */ | ||||
| 74723 | SQLITE_PRIVATEstatic int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ | ||||
| 74724 | int b; | ||||
| 74725 | if( p==0 ) return 0; | ||||
| 74726 | sqlite3BtreeEnter(p); | ||||
| 74727 | assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 )((void) (0)); | ||||
| 74728 | assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) )((void) (0)); | ||||
| 74729 | if( newFlag>=0 ){ | ||||
| 74730 | p->pBt->btsFlags &= ~BTS_FAST_SECURE0x000c; | ||||
| 74731 | p->pBt->btsFlags |= (u16)(BTS_SECURE_DELETE0x0004*newFlag); | ||||
| 74732 | } | ||||
| 74733 | b = (p->pBt->btsFlags & BTS_FAST_SECURE0x000c)/BTS_SECURE_DELETE0x0004; | ||||
| 74734 | sqlite3BtreeLeave(p); | ||||
| 74735 | return b; | ||||
| 74736 | } | ||||
| 74737 | |||||
| 74738 | /* | ||||
| 74739 | ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' | ||||
| 74740 | ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it | ||||
| 74741 | ** is disabled. The default value for the auto-vacuum property is | ||||
| 74742 | ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. | ||||
| 74743 | */ | ||||
| 74744 | SQLITE_PRIVATEstatic int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ | ||||
| 74745 | #ifdef SQLITE_OMIT_AUTOVACUUM | ||||
| 74746 | return SQLITE_READONLY8; | ||||
| 74747 | #else | ||||
| 74748 | BtShared *pBt = p->pBt; | ||||
| 74749 | int rc = SQLITE_OK0; | ||||
| 74750 | u8 av = (u8)autoVacuum; | ||||
| 74751 | |||||
| 74752 | sqlite3BtreeEnter(p); | ||||
| 74753 | if( (pBt->btsFlags & BTS_PAGESIZE_FIXED0x0002)!=0 && (av ?1:0)!=pBt->autoVacuum ){ | ||||
| 74754 | rc = SQLITE_READONLY8; | ||||
| 74755 | }else{ | ||||
| 74756 | pBt->autoVacuum = av ?1:0; | ||||
| 74757 | pBt->incrVacuum = av==2 ?1:0; | ||||
| 74758 | } | ||||
| 74759 | sqlite3BtreeLeave(p); | ||||
| 74760 | return rc; | ||||
| 74761 | #endif | ||||
| 74762 | } | ||||
| 74763 | |||||
| 74764 | /* | ||||
| 74765 | ** Return the value of the 'auto-vacuum' property. If auto-vacuum is | ||||
| 74766 | ** enabled 1 is returned. Otherwise 0. | ||||
| 74767 | */ | ||||
| 74768 | SQLITE_PRIVATEstatic int sqlite3BtreeGetAutoVacuum(Btree *p){ | ||||
| 74769 | #ifdef SQLITE_OMIT_AUTOVACUUM | ||||
| 74770 | return BTREE_AUTOVACUUM_NONE0; | ||||
| 74771 | #else | ||||
| 74772 | int rc; | ||||
| 74773 | sqlite3BtreeEnter(p); | ||||
| 74774 | rc = ( | ||||
| 74775 | (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE0: | ||||
| 74776 | (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL1: | ||||
| 74777 | BTREE_AUTOVACUUM_INCR2 | ||||
| 74778 | ); | ||||
| 74779 | sqlite3BtreeLeave(p); | ||||
| 74780 | return rc; | ||||
| 74781 | #endif | ||||
| 74782 | } | ||||
| 74783 | |||||
| 74784 | /* | ||||
| 74785 | ** If the user has not set the safety-level for this database connection | ||||
| 74786 | ** using "PRAGMA synchronous", and if the safety-level is not already | ||||
| 74787 | ** set to the value passed to this function as the second parameter, | ||||
| 74788 | ** set it so. | ||||
| 74789 | */ | ||||
| 74790 | #if SQLITE_DEFAULT_SYNCHRONOUS2!=SQLITE_DEFAULT_WAL_SYNCHRONOUS1 \ | ||||
| 74791 | && !defined(SQLITE_OMIT_WAL) | ||||
| 74792 | static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){ | ||||
| 74793 | sqlite3 *db; | ||||
| 74794 | Db *pDb; | ||||
| 74795 | if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ | ||||
| 74796 | while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } | ||||
| 74797 | if( pDb->bSyncSet==0 | ||||
| 74798 | && pDb->safety_level!=safety_level | ||||
| 74799 | && pDb!=&db->aDb[1] | ||||
| 74800 | ){ | ||||
| 74801 | pDb->safety_level = safety_level; | ||||
| 74802 | sqlite3PagerSetFlags(pBt->pPager, | ||||
| 74803 | pDb->safety_level | (db->flags & PAGER_FLAGS_MASK0x38)); | ||||
| 74804 | } | ||||
| 74805 | } | ||||
| 74806 | } | ||||
| 74807 | #else | ||||
| 74808 | # define setDefaultSyncFlag(pBt,safety_level) | ||||
| 74809 | #endif | ||||
| 74810 | |||||
| 74811 | /* Forward declaration */ | ||||
| 74812 | static int newDatabase(BtShared*); | ||||
| 74813 | |||||
| 74814 | |||||
| 74815 | /* | ||||
| 74816 | ** Get a reference to pPage1 of the database file. This will | ||||
| 74817 | ** also acquire a readlock on that file. | ||||
| 74818 | ** | ||||
| 74819 | ** SQLITE_OK is returned on success. If the file is not a | ||||
| 74820 | ** well-formed database file, then SQLITE_CORRUPT is returned. | ||||
| 74821 | ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM | ||||
| 74822 | ** is returned if we run out of memory. | ||||
| 74823 | */ | ||||
| 74824 | static int lockBtree(BtShared *pBt){ | ||||
| 74825 | int rc; /* Result code from subfunctions */ | ||||
| 74826 | MemPage *pPage1; /* Page 1 of the database file */ | ||||
| 74827 | u32 nPage; /* Number of pages in the database */ | ||||
| 74828 | u32 nPageFile = 0; /* Number of pages in the database file */ | ||||
| 74829 | |||||
| 74830 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 74831 | assert( pBt->pPage1==0 )((void) (0)); | ||||
| 74832 | rc = sqlite3PagerSharedLock(pBt->pPager); | ||||
| 74833 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 74834 | rc = btreeGetPage(pBt, 1, &pPage1, 0); | ||||
| 74835 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 74836 | |||||
| 74837 | /* Do some checking to help insure the file we opened really is | ||||
| 74838 | ** a valid database file. | ||||
| 74839 | */ | ||||
| 74840 | nPage = get4bytesqlite3Get4byte(28+(u8*)pPage1->aData); | ||||
| 74841 | sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile); | ||||
| 74842 | if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ | ||||
| 74843 | nPage = nPageFile; | ||||
| 74844 | } | ||||
| 74845 | if( (pBt->db->flags & SQLITE_ResetDatabase0x02000000)!=0 ){ | ||||
| 74846 | nPage = 0; | ||||
| 74847 | } | ||||
| 74848 | if( nPage>0 ){ | ||||
| 74849 | u32 pageSize; | ||||
| 74850 | u32 usableSize; | ||||
| 74851 | u8 *page1 = pPage1->aData; | ||||
| 74852 | rc = SQLITE_NOTADB26; | ||||
| 74853 | /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins | ||||
| 74854 | ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d | ||||
| 74855 | ** 61 74 20 33 00. */ | ||||
| 74856 | if( memcmp(page1, zMagicHeader, 16)!=0 ){ | ||||
| 74857 | goto page1_init_failed; | ||||
| 74858 | } | ||||
| 74859 | |||||
| 74860 | #ifdef SQLITE_OMIT_WAL | ||||
| 74861 | if( page1[18]>1 ){ | ||||
| 74862 | pBt->btsFlags |= BTS_READ_ONLY0x0001; | ||||
| 74863 | } | ||||
| 74864 | if( page1[19]>1 ){ | ||||
| 74865 | goto page1_init_failed; | ||||
| 74866 | } | ||||
| 74867 | #else | ||||
| 74868 | if( page1[18]>2 ){ | ||||
| 74869 | pBt->btsFlags |= BTS_READ_ONLY0x0001; | ||||
| 74870 | } | ||||
| 74871 | if( page1[19]>2 ){ | ||||
| 74872 | goto page1_init_failed; | ||||
| 74873 | } | ||||
| 74874 | |||||
| 74875 | /* If the read version is set to 2, this database should be accessed | ||||
| 74876 | ** in WAL mode. If the log is not already open, open it now. Then | ||||
| 74877 | ** return SQLITE_OK and return without populating BtShared.pPage1. | ||||
| 74878 | ** The caller detects this and calls this function again. This is | ||||
| 74879 | ** required as the version of page 1 currently in the page1 buffer | ||||
| 74880 | ** may not be the latest version - there may be a newer one in the log | ||||
| 74881 | ** file. | ||||
| 74882 | */ | ||||
| 74883 | if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL0x0020)==0 ){ | ||||
| 74884 | int isOpen = 0; | ||||
| 74885 | rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); | ||||
| 74886 | if( rc!=SQLITE_OK0 ){ | ||||
| 74887 | goto page1_init_failed; | ||||
| 74888 | }else{ | ||||
| 74889 | setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS1+1); | ||||
| 74890 | if( isOpen==0 ){ | ||||
| 74891 | releasePageOne(pPage1); | ||||
| 74892 | return SQLITE_OK0; | ||||
| 74893 | } | ||||
| 74894 | } | ||||
| 74895 | rc = SQLITE_NOTADB26; | ||||
| 74896 | }else{ | ||||
| 74897 | setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS2+1); | ||||
| 74898 | } | ||||
| 74899 | #endif | ||||
| 74900 | |||||
| 74901 | /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload | ||||
| 74902 | ** fractions and the leaf payload fraction values must be 64, 32, and 32. | ||||
| 74903 | ** | ||||
| 74904 | ** The original design allowed these amounts to vary, but as of | ||||
| 74905 | ** version 3.6.0, we require them to be fixed. | ||||
| 74906 | */ | ||||
| 74907 | if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ | ||||
| 74908 | goto page1_init_failed; | ||||
| 74909 | } | ||||
| 74910 | /* EVIDENCE-OF: R-51873-39618 The page size for a database file is | ||||
| 74911 | ** determined by the 2-byte integer located at an offset of 16 bytes from | ||||
| 74912 | ** the beginning of the database file. */ | ||||
| 74913 | pageSize = (page1[16]<<8) | (page1[17]<<16); | ||||
| 74914 | /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two | ||||
| 74915 | ** between 512 and 65536 inclusive. */ | ||||
| 74916 | if( ((pageSize-1)&pageSize)!=0 | ||||
| 74917 | || pageSize>SQLITE_MAX_PAGE_SIZE65536 | ||||
| 74918 | || pageSize<=256 | ||||
| 74919 | ){ | ||||
| 74920 | goto page1_init_failed; | ||||
| 74921 | } | ||||
| 74922 | assert( (pageSize & 7)==0 )((void) (0)); | ||||
| 74923 | /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte | ||||
| 74924 | ** integer at offset 20 is the number of bytes of space at the end of | ||||
| 74925 | ** each page to reserve for extensions. | ||||
| 74926 | ** | ||||
| 74927 | ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is | ||||
| 74928 | ** determined by the one-byte unsigned integer found at an offset of 20 | ||||
| 74929 | ** into the database file header. */ | ||||
| 74930 | usableSize = pageSize - page1[20]; | ||||
| 74931 | if( (u32)pageSize!=pBt->pageSize ){ | ||||
| 74932 | /* After reading the first page of the database assuming a page size | ||||
| 74933 | ** of BtShared.pageSize, we have discovered that the page-size is | ||||
| 74934 | ** actually pageSize. Unlock the database, leave pBt->pPage1 at | ||||
| 74935 | ** zero and return SQLITE_OK. The caller will call this function | ||||
| 74936 | ** again with the correct page-size. | ||||
| 74937 | */ | ||||
| 74938 | releasePageOne(pPage1); | ||||
| 74939 | pBt->usableSize = usableSize; | ||||
| 74940 | pBt->pageSize = pageSize; | ||||
| 74941 | pBt->btsFlags |= BTS_PAGESIZE_FIXED0x0002; | ||||
| 74942 | freeTempSpace(pBt); | ||||
| 74943 | rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, | ||||
| 74944 | pageSize-usableSize); | ||||
| 74945 | return rc; | ||||
| 74946 | } | ||||
| 74947 | if( nPage>nPageFile ){ | ||||
| 74948 | if( sqlite3WritableSchema(pBt->db)==0 ){ | ||||
| 74949 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(74949); | ||||
| 74950 | goto page1_init_failed; | ||||
| 74951 | }else{ | ||||
| 74952 | nPage = nPageFile; | ||||
| 74953 | } | ||||
| 74954 | } | ||||
| 74955 | /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to | ||||
| 74956 | ** be less than 480. In other words, if the page size is 512, then the | ||||
| 74957 | ** reserved space size cannot exceed 32. */ | ||||
| 74958 | if( usableSize<480 ){ | ||||
| 74959 | goto page1_init_failed; | ||||
| 74960 | } | ||||
| 74961 | pBt->btsFlags |= BTS_PAGESIZE_FIXED0x0002; | ||||
| 74962 | pBt->pageSize = pageSize; | ||||
| 74963 | pBt->usableSize = usableSize; | ||||
| 74964 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 74965 | pBt->autoVacuum = (get4bytesqlite3Get4byte(&page1[36 + 4*4])?1:0); | ||||
| 74966 | pBt->incrVacuum = (get4bytesqlite3Get4byte(&page1[36 + 7*4])?1:0); | ||||
| 74967 | #endif | ||||
| 74968 | } | ||||
| 74969 | |||||
| 74970 | /* maxLocal is the maximum amount of payload to store locally for | ||||
| 74971 | ** a cell. Make sure it is small enough so that at least minFanout | ||||
| 74972 | ** cells can will fit on one page. We assume a 10-byte page header. | ||||
| 74973 | ** Besides the payload, the cell must store: | ||||
| 74974 | ** 2-byte pointer to the cell | ||||
| 74975 | ** 4-byte child pointer | ||||
| 74976 | ** 9-byte nKey value | ||||
| 74977 | ** 4-byte nData value | ||||
| 74978 | ** 4-byte overflow page pointer | ||||
| 74979 | ** So a cell consists of a 2-byte pointer, a header which is as much as | ||||
| 74980 | ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow | ||||
| 74981 | ** page pointer. | ||||
| 74982 | */ | ||||
| 74983 | pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); | ||||
| 74984 | pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); | ||||
| 74985 | pBt->maxLeaf = (u16)(pBt->usableSize - 35); | ||||
| 74986 | pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); | ||||
| 74987 | if( pBt->maxLocal>127 ){ | ||||
| 74988 | pBt->max1bytePayload = 127; | ||||
| 74989 | }else{ | ||||
| 74990 | pBt->max1bytePayload = (u8)pBt->maxLocal; | ||||
| 74991 | } | ||||
| 74992 | assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) )((void) (0)); | ||||
| 74993 | pBt->pPage1 = pPage1; | ||||
| 74994 | pBt->nPage = nPage; | ||||
| 74995 | return SQLITE_OK0; | ||||
| 74996 | |||||
| 74997 | page1_init_failed: | ||||
| 74998 | releasePageOne(pPage1); | ||||
| 74999 | pBt->pPage1 = 0; | ||||
| 75000 | return rc; | ||||
| 75001 | } | ||||
| 75002 | |||||
| 75003 | #ifndef NDEBUG1 | ||||
| 75004 | /* | ||||
| 75005 | ** Return the number of cursors open on pBt. This is for use | ||||
| 75006 | ** in assert() expressions, so it is only compiled if NDEBUG is not | ||||
| 75007 | ** defined. | ||||
| 75008 | ** | ||||
| 75009 | ** Only write cursors are counted if wrOnly is true. If wrOnly is | ||||
| 75010 | ** false then all cursors are counted. | ||||
| 75011 | ** | ||||
| 75012 | ** For the purposes of this routine, a cursor is any cursor that | ||||
| 75013 | ** is capable of reading or writing to the database. Cursors that | ||||
| 75014 | ** have been tripped into the CURSOR_FAULT state are not counted. | ||||
| 75015 | */ | ||||
| 75016 | static int countValidCursors(BtShared *pBt, int wrOnly){ | ||||
| 75017 | BtCursor *pCur; | ||||
| 75018 | int r = 0; | ||||
| 75019 | for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ | ||||
| 75020 | if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag0x01)!=0) | ||||
| 75021 | && pCur->eState!=CURSOR_FAULT4 ) r++; | ||||
| 75022 | } | ||||
| 75023 | return r; | ||||
| 75024 | } | ||||
| 75025 | #endif | ||||
| 75026 | |||||
| 75027 | /* | ||||
| 75028 | ** If there are no outstanding cursors and we are not in the middle | ||||
| 75029 | ** of a transaction but there is a read lock on the database, then | ||||
| 75030 | ** this routine unrefs the first page of the database file which | ||||
| 75031 | ** has the effect of releasing the read lock. | ||||
| 75032 | ** | ||||
| 75033 | ** If there is a transaction in progress, this routine is a no-op. | ||||
| 75034 | */ | ||||
| 75035 | static void unlockBtreeIfUnused(BtShared *pBt){ | ||||
| 75036 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 75037 | assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE )((void) (0)); | ||||
| 75038 | if( pBt->inTransaction==TRANS_NONE0 && pBt->pPage1!=0 ){ | ||||
| 75039 | MemPage *pPage1 = pBt->pPage1; | ||||
| 75040 | assert( pPage1->aData )((void) (0)); | ||||
| 75041 | assert( sqlite3PagerRefcount(pBt->pPager)==1 )((void) (0)); | ||||
| 75042 | pBt->pPage1 = 0; | ||||
| 75043 | releasePageOne(pPage1); | ||||
| 75044 | } | ||||
| 75045 | } | ||||
| 75046 | |||||
| 75047 | /* | ||||
| 75048 | ** If pBt points to an empty file then convert that empty file | ||||
| 75049 | ** into a new empty database by initializing the first page of | ||||
| 75050 | ** the database. | ||||
| 75051 | */ | ||||
| 75052 | static int newDatabase(BtShared *pBt){ | ||||
| 75053 | MemPage *pP1; | ||||
| 75054 | unsigned char *data; | ||||
| 75055 | int rc; | ||||
| 75056 | |||||
| 75057 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 75058 | if( pBt->nPage>0 ){ | ||||
| 75059 | return SQLITE_OK0; | ||||
| 75060 | } | ||||
| 75061 | pP1 = pBt->pPage1; | ||||
| 75062 | assert( pP1!=0 )((void) (0)); | ||||
| 75063 | data = pP1->aData; | ||||
| 75064 | rc = sqlite3PagerWrite(pP1->pDbPage); | ||||
| 75065 | if( rc ) return rc; | ||||
| 75066 | memcpy(data, zMagicHeader, sizeof(zMagicHeader)); | ||||
| 75067 | assert( sizeof(zMagicHeader)==16 )((void) (0)); | ||||
| 75068 | data[16] = (u8)((pBt->pageSize>>8)&0xff); | ||||
| 75069 | data[17] = (u8)((pBt->pageSize>>16)&0xff); | ||||
| 75070 | data[18] = 1; | ||||
| 75071 | data[19] = 1; | ||||
| 75072 | assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize)((void) (0)); | ||||
| 75073 | data[20] = (u8)(pBt->pageSize - pBt->usableSize); | ||||
| 75074 | data[21] = 64; | ||||
| 75075 | data[22] = 32; | ||||
| 75076 | data[23] = 32; | ||||
| 75077 | memset(&data[24], 0, 100-24); | ||||
| 75078 | zeroPage(pP1, PTF_INTKEY0x01|PTF_LEAF0x08|PTF_LEAFDATA0x04 ); | ||||
| 75079 | pBt->btsFlags |= BTS_PAGESIZE_FIXED0x0002; | ||||
| 75080 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 75081 | assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 )((void) (0)); | ||||
| 75082 | assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 )((void) (0)); | ||||
| 75083 | put4bytesqlite3Put4byte(&data[36 + 4*4], pBt->autoVacuum); | ||||
| 75084 | put4bytesqlite3Put4byte(&data[36 + 7*4], pBt->incrVacuum); | ||||
| 75085 | #endif | ||||
| 75086 | pBt->nPage = 1; | ||||
| 75087 | data[31] = 1; | ||||
| 75088 | return SQLITE_OK0; | ||||
| 75089 | } | ||||
| 75090 | |||||
| 75091 | /* | ||||
| 75092 | ** Initialize the first page of the database file (creating a database | ||||
| 75093 | ** consisting of a single page and no schema objects). Return SQLITE_OK | ||||
| 75094 | ** if successful, or an SQLite error code otherwise. | ||||
| 75095 | */ | ||||
| 75096 | SQLITE_PRIVATEstatic int sqlite3BtreeNewDb(Btree *p){ | ||||
| 75097 | int rc; | ||||
| 75098 | sqlite3BtreeEnter(p); | ||||
| 75099 | p->pBt->nPage = 0; | ||||
| 75100 | rc = newDatabase(p->pBt); | ||||
| 75101 | sqlite3BtreeLeave(p); | ||||
| 75102 | return rc; | ||||
| 75103 | } | ||||
| 75104 | |||||
| 75105 | /* | ||||
| 75106 | ** Attempt to start a new transaction. A write-transaction | ||||
| 75107 | ** is started if the second argument is nonzero, otherwise a read- | ||||
| 75108 | ** transaction. If the second argument is 2 or more and exclusive | ||||
| 75109 | ** transaction is started, meaning that no other process is allowed | ||||
| 75110 | ** to access the database. A preexisting transaction may not be | ||||
| 75111 | ** upgraded to exclusive by calling this routine a second time - the | ||||
| 75112 | ** exclusivity flag only works for a new transaction. | ||||
| 75113 | ** | ||||
| 75114 | ** A write-transaction must be started before attempting any | ||||
| 75115 | ** changes to the database. None of the following routines | ||||
| 75116 | ** will work unless a transaction is started first: | ||||
| 75117 | ** | ||||
| 75118 | ** sqlite3BtreeCreateTable() | ||||
| 75119 | ** sqlite3BtreeCreateIndex() | ||||
| 75120 | ** sqlite3BtreeClearTable() | ||||
| 75121 | ** sqlite3BtreeDropTable() | ||||
| 75122 | ** sqlite3BtreeInsert() | ||||
| 75123 | ** sqlite3BtreeDelete() | ||||
| 75124 | ** sqlite3BtreeUpdateMeta() | ||||
| 75125 | ** | ||||
| 75126 | ** If an initial attempt to acquire the lock fails because of lock contention | ||||
| 75127 | ** and the database was previously unlocked, then invoke the busy handler | ||||
| 75128 | ** if there is one. But if there was previously a read-lock, do not | ||||
| 75129 | ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is | ||||
| 75130 | ** returned when there is already a read-lock in order to avoid a deadlock. | ||||
| 75131 | ** | ||||
| 75132 | ** Suppose there are two processes A and B. A has a read lock and B has | ||||
| 75133 | ** a reserved lock. B tries to promote to exclusive but is blocked because | ||||
| 75134 | ** of A's read lock. A tries to promote to reserved but is blocked by B. | ||||
| 75135 | ** One or the other of the two processes must give way or there can be | ||||
| 75136 | ** no progress. By returning SQLITE_BUSY and not invoking the busy callback | ||||
| 75137 | ** when A already has a read lock, we encourage A to give up and let B | ||||
| 75138 | ** proceed. | ||||
| 75139 | */ | ||||
| 75140 | static SQLITE_NOINLINE__attribute__((noinline)) int btreeBeginTrans( | ||||
| 75141 | Btree *p, /* The btree in which to start the transaction */ | ||||
| 75142 | int wrflag, /* True to start a write transaction */ | ||||
| 75143 | int *pSchemaVersion /* Put schema version number here, if not NULL */ | ||||
| 75144 | ){ | ||||
| 75145 | BtShared *pBt = p->pBt; | ||||
| 75146 | Pager *pPager = pBt->pPager; | ||||
| 75147 | int rc = SQLITE_OK0; | ||||
| 75148 | |||||
| 75149 | sqlite3BtreeEnter(p); | ||||
| 75150 | btreeIntegrity(p)((void) (0)); ((void) (0));; | ||||
| 75151 | |||||
| 75152 | /* If the btree is already in a write-transaction, or it | ||||
| 75153 | ** is already in a read-transaction and a read-transaction | ||||
| 75154 | ** is requested, this is a no-op. | ||||
| 75155 | */ | ||||
| 75156 | if( p->inTrans==TRANS_WRITE2 || (p->inTrans==TRANS_READ1 && !wrflag) ){ | ||||
| 75157 | goto trans_begun; | ||||
| 75158 | } | ||||
| 75159 | assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 )((void) (0)); | ||||
| 75160 | |||||
| 75161 | if( (p->db->flags & SQLITE_ResetDatabase0x02000000) | ||||
| 75162 | && sqlite3PagerIsreadonly(pPager)==0 | ||||
| 75163 | ){ | ||||
| 75164 | pBt->btsFlags &= ~BTS_READ_ONLY0x0001; | ||||
| 75165 | } | ||||
| 75166 | |||||
| 75167 | /* Write transactions are not possible on a read-only database */ | ||||
| 75168 | if( (pBt->btsFlags & BTS_READ_ONLY0x0001)!=0 && wrflag ){ | ||||
| 75169 | rc = SQLITE_READONLY8; | ||||
| 75170 | goto trans_begun; | ||||
| 75171 | } | ||||
| 75172 | |||||
| 75173 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 75174 | { | ||||
| 75175 | sqlite3 *pBlock = 0; | ||||
| 75176 | /* If another database handle has already opened a write transaction | ||||
| 75177 | ** on this shared-btree structure and a second write transaction is | ||||
| 75178 | ** requested, return SQLITE_LOCKED. | ||||
| 75179 | */ | ||||
| 75180 | if( (wrflag && pBt->inTransaction==TRANS_WRITE2) | ||||
| 75181 | || (pBt->btsFlags & BTS_PENDING0x0080)!=0 | ||||
| 75182 | ){ | ||||
| 75183 | pBlock = pBt->pWriter->db; | ||||
| 75184 | }else if( wrflag>1 ){ | ||||
| 75185 | BtLock *pIter; | ||||
| 75186 | for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ | ||||
| 75187 | if( pIter->pBtree!=p ){ | ||||
| 75188 | pBlock = pIter->pBtree->db; | ||||
| 75189 | break; | ||||
| 75190 | } | ||||
| 75191 | } | ||||
| 75192 | } | ||||
| 75193 | if( pBlock ){ | ||||
| 75194 | sqlite3ConnectionBlocked(p->db, pBlock); | ||||
| 75195 | rc = SQLITE_LOCKED_SHAREDCACHE(6 | (1<<8)); | ||||
| 75196 | goto trans_begun; | ||||
| 75197 | } | ||||
| 75198 | } | ||||
| 75199 | #endif | ||||
| 75200 | |||||
| 75201 | /* Any read-only or read-write transaction implies a read-lock on | ||||
| 75202 | ** page 1. So if some other shared-cache client already has a write-lock | ||||
| 75203 | ** on page 1, the transaction cannot be opened. */ | ||||
| 75204 | rc = querySharedCacheTableLock(p, SCHEMA_ROOT1, READ_LOCK1); | ||||
| 75205 | if( SQLITE_OK0!=rc ) goto trans_begun; | ||||
| 75206 | |||||
| 75207 | pBt->btsFlags &= ~BTS_INITIALLY_EMPTY0x0010; | ||||
| 75208 | if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY0x0010; | ||||
| 75209 | do { | ||||
| 75210 | sqlite3PagerWalDb(pPager, p->db); | ||||
| 75211 | |||||
| 75212 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 75213 | /* If transitioning from no transaction directly to a write transaction, | ||||
| 75214 | ** block for the WRITER lock first if possible. */ | ||||
| 75215 | if( pBt->pPage1==0 && wrflag ){ | ||||
| 75216 | assert( pBt->inTransaction==TRANS_NONE )((void) (0)); | ||||
| 75217 | rc = sqlite3PagerWalWriteLock(pPager, 1)0; | ||||
| 75218 | if( rc!=SQLITE_BUSY5 && rc!=SQLITE_OK0 ) break; | ||||
| 75219 | } | ||||
| 75220 | #endif | ||||
| 75221 | |||||
| 75222 | /* Call lockBtree() until either pBt->pPage1 is populated or | ||||
| 75223 | ** lockBtree() returns something other than SQLITE_OK. lockBtree() | ||||
| 75224 | ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after | ||||
| 75225 | ** reading page 1 it discovers that the page-size of the database | ||||
| 75226 | ** file is not pBt->pageSize. In this case lockBtree() will update | ||||
| 75227 | ** pBt->pageSize to the page-size of the file on disk. | ||||
| 75228 | */ | ||||
| 75229 | while( pBt->pPage1==0 && SQLITE_OK0==(rc = lockBtree(pBt)) ); | ||||
| 75230 | |||||
| 75231 | if( rc==SQLITE_OK0 && wrflag ){ | ||||
| 75232 | if( (pBt->btsFlags & BTS_READ_ONLY0x0001)!=0 ){ | ||||
| 75233 | rc = SQLITE_READONLY8; | ||||
| 75234 | }else{ | ||||
| 75235 | rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db)); | ||||
| 75236 | if( rc==SQLITE_OK0 ){ | ||||
| 75237 | rc = newDatabase(pBt); | ||||
| 75238 | }else if( rc==SQLITE_BUSY_SNAPSHOT(5 | (2<<8)) && pBt->inTransaction==TRANS_NONE0 ){ | ||||
| 75239 | /* if there was no transaction opened when this function was | ||||
| 75240 | ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error | ||||
| 75241 | ** code to SQLITE_BUSY. */ | ||||
| 75242 | rc = SQLITE_BUSY5; | ||||
| 75243 | } | ||||
| 75244 | } | ||||
| 75245 | } | ||||
| 75246 | |||||
| 75247 | if( rc!=SQLITE_OK0 ){ | ||||
| 75248 | (void)sqlite3PagerWalWriteLock(pPager, 0)0; | ||||
| 75249 | unlockBtreeIfUnused(pBt); | ||||
| 75250 | } | ||||
| 75251 | #if defined(SQLITE_ENABLE_SETLK_TIMEOUT) | ||||
| 75252 | if( rc==SQLITE_BUSY_TIMEOUT(5 | (3<<8)) ){ | ||||
| 75253 | /* If a blocking lock timed out, break out of the loop here so that | ||||
| 75254 | ** the busy-handler is not invoked. */ | ||||
| 75255 | break; | ||||
| 75256 | } | ||||
| 75257 | #endif | ||||
| 75258 | }while( (rc&0xFF)==SQLITE_BUSY5 && pBt->inTransaction==TRANS_NONE0 && | ||||
| 75259 | btreeInvokeBusyHandler(pBt) ); | ||||
| 75260 | sqlite3PagerWalDb(pPager, 0); | ||||
| 75261 | #ifdef SQLITE_ENABLE_SETLK_TIMEOUT | ||||
| 75262 | if( rc==SQLITE_BUSY_TIMEOUT(5 | (3<<8)) ) rc = SQLITE_BUSY5; | ||||
| 75263 | #endif | ||||
| 75264 | |||||
| 75265 | if( rc==SQLITE_OK0 ){ | ||||
| 75266 | if( p->inTrans==TRANS_NONE0 ){ | ||||
| 75267 | pBt->nTransaction++; | ||||
| 75268 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 75269 | if( p->sharable ){ | ||||
| 75270 | assert( p->lock.pBtree==p && p->lock.iTable==1 )((void) (0)); | ||||
| 75271 | p->lock.eLock = READ_LOCK1; | ||||
| 75272 | p->lock.pNext = pBt->pLock; | ||||
| 75273 | pBt->pLock = &p->lock; | ||||
| 75274 | } | ||||
| 75275 | #endif | ||||
| 75276 | } | ||||
| 75277 | p->inTrans = (wrflag?TRANS_WRITE2:TRANS_READ1); | ||||
| 75278 | if( p->inTrans>pBt->inTransaction ){ | ||||
| 75279 | pBt->inTransaction = p->inTrans; | ||||
| 75280 | } | ||||
| 75281 | if( wrflag ){ | ||||
| 75282 | MemPage *pPage1 = pBt->pPage1; | ||||
| 75283 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 75284 | assert( !pBt->pWriter )((void) (0)); | ||||
| 75285 | pBt->pWriter = p; | ||||
| 75286 | pBt->btsFlags &= ~BTS_EXCLUSIVE0x0040; | ||||
| 75287 | if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE0x0040; | ||||
| 75288 | #endif | ||||
| 75289 | |||||
| 75290 | /* If the db-size header field is incorrect (as it may be if an old | ||||
| 75291 | ** client has been writing the database file), update it now. Doing | ||||
| 75292 | ** this sooner rather than later means the database size can safely | ||||
| 75293 | ** re-read the database size from page 1 if a savepoint or transaction | ||||
| 75294 | ** rollback occurs within the transaction. | ||||
| 75295 | */ | ||||
| 75296 | if( pBt->nPage!=get4bytesqlite3Get4byte(&pPage1->aData[28]) ){ | ||||
| 75297 | rc = sqlite3PagerWrite(pPage1->pDbPage); | ||||
| 75298 | if( rc==SQLITE_OK0 ){ | ||||
| 75299 | put4bytesqlite3Put4byte(&pPage1->aData[28], pBt->nPage); | ||||
| 75300 | } | ||||
| 75301 | } | ||||
| 75302 | } | ||||
| 75303 | } | ||||
| 75304 | |||||
| 75305 | trans_begun: | ||||
| 75306 | if( rc==SQLITE_OK0 ){ | ||||
| 75307 | if( pSchemaVersion ){ | ||||
| 75308 | *pSchemaVersion = get4bytesqlite3Get4byte(&pBt->pPage1->aData[40]); | ||||
| 75309 | } | ||||
| 75310 | if( wrflag ){ | ||||
| 75311 | /* This call makes sure that the pager has the correct number of | ||||
| 75312 | ** open savepoints. If the second parameter is greater than 0 and | ||||
| 75313 | ** the sub-journal is not already open, then it will be opened here. | ||||
| 75314 | */ | ||||
| 75315 | rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint); | ||||
| 75316 | } | ||||
| 75317 | } | ||||
| 75318 | |||||
| 75319 | btreeIntegrity(p)((void) (0)); ((void) (0));; | ||||
| 75320 | sqlite3BtreeLeave(p); | ||||
| 75321 | return rc; | ||||
| 75322 | } | ||||
| 75323 | SQLITE_PRIVATEstatic int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){ | ||||
| 75324 | BtShared *pBt; | ||||
| 75325 | if( p->sharable | ||||
| 75326 | || p->inTrans==TRANS_NONE0 | ||||
| 75327 | || (p->inTrans==TRANS_READ1 && wrflag!=0) | ||||
| 75328 | ){ | ||||
| 75329 | return btreeBeginTrans(p,wrflag,pSchemaVersion); | ||||
| 75330 | } | ||||
| 75331 | pBt = p->pBt; | ||||
| 75332 | if( pSchemaVersion ){ | ||||
| 75333 | *pSchemaVersion = get4bytesqlite3Get4byte(&pBt->pPage1->aData[40]); | ||||
| 75334 | } | ||||
| 75335 | if( wrflag ){ | ||||
| 75336 | /* This call makes sure that the pager has the correct number of | ||||
| 75337 | ** open savepoints. If the second parameter is greater than 0 and | ||||
| 75338 | ** the sub-journal is not already open, then it will be opened here. | ||||
| 75339 | */ | ||||
| 75340 | return sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint); | ||||
| 75341 | }else{ | ||||
| 75342 | return SQLITE_OK0; | ||||
| 75343 | } | ||||
| 75344 | } | ||||
| 75345 | |||||
| 75346 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 75347 | |||||
| 75348 | /* | ||||
| 75349 | ** Set the pointer-map entries for all children of page pPage. Also, if | ||||
| 75350 | ** pPage contains cells that point to overflow pages, set the pointer | ||||
| 75351 | ** map entries for the overflow pages as well. | ||||
| 75352 | */ | ||||
| 75353 | static int setChildPtrmaps(MemPage *pPage){ | ||||
| 75354 | int i; /* Counter variable */ | ||||
| 75355 | int nCell; /* Number of cells in page pPage */ | ||||
| 75356 | int rc; /* Return code */ | ||||
| 75357 | BtShared *pBt = pPage->pBt; | ||||
| 75358 | Pgno pgno = pPage->pgno; | ||||
| 75359 | |||||
| 75360 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 75361 | rc = pPage->isInit ? SQLITE_OK0 : btreeInitPage(pPage); | ||||
| 75362 | if( rc!=SQLITE_OK0 ) return rc; | ||||
| 75363 | nCell = pPage->nCell; | ||||
| 75364 | |||||
| 75365 | for(i=0; i<nCell; i++){ | ||||
| 75366 | u8 *pCell = findCell(pPage, i)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(i)])[0]<<8 | (&(pPage)->aCellIdx [2*(i)])[1]))); | ||||
| 75367 | |||||
| 75368 | ptrmapPutOvflPtr(pPage, pPage, pCell, &rc); | ||||
| 75369 | |||||
| 75370 | if( !pPage->leaf ){ | ||||
| 75371 | Pgno childPgno = get4bytesqlite3Get4byte(pCell); | ||||
| 75372 | ptrmapPut(pBt, childPgno, PTRMAP_BTREE5, pgno, &rc); | ||||
| 75373 | } | ||||
| 75374 | } | ||||
| 75375 | |||||
| 75376 | if( !pPage->leaf ){ | ||||
| 75377 | Pgno childPgno = get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8]); | ||||
| 75378 | ptrmapPut(pBt, childPgno, PTRMAP_BTREE5, pgno, &rc); | ||||
| 75379 | } | ||||
| 75380 | |||||
| 75381 | return rc; | ||||
| 75382 | } | ||||
| 75383 | |||||
| 75384 | /* | ||||
| 75385 | ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so | ||||
| 75386 | ** that it points to iTo. Parameter eType describes the type of pointer to | ||||
| 75387 | ** be modified, as follows: | ||||
| 75388 | ** | ||||
| 75389 | ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child | ||||
| 75390 | ** page of pPage. | ||||
| 75391 | ** | ||||
| 75392 | ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow | ||||
| 75393 | ** page pointed to by one of the cells on pPage. | ||||
| 75394 | ** | ||||
| 75395 | ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next | ||||
| 75396 | ** overflow page in the list. | ||||
| 75397 | */ | ||||
| 75398 | static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ | ||||
| 75399 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 75400 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 75401 | if( eType==PTRMAP_OVERFLOW24 ){ | ||||
| 75402 | /* The pointer is always the first 4 bytes of the page in this case. */ | ||||
| 75403 | if( get4bytesqlite3Get4byte(pPage->aData)!=iFrom ){ | ||||
| 75404 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(75404); | ||||
| 75405 | } | ||||
| 75406 | put4bytesqlite3Put4byte(pPage->aData, iTo); | ||||
| 75407 | }else{ | ||||
| 75408 | int i; | ||||
| 75409 | int nCell; | ||||
| 75410 | int rc; | ||||
| 75411 | |||||
| 75412 | rc = pPage->isInit ? SQLITE_OK0 : btreeInitPage(pPage); | ||||
| 75413 | if( rc ) return rc; | ||||
| 75414 | nCell = pPage->nCell; | ||||
| 75415 | |||||
| 75416 | for(i=0; i<nCell; i++){ | ||||
| 75417 | u8 *pCell = findCell(pPage, i)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(i)])[0]<<8 | (&(pPage)->aCellIdx [2*(i)])[1]))); | ||||
| 75418 | if( eType==PTRMAP_OVERFLOW13 ){ | ||||
| 75419 | CellInfo info; | ||||
| 75420 | pPage->xParseCell(pPage, pCell, &info); | ||||
| 75421 | if( info.nLocal<info.nPayload ){ | ||||
| 75422 | if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){ | ||||
| 75423 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(75423); | ||||
| 75424 | } | ||||
| 75425 | if( iFrom==get4bytesqlite3Get4byte(pCell+info.nSize-4) ){ | ||||
| 75426 | put4bytesqlite3Put4byte(pCell+info.nSize-4, iTo); | ||||
| 75427 | break; | ||||
| 75428 | } | ||||
| 75429 | } | ||||
| 75430 | }else{ | ||||
| 75431 | if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){ | ||||
| 75432 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(75432); | ||||
| 75433 | } | ||||
| 75434 | if( get4bytesqlite3Get4byte(pCell)==iFrom ){ | ||||
| 75435 | put4bytesqlite3Put4byte(pCell, iTo); | ||||
| 75436 | break; | ||||
| 75437 | } | ||||
| 75438 | } | ||||
| 75439 | } | ||||
| 75440 | |||||
| 75441 | if( i==nCell ){ | ||||
| 75442 | if( eType!=PTRMAP_BTREE5 || | ||||
| 75443 | get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ | ||||
| 75444 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(75444); | ||||
| 75445 | } | ||||
| 75446 | put4bytesqlite3Put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); | ||||
| 75447 | } | ||||
| 75448 | } | ||||
| 75449 | return SQLITE_OK0; | ||||
| 75450 | } | ||||
| 75451 | |||||
| 75452 | |||||
| 75453 | /* | ||||
| 75454 | ** Move the open database page pDbPage to location iFreePage in the | ||||
| 75455 | ** database. The pDbPage reference remains valid. | ||||
| 75456 | ** | ||||
| 75457 | ** The isCommit flag indicates that there is no need to remember that | ||||
| 75458 | ** the journal needs to be sync()ed before database page pDbPage->pgno | ||||
| 75459 | ** can be written to. The caller has already promised not to write to that | ||||
| 75460 | ** page. | ||||
| 75461 | */ | ||||
| 75462 | static int relocatePage( | ||||
| 75463 | BtShared *pBt, /* Btree */ | ||||
| 75464 | MemPage *pDbPage, /* Open page to move */ | ||||
| 75465 | u8 eType, /* Pointer map 'type' entry for pDbPage */ | ||||
| 75466 | Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ | ||||
| 75467 | Pgno iFreePage, /* The location to move pDbPage to */ | ||||
| 75468 | int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ | ||||
| 75469 | ){ | ||||
| 75470 | MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ | ||||
| 75471 | Pgno iDbPage = pDbPage->pgno; | ||||
| 75472 | Pager *pPager = pBt->pPager; | ||||
| 75473 | int rc; | ||||
| 75474 | |||||
| 75475 | assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||((void) (0)) | ||||
| 75476 | eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE )((void) (0)); | ||||
| 75477 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 75478 | assert( pDbPage->pBt==pBt )((void) (0)); | ||||
| 75479 | if( iDbPage<3 ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(75479); | ||||
| 75480 | |||||
| 75481 | /* Move page iDbPage from its current location to page number iFreePage */ | ||||
| 75482 | TRACE(("AUTOVACUUM: Moving %u to free page %u (ptr page %u type %u)\n", | ||||
| 75483 | iDbPage, iFreePage, iPtrPage, eType)); | ||||
| 75484 | rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); | ||||
| 75485 | if( rc!=SQLITE_OK0 ){ | ||||
| 75486 | return rc; | ||||
| 75487 | } | ||||
| 75488 | pDbPage->pgno = iFreePage; | ||||
| 75489 | |||||
| 75490 | /* If pDbPage was a btree-page, then it may have child pages and/or cells | ||||
| 75491 | ** that point to overflow pages. The pointer map entries for all these | ||||
| 75492 | ** pages need to be changed. | ||||
| 75493 | ** | ||||
| 75494 | ** If pDbPage is an overflow page, then the first 4 bytes may store a | ||||
| 75495 | ** pointer to a subsequent overflow page. If this is the case, then | ||||
| 75496 | ** the pointer map needs to be updated for the subsequent overflow page. | ||||
| 75497 | */ | ||||
| 75498 | if( eType==PTRMAP_BTREE5 || eType==PTRMAP_ROOTPAGE1 ){ | ||||
| 75499 | rc = setChildPtrmaps(pDbPage); | ||||
| 75500 | if( rc!=SQLITE_OK0 ){ | ||||
| 75501 | return rc; | ||||
| 75502 | } | ||||
| 75503 | }else{ | ||||
| 75504 | Pgno nextOvfl = get4bytesqlite3Get4byte(pDbPage->aData); | ||||
| 75505 | if( nextOvfl!=0 ){ | ||||
| 75506 | ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW24, iFreePage, &rc); | ||||
| 75507 | if( rc!=SQLITE_OK0 ){ | ||||
| 75508 | return rc; | ||||
| 75509 | } | ||||
| 75510 | } | ||||
| 75511 | } | ||||
| 75512 | |||||
| 75513 | /* Fix the database pointer on page iPtrPage that pointed at iDbPage so | ||||
| 75514 | ** that it points at iFreePage. Also fix the pointer map entry for | ||||
| 75515 | ** iPtrPage. | ||||
| 75516 | */ | ||||
| 75517 | if( eType!=PTRMAP_ROOTPAGE1 ){ | ||||
| 75518 | rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); | ||||
| 75519 | if( rc!=SQLITE_OK0 ){ | ||||
| 75520 | return rc; | ||||
| 75521 | } | ||||
| 75522 | rc = sqlite3PagerWrite(pPtrPage->pDbPage); | ||||
| 75523 | if( rc!=SQLITE_OK0 ){ | ||||
| 75524 | releasePage(pPtrPage); | ||||
| 75525 | return rc; | ||||
| 75526 | } | ||||
| 75527 | rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); | ||||
| 75528 | releasePage(pPtrPage); | ||||
| 75529 | if( rc==SQLITE_OK0 ){ | ||||
| 75530 | ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); | ||||
| 75531 | } | ||||
| 75532 | } | ||||
| 75533 | return rc; | ||||
| 75534 | } | ||||
| 75535 | |||||
| 75536 | /* Forward declaration required by incrVacuumStep(). */ | ||||
| 75537 | static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); | ||||
| 75538 | |||||
| 75539 | /* | ||||
| 75540 | ** Perform a single step of an incremental-vacuum. If successful, return | ||||
| 75541 | ** SQLITE_OK. If there is no work to do (and therefore no point in | ||||
| 75542 | ** calling this function again), return SQLITE_DONE. Or, if an error | ||||
| 75543 | ** occurs, return some other error code. | ||||
| 75544 | ** | ||||
| 75545 | ** More specifically, this function attempts to re-organize the database so | ||||
| 75546 | ** that the last page of the file currently in use is no longer in use. | ||||
| 75547 | ** | ||||
| 75548 | ** Parameter nFin is the number of pages that this database would contain | ||||
| 75549 | ** were this function called until it returns SQLITE_DONE. | ||||
| 75550 | ** | ||||
| 75551 | ** If the bCommit parameter is non-zero, this function assumes that the | ||||
| 75552 | ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE | ||||
| 75553 | ** or an error. bCommit is passed true for an auto-vacuum-on-commit | ||||
| 75554 | ** operation, or false for an incremental vacuum. | ||||
| 75555 | */ | ||||
| 75556 | static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ | ||||
| 75557 | Pgno nFreeList; /* Number of pages still on the free-list */ | ||||
| 75558 | int rc; | ||||
| 75559 | |||||
| 75560 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 75561 | assert( iLastPg>nFin )((void) (0)); | ||||
| 75562 | |||||
| 75563 | if( !PTRMAP_ISPAGE(pBt, iLastPg)(ptrmapPageno((pBt), (iLastPg))==(iLastPg)) && iLastPg!=PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ | ||||
| 75564 | u8 eType; | ||||
| 75565 | Pgno iPtrPage; | ||||
| 75566 | |||||
| 75567 | nFreeList = get4bytesqlite3Get4byte(&pBt->pPage1->aData[36]); | ||||
| 75568 | if( nFreeList==0 ){ | ||||
| 75569 | return SQLITE_DONE101; | ||||
| 75570 | } | ||||
| 75571 | |||||
| 75572 | rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); | ||||
| 75573 | if( rc!=SQLITE_OK0 ){ | ||||
| 75574 | return rc; | ||||
| 75575 | } | ||||
| 75576 | if( eType==PTRMAP_ROOTPAGE1 ){ | ||||
| 75577 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(75577); | ||||
| 75578 | } | ||||
| 75579 | |||||
| 75580 | if( eType==PTRMAP_FREEPAGE2 ){ | ||||
| 75581 | if( bCommit==0 ){ | ||||
| 75582 | /* Remove the page from the files free-list. This is not required | ||||
| 75583 | ** if bCommit is non-zero. In that case, the free-list will be | ||||
| 75584 | ** truncated to zero after this function returns, so it doesn't | ||||
| 75585 | ** matter if it still contains some garbage entries. | ||||
| 75586 | */ | ||||
| 75587 | Pgno iFreePg; | ||||
| 75588 | MemPage *pFreePg; | ||||
| 75589 | rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT1); | ||||
| 75590 | if( rc!=SQLITE_OK0 ){ | ||||
| 75591 | return rc; | ||||
| 75592 | } | ||||
| 75593 | assert( iFreePg==iLastPg )((void) (0)); | ||||
| 75594 | releasePage(pFreePg); | ||||
| 75595 | } | ||||
| 75596 | } else { | ||||
| 75597 | Pgno iFreePg; /* Index of free page to move pLastPg to */ | ||||
| 75598 | MemPage *pLastPg; | ||||
| 75599 | u8 eMode = BTALLOC_ANY0; /* Mode parameter for allocateBtreePage() */ | ||||
| 75600 | Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ | ||||
| 75601 | |||||
| 75602 | rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); | ||||
| 75603 | if( rc!=SQLITE_OK0 ){ | ||||
| 75604 | return rc; | ||||
| 75605 | } | ||||
| 75606 | |||||
| 75607 | /* If bCommit is zero, this loop runs exactly once and page pLastPg | ||||
| 75608 | ** is swapped with the first free page pulled off the free list. | ||||
| 75609 | ** | ||||
| 75610 | ** On the other hand, if bCommit is greater than zero, then keep | ||||
| 75611 | ** looping until a free-page located within the first nFin pages | ||||
| 75612 | ** of the file is found. | ||||
| 75613 | */ | ||||
| 75614 | if( bCommit==0 ){ | ||||
| 75615 | eMode = BTALLOC_LE2; | ||||
| 75616 | iNear = nFin; | ||||
| 75617 | } | ||||
| 75618 | do { | ||||
| 75619 | MemPage *pFreePg; | ||||
| 75620 | Pgno dbSize = btreePagecount(pBt); | ||||
| 75621 | rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); | ||||
| 75622 | if( rc!=SQLITE_OK0 ){ | ||||
| 75623 | releasePage(pLastPg); | ||||
| 75624 | return rc; | ||||
| 75625 | } | ||||
| 75626 | releasePage(pFreePg); | ||||
| 75627 | if( iFreePg>dbSize ){ | ||||
| 75628 | releasePage(pLastPg); | ||||
| 75629 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(75629); | ||||
| 75630 | } | ||||
| 75631 | }while( bCommit && iFreePg>nFin ); | ||||
| 75632 | assert( iFreePg<iLastPg )((void) (0)); | ||||
| 75633 | |||||
| 75634 | rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit); | ||||
| 75635 | releasePage(pLastPg); | ||||
| 75636 | if( rc!=SQLITE_OK0 ){ | ||||
| 75637 | return rc; | ||||
| 75638 | } | ||||
| 75639 | } | ||||
| 75640 | } | ||||
| 75641 | |||||
| 75642 | if( bCommit==0 ){ | ||||
| 75643 | do { | ||||
| 75644 | iLastPg--; | ||||
| 75645 | }while( iLastPg==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) || PTRMAP_ISPAGE(pBt, iLastPg)(ptrmapPageno((pBt), (iLastPg))==(iLastPg)) ); | ||||
| 75646 | pBt->bDoTruncate = 1; | ||||
| 75647 | pBt->nPage = iLastPg; | ||||
| 75648 | } | ||||
| 75649 | return SQLITE_OK0; | ||||
| 75650 | } | ||||
| 75651 | |||||
| 75652 | /* | ||||
| 75653 | ** The database opened by the first argument is an auto-vacuum database | ||||
| 75654 | ** nOrig pages in size containing nFree free pages. Return the expected | ||||
| 75655 | ** size of the database in pages following an auto-vacuum operation. | ||||
| 75656 | */ | ||||
| 75657 | static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ | ||||
| 75658 | int nEntry; /* Number of entries on one ptrmap page */ | ||||
| 75659 | Pgno nPtrmap; /* Number of PtrMap pages to be freed */ | ||||
| 75660 | Pgno nFin; /* Return value */ | ||||
| 75661 | |||||
| 75662 | nEntry = pBt->usableSize/5; | ||||
| 75663 | nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)ptrmapPageno(pBt, nOrig)+nEntry)/nEntry; | ||||
| 75664 | nFin = nOrig - nFree - nPtrmap; | ||||
| 75665 | if( nOrig>PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) && nFin<PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ | ||||
| 75666 | nFin--; | ||||
| 75667 | } | ||||
| 75668 | while( PTRMAP_ISPAGE(pBt, nFin)(ptrmapPageno((pBt), (nFin))==(nFin)) || nFin==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ | ||||
| 75669 | nFin--; | ||||
| 75670 | } | ||||
| 75671 | |||||
| 75672 | return nFin; | ||||
| 75673 | } | ||||
| 75674 | |||||
| 75675 | /* | ||||
| 75676 | ** A write-transaction must be opened before calling this function. | ||||
| 75677 | ** It performs a single unit of work towards an incremental vacuum. | ||||
| 75678 | ** | ||||
| 75679 | ** If the incremental vacuum is finished after this function has run, | ||||
| 75680 | ** SQLITE_DONE is returned. If it is not finished, but no error occurred, | ||||
| 75681 | ** SQLITE_OK is returned. Otherwise an SQLite error code. | ||||
| 75682 | */ | ||||
| 75683 | SQLITE_PRIVATEstatic int sqlite3BtreeIncrVacuum(Btree *p){ | ||||
| 75684 | int rc; | ||||
| 75685 | BtShared *pBt = p->pBt; | ||||
| 75686 | |||||
| 75687 | sqlite3BtreeEnter(p); | ||||
| 75688 | assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE )((void) (0)); | ||||
| 75689 | if( !pBt->autoVacuum ){ | ||||
| 75690 | rc = SQLITE_DONE101; | ||||
| 75691 | }else{ | ||||
| 75692 | Pgno nOrig = btreePagecount(pBt); | ||||
| 75693 | Pgno nFree = get4bytesqlite3Get4byte(&pBt->pPage1->aData[36]); | ||||
| 75694 | Pgno nFin = finalDbSize(pBt, nOrig, nFree); | ||||
| 75695 | |||||
| 75696 | if( nOrig<nFin || nFree>=nOrig ){ | ||||
| 75697 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(75697); | ||||
| 75698 | }else if( nFree>0 ){ | ||||
| 75699 | rc = saveAllCursors(pBt, 0, 0); | ||||
| 75700 | if( rc==SQLITE_OK0 ){ | ||||
| 75701 | invalidateAllOverflowCache(pBt); | ||||
| 75702 | rc = incrVacuumStep(pBt, nFin, nOrig, 0); | ||||
| 75703 | } | ||||
| 75704 | if( rc==SQLITE_OK0 ){ | ||||
| 75705 | rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | ||||
| 75706 | put4bytesqlite3Put4byte(&pBt->pPage1->aData[28], pBt->nPage); | ||||
| 75707 | } | ||||
| 75708 | }else{ | ||||
| 75709 | rc = SQLITE_DONE101; | ||||
| 75710 | } | ||||
| 75711 | } | ||||
| 75712 | sqlite3BtreeLeave(p); | ||||
| 75713 | return rc; | ||||
| 75714 | } | ||||
| 75715 | |||||
| 75716 | /* | ||||
| 75717 | ** This routine is called prior to sqlite3PagerCommit when a transaction | ||||
| 75718 | ** is committed for an auto-vacuum database. | ||||
| 75719 | */ | ||||
| 75720 | static int autoVacuumCommit(Btree *p){ | ||||
| 75721 | int rc = SQLITE_OK0; | ||||
| 75722 | Pager *pPager; | ||||
| 75723 | BtShared *pBt; | ||||
| 75724 | sqlite3 *db; | ||||
| 75725 | VVA_ONLY( int nRef ); | ||||
| 75726 | |||||
| 75727 | assert( p!=0 )((void) (0)); | ||||
| 75728 | pBt = p->pBt; | ||||
| 75729 | pPager = pBt->pPager; | ||||
| 75730 | VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); ) | ||||
| 75731 | |||||
| 75732 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 75733 | invalidateAllOverflowCache(pBt); | ||||
| 75734 | assert(pBt->autoVacuum)((void) (0)); | ||||
| 75735 | if( !pBt->incrVacuum ){ | ||||
| 75736 | Pgno nFin; /* Number of pages in database after autovacuuming */ | ||||
| 75737 | Pgno nFree; /* Number of pages on the freelist initially */ | ||||
| 75738 | Pgno nVac; /* Number of pages to vacuum */ | ||||
| 75739 | Pgno iFree; /* The next page to be freed */ | ||||
| 75740 | Pgno nOrig; /* Database size before freeing */ | ||||
| 75741 | |||||
| 75742 | nOrig = btreePagecount(pBt); | ||||
| 75743 | if( PTRMAP_ISPAGE(pBt, nOrig)(ptrmapPageno((pBt), (nOrig))==(nOrig)) || nOrig==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ | ||||
| 75744 | /* It is not possible to create a database for which the final page | ||||
| 75745 | ** is either a pointer-map page or the pending-byte page. If one | ||||
| 75746 | ** is encountered, this indicates corruption. | ||||
| 75747 | */ | ||||
| 75748 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(75748); | ||||
| 75749 | } | ||||
| 75750 | |||||
| 75751 | nFree = get4bytesqlite3Get4byte(&pBt->pPage1->aData[36]); | ||||
| 75752 | db = p->db; | ||||
| 75753 | if( db->xAutovacPages ){ | ||||
| 75754 | int iDb; | ||||
| 75755 | for(iDb=0; ALWAYS(iDb<db->nDb)(iDb<db->nDb); iDb++){ | ||||
| 75756 | if( db->aDb[iDb].pBt==p ) break; | ||||
| 75757 | } | ||||
| 75758 | nVac = db->xAutovacPages( | ||||
| 75759 | db->pAutovacPagesArg, | ||||
| 75760 | db->aDb[iDb].zDbSName, | ||||
| 75761 | nOrig, | ||||
| 75762 | nFree, | ||||
| 75763 | pBt->pageSize | ||||
| 75764 | ); | ||||
| 75765 | if( nVac>nFree ){ | ||||
| 75766 | nVac = nFree; | ||||
| 75767 | } | ||||
| 75768 | if( nVac==0 ){ | ||||
| 75769 | return SQLITE_OK0; | ||||
| 75770 | } | ||||
| 75771 | }else{ | ||||
| 75772 | nVac = nFree; | ||||
| 75773 | } | ||||
| 75774 | nFin = finalDbSize(pBt, nOrig, nVac); | ||||
| 75775 | if( nFin>nOrig ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(75775); | ||||
| 75776 | if( nFin<nOrig ){ | ||||
| 75777 | rc = saveAllCursors(pBt, 0, 0); | ||||
| 75778 | } | ||||
| 75779 | for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK0; iFree--){ | ||||
| 75780 | rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree); | ||||
| 75781 | } | ||||
| 75782 | if( (rc==SQLITE_DONE101 || rc==SQLITE_OK0) && nFree>0 ){ | ||||
| 75783 | rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | ||||
| 75784 | if( nVac==nFree ){ | ||||
| 75785 | put4bytesqlite3Put4byte(&pBt->pPage1->aData[32], 0); | ||||
| 75786 | put4bytesqlite3Put4byte(&pBt->pPage1->aData[36], 0); | ||||
| 75787 | } | ||||
| 75788 | put4bytesqlite3Put4byte(&pBt->pPage1->aData[28], nFin); | ||||
| 75789 | pBt->bDoTruncate = 1; | ||||
| 75790 | pBt->nPage = nFin; | ||||
| 75791 | } | ||||
| 75792 | if( rc!=SQLITE_OK0 ){ | ||||
| 75793 | sqlite3PagerRollback(pPager); | ||||
| 75794 | } | ||||
| 75795 | } | ||||
| 75796 | |||||
| 75797 | assert( nRef>=sqlite3PagerRefcount(pPager) )((void) (0)); | ||||
| 75798 | return rc; | ||||
| 75799 | } | ||||
| 75800 | |||||
| 75801 | #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ | ||||
| 75802 | # define setChildPtrmaps(x) SQLITE_OK0 | ||||
| 75803 | #endif | ||||
| 75804 | |||||
| 75805 | /* | ||||
| 75806 | ** This routine does the first phase of a two-phase commit. This routine | ||||
| 75807 | ** causes a rollback journal to be created (if it does not already exist) | ||||
| 75808 | ** and populated with enough information so that if a power loss occurs | ||||
| 75809 | ** the database can be restored to its original state by playing back | ||||
| 75810 | ** the journal. Then the contents of the journal are flushed out to | ||||
| 75811 | ** the disk. After the journal is safely on oxide, the changes to the | ||||
| 75812 | ** database are written into the database file and flushed to oxide. | ||||
| 75813 | ** At the end of this call, the rollback journal still exists on the | ||||
| 75814 | ** disk and we are still holding all locks, so the transaction has not | ||||
| 75815 | ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the | ||||
| 75816 | ** commit process. | ||||
| 75817 | ** | ||||
| 75818 | ** This call is a no-op if no write-transaction is currently active on pBt. | ||||
| 75819 | ** | ||||
| 75820 | ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to | ||||
| 75821 | ** the name of a super-journal file that should be written into the | ||||
| 75822 | ** individual journal file, or is NULL, indicating no super-journal file | ||||
| 75823 | ** (single database transaction). | ||||
| 75824 | ** | ||||
| 75825 | ** When this is called, the super-journal should already have been | ||||
| 75826 | ** created, populated with this journal pointer and synced to disk. | ||||
| 75827 | ** | ||||
| 75828 | ** Once this is routine has returned, the only thing required to commit | ||||
| 75829 | ** the write-transaction for this database file is to delete the journal. | ||||
| 75830 | */ | ||||
| 75831 | SQLITE_PRIVATEstatic int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){ | ||||
| 75832 | int rc = SQLITE_OK0; | ||||
| 75833 | if( p->inTrans==TRANS_WRITE2 ){ | ||||
| 75834 | BtShared *pBt = p->pBt; | ||||
| 75835 | sqlite3BtreeEnter(p); | ||||
| 75836 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 75837 | if( pBt->autoVacuum ){ | ||||
| 75838 | rc = autoVacuumCommit(p); | ||||
| 75839 | if( rc!=SQLITE_OK0 ){ | ||||
| 75840 | sqlite3BtreeLeave(p); | ||||
| 75841 | return rc; | ||||
| 75842 | } | ||||
| 75843 | } | ||||
| 75844 | if( pBt->bDoTruncate ){ | ||||
| 75845 | sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); | ||||
| 75846 | } | ||||
| 75847 | #endif | ||||
| 75848 | rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0); | ||||
| 75849 | sqlite3BtreeLeave(p); | ||||
| 75850 | } | ||||
| 75851 | return rc; | ||||
| 75852 | } | ||||
| 75853 | |||||
| 75854 | /* | ||||
| 75855 | ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() | ||||
| 75856 | ** at the conclusion of a transaction. | ||||
| 75857 | */ | ||||
| 75858 | static void btreeEndTransaction(Btree *p){ | ||||
| 75859 | BtShared *pBt = p->pBt; | ||||
| 75860 | sqlite3 *db = p->db; | ||||
| 75861 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 75862 | |||||
| 75863 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 75864 | pBt->bDoTruncate = 0; | ||||
| 75865 | #endif | ||||
| 75866 | if( p->inTrans>TRANS_NONE0 && db->nVdbeRead>1 ){ | ||||
| 75867 | /* If there are other active statements that belong to this database | ||||
| 75868 | ** handle, downgrade to a read-only transaction. The other statements | ||||
| 75869 | ** may still be reading from the database. */ | ||||
| 75870 | downgradeAllSharedCacheTableLocks(p); | ||||
| 75871 | p->inTrans = TRANS_READ1; | ||||
| 75872 | }else{ | ||||
| 75873 | /* If the handle had any kind of transaction open, decrement the | ||||
| 75874 | ** transaction count of the shared btree. If the transaction count | ||||
| 75875 | ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() | ||||
| 75876 | ** call below will unlock the pager. */ | ||||
| 75877 | if( p->inTrans!=TRANS_NONE0 ){ | ||||
| 75878 | clearAllSharedCacheTableLocks(p); | ||||
| 75879 | pBt->nTransaction--; | ||||
| 75880 | if( 0==pBt->nTransaction ){ | ||||
| 75881 | pBt->inTransaction = TRANS_NONE0; | ||||
| 75882 | } | ||||
| 75883 | } | ||||
| 75884 | |||||
| 75885 | /* Set the current transaction state to TRANS_NONE and unlock the | ||||
| 75886 | ** pager if this call closed the only read or write transaction. */ | ||||
| 75887 | p->inTrans = TRANS_NONE0; | ||||
| 75888 | unlockBtreeIfUnused(pBt); | ||||
| 75889 | } | ||||
| 75890 | |||||
| 75891 | btreeIntegrity(p)((void) (0)); ((void) (0));; | ||||
| 75892 | } | ||||
| 75893 | |||||
| 75894 | /* | ||||
| 75895 | ** Commit the transaction currently in progress. | ||||
| 75896 | ** | ||||
| 75897 | ** This routine implements the second phase of a 2-phase commit. The | ||||
| 75898 | ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should | ||||
| 75899 | ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() | ||||
| 75900 | ** routine did all the work of writing information out to disk and flushing the | ||||
| 75901 | ** contents so that they are written onto the disk platter. All this | ||||
| 75902 | ** routine has to do is delete or truncate or zero the header in the | ||||
| 75903 | ** the rollback journal (which causes the transaction to commit) and | ||||
| 75904 | ** drop locks. | ||||
| 75905 | ** | ||||
| 75906 | ** Normally, if an error occurs while the pager layer is attempting to | ||||
| 75907 | ** finalize the underlying journal file, this function returns an error and | ||||
| 75908 | ** the upper layer will attempt a rollback. However, if the second argument | ||||
| 75909 | ** is non-zero then this b-tree transaction is part of a multi-file | ||||
| 75910 | ** transaction. In this case, the transaction has already been committed | ||||
| 75911 | ** (by deleting a super-journal file) and the caller will ignore this | ||||
| 75912 | ** functions return code. So, even if an error occurs in the pager layer, | ||||
| 75913 | ** reset the b-tree objects internal state to indicate that the write | ||||
| 75914 | ** transaction has been closed. This is quite safe, as the pager will have | ||||
| 75915 | ** transitioned to the error state. | ||||
| 75916 | ** | ||||
| 75917 | ** This will release the write lock on the database file. If there | ||||
| 75918 | ** are no active cursors, it also releases the read lock. | ||||
| 75919 | */ | ||||
| 75920 | SQLITE_PRIVATEstatic int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ | ||||
| 75921 | |||||
| 75922 | if( p->inTrans==TRANS_NONE0 ) return SQLITE_OK0; | ||||
| 75923 | sqlite3BtreeEnter(p); | ||||
| 75924 | btreeIntegrity(p)((void) (0)); ((void) (0));; | ||||
| 75925 | |||||
| 75926 | /* If the handle has a write-transaction open, commit the shared-btrees | ||||
| 75927 | ** transaction and set the shared state to TRANS_READ. | ||||
| 75928 | */ | ||||
| 75929 | if( p->inTrans==TRANS_WRITE2 ){ | ||||
| 75930 | int rc; | ||||
| 75931 | BtShared *pBt = p->pBt; | ||||
| 75932 | assert( pBt->inTransaction==TRANS_WRITE )((void) (0)); | ||||
| 75933 | assert( pBt->nTransaction>0 )((void) (0)); | ||||
| 75934 | rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); | ||||
| 75935 | if( rc!=SQLITE_OK0 && bCleanup==0 ){ | ||||
| 75936 | sqlite3BtreeLeave(p); | ||||
| 75937 | return rc; | ||||
| 75938 | } | ||||
| 75939 | p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */ | ||||
| 75940 | pBt->inTransaction = TRANS_READ1; | ||||
| 75941 | btreeClearHasContent(pBt); | ||||
| 75942 | } | ||||
| 75943 | |||||
| 75944 | btreeEndTransaction(p); | ||||
| 75945 | sqlite3BtreeLeave(p); | ||||
| 75946 | return SQLITE_OK0; | ||||
| 75947 | } | ||||
| 75948 | |||||
| 75949 | /* | ||||
| 75950 | ** Do both phases of a commit. | ||||
| 75951 | */ | ||||
| 75952 | SQLITE_PRIVATEstatic int sqlite3BtreeCommit(Btree *p){ | ||||
| 75953 | int rc; | ||||
| 75954 | sqlite3BtreeEnter(p); | ||||
| 75955 | rc = sqlite3BtreeCommitPhaseOne(p, 0); | ||||
| 75956 | if( rc==SQLITE_OK0 ){ | ||||
| 75957 | rc = sqlite3BtreeCommitPhaseTwo(p, 0); | ||||
| 75958 | } | ||||
| 75959 | sqlite3BtreeLeave(p); | ||||
| 75960 | return rc; | ||||
| 75961 | } | ||||
| 75962 | |||||
| 75963 | /* | ||||
| 75964 | ** This routine sets the state to CURSOR_FAULT and the error | ||||
| 75965 | ** code to errCode for every cursor on any BtShared that pBtree | ||||
| 75966 | ** references. Or if the writeOnly flag is set to 1, then only | ||||
| 75967 | ** trip write cursors and leave read cursors unchanged. | ||||
| 75968 | ** | ||||
| 75969 | ** Every cursor is a candidate to be tripped, including cursors | ||||
| 75970 | ** that belong to other database connections that happen to be | ||||
| 75971 | ** sharing the cache with pBtree. | ||||
| 75972 | ** | ||||
| 75973 | ** This routine gets called when a rollback occurs. If the writeOnly | ||||
| 75974 | ** flag is true, then only write-cursors need be tripped - read-only | ||||
| 75975 | ** cursors save their current positions so that they may continue | ||||
| 75976 | ** following the rollback. Or, if writeOnly is false, all cursors are | ||||
| 75977 | ** tripped. In general, writeOnly is false if the transaction being | ||||
| 75978 | ** rolled back modified the database schema. In this case b-tree root | ||||
| 75979 | ** pages may be moved or deleted from the database altogether, making | ||||
| 75980 | ** it unsafe for read cursors to continue. | ||||
| 75981 | ** | ||||
| 75982 | ** If the writeOnly flag is true and an error is encountered while | ||||
| 75983 | ** saving the current position of a read-only cursor, all cursors, | ||||
| 75984 | ** including all read-cursors are tripped. | ||||
| 75985 | ** | ||||
| 75986 | ** SQLITE_OK is returned if successful, or if an error occurs while | ||||
| 75987 | ** saving a cursor position, an SQLite error code. | ||||
| 75988 | */ | ||||
| 75989 | SQLITE_PRIVATEstatic int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ | ||||
| 75990 | BtCursor *p; | ||||
| 75991 | int rc = SQLITE_OK0; | ||||
| 75992 | |||||
| 75993 | assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 )((void) (0)); | ||||
| 75994 | if( pBtree ){ | ||||
| 75995 | sqlite3BtreeEnter(pBtree); | ||||
| 75996 | for(p=pBtree->pBt->pCursor; p; p=p->pNext){ | ||||
| 75997 | if( writeOnly && (p->curFlags & BTCF_WriteFlag0x01)==0 ){ | ||||
| 75998 | if( p->eState==CURSOR_VALID0 || p->eState==CURSOR_SKIPNEXT2 ){ | ||||
| 75999 | rc = saveCursorPosition(p); | ||||
| 76000 | if( rc!=SQLITE_OK0 ){ | ||||
| 76001 | (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); | ||||
| 76002 | break; | ||||
| 76003 | } | ||||
| 76004 | } | ||||
| 76005 | }else{ | ||||
| 76006 | sqlite3BtreeClearCursor(p); | ||||
| 76007 | p->eState = CURSOR_FAULT4; | ||||
| 76008 | p->skipNext = errCode; | ||||
| 76009 | } | ||||
| 76010 | btreeReleaseAllCursorPages(p); | ||||
| 76011 | } | ||||
| 76012 | sqlite3BtreeLeave(pBtree); | ||||
| 76013 | } | ||||
| 76014 | return rc; | ||||
| 76015 | } | ||||
| 76016 | |||||
| 76017 | /* | ||||
| 76018 | ** Set the pBt->nPage field correctly, according to the current | ||||
| 76019 | ** state of the database. Assume pBt->pPage1 is valid. | ||||
| 76020 | */ | ||||
| 76021 | static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){ | ||||
| 76022 | int nPage = get4bytesqlite3Get4byte(&pPage1->aData[28]); | ||||
| 76023 | testcase( nPage==0 ); | ||||
| 76024 | if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); | ||||
| 76025 | testcase( pBt->nPage!=(u32)nPage ); | ||||
| 76026 | pBt->nPage = nPage; | ||||
| 76027 | } | ||||
| 76028 | |||||
| 76029 | /* | ||||
| 76030 | ** Rollback the transaction in progress. | ||||
| 76031 | ** | ||||
| 76032 | ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). | ||||
| 76033 | ** Only write cursors are tripped if writeOnly is true but all cursors are | ||||
| 76034 | ** tripped if writeOnly is false. Any attempt to use | ||||
| 76035 | ** a tripped cursor will result in an error. | ||||
| 76036 | ** | ||||
| 76037 | ** This will release the write lock on the database file. If there | ||||
| 76038 | ** are no active cursors, it also releases the read lock. | ||||
| 76039 | */ | ||||
| 76040 | SQLITE_PRIVATEstatic int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ | ||||
| 76041 | int rc; | ||||
| 76042 | BtShared *pBt = p->pBt; | ||||
| 76043 | MemPage *pPage1; | ||||
| 76044 | |||||
| 76045 | assert( writeOnly==1 || writeOnly==0 )((void) (0)); | ||||
| 76046 | assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK )((void) (0)); | ||||
| 76047 | sqlite3BtreeEnter(p); | ||||
| 76048 | if( tripCode==SQLITE_OK0 ){ | ||||
| 76049 | rc = tripCode = saveAllCursors(pBt, 0, 0); | ||||
| 76050 | if( rc ) writeOnly = 0; | ||||
| 76051 | }else{ | ||||
| 76052 | rc = SQLITE_OK0; | ||||
| 76053 | } | ||||
| 76054 | if( tripCode ){ | ||||
| 76055 | int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); | ||||
| 76056 | assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) )((void) (0)); | ||||
| 76057 | if( rc2!=SQLITE_OK0 ) rc = rc2; | ||||
| 76058 | } | ||||
| 76059 | btreeIntegrity(p)((void) (0)); ((void) (0));; | ||||
| 76060 | |||||
| 76061 | if( p->inTrans==TRANS_WRITE2 ){ | ||||
| 76062 | int rc2; | ||||
| 76063 | |||||
| 76064 | assert( TRANS_WRITE==pBt->inTransaction )((void) (0)); | ||||
| 76065 | rc2 = sqlite3PagerRollback(pBt->pPager); | ||||
| 76066 | if( rc2!=SQLITE_OK0 ){ | ||||
| 76067 | rc = rc2; | ||||
| 76068 | } | ||||
| 76069 | |||||
| 76070 | /* The rollback may have destroyed the pPage1->aData value. So | ||||
| 76071 | ** call btreeGetPage() on page 1 again to make | ||||
| 76072 | ** sure pPage1->aData is set correctly. */ | ||||
| 76073 | if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK0 ){ | ||||
| 76074 | btreeSetNPage(pBt, pPage1); | ||||
| 76075 | releasePageOne(pPage1); | ||||
| 76076 | } | ||||
| 76077 | assert( countValidCursors(pBt, 1)==0 )((void) (0)); | ||||
| 76078 | pBt->inTransaction = TRANS_READ1; | ||||
| 76079 | btreeClearHasContent(pBt); | ||||
| 76080 | } | ||||
| 76081 | |||||
| 76082 | btreeEndTransaction(p); | ||||
| 76083 | sqlite3BtreeLeave(p); | ||||
| 76084 | return rc; | ||||
| 76085 | } | ||||
| 76086 | |||||
| 76087 | /* | ||||
| 76088 | ** Start a statement subtransaction. The subtransaction can be rolled | ||||
| 76089 | ** back independently of the main transaction. You must start a transaction | ||||
| 76090 | ** before starting a subtransaction. The subtransaction is ended automatically | ||||
| 76091 | ** if the main transaction commits or rolls back. | ||||
| 76092 | ** | ||||
| 76093 | ** Statement subtransactions are used around individual SQL statements | ||||
| 76094 | ** that are contained within a BEGIN...COMMIT block. If a constraint | ||||
| 76095 | ** error occurs within the statement, the effect of that one statement | ||||
| 76096 | ** can be rolled back without having to rollback the entire transaction. | ||||
| 76097 | ** | ||||
| 76098 | ** A statement sub-transaction is implemented as an anonymous savepoint. The | ||||
| 76099 | ** value passed as the second parameter is the total number of savepoints, | ||||
| 76100 | ** including the new anonymous savepoint, open on the B-Tree. i.e. if there | ||||
| 76101 | ** are no active savepoints and no other statement-transactions open, | ||||
| 76102 | ** iStatement is 1. This anonymous savepoint can be released or rolled back | ||||
| 76103 | ** using the sqlite3BtreeSavepoint() function. | ||||
| 76104 | */ | ||||
| 76105 | SQLITE_PRIVATEstatic int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ | ||||
| 76106 | int rc; | ||||
| 76107 | BtShared *pBt = p->pBt; | ||||
| 76108 | sqlite3BtreeEnter(p); | ||||
| 76109 | assert( p->inTrans==TRANS_WRITE )((void) (0)); | ||||
| 76110 | assert( (pBt->btsFlags & BTS_READ_ONLY)==0 )((void) (0)); | ||||
| 76111 | assert( iStatement>0 )((void) (0)); | ||||
| 76112 | assert( iStatement>p->db->nSavepoint )((void) (0)); | ||||
| 76113 | assert( pBt->inTransaction==TRANS_WRITE )((void) (0)); | ||||
| 76114 | /* At the pager level, a statement transaction is a savepoint with | ||||
| 76115 | ** an index greater than all savepoints created explicitly using | ||||
| 76116 | ** SQL statements. It is illegal to open, release or rollback any | ||||
| 76117 | ** such savepoints while the statement transaction savepoint is active. | ||||
| 76118 | */ | ||||
| 76119 | rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); | ||||
| 76120 | sqlite3BtreeLeave(p); | ||||
| 76121 | return rc; | ||||
| 76122 | } | ||||
| 76123 | |||||
| 76124 | /* | ||||
| 76125 | ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK | ||||
| 76126 | ** or SAVEPOINT_RELEASE. This function either releases or rolls back the | ||||
| 76127 | ** savepoint identified by parameter iSavepoint, depending on the value | ||||
| 76128 | ** of op. | ||||
| 76129 | ** | ||||
| 76130 | ** Normally, iSavepoint is greater than or equal to zero. However, if op is | ||||
| 76131 | ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the | ||||
| 76132 | ** contents of the entire transaction are rolled back. This is different | ||||
| 76133 | ** from a normal transaction rollback, as no locks are released and the | ||||
| 76134 | ** transaction remains open. | ||||
| 76135 | */ | ||||
| 76136 | SQLITE_PRIVATEstatic int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ | ||||
| 76137 | int rc = SQLITE_OK0; | ||||
| 76138 | if( p && p->inTrans==TRANS_WRITE2 ){ | ||||
| 76139 | BtShared *pBt = p->pBt; | ||||
| 76140 | assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK )((void) (0)); | ||||
| 76141 | assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) )((void) (0)); | ||||
| 76142 | sqlite3BtreeEnter(p); | ||||
| 76143 | if( op==SAVEPOINT_ROLLBACK2 ){ | ||||
| 76144 | rc = saveAllCursors(pBt, 0, 0); | ||||
| 76145 | } | ||||
| 76146 | if( rc==SQLITE_OK0 ){ | ||||
| 76147 | rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); | ||||
| 76148 | } | ||||
| 76149 | if( rc==SQLITE_OK0 ){ | ||||
| 76150 | if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY0x0010)!=0 ){ | ||||
| 76151 | pBt->nPage = 0; | ||||
| 76152 | } | ||||
| 76153 | rc = newDatabase(pBt); | ||||
| 76154 | btreeSetNPage(pBt, pBt->pPage1); | ||||
| 76155 | |||||
| 76156 | /* pBt->nPage might be zero if the database was corrupt when | ||||
| 76157 | ** the transaction was started. Otherwise, it must be at least 1. */ | ||||
| 76158 | assert( CORRUPT_DB || pBt->nPage>0 )((void) (0)); | ||||
| 76159 | } | ||||
| 76160 | sqlite3BtreeLeave(p); | ||||
| 76161 | } | ||||
| 76162 | return rc; | ||||
| 76163 | } | ||||
| 76164 | |||||
| 76165 | /* | ||||
| 76166 | ** Create a new cursor for the BTree whose root is on the page | ||||
| 76167 | ** iTable. If a read-only cursor is requested, it is assumed that | ||||
| 76168 | ** the caller already has at least a read-only transaction open | ||||
| 76169 | ** on the database already. If a write-cursor is requested, then | ||||
| 76170 | ** the caller is assumed to have an open write transaction. | ||||
| 76171 | ** | ||||
| 76172 | ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only | ||||
| 76173 | ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor | ||||
| 76174 | ** can be used for reading or for writing if other conditions for writing | ||||
| 76175 | ** are also met. These are the conditions that must be met in order | ||||
| 76176 | ** for writing to be allowed: | ||||
| 76177 | ** | ||||
| 76178 | ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR | ||||
| 76179 | ** | ||||
| 76180 | ** 2: Other database connections that share the same pager cache | ||||
| 76181 | ** but which are not in the READ_UNCOMMITTED state may not have | ||||
| 76182 | ** cursors open with wrFlag==0 on the same table. Otherwise | ||||
| 76183 | ** the changes made by this write cursor would be visible to | ||||
| 76184 | ** the read cursors in the other database connection. | ||||
| 76185 | ** | ||||
| 76186 | ** 3: The database must be writable (not on read-only media) | ||||
| 76187 | ** | ||||
| 76188 | ** 4: There must be an active transaction. | ||||
| 76189 | ** | ||||
| 76190 | ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR | ||||
| 76191 | ** is set. If FORDELETE is set, that is a hint to the implementation that | ||||
| 76192 | ** this cursor will only be used to seek to and delete entries of an index | ||||
| 76193 | ** as part of a larger DELETE statement. The FORDELETE hint is not used by | ||||
| 76194 | ** this implementation. But in a hypothetical alternative storage engine | ||||
| 76195 | ** in which index entries are automatically deleted when corresponding table | ||||
| 76196 | ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE | ||||
| 76197 | ** operations on this cursor can be no-ops and all READ operations can | ||||
| 76198 | ** return a null row (2-bytes: 0x01 0x00). | ||||
| 76199 | ** | ||||
| 76200 | ** No checking is done to make sure that page iTable really is the | ||||
| 76201 | ** root page of a b-tree. If it is not, then the cursor acquired | ||||
| 76202 | ** will not work correctly. | ||||
| 76203 | ** | ||||
| 76204 | ** It is assumed that the sqlite3BtreeCursorZero() has been called | ||||
| 76205 | ** on pCur to initialize the memory space prior to invoking this routine. | ||||
| 76206 | */ | ||||
| 76207 | static int btreeCursor( | ||||
| 76208 | Btree *p, /* The btree */ | ||||
| 76209 | Pgno iTable, /* Root page of table to open */ | ||||
| 76210 | int wrFlag, /* 1 to write. 0 read-only */ | ||||
| 76211 | struct KeyInfo *pKeyInfo, /* First arg to comparison function */ | ||||
| 76212 | BtCursor *pCur /* Space for new cursor */ | ||||
| 76213 | ){ | ||||
| 76214 | BtShared *pBt = p->pBt; /* Shared b-tree handle */ | ||||
| 76215 | BtCursor *pX; /* Looping over other all cursors */ | ||||
| 76216 | |||||
| 76217 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 76218 | assert( wrFlag==0((void) (0)) | ||||
| 76219 | || wrFlag==BTREE_WRCSR((void) (0)) | ||||
| 76220 | || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)((void) (0)) | ||||
| 76221 | )((void) (0)); | ||||
| 76222 | |||||
| 76223 | /* The following assert statements verify that if this is a sharable | ||||
| 76224 | ** b-tree database, the connection is holding the required table locks, | ||||
| 76225 | ** and that no other connection has any open cursor that conflicts with | ||||
| 76226 | ** this lock. The iTable<1 term disables the check for corrupt schemas. */ | ||||
| 76227 | assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))((void) (0)) | ||||
| 76228 | || iTable<1 )((void) (0)); | ||||
| 76229 | assert( wrFlag==0 || !hasReadConflicts(p, iTable) )((void) (0)); | ||||
| 76230 | |||||
| 76231 | /* Assert that the caller has opened the required transaction. */ | ||||
| 76232 | assert( p->inTrans>TRANS_NONE )((void) (0)); | ||||
| 76233 | assert( wrFlag==0 || p->inTrans==TRANS_WRITE )((void) (0)); | ||||
| 76234 | assert( pBt->pPage1 && pBt->pPage1->aData )((void) (0)); | ||||
| 76235 | assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 )((void) (0)); | ||||
| 76236 | |||||
| 76237 | if( iTable<=1 ){ | ||||
| 76238 | if( iTable<1 ){ | ||||
| 76239 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(76239); | ||||
| 76240 | }else if( btreePagecount(pBt)==0 ){ | ||||
| 76241 | assert( wrFlag==0 )((void) (0)); | ||||
| 76242 | iTable = 0; | ||||
| 76243 | } | ||||
| 76244 | } | ||||
| 76245 | |||||
| 76246 | /* Now that no other errors can occur, finish filling in the BtCursor | ||||
| 76247 | ** variables and link the cursor into the BtShared list. */ | ||||
| 76248 | pCur->pgnoRoot = iTable; | ||||
| 76249 | pCur->iPage = -1; | ||||
| 76250 | pCur->pKeyInfo = pKeyInfo; | ||||
| 76251 | pCur->pBtree = p; | ||||
| 76252 | pCur->pBt = pBt; | ||||
| 76253 | pCur->curFlags = 0; | ||||
| 76254 | /* If there are two or more cursors on the same btree, then all such | ||||
| 76255 | ** cursors *must* have the BTCF_Multiple flag set. */ | ||||
| 76256 | for(pX=pBt->pCursor; pX; pX=pX->pNext){ | ||||
| 76257 | if( pX->pgnoRoot==iTable ){ | ||||
| 76258 | pX->curFlags |= BTCF_Multiple0x20; | ||||
| 76259 | pCur->curFlags = BTCF_Multiple0x20; | ||||
| 76260 | } | ||||
| 76261 | } | ||||
| 76262 | pCur->eState = CURSOR_INVALID1; | ||||
| 76263 | pCur->pNext = pBt->pCursor; | ||||
| 76264 | pBt->pCursor = pCur; | ||||
| 76265 | if( wrFlag ){ | ||||
| 76266 | pCur->curFlags |= BTCF_WriteFlag0x01; | ||||
| 76267 | pCur->curPagerFlags = 0; | ||||
| 76268 | if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt); | ||||
| 76269 | }else{ | ||||
| 76270 | pCur->curPagerFlags = PAGER_GET_READONLY0x02; | ||||
| 76271 | } | ||||
| 76272 | return SQLITE_OK0; | ||||
| 76273 | } | ||||
| 76274 | static int btreeCursorWithLock( | ||||
| 76275 | Btree *p, /* The btree */ | ||||
| 76276 | Pgno iTable, /* Root page of table to open */ | ||||
| 76277 | int wrFlag, /* 1 to write. 0 read-only */ | ||||
| 76278 | struct KeyInfo *pKeyInfo, /* First arg to comparison function */ | ||||
| 76279 | BtCursor *pCur /* Space for new cursor */ | ||||
| 76280 | ){ | ||||
| 76281 | int rc; | ||||
| 76282 | sqlite3BtreeEnter(p); | ||||
| 76283 | rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); | ||||
| 76284 | sqlite3BtreeLeave(p); | ||||
| 76285 | return rc; | ||||
| 76286 | } | ||||
| 76287 | SQLITE_PRIVATEstatic int sqlite3BtreeCursor( | ||||
| 76288 | Btree *p, /* The btree */ | ||||
| 76289 | Pgno iTable, /* Root page of table to open */ | ||||
| 76290 | int wrFlag, /* 1 to write. 0 read-only */ | ||||
| 76291 | struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ | ||||
| 76292 | BtCursor *pCur /* Write new cursor here */ | ||||
| 76293 | ){ | ||||
| 76294 | if( p->sharable ){ | ||||
| 76295 | return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur); | ||||
| 76296 | }else{ | ||||
| 76297 | return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); | ||||
| 76298 | } | ||||
| 76299 | } | ||||
| 76300 | |||||
| 76301 | /* | ||||
| 76302 | ** Return the size of a BtCursor object in bytes. | ||||
| 76303 | ** | ||||
| 76304 | ** This interfaces is needed so that users of cursors can preallocate | ||||
| 76305 | ** sufficient storage to hold a cursor. The BtCursor object is opaque | ||||
| 76306 | ** to users so they cannot do the sizeof() themselves - they must call | ||||
| 76307 | ** this routine. | ||||
| 76308 | */ | ||||
| 76309 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorSize(void){ | ||||
| 76310 | return ROUND8(sizeof(BtCursor))(((sizeof(BtCursor))+7)&~7); | ||||
| 76311 | } | ||||
| 76312 | |||||
| 76313 | #ifdef SQLITE_DEBUG | ||||
| 76314 | /* | ||||
| 76315 | ** Return true if and only if the Btree object will be automatically | ||||
| 76316 | ** closed with the BtCursor closes. This is used within assert() statements | ||||
| 76317 | ** only. | ||||
| 76318 | */ | ||||
| 76319 | SQLITE_PRIVATEstatic int sqlite3BtreeClosesWithCursor( | ||||
| 76320 | Btree *pBtree, /* the btree object */ | ||||
| 76321 | BtCursor *pCur /* Corresponding cursor */ | ||||
| 76322 | ){ | ||||
| 76323 | BtShared *pBt = pBtree->pBt; | ||||
| 76324 | if( (pBt->openFlags & BTREE_SINGLE4)==0 ) return 0; | ||||
| 76325 | if( pBt->pCursor!=pCur ) return 0; | ||||
| 76326 | if( pCur->pNext!=0 ) return 0; | ||||
| 76327 | if( pCur->pBtree!=pBtree ) return 0; | ||||
| 76328 | return 1; | ||||
| 76329 | } | ||||
| 76330 | #endif | ||||
| 76331 | |||||
| 76332 | /* | ||||
| 76333 | ** Initialize memory that will be converted into a BtCursor object. | ||||
| 76334 | ** | ||||
| 76335 | ** The simple approach here would be to memset() the entire object | ||||
| 76336 | ** to zero. But it turns out that the apPage[] and aiIdx[] arrays | ||||
| 76337 | ** do not need to be zeroed and they are large, so we can save a lot | ||||
| 76338 | ** of run-time by skipping the initialization of those elements. | ||||
| 76339 | */ | ||||
| 76340 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorZero(BtCursor *p){ | ||||
| 76341 | memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT)__builtin_offsetof(BtCursor, pBt)); | ||||
| 76342 | } | ||||
| 76343 | |||||
| 76344 | /* | ||||
| 76345 | ** Close a cursor. The read lock on the database file is released | ||||
| 76346 | ** when the last cursor is closed. | ||||
| 76347 | */ | ||||
| 76348 | SQLITE_PRIVATEstatic int sqlite3BtreeCloseCursor(BtCursor *pCur){ | ||||
| 76349 | Btree *pBtree = pCur->pBtree; | ||||
| 76350 | if( pBtree ){ | ||||
| 76351 | BtShared *pBt = pCur->pBt; | ||||
| 76352 | sqlite3BtreeEnter(pBtree); | ||||
| 76353 | assert( pBt->pCursor!=0 )((void) (0)); | ||||
| 76354 | if( pBt->pCursor==pCur ){ | ||||
| 76355 | pBt->pCursor = pCur->pNext; | ||||
| 76356 | }else{ | ||||
| 76357 | BtCursor *pPrev = pBt->pCursor; | ||||
| 76358 | do{ | ||||
| 76359 | if( pPrev->pNext==pCur ){ | ||||
| 76360 | pPrev->pNext = pCur->pNext; | ||||
| 76361 | break; | ||||
| 76362 | } | ||||
| 76363 | pPrev = pPrev->pNext; | ||||
| 76364 | }while( ALWAYS(pPrev)(pPrev) ); | ||||
| 76365 | } | ||||
| 76366 | btreeReleaseAllCursorPages(pCur); | ||||
| 76367 | unlockBtreeIfUnused(pBt); | ||||
| 76368 | sqlite3_free(pCur->aOverflow); | ||||
| 76369 | sqlite3_free(pCur->pKey); | ||||
| 76370 | if( (pBt->openFlags & BTREE_SINGLE4) && pBt->pCursor==0 ){ | ||||
| 76371 | /* Since the BtShared is not sharable, there is no need to | ||||
| 76372 | ** worry about the missing sqlite3BtreeLeave() call here. */ | ||||
| 76373 | assert( pBtree->sharable==0 )((void) (0)); | ||||
| 76374 | sqlite3BtreeClose(pBtree); | ||||
| 76375 | }else{ | ||||
| 76376 | sqlite3BtreeLeave(pBtree); | ||||
| 76377 | } | ||||
| 76378 | pCur->pBtree = 0; | ||||
| 76379 | } | ||||
| 76380 | return SQLITE_OK0; | ||||
| 76381 | } | ||||
| 76382 | |||||
| 76383 | /* | ||||
| 76384 | ** Make sure the BtCursor* given in the argument has a valid | ||||
| 76385 | ** BtCursor.info structure. If it is not already valid, call | ||||
| 76386 | ** btreeParseCell() to fill it in. | ||||
| 76387 | ** | ||||
| 76388 | ** BtCursor.info is a cache of the information in the current cell. | ||||
| 76389 | ** Using this cache reduces the number of calls to btreeParseCell(). | ||||
| 76390 | */ | ||||
| 76391 | #ifndef NDEBUG1 | ||||
| 76392 | static int cellInfoEqual(CellInfo *a, CellInfo *b){ | ||||
| 76393 | if( a->nKey!=b->nKey ) return 0; | ||||
| 76394 | if( a->pPayload!=b->pPayload ) return 0; | ||||
| 76395 | if( a->nPayload!=b->nPayload ) return 0; | ||||
| 76396 | if( a->nLocal!=b->nLocal ) return 0; | ||||
| 76397 | if( a->nSize!=b->nSize ) return 0; | ||||
| 76398 | return 1; | ||||
| 76399 | } | ||||
| 76400 | static void assertCellInfo(BtCursor *pCur){ | ||||
| 76401 | CellInfo info; | ||||
| 76402 | memset(&info, 0, sizeof(info)); | ||||
| 76403 | btreeParseCell(pCur->pPage, pCur->ix, &info); | ||||
| 76404 | assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) )((void) (0)); | ||||
| 76405 | } | ||||
| 76406 | #else | ||||
| 76407 | #define assertCellInfo(x) | ||||
| 76408 | #endif | ||||
| 76409 | static SQLITE_NOINLINE__attribute__((noinline)) void getCellInfo(BtCursor *pCur){ | ||||
| 76410 | if( pCur->info.nSize==0 ){ | ||||
| 76411 | pCur->curFlags |= BTCF_ValidNKey0x02; | ||||
| 76412 | btreeParseCell(pCur->pPage,pCur->ix,&pCur->info); | ||||
| 76413 | }else{ | ||||
| 76414 | assertCellInfo(pCur); | ||||
| 76415 | } | ||||
| 76416 | } | ||||
| 76417 | |||||
| 76418 | #ifndef NDEBUG1 /* The next routine used only within assert() statements */ | ||||
| 76419 | /* | ||||
| 76420 | ** Return true if the given BtCursor is valid. A valid cursor is one | ||||
| 76421 | ** that is currently pointing to a row in a (non-empty) table. | ||||
| 76422 | ** This is a verification routine is used only within assert() statements. | ||||
| 76423 | */ | ||||
| 76424 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorIsValid(BtCursor *pCur){ | ||||
| 76425 | return pCur && pCur->eState==CURSOR_VALID0; | ||||
| 76426 | } | ||||
| 76427 | #endif /* NDEBUG */ | ||||
| 76428 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){ | ||||
| 76429 | assert( pCur!=0 )((void) (0)); | ||||
| 76430 | return pCur->eState==CURSOR_VALID0; | ||||
| 76431 | } | ||||
| 76432 | |||||
| 76433 | /* | ||||
| 76434 | ** Return the value of the integer key or "rowid" for a table btree. | ||||
| 76435 | ** This routine is only valid for a cursor that is pointing into a | ||||
| 76436 | ** ordinary table btree. If the cursor points to an index btree or | ||||
| 76437 | ** is invalid, the result of this routine is undefined. | ||||
| 76438 | */ | ||||
| 76439 | SQLITE_PRIVATEstatic i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ | ||||
| 76440 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 76441 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76442 | assert( pCur->curIntKey )((void) (0)); | ||||
| 76443 | getCellInfo(pCur); | ||||
| 76444 | return pCur->info.nKey; | ||||
| 76445 | } | ||||
| 76446 | |||||
| 76447 | /* | ||||
| 76448 | ** Pin or unpin a cursor. | ||||
| 76449 | */ | ||||
| 76450 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorPin(BtCursor *pCur){ | ||||
| 76451 | assert( (pCur->curFlags & BTCF_Pinned)==0 )((void) (0)); | ||||
| 76452 | pCur->curFlags |= BTCF_Pinned0x40; | ||||
| 76453 | } | ||||
| 76454 | SQLITE_PRIVATEstatic void sqlite3BtreeCursorUnpin(BtCursor *pCur){ | ||||
| 76455 | assert( (pCur->curFlags & BTCF_Pinned)!=0 )((void) (0)); | ||||
| 76456 | pCur->curFlags &= ~BTCF_Pinned0x40; | ||||
| 76457 | } | ||||
| 76458 | |||||
| 76459 | /* | ||||
| 76460 | ** Return the offset into the database file for the start of the | ||||
| 76461 | ** payload to which the cursor is pointing. | ||||
| 76462 | */ | ||||
| 76463 | SQLITE_PRIVATEstatic i64 sqlite3BtreeOffset(BtCursor *pCur){ | ||||
| 76464 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 76465 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76466 | getCellInfo(pCur); | ||||
| 76467 | return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) + | ||||
| 76468 | (i64)(pCur->info.pPayload - pCur->pPage->aData); | ||||
| 76469 | } | ||||
| 76470 | |||||
| 76471 | /* | ||||
| 76472 | ** Return the number of bytes of payload for the entry that pCur is | ||||
| 76473 | ** currently pointing to. For table btrees, this will be the amount | ||||
| 76474 | ** of data. For index btrees, this will be the size of the key. | ||||
| 76475 | ** | ||||
| 76476 | ** The caller must guarantee that the cursor is pointing to a non-NULL | ||||
| 76477 | ** valid entry. In other words, the calling procedure must guarantee | ||||
| 76478 | ** that the cursor has Cursor.eState==CURSOR_VALID. | ||||
| 76479 | */ | ||||
| 76480 | SQLITE_PRIVATEstatic u32 sqlite3BtreePayloadSize(BtCursor *pCur){ | ||||
| 76481 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 76482 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76483 | getCellInfo(pCur); | ||||
| 76484 | return pCur->info.nPayload; | ||||
| 76485 | } | ||||
| 76486 | |||||
| 76487 | /* | ||||
| 76488 | ** Return an upper bound on the size of any record for the table | ||||
| 76489 | ** that the cursor is pointing into. | ||||
| 76490 | ** | ||||
| 76491 | ** This is an optimization. Everything will still work if this | ||||
| 76492 | ** routine always returns 2147483647 (which is the largest record | ||||
| 76493 | ** that SQLite can handle) or more. But returning a smaller value might | ||||
| 76494 | ** prevent large memory allocations when trying to interpret a | ||||
| 76495 | ** corrupt database. | ||||
| 76496 | ** | ||||
| 76497 | ** The current implementation merely returns the size of the underlying | ||||
| 76498 | ** database file. | ||||
| 76499 | */ | ||||
| 76500 | SQLITE_PRIVATEstatic sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){ | ||||
| 76501 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 76502 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76503 | return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage; | ||||
| 76504 | } | ||||
| 76505 | |||||
| 76506 | /* | ||||
| 76507 | ** Given the page number of an overflow page in the database (parameter | ||||
| 76508 | ** ovfl), this function finds the page number of the next page in the | ||||
| 76509 | ** linked list of overflow pages. If possible, it uses the auto-vacuum | ||||
| 76510 | ** pointer-map data instead of reading the content of page ovfl to do so. | ||||
| 76511 | ** | ||||
| 76512 | ** If an error occurs an SQLite error code is returned. Otherwise: | ||||
| 76513 | ** | ||||
| 76514 | ** The page number of the next overflow page in the linked list is | ||||
| 76515 | ** written to *pPgnoNext. If page ovfl is the last page in its linked | ||||
| 76516 | ** list, *pPgnoNext is set to zero. | ||||
| 76517 | ** | ||||
| 76518 | ** If ppPage is not NULL, and a reference to the MemPage object corresponding | ||||
| 76519 | ** to page number pOvfl was obtained, then *ppPage is set to point to that | ||||
| 76520 | ** reference. It is the responsibility of the caller to call releasePage() | ||||
| 76521 | ** on *ppPage to free the reference. In no reference was obtained (because | ||||
| 76522 | ** the pointer-map was used to obtain the value for *pPgnoNext), then | ||||
| 76523 | ** *ppPage is set to zero. | ||||
| 76524 | */ | ||||
| 76525 | static int getOverflowPage( | ||||
| 76526 | BtShared *pBt, /* The database file */ | ||||
| 76527 | Pgno ovfl, /* Current overflow page number */ | ||||
| 76528 | MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ | ||||
| 76529 | Pgno *pPgnoNext /* OUT: Next overflow page number */ | ||||
| 76530 | ){ | ||||
| 76531 | Pgno next = 0; | ||||
| 76532 | MemPage *pPage = 0; | ||||
| 76533 | int rc = SQLITE_OK0; | ||||
| 76534 | |||||
| 76535 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 76536 | assert(pPgnoNext)((void) (0)); | ||||
| 76537 | |||||
| 76538 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 76539 | /* Try to find the next page in the overflow list using the | ||||
| 76540 | ** autovacuum pointer-map pages. Guess that the next page in | ||||
| 76541 | ** the overflow list is page number (ovfl+1). If that guess turns | ||||
| 76542 | ** out to be wrong, fall back to loading the data of page | ||||
| 76543 | ** number ovfl to determine the next page number. | ||||
| 76544 | */ | ||||
| 76545 | if( pBt->autoVacuum ){ | ||||
| 76546 | Pgno pgno; | ||||
| 76547 | Pgno iGuess = ovfl+1; | ||||
| 76548 | u8 eType; | ||||
| 76549 | |||||
| 76550 | while( PTRMAP_ISPAGE(pBt, iGuess)(ptrmapPageno((pBt), (iGuess))==(iGuess)) || iGuess==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ | ||||
| 76551 | iGuess++; | ||||
| 76552 | } | ||||
| 76553 | |||||
| 76554 | if( iGuess<=btreePagecount(pBt) ){ | ||||
| 76555 | rc = ptrmapGet(pBt, iGuess, &eType, &pgno); | ||||
| 76556 | if( rc==SQLITE_OK0 && eType==PTRMAP_OVERFLOW24 && pgno==ovfl ){ | ||||
| 76557 | next = iGuess; | ||||
| 76558 | rc = SQLITE_DONE101; | ||||
| 76559 | } | ||||
| 76560 | } | ||||
| 76561 | } | ||||
| 76562 | #endif | ||||
| 76563 | |||||
| 76564 | assert( next==0 || rc==SQLITE_DONE )((void) (0)); | ||||
| 76565 | if( rc==SQLITE_OK0 ){ | ||||
| 76566 | rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY0x02 : 0); | ||||
| 76567 | assert( rc==SQLITE_OK || pPage==0 )((void) (0)); | ||||
| 76568 | if( rc==SQLITE_OK0 ){ | ||||
| 76569 | next = get4bytesqlite3Get4byte(pPage->aData); | ||||
| 76570 | } | ||||
| 76571 | } | ||||
| 76572 | |||||
| 76573 | *pPgnoNext = next; | ||||
| 76574 | if( ppPage ){ | ||||
| 76575 | *ppPage = pPage; | ||||
| 76576 | }else{ | ||||
| 76577 | releasePage(pPage); | ||||
| 76578 | } | ||||
| 76579 | return (rc==SQLITE_DONE101 ? SQLITE_OK0 : rc); | ||||
| 76580 | } | ||||
| 76581 | |||||
| 76582 | /* | ||||
| 76583 | ** Copy data from a buffer to a page, or from a page to a buffer. | ||||
| 76584 | ** | ||||
| 76585 | ** pPayload is a pointer to data stored on database page pDbPage. | ||||
| 76586 | ** If argument eOp is false, then nByte bytes of data are copied | ||||
| 76587 | ** from pPayload to the buffer pointed at by pBuf. If eOp is true, | ||||
| 76588 | ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes | ||||
| 76589 | ** of data are copied from the buffer pBuf to pPayload. | ||||
| 76590 | ** | ||||
| 76591 | ** SQLITE_OK is returned on success, otherwise an error code. | ||||
| 76592 | */ | ||||
| 76593 | static int copyPayload( | ||||
| 76594 | void *pPayload, /* Pointer to page data */ | ||||
| 76595 | void *pBuf, /* Pointer to buffer */ | ||||
| 76596 | int nByte, /* Number of bytes to copy */ | ||||
| 76597 | int eOp, /* 0 -> copy from page, 1 -> copy to page */ | ||||
| 76598 | DbPage *pDbPage /* Page containing pPayload */ | ||||
| 76599 | ){ | ||||
| 76600 | if( eOp ){ | ||||
| 76601 | /* Copy data from buffer to page (a write operation) */ | ||||
| 76602 | int rc = sqlite3PagerWrite(pDbPage); | ||||
| 76603 | if( rc!=SQLITE_OK0 ){ | ||||
| 76604 | return rc; | ||||
| 76605 | } | ||||
| 76606 | memcpy(pPayload, pBuf, nByte); | ||||
| 76607 | }else{ | ||||
| 76608 | /* Copy data from page to buffer (a read operation) */ | ||||
| 76609 | memcpy(pBuf, pPayload, nByte); | ||||
| 76610 | } | ||||
| 76611 | return SQLITE_OK0; | ||||
| 76612 | } | ||||
| 76613 | |||||
| 76614 | /* | ||||
| 76615 | ** This function is used to read or overwrite payload information | ||||
| 76616 | ** for the entry that the pCur cursor is pointing to. The eOp | ||||
| 76617 | ** argument is interpreted as follows: | ||||
| 76618 | ** | ||||
| 76619 | ** 0: The operation is a read. Populate the overflow cache. | ||||
| 76620 | ** 1: The operation is a write. Populate the overflow cache. | ||||
| 76621 | ** | ||||
| 76622 | ** A total of "amt" bytes are read or written beginning at "offset". | ||||
| 76623 | ** Data is read to or from the buffer pBuf. | ||||
| 76624 | ** | ||||
| 76625 | ** The content being read or written might appear on the main page | ||||
| 76626 | ** or be scattered out on multiple overflow pages. | ||||
| 76627 | ** | ||||
| 76628 | ** If the current cursor entry uses one or more overflow pages | ||||
| 76629 | ** this function may allocate space for and lazily populate | ||||
| 76630 | ** the overflow page-list cache array (BtCursor.aOverflow). | ||||
| 76631 | ** Subsequent calls use this cache to make seeking to the supplied offset | ||||
| 76632 | ** more efficient. | ||||
| 76633 | ** | ||||
| 76634 | ** Once an overflow page-list cache has been allocated, it must be | ||||
| 76635 | ** invalidated if some other cursor writes to the same table, or if | ||||
| 76636 | ** the cursor is moved to a different row. Additionally, in auto-vacuum | ||||
| 76637 | ** mode, the following events may invalidate an overflow page-list cache. | ||||
| 76638 | ** | ||||
| 76639 | ** * An incremental vacuum, | ||||
| 76640 | ** * A commit in auto_vacuum="full" mode, | ||||
| 76641 | ** * Creating a table (may require moving an overflow page). | ||||
| 76642 | */ | ||||
| 76643 | static int accessPayload( | ||||
| 76644 | BtCursor *pCur, /* Cursor pointing to entry to read from */ | ||||
| 76645 | u32 offset, /* Begin reading this far into payload */ | ||||
| 76646 | u32 amt, /* Read this many bytes */ | ||||
| 76647 | unsigned char *pBuf, /* Write the bytes into this buffer */ | ||||
| 76648 | int eOp /* zero to read. non-zero to write. */ | ||||
| 76649 | ){ | ||||
| 76650 | unsigned char *aPayload; | ||||
| 76651 | int rc = SQLITE_OK0; | ||||
| 76652 | int iIdx = 0; | ||||
| 76653 | MemPage *pPage = pCur->pPage; /* Btree page of current entry */ | ||||
| 76654 | BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ | ||||
| 76655 | #ifdef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 76656 | unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ | ||||
| 76657 | #endif | ||||
| 76658 | |||||
| 76659 | assert( pPage )((void) (0)); | ||||
| 76660 | assert( eOp==0 || eOp==1 )((void) (0)); | ||||
| 76661 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76662 | if( pCur->ix>=pPage->nCell ){ | ||||
| 76663 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(76663); | ||||
| 76664 | } | ||||
| 76665 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 76666 | |||||
| 76667 | getCellInfo(pCur); | ||||
| 76668 | aPayload = pCur->info.pPayload; | ||||
| 76669 | assert( offset+amt <= pCur->info.nPayload )((void) (0)); | ||||
| 76670 | |||||
| 76671 | assert( aPayload > pPage->aData )((void) (0)); | ||||
| 76672 | if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ | ||||
| 76673 | /* Trying to read or write past the end of the data is an error. The | ||||
| 76674 | ** conditional above is really: | ||||
| 76675 | ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] | ||||
| 76676 | ** but is recast into its current form to avoid integer overflow problems | ||||
| 76677 | */ | ||||
| 76678 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(76678); | ||||
| 76679 | } | ||||
| 76680 | |||||
| 76681 | /* Check if data must be read/written to/from the btree page itself. */ | ||||
| 76682 | if( offset<pCur->info.nLocal ){ | ||||
| 76683 | int a = amt; | ||||
| 76684 | if( a+offset>pCur->info.nLocal ){ | ||||
| 76685 | a = pCur->info.nLocal - offset; | ||||
| 76686 | } | ||||
| 76687 | rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); | ||||
| 76688 | offset = 0; | ||||
| 76689 | pBuf += a; | ||||
| 76690 | amt -= a; | ||||
| 76691 | }else{ | ||||
| 76692 | offset -= pCur->info.nLocal; | ||||
| 76693 | } | ||||
| 76694 | |||||
| 76695 | |||||
| 76696 | if( rc==SQLITE_OK0 && amt>0 ){ | ||||
| 76697 | const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ | ||||
| 76698 | Pgno nextPage; | ||||
| 76699 | |||||
| 76700 | nextPage = get4bytesqlite3Get4byte(&aPayload[pCur->info.nLocal]); | ||||
| 76701 | |||||
| 76702 | /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. | ||||
| 76703 | ** | ||||
| 76704 | ** The aOverflow[] array is sized at one entry for each overflow page | ||||
| 76705 | ** in the overflow chain. The page number of the first overflow page is | ||||
| 76706 | ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array | ||||
| 76707 | ** means "not yet known" (the cache is lazily populated). | ||||
| 76708 | */ | ||||
| 76709 | if( (pCur->curFlags & BTCF_ValidOvfl0x04)==0 ){ | ||||
| 76710 | int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; | ||||
| 76711 | if( pCur->aOverflow==0 | ||||
| 76712 | || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) | ||||
| 76713 | ){ | ||||
| 76714 | Pgno *aNew; | ||||
| 76715 | if( sqlite3FaultSim(413) ){ | ||||
| 76716 | aNew = 0; | ||||
| 76717 | }else{ | ||||
| 76718 | aNew = (Pgno*)sqlite3Realloc(pCur->aOverflow, nOvfl*2*sizeof(Pgno)); | ||||
| 76719 | } | ||||
| 76720 | if( aNew==0 ){ | ||||
| 76721 | return SQLITE_NOMEM_BKPT7; | ||||
| 76722 | }else{ | ||||
| 76723 | pCur->aOverflow = aNew; | ||||
| 76724 | } | ||||
| 76725 | } | ||||
| 76726 | memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); | ||||
| 76727 | pCur->curFlags |= BTCF_ValidOvfl0x04; | ||||
| 76728 | }else{ | ||||
| 76729 | /* Sanity check the validity of the overflow page cache */ | ||||
| 76730 | assert( pCur->aOverflow[0]==nextPage((void) (0)) | ||||
| 76731 | || pCur->aOverflow[0]==0((void) (0)) | ||||
| 76732 | || CORRUPT_DB )((void) (0)); | ||||
| 76733 | assert( pCur->aOverflow[0]!=0 || pCur->aOverflow[offset/ovflSize]==0 )((void) (0)); | ||||
| 76734 | |||||
| 76735 | /* If the overflow page-list cache has been allocated and the | ||||
| 76736 | ** entry for the first required overflow page is valid, skip | ||||
| 76737 | ** directly to it. | ||||
| 76738 | */ | ||||
| 76739 | if( pCur->aOverflow[offset/ovflSize] ){ | ||||
| 76740 | iIdx = (offset/ovflSize); | ||||
| 76741 | nextPage = pCur->aOverflow[iIdx]; | ||||
| 76742 | offset = (offset%ovflSize); | ||||
| 76743 | } | ||||
| 76744 | } | ||||
| 76745 | |||||
| 76746 | assert( rc==SQLITE_OK && amt>0 )((void) (0)); | ||||
| 76747 | while( nextPage ){ | ||||
| 76748 | /* If required, populate the overflow page-list cache. */ | ||||
| 76749 | if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(76749); | ||||
| 76750 | assert( pCur->aOverflow[iIdx]==0((void) (0)) | ||||
| 76751 | || pCur->aOverflow[iIdx]==nextPage((void) (0)) | ||||
| 76752 | || CORRUPT_DB )((void) (0)); | ||||
| 76753 | pCur->aOverflow[iIdx] = nextPage; | ||||
| 76754 | |||||
| 76755 | if( offset>=ovflSize ){ | ||||
| 76756 | /* The only reason to read this page is to obtain the page | ||||
| 76757 | ** number for the next page in the overflow chain. The page | ||||
| 76758 | ** data is not required. So first try to lookup the overflow | ||||
| 76759 | ** page-list cache, if any, then fall back to the getOverflowPage() | ||||
| 76760 | ** function. | ||||
| 76761 | */ | ||||
| 76762 | assert( pCur->curFlags & BTCF_ValidOvfl )((void) (0)); | ||||
| 76763 | assert( pCur->pBtree->db==pBt->db )((void) (0)); | ||||
| 76764 | if( pCur->aOverflow[iIdx+1] ){ | ||||
| 76765 | nextPage = pCur->aOverflow[iIdx+1]; | ||||
| 76766 | }else{ | ||||
| 76767 | rc = getOverflowPage(pBt, nextPage, 0, &nextPage); | ||||
| 76768 | } | ||||
| 76769 | offset -= ovflSize; | ||||
| 76770 | }else{ | ||||
| 76771 | /* Need to read this page properly. It contains some of the | ||||
| 76772 | ** range of data that is being read (eOp==0) or written (eOp!=0). | ||||
| 76773 | */ | ||||
| 76774 | int a = amt; | ||||
| 76775 | if( a + offset > ovflSize ){ | ||||
| 76776 | a = ovflSize - offset; | ||||
| 76777 | } | ||||
| 76778 | |||||
| 76779 | #ifdef SQLITE_DIRECT_OVERFLOW_READ1 | ||||
| 76780 | /* If all the following are true: | ||||
| 76781 | ** | ||||
| 76782 | ** 1) this is a read operation, and | ||||
| 76783 | ** 2) data is required from the start of this overflow page, and | ||||
| 76784 | ** 3) there are no dirty pages in the page-cache | ||||
| 76785 | ** 4) the database is file-backed, and | ||||
| 76786 | ** 5) the page is not in the WAL file | ||||
| 76787 | ** 6) at least 4 bytes have already been read into the output buffer | ||||
| 76788 | ** | ||||
| 76789 | ** then data can be read directly from the database file into the | ||||
| 76790 | ** output buffer, bypassing the page-cache altogether. This speeds | ||||
| 76791 | ** up loading large records that span many overflow pages. | ||||
| 76792 | */ | ||||
| 76793 | if( eOp==0 /* (1) */ | ||||
| 76794 | && offset==0 /* (2) */ | ||||
| 76795 | && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */ | ||||
| 76796 | && &pBuf[-4]>=pBufStart /* (6) */ | ||||
| 76797 | ){ | ||||
| 76798 | sqlite3_file *fd = sqlite3PagerFile(pBt->pPager); | ||||
| 76799 | u8 aSave[4]; | ||||
| 76800 | u8 *aWrite = &pBuf[-4]; | ||||
| 76801 | assert( aWrite>=pBufStart )((void) (0)); /* due to (6) */ | ||||
| 76802 | memcpy(aSave, aWrite, 4); | ||||
| 76803 | rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); | ||||
| 76804 | nextPage = get4bytesqlite3Get4byte(aWrite); | ||||
| 76805 | memcpy(aWrite, aSave, 4); | ||||
| 76806 | }else | ||||
| 76807 | #endif | ||||
| 76808 | |||||
| 76809 | { | ||||
| 76810 | DbPage *pDbPage; | ||||
| 76811 | rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, | ||||
| 76812 | (eOp==0 ? PAGER_GET_READONLY0x02 : 0) | ||||
| 76813 | ); | ||||
| 76814 | if( rc==SQLITE_OK0 ){ | ||||
| 76815 | aPayload = sqlite3PagerGetData(pDbPage); | ||||
| 76816 | nextPage = get4bytesqlite3Get4byte(aPayload); | ||||
| 76817 | rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); | ||||
| 76818 | sqlite3PagerUnref(pDbPage); | ||||
| 76819 | offset = 0; | ||||
| 76820 | } | ||||
| 76821 | } | ||||
| 76822 | amt -= a; | ||||
| 76823 | if( amt==0 ) return rc; | ||||
| 76824 | pBuf += a; | ||||
| 76825 | } | ||||
| 76826 | if( rc ) break; | ||||
| 76827 | iIdx++; | ||||
| 76828 | } | ||||
| 76829 | } | ||||
| 76830 | |||||
| 76831 | if( rc==SQLITE_OK0 && amt>0 ){ | ||||
| 76832 | /* Overflow chain ends prematurely */ | ||||
| 76833 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(76833); | ||||
| 76834 | } | ||||
| 76835 | return rc; | ||||
| 76836 | } | ||||
| 76837 | |||||
| 76838 | /* | ||||
| 76839 | ** Read part of the payload for the row at which that cursor pCur is currently | ||||
| 76840 | ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer | ||||
| 76841 | ** begins at "offset". | ||||
| 76842 | ** | ||||
| 76843 | ** pCur can be pointing to either a table or an index b-tree. | ||||
| 76844 | ** If pointing to a table btree, then the content section is read. If | ||||
| 76845 | ** pCur is pointing to an index b-tree then the key section is read. | ||||
| 76846 | ** | ||||
| 76847 | ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing | ||||
| 76848 | ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the | ||||
| 76849 | ** cursor might be invalid or might need to be restored before being read. | ||||
| 76850 | ** | ||||
| 76851 | ** Return SQLITE_OK on success or an error code if anything goes | ||||
| 76852 | ** wrong. An error is returned if "offset+amt" is larger than | ||||
| 76853 | ** the available payload. | ||||
| 76854 | */ | ||||
| 76855 | SQLITE_PRIVATEstatic int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ | ||||
| 76856 | assert( cursorHoldsMutex(pCur) )((void) (0)); | ||||
| 76857 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76858 | assert( pCur->iPage>=0 && pCur->pPage )((void) (0)); | ||||
| 76859 | return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); | ||||
| 76860 | } | ||||
| 76861 | |||||
| 76862 | /* | ||||
| 76863 | ** This variant of sqlite3BtreePayload() works even if the cursor has not | ||||
| 76864 | ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read() | ||||
| 76865 | ** interface. | ||||
| 76866 | */ | ||||
| 76867 | #ifndef SQLITE_OMIT_INCRBLOB | ||||
| 76868 | static SQLITE_NOINLINE__attribute__((noinline)) int accessPayloadChecked( | ||||
| 76869 | BtCursor *pCur, | ||||
| 76870 | u32 offset, | ||||
| 76871 | u32 amt, | ||||
| 76872 | void *pBuf | ||||
| 76873 | ){ | ||||
| 76874 | int rc; | ||||
| 76875 | if ( pCur->eState==CURSOR_INVALID1 ){ | ||||
| 76876 | return SQLITE_ABORT4; | ||||
| 76877 | } | ||||
| 76878 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 76879 | rc = btreeRestoreCursorPosition(pCur); | ||||
| 76880 | return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0); | ||||
| 76881 | } | ||||
| 76882 | SQLITE_PRIVATEstatic int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ | ||||
| 76883 | if( pCur->eState==CURSOR_VALID0 ){ | ||||
| 76884 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 76885 | return accessPayload(pCur, offset, amt, pBuf, 0); | ||||
| 76886 | }else{ | ||||
| 76887 | return accessPayloadChecked(pCur, offset, amt, pBuf); | ||||
| 76888 | } | ||||
| 76889 | } | ||||
| 76890 | #endif /* SQLITE_OMIT_INCRBLOB */ | ||||
| 76891 | |||||
| 76892 | /* | ||||
| 76893 | ** Return a pointer to payload information from the entry that the | ||||
| 76894 | ** pCur cursor is pointing to. The pointer is to the beginning of | ||||
| 76895 | ** the key if index btrees (pPage->intKey==0) and is the data for | ||||
| 76896 | ** table btrees (pPage->intKey==1). The number of bytes of available | ||||
| 76897 | ** key/data is written into *pAmt. If *pAmt==0, then the value | ||||
| 76898 | ** returned will not be a valid pointer. | ||||
| 76899 | ** | ||||
| 76900 | ** This routine is an optimization. It is common for the entire key | ||||
| 76901 | ** and data to fit on the local page and for there to be no overflow | ||||
| 76902 | ** pages. When that is so, this routine can be used to access the | ||||
| 76903 | ** key and data without making a copy. If the key and/or data spills | ||||
| 76904 | ** onto overflow pages, then accessPayload() must be used to reassemble | ||||
| 76905 | ** the key/data and copy it into a preallocated buffer. | ||||
| 76906 | ** | ||||
| 76907 | ** The pointer returned by this routine looks directly into the cached | ||||
| 76908 | ** page of the database. The data might change or move the next time | ||||
| 76909 | ** any btree routine is called. | ||||
| 76910 | */ | ||||
| 76911 | static const void *fetchPayload( | ||||
| 76912 | BtCursor *pCur, /* Cursor pointing to entry to read from */ | ||||
| 76913 | u32 *pAmt /* Write the number of available bytes here */ | ||||
| 76914 | ){ | ||||
| 76915 | int amt; | ||||
| 76916 | assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage)((void) (0)); | ||||
| 76917 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76918 | assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) )((void) (0)); | ||||
| 76919 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 76920 | assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB )((void) (0)); | ||||
| 76921 | assert( pCur->info.nSize>0 )((void) (0)); | ||||
| 76922 | assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB )((void) (0)); | ||||
| 76923 | assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB)((void) (0)); | ||||
| 76924 | amt = pCur->info.nLocal; | ||||
| 76925 | if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){ | ||||
| 76926 | /* There is too little space on the page for the expected amount | ||||
| 76927 | ** of local content. Database must be corrupt. */ | ||||
| 76928 | assert( CORRUPT_DB )((void) (0)); | ||||
| 76929 | amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload))((0)>((int)(pCur->pPage->aDataEnd - pCur->info.pPayload ))?(0):((int)(pCur->pPage->aDataEnd - pCur->info.pPayload ))); | ||||
| 76930 | } | ||||
| 76931 | *pAmt = (u32)amt; | ||||
| 76932 | return (void*)pCur->info.pPayload; | ||||
| 76933 | } | ||||
| 76934 | |||||
| 76935 | |||||
| 76936 | /* | ||||
| 76937 | ** For the entry that cursor pCur is point to, return as | ||||
| 76938 | ** many bytes of the key or data as are available on the local | ||||
| 76939 | ** b-tree page. Write the number of available bytes into *pAmt. | ||||
| 76940 | ** | ||||
| 76941 | ** The pointer returned is ephemeral. The key/data may move | ||||
| 76942 | ** or be destroyed on the next call to any Btree routine, | ||||
| 76943 | ** including calls from other threads against the same cache. | ||||
| 76944 | ** Hence, a mutex on the BtShared should be held prior to calling | ||||
| 76945 | ** this routine. | ||||
| 76946 | ** | ||||
| 76947 | ** These routines is used to get quick access to key and data | ||||
| 76948 | ** in the common case where no overflow pages are used. | ||||
| 76949 | */ | ||||
| 76950 | SQLITE_PRIVATEstatic const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ | ||||
| 76951 | return fetchPayload(pCur, pAmt); | ||||
| 76952 | } | ||||
| 76953 | |||||
| 76954 | |||||
| 76955 | /* | ||||
| 76956 | ** Move the cursor down to a new child page. The newPgno argument is the | ||||
| 76957 | ** page number of the child page to move to. | ||||
| 76958 | ** | ||||
| 76959 | ** This function returns SQLITE_CORRUPT if the page-header flags field of | ||||
| 76960 | ** the new child page does not match the flags field of the parent (i.e. | ||||
| 76961 | ** if an intkey page appears to be the parent of a non-intkey page, or | ||||
| 76962 | ** vice-versa). | ||||
| 76963 | */ | ||||
| 76964 | static int moveToChild(BtCursor *pCur, u32 newPgno){ | ||||
| 76965 | int rc; | ||||
| 76966 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 76967 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 76968 | assert( pCur->iPage<BTCURSOR_MAX_DEPTH )((void) (0)); | ||||
| 76969 | assert( pCur->iPage>=0 )((void) (0)); | ||||
| 76970 | if( pCur->iPage>=(BTCURSOR_MAX_DEPTH20-1) ){ | ||||
| 76971 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(76971); | ||||
| 76972 | } | ||||
| 76973 | pCur->info.nSize = 0; | ||||
| 76974 | pCur->curFlags &= ~(BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04); | ||||
| 76975 | pCur->aiIdx[pCur->iPage] = pCur->ix; | ||||
| 76976 | pCur->apPage[pCur->iPage] = pCur->pPage; | ||||
| 76977 | pCur->ix = 0; | ||||
| 76978 | pCur->iPage++; | ||||
| 76979 | rc = getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur->curPagerFlags); | ||||
| 76980 | assert( pCur->pPage!=0 || rc!=SQLITE_OK )((void) (0)); | ||||
| 76981 | if( rc==SQLITE_OK0 | ||||
| 76982 | && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey) | ||||
| 76983 | ){ | ||||
| 76984 | releasePage(pCur->pPage); | ||||
| 76985 | rc = SQLITE_CORRUPT_PGNO(newPgno)sqlite3CorruptError(76985); | ||||
| 76986 | } | ||||
| 76987 | if( rc ){ | ||||
| 76988 | pCur->pPage = pCur->apPage[--pCur->iPage]; | ||||
| 76989 | } | ||||
| 76990 | return rc; | ||||
| 76991 | } | ||||
| 76992 | |||||
| 76993 | #ifdef SQLITE_DEBUG | ||||
| 76994 | /* | ||||
| 76995 | ** Page pParent is an internal (non-leaf) tree page. This function | ||||
| 76996 | ** asserts that page number iChild is the left-child if the iIdx'th | ||||
| 76997 | ** cell in page pParent. Or, if iIdx is equal to the total number of | ||||
| 76998 | ** cells in pParent, that page number iChild is the right-child of | ||||
| 76999 | ** the page. | ||||
| 77000 | */ | ||||
| 77001 | static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ | ||||
| 77002 | if( CORRUPT_DB(sqlite3Config.neverCorrupt==0) ) return; /* The conditions tested below might not be true | ||||
| 77003 | ** in a corrupt database */ | ||||
| 77004 | assert( iIdx<=pParent->nCell )((void) (0)); | ||||
| 77005 | if( iIdx==pParent->nCell ){ | ||||
| 77006 | assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild )((void) (0)); | ||||
| 77007 | }else{ | ||||
| 77008 | assert( get4byte(findCell(pParent, iIdx))==iChild )((void) (0)); | ||||
| 77009 | } | ||||
| 77010 | } | ||||
| 77011 | #else | ||||
| 77012 | # define assertParentIndex(x,y,z) | ||||
| 77013 | #endif | ||||
| 77014 | |||||
| 77015 | /* | ||||
| 77016 | ** Move the cursor up to the parent page. | ||||
| 77017 | ** | ||||
| 77018 | ** pCur->idx is set to the cell index that contains the pointer | ||||
| 77019 | ** to the page we are coming from. If we are coming from the | ||||
| 77020 | ** right-most child page then pCur->idx is set to one more than | ||||
| 77021 | ** the largest cell index. | ||||
| 77022 | */ | ||||
| 77023 | static void moveToParent(BtCursor *pCur){ | ||||
| 77024 | MemPage *pLeaf; | ||||
| 77025 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77026 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 77027 | assert( pCur->iPage>0 )((void) (0)); | ||||
| 77028 | assert( pCur->pPage )((void) (0)); | ||||
| 77029 | assertParentIndex( | ||||
| 77030 | pCur->apPage[pCur->iPage-1], | ||||
| 77031 | pCur->aiIdx[pCur->iPage-1], | ||||
| 77032 | pCur->pPage->pgno | ||||
| 77033 | ); | ||||
| 77034 | testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); | ||||
| 77035 | pCur->info.nSize = 0; | ||||
| 77036 | pCur->curFlags &= ~(BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04); | ||||
| 77037 | pCur->ix = pCur->aiIdx[pCur->iPage-1]; | ||||
| 77038 | pLeaf = pCur->pPage; | ||||
| 77039 | pCur->pPage = pCur->apPage[--pCur->iPage]; | ||||
| 77040 | releasePageNotNull(pLeaf); | ||||
| 77041 | } | ||||
| 77042 | |||||
| 77043 | /* | ||||
| 77044 | ** Move the cursor to point to the root page of its b-tree structure. | ||||
| 77045 | ** | ||||
| 77046 | ** If the table has a virtual root page, then the cursor is moved to point | ||||
| 77047 | ** to the virtual root page instead of the actual root page. A table has a | ||||
| 77048 | ** virtual root page when the actual root page contains no cells and a | ||||
| 77049 | ** single child page. This can only happen with the table rooted at page 1. | ||||
| 77050 | ** | ||||
| 77051 | ** If the b-tree structure is empty, the cursor state is set to | ||||
| 77052 | ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise, | ||||
| 77053 | ** the cursor is set to point to the first cell located on the root | ||||
| 77054 | ** (or virtual root) page and the cursor state is set to CURSOR_VALID. | ||||
| 77055 | ** | ||||
| 77056 | ** If this function returns successfully, it may be assumed that the | ||||
| 77057 | ** page-header flags indicate that the [virtual] root-page is the expected | ||||
| 77058 | ** kind of b-tree page (i.e. if when opening the cursor the caller did not | ||||
| 77059 | ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, | ||||
| 77060 | ** indicating a table b-tree, or if the caller did specify a KeyInfo | ||||
| 77061 | ** structure the flags byte is set to 0x02 or 0x0A, indicating an index | ||||
| 77062 | ** b-tree). | ||||
| 77063 | */ | ||||
| 77064 | static int moveToRoot(BtCursor *pCur){ | ||||
| 77065 | MemPage *pRoot; | ||||
| 77066 | int rc = SQLITE_OK0; | ||||
| 77067 | |||||
| 77068 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77069 | assert( CURSOR_INVALID < CURSOR_REQUIRESEEK )((void) (0)); | ||||
| 77070 | assert( CURSOR_VALID < CURSOR_REQUIRESEEK )((void) (0)); | ||||
| 77071 | assert( CURSOR_FAULT > CURSOR_REQUIRESEEK )((void) (0)); | ||||
| 77072 | assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 )((void) (0)); | ||||
| 77073 | assert( pCur->pgnoRoot>0 || pCur->iPage<0 )((void) (0)); | ||||
| 77074 | |||||
| 77075 | if( pCur->iPage>=0 ){ | ||||
| 77076 | if( pCur->iPage ){ | ||||
| 77077 | releasePageNotNull(pCur->pPage); | ||||
| 77078 | while( --pCur->iPage ){ | ||||
| 77079 | releasePageNotNull(pCur->apPage[pCur->iPage]); | ||||
| 77080 | } | ||||
| 77081 | pRoot = pCur->pPage = pCur->apPage[0]; | ||||
| 77082 | goto skip_init; | ||||
| 77083 | } | ||||
| 77084 | }else if( pCur->pgnoRoot==0 ){ | ||||
| 77085 | pCur->eState = CURSOR_INVALID1; | ||||
| 77086 | return SQLITE_EMPTY16; | ||||
| 77087 | }else{ | ||||
| 77088 | assert( pCur->iPage==(-1) )((void) (0)); | ||||
| 77089 | if( pCur->eState>=CURSOR_REQUIRESEEK3 ){ | ||||
| 77090 | if( pCur->eState==CURSOR_FAULT4 ){ | ||||
| 77091 | assert( pCur->skipNext!=SQLITE_OK )((void) (0)); | ||||
| 77092 | return pCur->skipNext; | ||||
| 77093 | } | ||||
| 77094 | sqlite3BtreeClearCursor(pCur); | ||||
| 77095 | } | ||||
| 77096 | rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage, | ||||
| 77097 | pCur->curPagerFlags); | ||||
| 77098 | if( rc!=SQLITE_OK0 ){ | ||||
| 77099 | pCur->eState = CURSOR_INVALID1; | ||||
| 77100 | return rc; | ||||
| 77101 | } | ||||
| 77102 | pCur->iPage = 0; | ||||
| 77103 | pCur->curIntKey = pCur->pPage->intKey; | ||||
| 77104 | } | ||||
| 77105 | pRoot = pCur->pPage; | ||||
| 77106 | assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB )((void) (0)); | ||||
| 77107 | |||||
| 77108 | /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor | ||||
| 77109 | ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is | ||||
| 77110 | ** NULL, the caller expects a table b-tree. If this is not the case, | ||||
| 77111 | ** return an SQLITE_CORRUPT error. | ||||
| 77112 | ** | ||||
| 77113 | ** Earlier versions of SQLite assumed that this test could not fail | ||||
| 77114 | ** if the root page was already loaded when this function was called (i.e. | ||||
| 77115 | ** if pCur->iPage>=0). But this is not so if the database is corrupted | ||||
| 77116 | ** in such a way that page pRoot is linked into a second b-tree table | ||||
| 77117 | ** (or the freelist). */ | ||||
| 77118 | assert( pRoot->intKey==1 || pRoot->intKey==0 )((void) (0)); | ||||
| 77119 | if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ | ||||
| 77120 | return SQLITE_CORRUPT_PAGE(pCur->pPage)sqlite3CorruptError(77120); | ||||
| 77121 | } | ||||
| 77122 | |||||
| 77123 | skip_init: | ||||
| 77124 | pCur->ix = 0; | ||||
| 77125 | pCur->info.nSize = 0; | ||||
| 77126 | pCur->curFlags &= ~(BTCF_AtLast0x08|BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04); | ||||
| 77127 | |||||
| 77128 | if( pRoot->nCell>0 ){ | ||||
| 77129 | pCur->eState = CURSOR_VALID0; | ||||
| 77130 | }else if( !pRoot->leaf ){ | ||||
| 77131 | Pgno subpage; | ||||
| 77132 | if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(77132); | ||||
| 77133 | subpage = get4bytesqlite3Get4byte(&pRoot->aData[pRoot->hdrOffset+8]); | ||||
| 77134 | pCur->eState = CURSOR_VALID0; | ||||
| 77135 | rc = moveToChild(pCur, subpage); | ||||
| 77136 | }else{ | ||||
| 77137 | pCur->eState = CURSOR_INVALID1; | ||||
| 77138 | rc = SQLITE_EMPTY16; | ||||
| 77139 | } | ||||
| 77140 | return rc; | ||||
| 77141 | } | ||||
| 77142 | |||||
| 77143 | /* | ||||
| 77144 | ** Move the cursor down to the left-most leaf entry beneath the | ||||
| 77145 | ** entry to which it is currently pointing. | ||||
| 77146 | ** | ||||
| 77147 | ** The left-most leaf is the one with the smallest key - the first | ||||
| 77148 | ** in ascending order. | ||||
| 77149 | */ | ||||
| 77150 | static int moveToLeftmost(BtCursor *pCur){ | ||||
| 77151 | Pgno pgno; | ||||
| 77152 | int rc = SQLITE_OK0; | ||||
| 77153 | MemPage *pPage; | ||||
| 77154 | |||||
| 77155 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77156 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 77157 | while( rc==SQLITE_OK0 && !(pPage = pCur->pPage)->leaf ){ | ||||
| 77158 | assert( pCur->ix<pPage->nCell )((void) (0)); | ||||
| 77159 | pgno = get4bytesqlite3Get4byte(findCell(pPage, pCur->ix)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(pCur->ix)])[0]<<8 | (&(pPage)-> aCellIdx[2*(pCur->ix)])[1])))); | ||||
| 77160 | rc = moveToChild(pCur, pgno); | ||||
| 77161 | } | ||||
| 77162 | return rc; | ||||
| 77163 | } | ||||
| 77164 | |||||
| 77165 | /* | ||||
| 77166 | ** Move the cursor down to the right-most leaf entry beneath the | ||||
| 77167 | ** page to which it is currently pointing. Notice the difference | ||||
| 77168 | ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() | ||||
| 77169 | ** finds the left-most entry beneath the *entry* whereas moveToRightmost() | ||||
| 77170 | ** finds the right-most entry beneath the *page*. | ||||
| 77171 | ** | ||||
| 77172 | ** The right-most entry is the one with the largest key - the last | ||||
| 77173 | ** key in ascending order. | ||||
| 77174 | */ | ||||
| 77175 | static int moveToRightmost(BtCursor *pCur){ | ||||
| 77176 | Pgno pgno; | ||||
| 77177 | int rc = SQLITE_OK0; | ||||
| 77178 | MemPage *pPage = 0; | ||||
| 77179 | |||||
| 77180 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77181 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 77182 | while( !(pPage = pCur->pPage)->leaf ){ | ||||
| 77183 | pgno = get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8]); | ||||
| 77184 | pCur->ix = pPage->nCell; | ||||
| 77185 | rc = moveToChild(pCur, pgno); | ||||
| 77186 | if( rc ) return rc; | ||||
| 77187 | } | ||||
| 77188 | pCur->ix = pPage->nCell-1; | ||||
| 77189 | assert( pCur->info.nSize==0 )((void) (0)); | ||||
| 77190 | assert( (pCur->curFlags & BTCF_ValidNKey)==0 )((void) (0)); | ||||
| 77191 | return SQLITE_OK0; | ||||
| 77192 | } | ||||
| 77193 | |||||
| 77194 | /* Move the cursor to the first entry in the table. Return SQLITE_OK | ||||
| 77195 | ** on success. Set *pRes to 0 if the cursor actually points to something | ||||
| 77196 | ** or set *pRes to 1 if the table is empty. | ||||
| 77197 | */ | ||||
| 77198 | SQLITE_PRIVATEstatic int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ | ||||
| 77199 | int rc; | ||||
| 77200 | |||||
| 77201 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77202 | assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) )((void) (0)); | ||||
| 77203 | rc = moveToRoot(pCur); | ||||
| 77204 | if( rc==SQLITE_OK0 ){ | ||||
| 77205 | assert( pCur->pPage->nCell>0 )((void) (0)); | ||||
| 77206 | *pRes = 0; | ||||
| 77207 | rc = moveToLeftmost(pCur); | ||||
| 77208 | }else if( rc==SQLITE_EMPTY16 ){ | ||||
| 77209 | assert( pCur->pgnoRoot==0 || (pCur->pPage!=0 && pCur->pPage->nCell==0) )((void) (0)); | ||||
| 77210 | *pRes = 1; | ||||
| 77211 | rc = SQLITE_OK0; | ||||
| 77212 | } | ||||
| 77213 | return rc; | ||||
| 77214 | } | ||||
| 77215 | |||||
| 77216 | #ifdef SQLITE_DEBUG | ||||
| 77217 | /* The cursors is CURSOR_VALID and has BTCF_AtLast set. Verify that | ||||
| 77218 | ** this flags are true for a consistent database. | ||||
| 77219 | ** | ||||
| 77220 | ** This routine is is called from within assert() statements only. | ||||
| 77221 | ** It is an internal verification routine and does not appear in production | ||||
| 77222 | ** builds. | ||||
| 77223 | */ | ||||
| 77224 | static int cursorIsAtLastEntry(BtCursor *pCur){ | ||||
| 77225 | int ii; | ||||
| 77226 | for(ii=0; ii<pCur->iPage; ii++){ | ||||
| 77227 | if( pCur->aiIdx[ii]!=pCur->apPage[ii]->nCell ) return 0; | ||||
| 77228 | } | ||||
| 77229 | return pCur->ix==pCur->pPage->nCell-1 && pCur->pPage->leaf!=0; | ||||
| 77230 | } | ||||
| 77231 | #endif | ||||
| 77232 | |||||
| 77233 | /* Move the cursor to the last entry in the table. Return SQLITE_OK | ||||
| 77234 | ** on success. Set *pRes to 0 if the cursor actually points to something | ||||
| 77235 | ** or set *pRes to 1 if the table is empty. | ||||
| 77236 | */ | ||||
| 77237 | static SQLITE_NOINLINE__attribute__((noinline)) int btreeLast(BtCursor *pCur, int *pRes){ | ||||
| 77238 | int rc = moveToRoot(pCur); | ||||
| 77239 | if( rc==SQLITE_OK0 ){ | ||||
| 77240 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 77241 | *pRes = 0; | ||||
| 77242 | rc = moveToRightmost(pCur); | ||||
| 77243 | if( rc==SQLITE_OK0 ){ | ||||
| 77244 | pCur->curFlags |= BTCF_AtLast0x08; | ||||
| 77245 | }else{ | ||||
| 77246 | pCur->curFlags &= ~BTCF_AtLast0x08; | ||||
| 77247 | } | ||||
| 77248 | }else if( rc==SQLITE_EMPTY16 ){ | ||||
| 77249 | assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 )((void) (0)); | ||||
| 77250 | *pRes = 1; | ||||
| 77251 | rc = SQLITE_OK0; | ||||
| 77252 | } | ||||
| 77253 | return rc; | ||||
| 77254 | } | ||||
| 77255 | SQLITE_PRIVATEstatic int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ | ||||
| 77256 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77257 | assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) )((void) (0)); | ||||
| 77258 | |||||
| 77259 | /* If the cursor already points to the last entry, this is a no-op. */ | ||||
| 77260 | if( CURSOR_VALID0==pCur->eState && (pCur->curFlags & BTCF_AtLast0x08)!=0 ){ | ||||
| 77261 | assert( cursorIsAtLastEntry(pCur) || CORRUPT_DB )((void) (0)); | ||||
| 77262 | *pRes = 0; | ||||
| 77263 | return SQLITE_OK0; | ||||
| 77264 | } | ||||
| 77265 | return btreeLast(pCur, pRes); | ||||
| 77266 | } | ||||
| 77267 | |||||
| 77268 | /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY) | ||||
| 77269 | ** table near the key intKey. Return a success code. | ||||
| 77270 | ** | ||||
| 77271 | ** If an exact match is not found, then the cursor is always | ||||
| 77272 | ** left pointing at a leaf page which would hold the entry if it | ||||
| 77273 | ** were present. The cursor might point to an entry that comes | ||||
| 77274 | ** before or after the key. | ||||
| 77275 | ** | ||||
| 77276 | ** An integer is written into *pRes which is the result of | ||||
| 77277 | ** comparing the key with the entry to which the cursor is | ||||
| 77278 | ** pointing. The meaning of the integer written into | ||||
| 77279 | ** *pRes is as follows: | ||||
| 77280 | ** | ||||
| 77281 | ** *pRes<0 The cursor is left pointing at an entry that | ||||
| 77282 | ** is smaller than intKey or if the table is empty | ||||
| 77283 | ** and the cursor is therefore left point to nothing. | ||||
| 77284 | ** | ||||
| 77285 | ** *pRes==0 The cursor is left pointing at an entry that | ||||
| 77286 | ** exactly matches intKey. | ||||
| 77287 | ** | ||||
| 77288 | ** *pRes>0 The cursor is left pointing at an entry that | ||||
| 77289 | ** is larger than intKey. | ||||
| 77290 | */ | ||||
| 77291 | SQLITE_PRIVATEstatic int sqlite3BtreeTableMoveto( | ||||
| 77292 | BtCursor *pCur, /* The cursor to be moved */ | ||||
| 77293 | i64 intKey, /* The table key */ | ||||
| 77294 | int biasRight, /* If true, bias the search to the high end */ | ||||
| 77295 | int *pRes /* Write search results here */ | ||||
| 77296 | ){ | ||||
| 77297 | int rc; | ||||
| 77298 | |||||
| 77299 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77300 | assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) )((void) (0)); | ||||
| 77301 | assert( pRes )((void) (0)); | ||||
| 77302 | assert( pCur->pKeyInfo==0 )((void) (0)); | ||||
| 77303 | assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 )((void) (0)); | ||||
| 77304 | |||||
| 77305 | /* If the cursor is already positioned at the point we are trying | ||||
| 77306 | ** to move to, then just return without doing any work */ | ||||
| 77307 | if( pCur->eState==CURSOR_VALID0 && (pCur->curFlags & BTCF_ValidNKey0x02)!=0 ){ | ||||
| 77308 | if( pCur->info.nKey==intKey ){ | ||||
| 77309 | *pRes = 0; | ||||
| 77310 | return SQLITE_OK0; | ||||
| 77311 | } | ||||
| 77312 | if( pCur->info.nKey<intKey ){ | ||||
| 77313 | if( (pCur->curFlags & BTCF_AtLast0x08)!=0 ){ | ||||
| 77314 | assert( cursorIsAtLastEntry(pCur) || CORRUPT_DB )((void) (0)); | ||||
| 77315 | *pRes = -1; | ||||
| 77316 | return SQLITE_OK0; | ||||
| 77317 | } | ||||
| 77318 | /* If the requested key is one more than the previous key, then | ||||
| 77319 | ** try to get there using sqlite3BtreeNext() rather than a full | ||||
| 77320 | ** binary search. This is an optimization only. The correct answer | ||||
| 77321 | ** is still obtained without this case, only a little more slowly. */ | ||||
| 77322 | if( pCur->info.nKey+1==intKey ){ | ||||
| 77323 | *pRes = 0; | ||||
| 77324 | rc = sqlite3BtreeNext(pCur, 0); | ||||
| 77325 | if( rc==SQLITE_OK0 ){ | ||||
| 77326 | getCellInfo(pCur); | ||||
| 77327 | if( pCur->info.nKey==intKey ){ | ||||
| 77328 | return SQLITE_OK0; | ||||
| 77329 | } | ||||
| 77330 | }else if( rc!=SQLITE_DONE101 ){ | ||||
| 77331 | return rc; | ||||
| 77332 | } | ||||
| 77333 | } | ||||
| 77334 | } | ||||
| 77335 | } | ||||
| 77336 | |||||
| 77337 | #ifdef SQLITE_DEBUG | ||||
| 77338 | pCur->pBtree->nSeek++; /* Performance measurement during testing */ | ||||
| 77339 | #endif | ||||
| 77340 | |||||
| 77341 | rc = moveToRoot(pCur); | ||||
| 77342 | if( rc ){ | ||||
| 77343 | if( rc==SQLITE_EMPTY16 ){ | ||||
| 77344 | assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 )((void) (0)); | ||||
| 77345 | *pRes = -1; | ||||
| 77346 | return SQLITE_OK0; | ||||
| 77347 | } | ||||
| 77348 | return rc; | ||||
| 77349 | } | ||||
| 77350 | assert( pCur->pPage )((void) (0)); | ||||
| 77351 | assert( pCur->pPage->isInit )((void) (0)); | ||||
| 77352 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 77353 | assert( pCur->pPage->nCell > 0 )((void) (0)); | ||||
| 77354 | assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey )((void) (0)); | ||||
| 77355 | assert( pCur->curIntKey )((void) (0)); | ||||
| 77356 | |||||
| 77357 | for(;;){ | ||||
| 77358 | int lwr, upr, idx, c; | ||||
| 77359 | Pgno chldPg; | ||||
| 77360 | MemPage *pPage = pCur->pPage; | ||||
| 77361 | u8 *pCell; /* Pointer to current cell in pPage */ | ||||
| 77362 | |||||
| 77363 | /* pPage->nCell must be greater than zero. If this is the root-page | ||||
| 77364 | ** the cursor would have been INVALID above and this for(;;) loop | ||||
| 77365 | ** not run. If this is not the root-page, then the moveToChild() routine | ||||
| 77366 | ** would have already detected db corruption. Similarly, pPage must | ||||
| 77367 | ** be the right kind (index or table) of b-tree page. Otherwise | ||||
| 77368 | ** a moveToChild() or moveToRoot() call would have detected corruption. */ | ||||
| 77369 | assert( pPage->nCell>0 )((void) (0)); | ||||
| 77370 | assert( pPage->intKey )((void) (0)); | ||||
| 77371 | lwr = 0; | ||||
| 77372 | upr = pPage->nCell-1; | ||||
| 77373 | assert( biasRight==0 || biasRight==1 )((void) (0)); | ||||
| 77374 | idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ | ||||
| 77375 | for(;;){ | ||||
| 77376 | i64 nCellKey; | ||||
| 77377 | pCell = findCellPastPtr(pPage, idx)((pPage)->aDataOfst + ((pPage)->maskPage & ((&( pPage)->aCellIdx[2*(idx)])[0]<<8 | (&(pPage)-> aCellIdx[2*(idx)])[1]))); | ||||
| 77378 | if( pPage->intKeyLeaf ){ | ||||
| 77379 | while( 0x80 <= *(pCell++) ){ | ||||
| 77380 | if( pCell>=pPage->aDataEnd ){ | ||||
| 77381 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(77381); | ||||
| 77382 | } | ||||
| 77383 | } | ||||
| 77384 | } | ||||
| 77385 | getVarintsqlite3GetVarint(pCell, (u64*)&nCellKey); | ||||
| 77386 | if( nCellKey<intKey ){ | ||||
| 77387 | lwr = idx+1; | ||||
| 77388 | if( lwr>upr ){ c = -1; break; } | ||||
| 77389 | }else if( nCellKey>intKey ){ | ||||
| 77390 | upr = idx-1; | ||||
| 77391 | if( lwr>upr ){ c = +1; break; } | ||||
| 77392 | }else{ | ||||
| 77393 | assert( nCellKey==intKey )((void) (0)); | ||||
| 77394 | pCur->ix = (u16)idx; | ||||
| 77395 | if( !pPage->leaf ){ | ||||
| 77396 | lwr = idx; | ||||
| 77397 | goto moveto_table_next_layer; | ||||
| 77398 | }else{ | ||||
| 77399 | pCur->curFlags |= BTCF_ValidNKey0x02; | ||||
| 77400 | pCur->info.nKey = nCellKey; | ||||
| 77401 | pCur->info.nSize = 0; | ||||
| 77402 | *pRes = 0; | ||||
| 77403 | return SQLITE_OK0; | ||||
| 77404 | } | ||||
| 77405 | } | ||||
| 77406 | assert( lwr+upr>=0 )((void) (0)); | ||||
| 77407 | idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ | ||||
| 77408 | } | ||||
| 77409 | assert( lwr==upr+1 || !pPage->leaf )((void) (0)); | ||||
| 77410 | assert( pPage->isInit )((void) (0)); | ||||
| 77411 | if( pPage->leaf ){ | ||||
| 77412 | assert( pCur->ix<pCur->pPage->nCell )((void) (0)); | ||||
| 77413 | pCur->ix = (u16)idx; | ||||
| 77414 | *pRes = c; | ||||
| 77415 | rc = SQLITE_OK0; | ||||
| 77416 | goto moveto_table_finish; | ||||
| 77417 | } | ||||
| 77418 | moveto_table_next_layer: | ||||
| 77419 | if( lwr>=pPage->nCell ){ | ||||
| 77420 | chldPg = get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8]); | ||||
| 77421 | }else{ | ||||
| 77422 | chldPg = get4bytesqlite3Get4byte(findCell(pPage, lwr)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(lwr)])[0]<<8 | (&(pPage)->aCellIdx [2*(lwr)])[1])))); | ||||
| 77423 | } | ||||
| 77424 | pCur->ix = (u16)lwr; | ||||
| 77425 | rc = moveToChild(pCur, chldPg); | ||||
| 77426 | if( rc ) break; | ||||
| 77427 | } | ||||
| 77428 | moveto_table_finish: | ||||
| 77429 | pCur->info.nSize = 0; | ||||
| 77430 | assert( (pCur->curFlags & BTCF_ValidOvfl)==0 )((void) (0)); | ||||
| 77431 | return rc; | ||||
| 77432 | } | ||||
| 77433 | |||||
| 77434 | /* | ||||
| 77435 | ** Compare the "idx"-th cell on the page the cursor pCur is currently | ||||
| 77436 | ** pointing to to pIdxKey using xRecordCompare. Return negative or | ||||
| 77437 | ** zero if the cell is less than or equal pIdxKey. Return positive | ||||
| 77438 | ** if unknown. | ||||
| 77439 | ** | ||||
| 77440 | ** Return value negative: Cell at pCur[idx] less than pIdxKey | ||||
| 77441 | ** | ||||
| 77442 | ** Return value is zero: Cell at pCur[idx] equals pIdxKey | ||||
| 77443 | ** | ||||
| 77444 | ** Return value positive: Nothing is known about the relationship | ||||
| 77445 | ** of the cell at pCur[idx] and pIdxKey. | ||||
| 77446 | ** | ||||
| 77447 | ** This routine is part of an optimization. It is always safe to return | ||||
| 77448 | ** a positive value as that will cause the optimization to be skipped. | ||||
| 77449 | */ | ||||
| 77450 | static int indexCellCompare( | ||||
| 77451 | BtCursor *pCur, | ||||
| 77452 | int idx, | ||||
| 77453 | UnpackedRecord *pIdxKey, | ||||
| 77454 | RecordCompare xRecordCompare | ||||
| 77455 | ){ | ||||
| 77456 | MemPage *pPage = pCur->pPage; | ||||
| 77457 | int c; | ||||
| 77458 | int nCell; /* Size of the pCell cell in bytes */ | ||||
| 77459 | u8 *pCell = findCellPastPtr(pPage, idx)((pPage)->aDataOfst + ((pPage)->maskPage & ((&( pPage)->aCellIdx[2*(idx)])[0]<<8 | (&(pPage)-> aCellIdx[2*(idx)])[1]))); | ||||
| 77460 | |||||
| 77461 | nCell = pCell[0]; | ||||
| 77462 | if( nCell<=pPage->max1bytePayload ){ | ||||
| 77463 | /* This branch runs if the record-size field of the cell is a | ||||
| 77464 | ** single byte varint and the record fits entirely on the main | ||||
| 77465 | ** b-tree page. */ | ||||
| 77466 | testcase( pCell+nCell+1==pPage->aDataEnd ); | ||||
| 77467 | c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); | ||||
| 77468 | }else if( !(pCell[1] & 0x80) | ||||
| 77469 | && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal | ||||
| 77470 | ){ | ||||
| 77471 | /* The record-size field is a 2 byte varint and the record | ||||
| 77472 | ** fits entirely on the main b-tree page. */ | ||||
| 77473 | testcase( pCell+nCell+2==pPage->aDataEnd ); | ||||
| 77474 | c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); | ||||
| 77475 | }else{ | ||||
| 77476 | /* If the record extends into overflow pages, do not attempt | ||||
| 77477 | ** the optimization. */ | ||||
| 77478 | c = 99; | ||||
| 77479 | } | ||||
| 77480 | return c; | ||||
| 77481 | } | ||||
| 77482 | |||||
| 77483 | /* | ||||
| 77484 | ** Return true (non-zero) if pCur is current pointing to the last | ||||
| 77485 | ** page of a table. | ||||
| 77486 | */ | ||||
| 77487 | static int cursorOnLastPage(BtCursor *pCur){ | ||||
| 77488 | int i; | ||||
| 77489 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 77490 | for(i=0; i<pCur->iPage; i++){ | ||||
| 77491 | MemPage *pPage = pCur->apPage[i]; | ||||
| 77492 | if( pCur->aiIdx[i]<pPage->nCell ) return 0; | ||||
| 77493 | } | ||||
| 77494 | return 1; | ||||
| 77495 | } | ||||
| 77496 | |||||
| 77497 | /* Move the cursor so that it points to an entry in an index table | ||||
| 77498 | ** near the key pIdxKey. Return a success code. | ||||
| 77499 | ** | ||||
| 77500 | ** If an exact match is not found, then the cursor is always | ||||
| 77501 | ** left pointing at a leaf page which would hold the entry if it | ||||
| 77502 | ** were present. The cursor might point to an entry that comes | ||||
| 77503 | ** before or after the key. | ||||
| 77504 | ** | ||||
| 77505 | ** An integer is written into *pRes which is the result of | ||||
| 77506 | ** comparing the key with the entry to which the cursor is | ||||
| 77507 | ** pointing. The meaning of the integer written into | ||||
| 77508 | ** *pRes is as follows: | ||||
| 77509 | ** | ||||
| 77510 | ** *pRes<0 The cursor is left pointing at an entry that | ||||
| 77511 | ** is smaller than pIdxKey or if the table is empty | ||||
| 77512 | ** and the cursor is therefore left point to nothing. | ||||
| 77513 | ** | ||||
| 77514 | ** *pRes==0 The cursor is left pointing at an entry that | ||||
| 77515 | ** exactly matches pIdxKey. | ||||
| 77516 | ** | ||||
| 77517 | ** *pRes>0 The cursor is left pointing at an entry that | ||||
| 77518 | ** is larger than pIdxKey. | ||||
| 77519 | ** | ||||
| 77520 | ** The pIdxKey->eqSeen field is set to 1 if there | ||||
| 77521 | ** exists an entry in the table that exactly matches pIdxKey. | ||||
| 77522 | */ | ||||
| 77523 | SQLITE_PRIVATEstatic int sqlite3BtreeIndexMoveto( | ||||
| 77524 | BtCursor *pCur, /* The cursor to be moved */ | ||||
| 77525 | UnpackedRecord *pIdxKey, /* Unpacked index key */ | ||||
| 77526 | int *pRes /* Write search results here */ | ||||
| 77527 | ){ | ||||
| 77528 | int rc; | ||||
| 77529 | RecordCompare xRecordCompare; | ||||
| 77530 | |||||
| 77531 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77532 | assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) )((void) (0)); | ||||
| 77533 | assert( pRes )((void) (0)); | ||||
| 77534 | assert( pCur->pKeyInfo!=0 )((void) (0)); | ||||
| 77535 | |||||
| 77536 | #ifdef SQLITE_DEBUG | ||||
| 77537 | pCur->pBtree->nSeek++; /* Performance measurement during testing */ | ||||
| 77538 | #endif | ||||
| 77539 | |||||
| 77540 | xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); | ||||
| 77541 | pIdxKey->errCode = 0; | ||||
| 77542 | assert( pIdxKey->default_rc==1((void) (0)) | ||||
| 77543 | || pIdxKey->default_rc==0((void) (0)) | ||||
| 77544 | || pIdxKey->default_rc==-1((void) (0)) | ||||
| 77545 | )((void) (0)); | ||||
| 77546 | |||||
| 77547 | |||||
| 77548 | /* Check to see if we can skip a lot of work. Two cases: | ||||
| 77549 | ** | ||||
| 77550 | ** (1) If the cursor is already pointing to the very last cell | ||||
| 77551 | ** in the table and the pIdxKey search key is greater than or | ||||
| 77552 | ** equal to that last cell, then no movement is required. | ||||
| 77553 | ** | ||||
| 77554 | ** (2) If the cursor is on the last page of the table and the first | ||||
| 77555 | ** cell on that last page is less than or equal to the pIdxKey | ||||
| 77556 | ** search key, then we can start the search on the current page | ||||
| 77557 | ** without needing to go back to root. | ||||
| 77558 | */ | ||||
| 77559 | if( pCur->eState==CURSOR_VALID0 | ||||
| 77560 | && pCur->pPage->leaf | ||||
| 77561 | && cursorOnLastPage(pCur) | ||||
| 77562 | ){ | ||||
| 77563 | int c; | ||||
| 77564 | if( pCur->ix==pCur->pPage->nCell-1 | ||||
| 77565 | && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0 | ||||
| 77566 | && pIdxKey->errCode==SQLITE_OK0 | ||||
| 77567 | ){ | ||||
| 77568 | *pRes = c; | ||||
| 77569 | return SQLITE_OK0; /* Cursor already pointing at the correct spot */ | ||||
| 77570 | } | ||||
| 77571 | if( pCur->iPage>0 | ||||
| 77572 | && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0 | ||||
| 77573 | && pIdxKey->errCode==SQLITE_OK0 | ||||
| 77574 | ){ | ||||
| 77575 | pCur->curFlags &= ~(BTCF_ValidOvfl0x04|BTCF_AtLast0x08); | ||||
| 77576 | if( !pCur->pPage->isInit ){ | ||||
| 77577 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(77577); | ||||
| 77578 | } | ||||
| 77579 | goto bypass_moveto_root; /* Start search on the current page */ | ||||
| 77580 | } | ||||
| 77581 | pIdxKey->errCode = SQLITE_OK0; | ||||
| 77582 | } | ||||
| 77583 | |||||
| 77584 | rc = moveToRoot(pCur); | ||||
| 77585 | if( rc ){ | ||||
| 77586 | if( rc==SQLITE_EMPTY16 ){ | ||||
| 77587 | assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 )((void) (0)); | ||||
| 77588 | *pRes = -1; | ||||
| 77589 | return SQLITE_OK0; | ||||
| 77590 | } | ||||
| 77591 | return rc; | ||||
| 77592 | } | ||||
| 77593 | |||||
| 77594 | bypass_moveto_root: | ||||
| 77595 | assert( pCur->pPage )((void) (0)); | ||||
| 77596 | assert( pCur->pPage->isInit )((void) (0)); | ||||
| 77597 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 77598 | assert( pCur->pPage->nCell > 0 )((void) (0)); | ||||
| 77599 | assert( pCur->curIntKey==0 )((void) (0)); | ||||
| 77600 | assert( pIdxKey!=0 )((void) (0)); | ||||
| 77601 | for(;;){ | ||||
| 77602 | int lwr, upr, idx, c; | ||||
| 77603 | Pgno chldPg; | ||||
| 77604 | MemPage *pPage = pCur->pPage; | ||||
| 77605 | u8 *pCell; /* Pointer to current cell in pPage */ | ||||
| 77606 | |||||
| 77607 | /* pPage->nCell must be greater than zero. If this is the root-page | ||||
| 77608 | ** the cursor would have been INVALID above and this for(;;) loop | ||||
| 77609 | ** not run. If this is not the root-page, then the moveToChild() routine | ||||
| 77610 | ** would have already detected db corruption. Similarly, pPage must | ||||
| 77611 | ** be the right kind (index or table) of b-tree page. Otherwise | ||||
| 77612 | ** a moveToChild() or moveToRoot() call would have detected corruption. */ | ||||
| 77613 | assert( pPage->nCell>0 )((void) (0)); | ||||
| 77614 | assert( pPage->intKey==0 )((void) (0)); | ||||
| 77615 | lwr = 0; | ||||
| 77616 | upr = pPage->nCell-1; | ||||
| 77617 | idx = upr>>1; /* idx = (lwr+upr)/2; */ | ||||
| 77618 | for(;;){ | ||||
| 77619 | int nCell; /* Size of the pCell cell in bytes */ | ||||
| 77620 | pCell = findCellPastPtr(pPage, idx)((pPage)->aDataOfst + ((pPage)->maskPage & ((&( pPage)->aCellIdx[2*(idx)])[0]<<8 | (&(pPage)-> aCellIdx[2*(idx)])[1]))); | ||||
| 77621 | |||||
| 77622 | /* The maximum supported page-size is 65536 bytes. This means that | ||||
| 77623 | ** the maximum number of record bytes stored on an index B-Tree | ||||
| 77624 | ** page is less than 16384 bytes and may be stored as a 2-byte | ||||
| 77625 | ** varint. This information is used to attempt to avoid parsing | ||||
| 77626 | ** the entire cell by checking for the cases where the record is | ||||
| 77627 | ** stored entirely within the b-tree page by inspecting the first | ||||
| 77628 | ** 2 bytes of the cell. | ||||
| 77629 | */ | ||||
| 77630 | nCell = pCell[0]; | ||||
| 77631 | if( nCell<=pPage->max1bytePayload ){ | ||||
| 77632 | /* This branch runs if the record-size field of the cell is a | ||||
| 77633 | ** single byte varint and the record fits entirely on the main | ||||
| 77634 | ** b-tree page. */ | ||||
| 77635 | testcase( pCell+nCell+1==pPage->aDataEnd ); | ||||
| 77636 | c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); | ||||
| 77637 | }else if( !(pCell[1] & 0x80) | ||||
| 77638 | && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal | ||||
| 77639 | ){ | ||||
| 77640 | /* The record-size field is a 2 byte varint and the record | ||||
| 77641 | ** fits entirely on the main b-tree page. */ | ||||
| 77642 | testcase( pCell+nCell+2==pPage->aDataEnd ); | ||||
| 77643 | c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); | ||||
| 77644 | }else{ | ||||
| 77645 | /* The record flows over onto one or more overflow pages. In | ||||
| 77646 | ** this case the whole cell needs to be parsed, a buffer allocated | ||||
| 77647 | ** and accessPayload() used to retrieve the record into the | ||||
| 77648 | ** buffer before VdbeRecordCompare() can be called. | ||||
| 77649 | ** | ||||
| 77650 | ** If the record is corrupt, the xRecordCompare routine may read | ||||
| 77651 | ** up to two varints past the end of the buffer. An extra 18 | ||||
| 77652 | ** bytes of padding is allocated at the end of the buffer in | ||||
| 77653 | ** case this happens. */ | ||||
| 77654 | void *pCellKey; | ||||
| 77655 | u8 * const pCellBody = pCell - pPage->childPtrSize; | ||||
| 77656 | const int nOverrun = 18; /* Size of the overrun padding */ | ||||
| 77657 | pPage->xParseCell(pPage, pCellBody, &pCur->info); | ||||
| 77658 | nCell = (int)pCur->info.nKey; | ||||
| 77659 | testcase( nCell<0 ); /* True if key size is 2^32 or more */ | ||||
| 77660 | testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ | ||||
| 77661 | testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ | ||||
| 77662 | testcase( nCell==2 ); /* Minimum legal index key size */ | ||||
| 77663 | if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){ | ||||
| 77664 | rc = SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(77664); | ||||
| 77665 | goto moveto_index_finish; | ||||
| 77666 | } | ||||
| 77667 | pCellKey = sqlite3Malloc( (u64)nCell+(u64)nOverrun ); | ||||
| 77668 | if( pCellKey==0 ){ | ||||
| 77669 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 77670 | goto moveto_index_finish; | ||||
| 77671 | } | ||||
| 77672 | pCur->ix = (u16)idx; | ||||
| 77673 | rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); | ||||
| 77674 | memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */ | ||||
| 77675 | pCur->curFlags &= ~BTCF_ValidOvfl0x04; | ||||
| 77676 | if( rc ){ | ||||
| 77677 | sqlite3_free(pCellKey); | ||||
| 77678 | goto moveto_index_finish; | ||||
| 77679 | } | ||||
| 77680 | c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); | ||||
| 77681 | sqlite3_free(pCellKey); | ||||
| 77682 | } | ||||
| 77683 | assert(((void) (0)) | ||||
| 77684 | (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)((void) (0)) | ||||
| 77685 | && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)((void) (0)) | ||||
| 77686 | )((void) (0)); | ||||
| 77687 | if( c<0 ){ | ||||
| 77688 | lwr = idx+1; | ||||
| 77689 | }else if( c>0 ){ | ||||
| 77690 | upr = idx-1; | ||||
| 77691 | }else{ | ||||
| 77692 | assert( c==0 )((void) (0)); | ||||
| 77693 | *pRes = 0; | ||||
| 77694 | rc = SQLITE_OK0; | ||||
| 77695 | pCur->ix = (u16)idx; | ||||
| 77696 | if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(77696); | ||||
| 77697 | goto moveto_index_finish; | ||||
| 77698 | } | ||||
| 77699 | if( lwr>upr ) break; | ||||
| 77700 | assert( lwr+upr>=0 )((void) (0)); | ||||
| 77701 | idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ | ||||
| 77702 | } | ||||
| 77703 | assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) )((void) (0)); | ||||
| 77704 | assert( pPage->isInit )((void) (0)); | ||||
| 77705 | if( pPage->leaf ){ | ||||
| 77706 | assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB )((void) (0)); | ||||
| 77707 | pCur->ix = (u16)idx; | ||||
| 77708 | *pRes = c; | ||||
| 77709 | rc = SQLITE_OK0; | ||||
| 77710 | goto moveto_index_finish; | ||||
| 77711 | } | ||||
| 77712 | if( lwr>=pPage->nCell ){ | ||||
| 77713 | chldPg = get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8]); | ||||
| 77714 | }else{ | ||||
| 77715 | chldPg = get4bytesqlite3Get4byte(findCell(pPage, lwr)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(lwr)])[0]<<8 | (&(pPage)->aCellIdx [2*(lwr)])[1])))); | ||||
| 77716 | } | ||||
| 77717 | |||||
| 77718 | /* This block is similar to an in-lined version of: | ||||
| 77719 | ** | ||||
| 77720 | ** pCur->ix = (u16)lwr; | ||||
| 77721 | ** rc = moveToChild(pCur, chldPg); | ||||
| 77722 | ** if( rc ) break; | ||||
| 77723 | */ | ||||
| 77724 | pCur->info.nSize = 0; | ||||
| 77725 | pCur->curFlags &= ~(BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04); | ||||
| 77726 | if( pCur->iPage>=(BTCURSOR_MAX_DEPTH20-1) ){ | ||||
| 77727 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(77727); | ||||
| 77728 | } | ||||
| 77729 | pCur->aiIdx[pCur->iPage] = (u16)lwr; | ||||
| 77730 | pCur->apPage[pCur->iPage] = pCur->pPage; | ||||
| 77731 | pCur->ix = 0; | ||||
| 77732 | pCur->iPage++; | ||||
| 77733 | rc = getAndInitPage(pCur->pBt, chldPg, &pCur->pPage, pCur->curPagerFlags); | ||||
| 77734 | if( rc==SQLITE_OK0 | ||||
| 77735 | && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey) | ||||
| 77736 | ){ | ||||
| 77737 | releasePage(pCur->pPage); | ||||
| 77738 | rc = SQLITE_CORRUPT_PGNO(chldPg)sqlite3CorruptError(77738); | ||||
| 77739 | } | ||||
| 77740 | if( rc ){ | ||||
| 77741 | pCur->pPage = pCur->apPage[--pCur->iPage]; | ||||
| 77742 | break; | ||||
| 77743 | } | ||||
| 77744 | /* | ||||
| 77745 | ***** End of in-lined moveToChild() call */ | ||||
| 77746 | } | ||||
| 77747 | moveto_index_finish: | ||||
| 77748 | pCur->info.nSize = 0; | ||||
| 77749 | assert( (pCur->curFlags & BTCF_ValidOvfl)==0 )((void) (0)); | ||||
| 77750 | return rc; | ||||
| 77751 | } | ||||
| 77752 | |||||
| 77753 | |||||
| 77754 | /* | ||||
| 77755 | ** Return TRUE if the cursor is not pointing at an entry of the table. | ||||
| 77756 | ** | ||||
| 77757 | ** TRUE will be returned after a call to sqlite3BtreeNext() moves | ||||
| 77758 | ** past the last entry in the table or sqlite3BtreePrev() moves past | ||||
| 77759 | ** the first entry. TRUE is also returned if the table is empty. | ||||
| 77760 | */ | ||||
| 77761 | SQLITE_PRIVATEstatic int sqlite3BtreeEof(BtCursor *pCur){ | ||||
| 77762 | /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries | ||||
| 77763 | ** have been deleted? This API will need to change to return an error code | ||||
| 77764 | ** as well as the boolean result value. | ||||
| 77765 | */ | ||||
| 77766 | return (CURSOR_VALID0!=pCur->eState); | ||||
| 77767 | } | ||||
| 77768 | |||||
| 77769 | /* | ||||
| 77770 | ** Return an estimate for the number of rows in the table that pCur is | ||||
| 77771 | ** pointing to. Return a negative number if no estimate is currently | ||||
| 77772 | ** available. | ||||
| 77773 | */ | ||||
| 77774 | SQLITE_PRIVATEstatic i64 sqlite3BtreeRowCountEst(BtCursor *pCur){ | ||||
| 77775 | i64 n; | ||||
| 77776 | u8 i; | ||||
| 77777 | |||||
| 77778 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77779 | assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) )((void) (0)); | ||||
| 77780 | |||||
| 77781 | /* Currently this interface is only called by the OP_IfSizeBetween | ||||
| 77782 | ** opcode and the OP_Count opcode with P3=1. In either case, | ||||
| 77783 | ** the cursor will always be valid unless the btree is empty. */ | ||||
| 77784 | if( pCur->eState!=CURSOR_VALID0 ) return 0; | ||||
| 77785 | if( NEVER(pCur->pPage->leaf==0)(pCur->pPage->leaf==0) ) return -1; | ||||
| 77786 | |||||
| 77787 | n = pCur->pPage->nCell; | ||||
| 77788 | for(i=0; i<pCur->iPage; i++){ | ||||
| 77789 | n *= pCur->apPage[i]->nCell; | ||||
| 77790 | } | ||||
| 77791 | return n; | ||||
| 77792 | } | ||||
| 77793 | |||||
| 77794 | /* | ||||
| 77795 | ** Advance the cursor to the next entry in the database. | ||||
| 77796 | ** Return value: | ||||
| 77797 | ** | ||||
| 77798 | ** SQLITE_OK success | ||||
| 77799 | ** SQLITE_DONE cursor is already pointing at the last element | ||||
| 77800 | ** otherwise some kind of error occurred | ||||
| 77801 | ** | ||||
| 77802 | ** The main entry point is sqlite3BtreeNext(). That routine is optimized | ||||
| 77803 | ** for the common case of merely incrementing the cell counter BtCursor.aiIdx | ||||
| 77804 | ** to the next cell on the current page. The (slower) btreeNext() helper | ||||
| 77805 | ** routine is called when it is necessary to move to a different page or | ||||
| 77806 | ** to restore the cursor. | ||||
| 77807 | ** | ||||
| 77808 | ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the | ||||
| 77809 | ** cursor corresponds to an SQL index and this routine could have been | ||||
| 77810 | ** skipped if the SQL index had been a unique index. The F argument | ||||
| 77811 | ** is a hint to the implement. SQLite btree implementation does not use | ||||
| 77812 | ** this hint, but COMDB2 does. | ||||
| 77813 | */ | ||||
| 77814 | static SQLITE_NOINLINE__attribute__((noinline)) int btreeNext(BtCursor *pCur){ | ||||
| 77815 | int rc; | ||||
| 77816 | int idx; | ||||
| 77817 | MemPage *pPage; | ||||
| 77818 | |||||
| 77819 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77820 | if( pCur->eState!=CURSOR_VALID0 ){ | ||||
| 77821 | assert( (pCur->curFlags & BTCF_ValidOvfl)==0 )((void) (0)); | ||||
| 77822 | rc = restoreCursorPosition(pCur)(pCur->eState>=3 ? btreeRestoreCursorPosition(pCur) : 0 ); | ||||
| 77823 | if( rc!=SQLITE_OK0 ){ | ||||
| 77824 | return rc; | ||||
| 77825 | } | ||||
| 77826 | if( CURSOR_INVALID1==pCur->eState ){ | ||||
| 77827 | return SQLITE_DONE101; | ||||
| 77828 | } | ||||
| 77829 | if( pCur->eState==CURSOR_SKIPNEXT2 ){ | ||||
| 77830 | pCur->eState = CURSOR_VALID0; | ||||
| 77831 | if( pCur->skipNext>0 ) return SQLITE_OK0; | ||||
| 77832 | } | ||||
| 77833 | } | ||||
| 77834 | |||||
| 77835 | pPage = pCur->pPage; | ||||
| 77836 | idx = ++pCur->ix; | ||||
| 77837 | if( sqlite3FaultSim(412) ) pPage->isInit = 0; | ||||
| 77838 | if( !pPage->isInit ){ | ||||
| 77839 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(77839); | ||||
| 77840 | } | ||||
| 77841 | |||||
| 77842 | if( idx>=pPage->nCell ){ | ||||
| 77843 | if( !pPage->leaf ){ | ||||
| 77844 | rc = moveToChild(pCur, get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8])); | ||||
| 77845 | if( rc ) return rc; | ||||
| 77846 | return moveToLeftmost(pCur); | ||||
| 77847 | } | ||||
| 77848 | do{ | ||||
| 77849 | if( pCur->iPage==0 ){ | ||||
| 77850 | pCur->eState = CURSOR_INVALID1; | ||||
| 77851 | return SQLITE_DONE101; | ||||
| 77852 | } | ||||
| 77853 | moveToParent(pCur); | ||||
| 77854 | pPage = pCur->pPage; | ||||
| 77855 | }while( pCur->ix>=pPage->nCell ); | ||||
| 77856 | if( pPage->intKey ){ | ||||
| 77857 | return sqlite3BtreeNext(pCur, 0); | ||||
| 77858 | }else{ | ||||
| 77859 | return SQLITE_OK0; | ||||
| 77860 | } | ||||
| 77861 | } | ||||
| 77862 | if( pPage->leaf ){ | ||||
| 77863 | return SQLITE_OK0; | ||||
| 77864 | }else{ | ||||
| 77865 | return moveToLeftmost(pCur); | ||||
| 77866 | } | ||||
| 77867 | } | ||||
| 77868 | SQLITE_PRIVATEstatic int sqlite3BtreeNext(BtCursor *pCur, int flags){ | ||||
| 77869 | MemPage *pPage; | ||||
| 77870 | UNUSED_PARAMETER( flags )(void)(flags); /* Used in COMDB2 but not native SQLite */ | ||||
| 77871 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77872 | assert( flags==0 || flags==1 )((void) (0)); | ||||
| 77873 | pCur->info.nSize = 0; | ||||
| 77874 | pCur->curFlags &= ~(BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04); | ||||
| 77875 | if( pCur->eState!=CURSOR_VALID0 ) return btreeNext(pCur); | ||||
| 77876 | pPage = pCur->pPage; | ||||
| 77877 | if( (++pCur->ix)>=pPage->nCell ){ | ||||
| 77878 | pCur->ix--; | ||||
| 77879 | return btreeNext(pCur); | ||||
| 77880 | } | ||||
| 77881 | if( pPage->leaf ){ | ||||
| 77882 | return SQLITE_OK0; | ||||
| 77883 | }else{ | ||||
| 77884 | return moveToLeftmost(pCur); | ||||
| 77885 | } | ||||
| 77886 | } | ||||
| 77887 | |||||
| 77888 | /* | ||||
| 77889 | ** Step the cursor to the back to the previous entry in the database. | ||||
| 77890 | ** Return values: | ||||
| 77891 | ** | ||||
| 77892 | ** SQLITE_OK success | ||||
| 77893 | ** SQLITE_DONE the cursor is already on the first element of the table | ||||
| 77894 | ** otherwise some kind of error occurred | ||||
| 77895 | ** | ||||
| 77896 | ** The main entry point is sqlite3BtreePrevious(). That routine is optimized | ||||
| 77897 | ** for the common case of merely decrementing the cell counter BtCursor.aiIdx | ||||
| 77898 | ** to the previous cell on the current page. The (slower) btreePrevious() | ||||
| 77899 | ** helper routine is called when it is necessary to move to a different page | ||||
| 77900 | ** or to restore the cursor. | ||||
| 77901 | ** | ||||
| 77902 | ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then | ||||
| 77903 | ** the cursor corresponds to an SQL index and this routine could have been | ||||
| 77904 | ** skipped if the SQL index had been a unique index. The F argument is a | ||||
| 77905 | ** hint to the implement. The native SQLite btree implementation does not | ||||
| 77906 | ** use this hint, but COMDB2 does. | ||||
| 77907 | */ | ||||
| 77908 | static SQLITE_NOINLINE__attribute__((noinline)) int btreePrevious(BtCursor *pCur){ | ||||
| 77909 | int rc; | ||||
| 77910 | MemPage *pPage; | ||||
| 77911 | |||||
| 77912 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77913 | assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 )((void) (0)); | ||||
| 77914 | assert( pCur->info.nSize==0 )((void) (0)); | ||||
| 77915 | if( pCur->eState!=CURSOR_VALID0 ){ | ||||
| 77916 | rc = restoreCursorPosition(pCur)(pCur->eState>=3 ? btreeRestoreCursorPosition(pCur) : 0 ); | ||||
| 77917 | if( rc!=SQLITE_OK0 ){ | ||||
| 77918 | return rc; | ||||
| 77919 | } | ||||
| 77920 | if( CURSOR_INVALID1==pCur->eState ){ | ||||
| 77921 | return SQLITE_DONE101; | ||||
| 77922 | } | ||||
| 77923 | if( CURSOR_SKIPNEXT2==pCur->eState ){ | ||||
| 77924 | pCur->eState = CURSOR_VALID0; | ||||
| 77925 | if( pCur->skipNext<0 ) return SQLITE_OK0; | ||||
| 77926 | } | ||||
| 77927 | } | ||||
| 77928 | |||||
| 77929 | pPage = pCur->pPage; | ||||
| 77930 | if( sqlite3FaultSim(412) ) pPage->isInit = 0; | ||||
| 77931 | if( !pPage->isInit ){ | ||||
| 77932 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(77932); | ||||
| 77933 | } | ||||
| 77934 | if( !pPage->leaf ){ | ||||
| 77935 | int idx = pCur->ix; | ||||
| 77936 | rc = moveToChild(pCur, get4bytesqlite3Get4byte(findCell(pPage, idx)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(idx)])[0]<<8 | (&(pPage)->aCellIdx [2*(idx)])[1]))))); | ||||
| 77937 | if( rc ) return rc; | ||||
| 77938 | rc = moveToRightmost(pCur); | ||||
| 77939 | }else{ | ||||
| 77940 | while( pCur->ix==0 ){ | ||||
| 77941 | if( pCur->iPage==0 ){ | ||||
| 77942 | pCur->eState = CURSOR_INVALID1; | ||||
| 77943 | return SQLITE_DONE101; | ||||
| 77944 | } | ||||
| 77945 | moveToParent(pCur); | ||||
| 77946 | } | ||||
| 77947 | assert( pCur->info.nSize==0 )((void) (0)); | ||||
| 77948 | assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 )((void) (0)); | ||||
| 77949 | |||||
| 77950 | pCur->ix--; | ||||
| 77951 | pPage = pCur->pPage; | ||||
| 77952 | if( pPage->intKey && !pPage->leaf ){ | ||||
| 77953 | rc = sqlite3BtreePrevious(pCur, 0); | ||||
| 77954 | }else{ | ||||
| 77955 | rc = SQLITE_OK0; | ||||
| 77956 | } | ||||
| 77957 | } | ||||
| 77958 | return rc; | ||||
| 77959 | } | ||||
| 77960 | SQLITE_PRIVATEstatic int sqlite3BtreePrevious(BtCursor *pCur, int flags){ | ||||
| 77961 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 77962 | assert( flags==0 || flags==1 )((void) (0)); | ||||
| 77963 | UNUSED_PARAMETER( flags )(void)(flags); /* Used in COMDB2 but not native SQLite */ | ||||
| 77964 | pCur->curFlags &= ~(BTCF_AtLast0x08|BTCF_ValidOvfl0x04|BTCF_ValidNKey0x02); | ||||
| 77965 | pCur->info.nSize = 0; | ||||
| 77966 | if( pCur->eState!=CURSOR_VALID0 | ||||
| 77967 | || pCur->ix==0 | ||||
| 77968 | || pCur->pPage->leaf==0 | ||||
| 77969 | ){ | ||||
| 77970 | return btreePrevious(pCur); | ||||
| 77971 | } | ||||
| 77972 | pCur->ix--; | ||||
| 77973 | return SQLITE_OK0; | ||||
| 77974 | } | ||||
| 77975 | |||||
| 77976 | /* | ||||
| 77977 | ** Allocate a new page from the database file. | ||||
| 77978 | ** | ||||
| 77979 | ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() | ||||
| 77980 | ** has already been called on the new page.) The new page has also | ||||
| 77981 | ** been referenced and the calling routine is responsible for calling | ||||
| 77982 | ** sqlite3PagerUnref() on the new page when it is done. | ||||
| 77983 | ** | ||||
| 77984 | ** SQLITE_OK is returned on success. Any other return value indicates | ||||
| 77985 | ** an error. *ppPage is set to NULL in the event of an error. | ||||
| 77986 | ** | ||||
| 77987 | ** If the "nearby" parameter is not 0, then an effort is made to | ||||
| 77988 | ** locate a page close to the page number "nearby". This can be used in an | ||||
| 77989 | ** attempt to keep related pages close to each other in the database file, | ||||
| 77990 | ** which in turn can make database access faster. | ||||
| 77991 | ** | ||||
| 77992 | ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists | ||||
| 77993 | ** anywhere on the free-list, then it is guaranteed to be returned. If | ||||
| 77994 | ** eMode is BTALLOC_LT then the page returned will be less than or equal | ||||
| 77995 | ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there | ||||
| 77996 | ** are no restrictions on which page is returned. | ||||
| 77997 | */ | ||||
| 77998 | static int allocateBtreePage( | ||||
| 77999 | BtShared *pBt, /* The btree */ | ||||
| 78000 | MemPage **ppPage, /* Store pointer to the allocated page here */ | ||||
| 78001 | Pgno *pPgno, /* Store the page number here */ | ||||
| 78002 | Pgno nearby, /* Search for a page near this one */ | ||||
| 78003 | u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ | ||||
| 78004 | ){ | ||||
| 78005 | MemPage *pPage1; | ||||
| 78006 | int rc; | ||||
| 78007 | u32 n; /* Number of pages on the freelist */ | ||||
| 78008 | u32 k; /* Number of leaves on the trunk of the freelist */ | ||||
| 78009 | MemPage *pTrunk = 0; | ||||
| 78010 | MemPage *pPrevTrunk = 0; | ||||
| 78011 | Pgno mxPage; /* Total size of the database file */ | ||||
| 78012 | |||||
| 78013 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 78014 | assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) )((void) (0)); | ||||
| 78015 | pPage1 = pBt->pPage1; | ||||
| 78016 | mxPage = btreePagecount(pBt); | ||||
| 78017 | /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36 | ||||
| 78018 | ** stores the total number of pages on the freelist. */ | ||||
| 78019 | n = get4bytesqlite3Get4byte(&pPage1->aData[36]); | ||||
| 78020 | testcase( n==mxPage-1 ); | ||||
| 78021 | if( n>=mxPage ){ | ||||
| 78022 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(78022); | ||||
| 78023 | } | ||||
| 78024 | if( n>0 ){ | ||||
| 78025 | /* There are pages on the freelist. Reuse one of those pages. */ | ||||
| 78026 | Pgno iTrunk; | ||||
| 78027 | u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ | ||||
| 78028 | u32 nSearch = 0; /* Count of the number of search attempts */ | ||||
| 78029 | |||||
| 78030 | /* If eMode==BTALLOC_EXACT and a query of the pointer-map | ||||
| 78031 | ** shows that the page 'nearby' is somewhere on the free-list, then | ||||
| 78032 | ** the entire-list will be searched for that page. | ||||
| 78033 | */ | ||||
| 78034 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 78035 | if( eMode==BTALLOC_EXACT1 ){ | ||||
| 78036 | if( nearby<=mxPage ){ | ||||
| 78037 | u8 eType; | ||||
| 78038 | assert( nearby>0 )((void) (0)); | ||||
| 78039 | assert( pBt->autoVacuum )((void) (0)); | ||||
| 78040 | rc = ptrmapGet(pBt, nearby, &eType, 0); | ||||
| 78041 | if( rc ) return rc; | ||||
| 78042 | if( eType==PTRMAP_FREEPAGE2 ){ | ||||
| 78043 | searchList = 1; | ||||
| 78044 | } | ||||
| 78045 | } | ||||
| 78046 | }else if( eMode==BTALLOC_LE2 ){ | ||||
| 78047 | searchList = 1; | ||||
| 78048 | } | ||||
| 78049 | #endif | ||||
| 78050 | |||||
| 78051 | /* Decrement the free-list count by 1. Set iTrunk to the index of the | ||||
| 78052 | ** first free-list trunk page. iPrevTrunk is initially 1. | ||||
| 78053 | */ | ||||
| 78054 | rc = sqlite3PagerWrite(pPage1->pDbPage); | ||||
| 78055 | if( rc ) return rc; | ||||
| 78056 | put4bytesqlite3Put4byte(&pPage1->aData[36], n-1); | ||||
| 78057 | |||||
| 78058 | /* The code within this loop is run only once if the 'searchList' variable | ||||
| 78059 | ** is not true. Otherwise, it runs once for each trunk-page on the | ||||
| 78060 | ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) | ||||
| 78061 | ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) | ||||
| 78062 | */ | ||||
| 78063 | do { | ||||
| 78064 | pPrevTrunk = pTrunk; | ||||
| 78065 | if( pPrevTrunk ){ | ||||
| 78066 | /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page | ||||
| 78067 | ** is the page number of the next freelist trunk page in the list or | ||||
| 78068 | ** zero if this is the last freelist trunk page. */ | ||||
| 78069 | iTrunk = get4bytesqlite3Get4byte(&pPrevTrunk->aData[0]); | ||||
| 78070 | }else{ | ||||
| 78071 | /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32 | ||||
| 78072 | ** stores the page number of the first page of the freelist, or zero if | ||||
| 78073 | ** the freelist is empty. */ | ||||
| 78074 | iTrunk = get4bytesqlite3Get4byte(&pPage1->aData[32]); | ||||
| 78075 | } | ||||
| 78076 | testcase( iTrunk==mxPage ); | ||||
| 78077 | if( iTrunk>mxPage || nSearch++ > n ){ | ||||
| 78078 | rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1)sqlite3CorruptError(78078); | ||||
| 78079 | }else{ | ||||
| 78080 | rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); | ||||
| 78081 | } | ||||
| 78082 | if( rc ){ | ||||
| 78083 | pTrunk = 0; | ||||
| 78084 | goto end_allocate_page; | ||||
| 78085 | } | ||||
| 78086 | assert( pTrunk!=0 )((void) (0)); | ||||
| 78087 | assert( pTrunk->aData!=0 )((void) (0)); | ||||
| 78088 | /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page | ||||
| 78089 | ** is the number of leaf page pointers to follow. */ | ||||
| 78090 | k = get4bytesqlite3Get4byte(&pTrunk->aData[4]); | ||||
| 78091 | if( k==0 && !searchList ){ | ||||
| 78092 | /* The trunk has no leaves and the list is not being searched. | ||||
| 78093 | ** So extract the trunk page itself and use it as the newly | ||||
| 78094 | ** allocated page */ | ||||
| 78095 | assert( pPrevTrunk==0 )((void) (0)); | ||||
| 78096 | rc = sqlite3PagerWrite(pTrunk->pDbPage); | ||||
| 78097 | if( rc ){ | ||||
| 78098 | goto end_allocate_page; | ||||
| 78099 | } | ||||
| 78100 | *pPgno = iTrunk; | ||||
| 78101 | memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); | ||||
| 78102 | *ppPage = pTrunk; | ||||
| 78103 | pTrunk = 0; | ||||
| 78104 | TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1)); | ||||
| 78105 | }else if( k>(u32)(pBt->usableSize/4 - 2) ){ | ||||
| 78106 | /* Value of k is out of range. Database corruption */ | ||||
| 78107 | rc = SQLITE_CORRUPT_PGNO(iTrunk)sqlite3CorruptError(78107); | ||||
| 78108 | goto end_allocate_page; | ||||
| 78109 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 78110 | }else if( searchList | ||||
| 78111 | && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE2)) | ||||
| 78112 | ){ | ||||
| 78113 | /* The list is being searched and this trunk page is the page | ||||
| 78114 | ** to allocate, regardless of whether it has leaves. | ||||
| 78115 | */ | ||||
| 78116 | *pPgno = iTrunk; | ||||
| 78117 | *ppPage = pTrunk; | ||||
| 78118 | searchList = 0; | ||||
| 78119 | rc = sqlite3PagerWrite(pTrunk->pDbPage); | ||||
| 78120 | if( rc ){ | ||||
| 78121 | goto end_allocate_page; | ||||
| 78122 | } | ||||
| 78123 | if( k==0 ){ | ||||
| 78124 | if( !pPrevTrunk ){ | ||||
| 78125 | memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); | ||||
| 78126 | }else{ | ||||
| 78127 | rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); | ||||
| 78128 | if( rc!=SQLITE_OK0 ){ | ||||
| 78129 | goto end_allocate_page; | ||||
| 78130 | } | ||||
| 78131 | memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); | ||||
| 78132 | } | ||||
| 78133 | }else{ | ||||
| 78134 | /* The trunk page is required by the caller but it contains | ||||
| 78135 | ** pointers to free-list leaves. The first leaf becomes a trunk | ||||
| 78136 | ** page in this case. | ||||
| 78137 | */ | ||||
| 78138 | MemPage *pNewTrunk; | ||||
| 78139 | Pgno iNewTrunk = get4bytesqlite3Get4byte(&pTrunk->aData[8]); | ||||
| 78140 | if( iNewTrunk>mxPage ){ | ||||
| 78141 | rc = SQLITE_CORRUPT_PGNO(iTrunk)sqlite3CorruptError(78141); | ||||
| 78142 | goto end_allocate_page; | ||||
| 78143 | } | ||||
| 78144 | testcase( iNewTrunk==mxPage ); | ||||
| 78145 | rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0); | ||||
| 78146 | if( rc!=SQLITE_OK0 ){ | ||||
| 78147 | goto end_allocate_page; | ||||
| 78148 | } | ||||
| 78149 | rc = sqlite3PagerWrite(pNewTrunk->pDbPage); | ||||
| 78150 | if( rc!=SQLITE_OK0 ){ | ||||
| 78151 | releasePage(pNewTrunk); | ||||
| 78152 | goto end_allocate_page; | ||||
| 78153 | } | ||||
| 78154 | memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); | ||||
| 78155 | put4bytesqlite3Put4byte(&pNewTrunk->aData[4], k-1); | ||||
| 78156 | memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); | ||||
| 78157 | releasePage(pNewTrunk); | ||||
| 78158 | if( !pPrevTrunk ){ | ||||
| 78159 | assert( sqlite3PagerIswriteable(pPage1->pDbPage) )((void) (0)); | ||||
| 78160 | put4bytesqlite3Put4byte(&pPage1->aData[32], iNewTrunk); | ||||
| 78161 | }else{ | ||||
| 78162 | rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); | ||||
| 78163 | if( rc ){ | ||||
| 78164 | goto end_allocate_page; | ||||
| 78165 | } | ||||
| 78166 | put4bytesqlite3Put4byte(&pPrevTrunk->aData[0], iNewTrunk); | ||||
| 78167 | } | ||||
| 78168 | } | ||||
| 78169 | pTrunk = 0; | ||||
| 78170 | TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1)); | ||||
| 78171 | #endif | ||||
| 78172 | }else if( k>0 ){ | ||||
| 78173 | /* Extract a leaf from the trunk */ | ||||
| 78174 | u32 closest; | ||||
| 78175 | Pgno iPage; | ||||
| 78176 | unsigned char *aData = pTrunk->aData; | ||||
| 78177 | if( nearby>0 ){ | ||||
| 78178 | u32 i; | ||||
| 78179 | closest = 0; | ||||
| 78180 | if( eMode==BTALLOC_LE2 ){ | ||||
| 78181 | for(i=0; i<k; i++){ | ||||
| 78182 | iPage = get4bytesqlite3Get4byte(&aData[8+i*4]); | ||||
| 78183 | if( iPage<=nearby ){ | ||||
| 78184 | closest = i; | ||||
| 78185 | break; | ||||
| 78186 | } | ||||
| 78187 | } | ||||
| 78188 | }else{ | ||||
| 78189 | int dist; | ||||
| 78190 | dist = sqlite3AbsInt32(get4bytesqlite3Get4byte(&aData[8]) - nearby); | ||||
| 78191 | for(i=1; i<k; i++){ | ||||
| 78192 | int d2 = sqlite3AbsInt32(get4bytesqlite3Get4byte(&aData[8+i*4]) - nearby); | ||||
| 78193 | if( d2<dist ){ | ||||
| 78194 | closest = i; | ||||
| 78195 | dist = d2; | ||||
| 78196 | } | ||||
| 78197 | } | ||||
| 78198 | } | ||||
| 78199 | }else{ | ||||
| 78200 | closest = 0; | ||||
| 78201 | } | ||||
| 78202 | |||||
| 78203 | iPage = get4bytesqlite3Get4byte(&aData[8+closest*4]); | ||||
| 78204 | testcase( iPage==mxPage ); | ||||
| 78205 | if( iPage>mxPage || iPage<2 ){ | ||||
| 78206 | rc = SQLITE_CORRUPT_PGNO(iTrunk)sqlite3CorruptError(78206); | ||||
| 78207 | goto end_allocate_page; | ||||
| 78208 | } | ||||
| 78209 | testcase( iPage==mxPage ); | ||||
| 78210 | if( !searchList | ||||
| 78211 | || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE2)) | ||||
| 78212 | ){ | ||||
| 78213 | int noContent; | ||||
| 78214 | *pPgno = iPage; | ||||
| 78215 | TRACE(("ALLOCATE: %u was leaf %u of %u on trunk %u" | ||||
| 78216 | ": %u more free pages\n", | ||||
| 78217 | *pPgno, closest+1, k, pTrunk->pgno, n-1)); | ||||
| 78218 | rc = sqlite3PagerWrite(pTrunk->pDbPage); | ||||
| 78219 | if( rc ) goto end_allocate_page; | ||||
| 78220 | if( closest<k-1 ){ | ||||
| 78221 | memcpy(&aData[8+closest*4], &aData[4+k*4], 4); | ||||
| 78222 | } | ||||
| 78223 | put4bytesqlite3Put4byte(&aData[4], k-1); | ||||
| 78224 | noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT0x01 : 0; | ||||
| 78225 | rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent); | ||||
| 78226 | if( rc==SQLITE_OK0 ){ | ||||
| 78227 | rc = sqlite3PagerWrite((*ppPage)->pDbPage); | ||||
| 78228 | if( rc!=SQLITE_OK0 ){ | ||||
| 78229 | releasePage(*ppPage); | ||||
| 78230 | *ppPage = 0; | ||||
| 78231 | } | ||||
| 78232 | } | ||||
| 78233 | searchList = 0; | ||||
| 78234 | } | ||||
| 78235 | } | ||||
| 78236 | releasePage(pPrevTrunk); | ||||
| 78237 | pPrevTrunk = 0; | ||||
| 78238 | }while( searchList ); | ||||
| 78239 | }else{ | ||||
| 78240 | /* There are no pages on the freelist, so append a new page to the | ||||
| 78241 | ** database image. | ||||
| 78242 | ** | ||||
| 78243 | ** Normally, new pages allocated by this block can be requested from the | ||||
| 78244 | ** pager layer with the 'no-content' flag set. This prevents the pager | ||||
| 78245 | ** from trying to read the pages content from disk. However, if the | ||||
| 78246 | ** current transaction has already run one or more incremental-vacuum | ||||
| 78247 | ** steps, then the page we are about to allocate may contain content | ||||
| 78248 | ** that is required in the event of a rollback. In this case, do | ||||
| 78249 | ** not set the no-content flag. This causes the pager to load and journal | ||||
| 78250 | ** the current page content before overwriting it. | ||||
| 78251 | ** | ||||
| 78252 | ** Note that the pager will not actually attempt to load or journal | ||||
| 78253 | ** content for any page that really does lie past the end of the database | ||||
| 78254 | ** file on disk. So the effects of disabling the no-content optimization | ||||
| 78255 | ** here are confined to those pages that lie between the end of the | ||||
| 78256 | ** database image and the end of the database file. | ||||
| 78257 | */ | ||||
| 78258 | int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)(pBt->bDoTruncate))? PAGER_GET_NOCONTENT0x01:0; | ||||
| 78259 | |||||
| 78260 | rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | ||||
| 78261 | if( rc ) return rc; | ||||
| 78262 | pBt->nPage++; | ||||
| 78263 | if( pBt->nPage==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ) pBt->nPage++; | ||||
| 78264 | |||||
| 78265 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 78266 | if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage)(ptrmapPageno((pBt), (pBt->nPage))==(pBt->nPage)) ){ | ||||
| 78267 | /* If *pPgno refers to a pointer-map page, allocate two new pages | ||||
| 78268 | ** at the end of the file instead of one. The first allocated page | ||||
| 78269 | ** becomes a new pointer-map page, the second is used by the caller. | ||||
| 78270 | */ | ||||
| 78271 | MemPage *pPg = 0; | ||||
| 78272 | TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage)); | ||||
| 78273 | assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) )((void) (0)); | ||||
| 78274 | rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); | ||||
| 78275 | if( rc==SQLITE_OK0 ){ | ||||
| 78276 | rc = sqlite3PagerWrite(pPg->pDbPage); | ||||
| 78277 | releasePage(pPg); | ||||
| 78278 | } | ||||
| 78279 | if( rc ) return rc; | ||||
| 78280 | pBt->nPage++; | ||||
| 78281 | if( pBt->nPage==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ pBt->nPage++; } | ||||
| 78282 | } | ||||
| 78283 | #endif | ||||
| 78284 | put4bytesqlite3Put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); | ||||
| 78285 | *pPgno = pBt->nPage; | ||||
| 78286 | |||||
| 78287 | assert( *pPgno!=PENDING_BYTE_PAGE(pBt) )((void) (0)); | ||||
| 78288 | rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); | ||||
| 78289 | if( rc ) return rc; | ||||
| 78290 | rc = sqlite3PagerWrite((*ppPage)->pDbPage); | ||||
| 78291 | if( rc!=SQLITE_OK0 ){ | ||||
| 78292 | releasePage(*ppPage); | ||||
| 78293 | *ppPage = 0; | ||||
| 78294 | } | ||||
| 78295 | TRACE(("ALLOCATE: %u from end of file\n", *pPgno)); | ||||
| 78296 | } | ||||
| 78297 | |||||
| 78298 | assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) )((void) (0)); | ||||
| 78299 | |||||
| 78300 | end_allocate_page: | ||||
| 78301 | releasePage(pTrunk); | ||||
| 78302 | releasePage(pPrevTrunk); | ||||
| 78303 | assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 )((void) (0)); | ||||
| 78304 | assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 )((void) (0)); | ||||
| 78305 | return rc; | ||||
| 78306 | } | ||||
| 78307 | |||||
| 78308 | /* | ||||
| 78309 | ** This function is used to add page iPage to the database file free-list. | ||||
| 78310 | ** It is assumed that the page is not already a part of the free-list. | ||||
| 78311 | ** | ||||
| 78312 | ** The value passed as the second argument to this function is optional. | ||||
| 78313 | ** If the caller happens to have a pointer to the MemPage object | ||||
| 78314 | ** corresponding to page iPage handy, it may pass it as the second value. | ||||
| 78315 | ** Otherwise, it may pass NULL. | ||||
| 78316 | ** | ||||
| 78317 | ** If a pointer to a MemPage object is passed as the second argument, | ||||
| 78318 | ** its reference count is not altered by this function. | ||||
| 78319 | */ | ||||
| 78320 | static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ | ||||
| 78321 | MemPage *pTrunk = 0; /* Free-list trunk page */ | ||||
| 78322 | Pgno iTrunk = 0; /* Page number of free-list trunk page */ | ||||
| 78323 | MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ | ||||
| 78324 | MemPage *pPage; /* Page being freed. May be NULL. */ | ||||
| 78325 | int rc; /* Return Code */ | ||||
| 78326 | u32 nFree; /* Initial number of pages on free-list */ | ||||
| 78327 | |||||
| 78328 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 78329 | assert( CORRUPT_DB || iPage>1 )((void) (0)); | ||||
| 78330 | assert( !pMemPage || pMemPage->pgno==iPage )((void) (0)); | ||||
| 78331 | |||||
| 78332 | if( iPage<2 || iPage>pBt->nPage ){ | ||||
| 78333 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(78333); | ||||
| 78334 | } | ||||
| 78335 | if( pMemPage ){ | ||||
| 78336 | pPage = pMemPage; | ||||
| 78337 | sqlite3PagerRef(pPage->pDbPage); | ||||
| 78338 | }else{ | ||||
| 78339 | pPage = btreePageLookup(pBt, iPage); | ||||
| 78340 | } | ||||
| 78341 | |||||
| 78342 | /* Increment the free page count on pPage1 */ | ||||
| 78343 | rc = sqlite3PagerWrite(pPage1->pDbPage); | ||||
| 78344 | if( rc ) goto freepage_out; | ||||
| 78345 | nFree = get4bytesqlite3Get4byte(&pPage1->aData[36]); | ||||
| 78346 | put4bytesqlite3Put4byte(&pPage1->aData[36], nFree+1); | ||||
| 78347 | |||||
| 78348 | if( pBt->btsFlags & BTS_SECURE_DELETE0x0004 ){ | ||||
| 78349 | /* If the secure_delete option is enabled, then | ||||
| 78350 | ** always fully overwrite deleted information with zeros. | ||||
| 78351 | */ | ||||
| 78352 | if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) | ||||
| 78353 | || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) | ||||
| 78354 | ){ | ||||
| 78355 | goto freepage_out; | ||||
| 78356 | } | ||||
| 78357 | memset(pPage->aData, 0, pPage->pBt->pageSize); | ||||
| 78358 | } | ||||
| 78359 | |||||
| 78360 | /* If the database supports auto-vacuum, write an entry in the pointer-map | ||||
| 78361 | ** to indicate that the page is free. | ||||
| 78362 | */ | ||||
| 78363 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) ){ | ||||
| 78364 | ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE2, 0, &rc); | ||||
| 78365 | if( rc ) goto freepage_out; | ||||
| 78366 | } | ||||
| 78367 | |||||
| 78368 | /* Now manipulate the actual database free-list structure. There are two | ||||
| 78369 | ** possibilities. If the free-list is currently empty, or if the first | ||||
| 78370 | ** trunk page in the free-list is full, then this page will become a | ||||
| 78371 | ** new free-list trunk page. Otherwise, it will become a leaf of the | ||||
| 78372 | ** first trunk page in the current free-list. This block tests if it | ||||
| 78373 | ** is possible to add the page as a new free-list leaf. | ||||
| 78374 | */ | ||||
| 78375 | if( nFree!=0 ){ | ||||
| 78376 | u32 nLeaf; /* Initial number of leaf cells on trunk page */ | ||||
| 78377 | |||||
| 78378 | iTrunk = get4bytesqlite3Get4byte(&pPage1->aData[32]); | ||||
| 78379 | if( iTrunk>btreePagecount(pBt) ){ | ||||
| 78380 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(78380); | ||||
| 78381 | goto freepage_out; | ||||
| 78382 | } | ||||
| 78383 | rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); | ||||
| 78384 | if( rc!=SQLITE_OK0 ){ | ||||
| 78385 | goto freepage_out; | ||||
| 78386 | } | ||||
| 78387 | |||||
| 78388 | nLeaf = get4bytesqlite3Get4byte(&pTrunk->aData[4]); | ||||
| 78389 | assert( pBt->usableSize>32 )((void) (0)); | ||||
| 78390 | if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ | ||||
| 78391 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(78391); | ||||
| 78392 | goto freepage_out; | ||||
| 78393 | } | ||||
| 78394 | if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ | ||||
| 78395 | /* In this case there is room on the trunk page to insert the page | ||||
| 78396 | ** being freed as a new leaf. | ||||
| 78397 | ** | ||||
| 78398 | ** Note that the trunk page is not really full until it contains | ||||
| 78399 | ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have | ||||
| 78400 | ** coded. But due to a coding error in versions of SQLite prior to | ||||
| 78401 | ** 3.6.0, databases with freelist trunk pages holding more than | ||||
| 78402 | ** usableSize/4 - 8 entries will be reported as corrupt. In order | ||||
| 78403 | ** to maintain backwards compatibility with older versions of SQLite, | ||||
| 78404 | ** we will continue to restrict the number of entries to usableSize/4 - 8 | ||||
| 78405 | ** for now. At some point in the future (once everyone has upgraded | ||||
| 78406 | ** to 3.6.0 or later) we should consider fixing the conditional above | ||||
| 78407 | ** to read "usableSize/4-2" instead of "usableSize/4-8". | ||||
| 78408 | ** | ||||
| 78409 | ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still | ||||
| 78410 | ** avoid using the last six entries in the freelist trunk page array in | ||||
| 78411 | ** order that database files created by newer versions of SQLite can be | ||||
| 78412 | ** read by older versions of SQLite. | ||||
| 78413 | */ | ||||
| 78414 | rc = sqlite3PagerWrite(pTrunk->pDbPage); | ||||
| 78415 | if( rc==SQLITE_OK0 ){ | ||||
| 78416 | put4bytesqlite3Put4byte(&pTrunk->aData[4], nLeaf+1); | ||||
| 78417 | put4bytesqlite3Put4byte(&pTrunk->aData[8+nLeaf*4], iPage); | ||||
| 78418 | if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE0x0004)==0 ){ | ||||
| 78419 | sqlite3PagerDontWrite(pPage->pDbPage); | ||||
| 78420 | } | ||||
| 78421 | rc = btreeSetHasContent(pBt, iPage); | ||||
| 78422 | } | ||||
| 78423 | TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno)); | ||||
| 78424 | goto freepage_out; | ||||
| 78425 | } | ||||
| 78426 | } | ||||
| 78427 | |||||
| 78428 | /* If control flows to this point, then it was not possible to add the | ||||
| 78429 | ** the page being freed as a leaf page of the first trunk in the free-list. | ||||
| 78430 | ** Possibly because the free-list is empty, or possibly because the | ||||
| 78431 | ** first trunk in the free-list is full. Either way, the page being freed | ||||
| 78432 | ** will become the new first trunk page in the free-list. | ||||
| 78433 | */ | ||||
| 78434 | if( pPage==0 && SQLITE_OK0!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ | ||||
| 78435 | goto freepage_out; | ||||
| 78436 | } | ||||
| 78437 | rc = sqlite3PagerWrite(pPage->pDbPage); | ||||
| 78438 | if( rc!=SQLITE_OK0 ){ | ||||
| 78439 | goto freepage_out; | ||||
| 78440 | } | ||||
| 78441 | put4bytesqlite3Put4byte(pPage->aData, iTrunk); | ||||
| 78442 | put4bytesqlite3Put4byte(&pPage->aData[4], 0); | ||||
| 78443 | put4bytesqlite3Put4byte(&pPage1->aData[32], iPage); | ||||
| 78444 | TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk)); | ||||
| 78445 | |||||
| 78446 | freepage_out: | ||||
| 78447 | if( pPage ){ | ||||
| 78448 | pPage->isInit = 0; | ||||
| 78449 | } | ||||
| 78450 | releasePage(pPage); | ||||
| 78451 | releasePage(pTrunk); | ||||
| 78452 | return rc; | ||||
| 78453 | } | ||||
| 78454 | static void freePage(MemPage *pPage, int *pRC){ | ||||
| 78455 | if( (*pRC)==SQLITE_OK0 ){ | ||||
| 78456 | *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); | ||||
| 78457 | } | ||||
| 78458 | } | ||||
| 78459 | |||||
| 78460 | /* | ||||
| 78461 | ** Free the overflow pages associated with the given Cell. | ||||
| 78462 | */ | ||||
| 78463 | static SQLITE_NOINLINE__attribute__((noinline)) int clearCellOverflow( | ||||
| 78464 | MemPage *pPage, /* The page that contains the Cell */ | ||||
| 78465 | unsigned char *pCell, /* First byte of the Cell */ | ||||
| 78466 | CellInfo *pInfo /* Size information about the cell */ | ||||
| 78467 | ){ | ||||
| 78468 | BtShared *pBt; | ||||
| 78469 | Pgno ovflPgno; | ||||
| 78470 | int rc; | ||||
| 78471 | int nOvfl; | ||||
| 78472 | u32 ovflPageSize; | ||||
| 78473 | |||||
| 78474 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 78475 | assert( pInfo->nLocal!=pInfo->nPayload )((void) (0)); | ||||
| 78476 | testcase( pCell + pInfo->nSize == pPage->aDataEnd ); | ||||
| 78477 | testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd ); | ||||
| 78478 | if( pCell + pInfo->nSize > pPage->aDataEnd ){ | ||||
| 78479 | /* Cell extends past end of page */ | ||||
| 78480 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(78480); | ||||
| 78481 | } | ||||
| 78482 | ovflPgno = get4bytesqlite3Get4byte(pCell + pInfo->nSize - 4); | ||||
| 78483 | pBt = pPage->pBt; | ||||
| 78484 | assert( pBt->usableSize > 4 )((void) (0)); | ||||
| 78485 | ovflPageSize = pBt->usableSize - 4; | ||||
| 78486 | nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize; | ||||
| 78487 | assert( nOvfl>0 ||((void) (0)) | ||||
| 78488 | (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)((void) (0)) | ||||
| 78489 | )((void) (0)); | ||||
| 78490 | while( nOvfl-- ){ | ||||
| 78491 | Pgno iNext = 0; | ||||
| 78492 | MemPage *pOvfl = 0; | ||||
| 78493 | if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ | ||||
| 78494 | /* 0 is not a legal page number and page 1 cannot be an | ||||
| 78495 | ** overflow page. Therefore if ovflPgno<2 or past the end of the | ||||
| 78496 | ** file the database must be corrupt. */ | ||||
| 78497 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(78497); | ||||
| 78498 | } | ||||
| 78499 | if( nOvfl ){ | ||||
| 78500 | rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); | ||||
| 78501 | if( rc ) return rc; | ||||
| 78502 | } | ||||
| 78503 | |||||
| 78504 | if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) | ||||
| 78505 | && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 | ||||
| 78506 | ){ | ||||
| 78507 | /* There is no reason any cursor should have an outstanding reference | ||||
| 78508 | ** to an overflow page belonging to a cell that is being deleted/updated. | ||||
| 78509 | ** So if there exists more than one reference to this page, then it | ||||
| 78510 | ** must not really be an overflow page and the database must be corrupt. | ||||
| 78511 | ** It is helpful to detect this before calling freePage2(), as | ||||
| 78512 | ** freePage2() may zero the page contents if secure-delete mode is | ||||
| 78513 | ** enabled. If this 'overflow' page happens to be a page that the | ||||
| 78514 | ** caller is iterating through or using in some other way, this | ||||
| 78515 | ** can be problematic. | ||||
| 78516 | */ | ||||
| 78517 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(78517); | ||||
| 78518 | }else{ | ||||
| 78519 | rc = freePage2(pBt, pOvfl, ovflPgno); | ||||
| 78520 | } | ||||
| 78521 | |||||
| 78522 | if( pOvfl ){ | ||||
| 78523 | sqlite3PagerUnref(pOvfl->pDbPage); | ||||
| 78524 | } | ||||
| 78525 | if( rc ) return rc; | ||||
| 78526 | ovflPgno = iNext; | ||||
| 78527 | } | ||||
| 78528 | return SQLITE_OK0; | ||||
| 78529 | } | ||||
| 78530 | |||||
| 78531 | /* Call xParseCell to compute the size of a cell. If the cell contains | ||||
| 78532 | ** overflow, then invoke cellClearOverflow to clear out that overflow. | ||||
| 78533 | ** Store the result code (SQLITE_OK or some error code) in rc. | ||||
| 78534 | ** | ||||
| 78535 | ** Implemented as macro to force inlining for performance. | ||||
| 78536 | */ | ||||
| 78537 | #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo)pPage->xParseCell(pPage, pCell, &sInfo); if( sInfo.nLocal !=sInfo.nPayload ){ rc = clearCellOverflow(pPage, pCell, & sInfo); }else{ rc = 0; } \ | ||||
| 78538 | pPage->xParseCell(pPage, pCell, &sInfo); \ | ||||
| 78539 | if( sInfo.nLocal!=sInfo.nPayload ){ \ | ||||
| 78540 | rc = clearCellOverflow(pPage, pCell, &sInfo); \ | ||||
| 78541 | }else{ \ | ||||
| 78542 | rc = SQLITE_OK0; \ | ||||
| 78543 | } | ||||
| 78544 | |||||
| 78545 | |||||
| 78546 | /* | ||||
| 78547 | ** Create the byte sequence used to represent a cell on page pPage | ||||
| 78548 | ** and write that byte sequence into pCell[]. Overflow pages are | ||||
| 78549 | ** allocated and filled in as necessary. The calling procedure | ||||
| 78550 | ** is responsible for making sure sufficient space has been allocated | ||||
| 78551 | ** for pCell[]. | ||||
| 78552 | ** | ||||
| 78553 | ** Note that pCell does not necessary need to point to the pPage->aData | ||||
| 78554 | ** area. pCell might point to some temporary storage. The cell will | ||||
| 78555 | ** be constructed in this temporary area then copied into pPage->aData | ||||
| 78556 | ** later. | ||||
| 78557 | */ | ||||
| 78558 | static int fillInCell( | ||||
| 78559 | MemPage *pPage, /* The page that contains the cell */ | ||||
| 78560 | unsigned char *pCell, /* Complete text of the cell */ | ||||
| 78561 | const BtreePayload *pX, /* Payload with which to construct the cell */ | ||||
| 78562 | int *pnSize /* Write cell size here */ | ||||
| 78563 | ){ | ||||
| 78564 | int nPayload; | ||||
| 78565 | const u8 *pSrc; | ||||
| 78566 | int nSrc, n, rc, mn; | ||||
| 78567 | int spaceLeft; | ||||
| 78568 | MemPage *pToRelease; | ||||
| 78569 | unsigned char *pPrior; | ||||
| 78570 | unsigned char *pPayload; | ||||
| 78571 | BtShared *pBt; | ||||
| 78572 | Pgno pgnoOvfl; | ||||
| 78573 | int nHeader; | ||||
| 78574 | |||||
| 78575 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 78576 | |||||
| 78577 | /* pPage is not necessarily writeable since pCell might be auxiliary | ||||
| 78578 | ** buffer space that is separate from the pPage buffer area */ | ||||
| 78579 | assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]((void) (0)) | ||||
| 78580 | || sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 78581 | |||||
| 78582 | /* Fill in the header. */ | ||||
| 78583 | nHeader = pPage->childPtrSize; | ||||
| 78584 | if( pPage->intKey ){ | ||||
| 78585 | nPayload = pX->nData + pX->nZero; | ||||
| 78586 | pSrc = pX->pData; | ||||
| 78587 | nSrc = pX->nData; | ||||
| 78588 | assert( pPage->intKeyLeaf )((void) (0)); /* fillInCell() only called for leaves */ | ||||
| 78589 | nHeader += putVarint32(&pCell[nHeader], nPayload)(u8)(((u32)(nPayload)<(u32)0x80)?(*(&pCell[nHeader])=( unsigned char)(nPayload)),1: sqlite3PutVarint((&pCell[nHeader ]),(nPayload))); | ||||
| 78590 | nHeader += putVarintsqlite3PutVarint(&pCell[nHeader], *(u64*)&pX->nKey); | ||||
| 78591 | }else{ | ||||
| 78592 | assert( pX->nKey<=0x7fffffff && pX->pKey!=0 )((void) (0)); | ||||
| 78593 | nSrc = nPayload = (int)pX->nKey; | ||||
| 78594 | pSrc = pX->pKey; | ||||
| 78595 | nHeader += putVarint32(&pCell[nHeader], nPayload)(u8)(((u32)(nPayload)<(u32)0x80)?(*(&pCell[nHeader])=( unsigned char)(nPayload)),1: sqlite3PutVarint((&pCell[nHeader ]),(nPayload))); | ||||
| 78596 | } | ||||
| 78597 | |||||
| 78598 | /* Fill in the payload */ | ||||
| 78599 | pPayload = &pCell[nHeader]; | ||||
| 78600 | if( nPayload<=pPage->maxLocal ){ | ||||
| 78601 | /* This is the common case where everything fits on the btree page | ||||
| 78602 | ** and no overflow pages are required. */ | ||||
| 78603 | n = nHeader + nPayload; | ||||
| 78604 | testcase( n==3 ); | ||||
| 78605 | testcase( n==4 ); | ||||
| 78606 | if( n<4 ){ | ||||
| 78607 | n = 4; | ||||
| 78608 | pPayload[nPayload] = 0; | ||||
| 78609 | } | ||||
| 78610 | *pnSize = n; | ||||
| 78611 | assert( nSrc<=nPayload )((void) (0)); | ||||
| 78612 | testcase( nSrc<nPayload ); | ||||
| 78613 | memcpy(pPayload, pSrc, nSrc); | ||||
| 78614 | memset(pPayload+nSrc, 0, nPayload-nSrc); | ||||
| 78615 | return SQLITE_OK0; | ||||
| 78616 | } | ||||
| 78617 | |||||
| 78618 | /* If we reach this point, it means that some of the content will need | ||||
| 78619 | ** to spill onto overflow pages. | ||||
| 78620 | */ | ||||
| 78621 | mn = pPage->minLocal; | ||||
| 78622 | n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); | ||||
| 78623 | testcase( n==pPage->maxLocal ); | ||||
| 78624 | testcase( n==pPage->maxLocal+1 ); | ||||
| 78625 | if( n > pPage->maxLocal ) n = mn; | ||||
| 78626 | spaceLeft = n; | ||||
| 78627 | *pnSize = n + nHeader + 4; | ||||
| 78628 | pPrior = &pCell[nHeader+n]; | ||||
| 78629 | pToRelease = 0; | ||||
| 78630 | pgnoOvfl = 0; | ||||
| 78631 | pBt = pPage->pBt; | ||||
| 78632 | |||||
| 78633 | /* At this point variables should be set as follows: | ||||
| 78634 | ** | ||||
| 78635 | ** nPayload Total payload size in bytes | ||||
| 78636 | ** pPayload Begin writing payload here | ||||
| 78637 | ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, | ||||
| 78638 | ** that means content must spill into overflow pages. | ||||
| 78639 | ** *pnSize Size of the local cell (not counting overflow pages) | ||||
| 78640 | ** pPrior Where to write the pgno of the first overflow page | ||||
| 78641 | ** | ||||
| 78642 | ** Use a call to btreeParseCellPtr() to verify that the values above | ||||
| 78643 | ** were computed correctly. | ||||
| 78644 | */ | ||||
| 78645 | #ifdef SQLITE_DEBUG | ||||
| 78646 | { | ||||
| 78647 | CellInfo info; | ||||
| 78648 | pPage->xParseCell(pPage, pCell, &info); | ||||
| 78649 | assert( nHeader==(int)(info.pPayload - pCell) )((void) (0)); | ||||
| 78650 | assert( info.nKey==pX->nKey )((void) (0)); | ||||
| 78651 | assert( *pnSize == info.nSize )((void) (0)); | ||||
| 78652 | assert( spaceLeft == info.nLocal )((void) (0)); | ||||
| 78653 | } | ||||
| 78654 | #endif | ||||
| 78655 | |||||
| 78656 | /* Write the payload into the local Cell and any extra into overflow pages */ | ||||
| 78657 | while( 1 ){ | ||||
| 78658 | n = nPayload; | ||||
| 78659 | if( n>spaceLeft ) n = spaceLeft; | ||||
| 78660 | |||||
| 78661 | /* If pToRelease is not zero than pPayload points into the data area | ||||
| 78662 | ** of pToRelease. Make sure pToRelease is still writeable. */ | ||||
| 78663 | assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) )((void) (0)); | ||||
| 78664 | |||||
| 78665 | /* If pPayload is part of the data area of pPage, then make sure pPage | ||||
| 78666 | ** is still writeable */ | ||||
| 78667 | assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]((void) (0)) | ||||
| 78668 | || sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 78669 | |||||
| 78670 | if( nSrc>=n ){ | ||||
| 78671 | memcpy(pPayload, pSrc, n); | ||||
| 78672 | }else if( nSrc>0 ){ | ||||
| 78673 | n = nSrc; | ||||
| 78674 | memcpy(pPayload, pSrc, n); | ||||
| 78675 | }else{ | ||||
| 78676 | memset(pPayload, 0, n); | ||||
| 78677 | } | ||||
| 78678 | nPayload -= n; | ||||
| 78679 | if( nPayload<=0 ) break; | ||||
| 78680 | pPayload += n; | ||||
| 78681 | pSrc += n; | ||||
| 78682 | nSrc -= n; | ||||
| 78683 | spaceLeft -= n; | ||||
| 78684 | if( spaceLeft==0 ){ | ||||
| 78685 | MemPage *pOvfl = 0; | ||||
| 78686 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 78687 | Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ | ||||
| 78688 | if( pBt->autoVacuum ){ | ||||
| 78689 | do{ | ||||
| 78690 | pgnoOvfl++; | ||||
| 78691 | } while( | ||||
| 78692 | PTRMAP_ISPAGE(pBt, pgnoOvfl)(ptrmapPageno((pBt), (pgnoOvfl))==(pgnoOvfl)) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) | ||||
| 78693 | ); | ||||
| 78694 | } | ||||
| 78695 | #endif | ||||
| 78696 | rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); | ||||
| 78697 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 78698 | /* If the database supports auto-vacuum, and the second or subsequent | ||||
| 78699 | ** overflow page is being allocated, add an entry to the pointer-map | ||||
| 78700 | ** for that page now. | ||||
| 78701 | ** | ||||
| 78702 | ** If this is the first overflow page, then write a partial entry | ||||
| 78703 | ** to the pointer-map. If we write nothing to this pointer-map slot, | ||||
| 78704 | ** then the optimistic overflow chain processing in clearCell() | ||||
| 78705 | ** may misinterpret the uninitialized values and delete the | ||||
| 78706 | ** wrong pages from the database. | ||||
| 78707 | */ | ||||
| 78708 | if( pBt->autoVacuum && rc==SQLITE_OK0 ){ | ||||
| 78709 | u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW24:PTRMAP_OVERFLOW13); | ||||
| 78710 | ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); | ||||
| 78711 | if( rc ){ | ||||
| 78712 | releasePage(pOvfl); | ||||
| 78713 | } | ||||
| 78714 | } | ||||
| 78715 | #endif | ||||
| 78716 | if( rc ){ | ||||
| 78717 | releasePage(pToRelease); | ||||
| 78718 | return rc; | ||||
| 78719 | } | ||||
| 78720 | |||||
| 78721 | /* If pToRelease is not zero than pPrior points into the data area | ||||
| 78722 | ** of pToRelease. Make sure pToRelease is still writeable. */ | ||||
| 78723 | assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) )((void) (0)); | ||||
| 78724 | |||||
| 78725 | /* If pPrior is part of the data area of pPage, then make sure pPage | ||||
| 78726 | ** is still writeable */ | ||||
| 78727 | assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]((void) (0)) | ||||
| 78728 | || sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 78729 | |||||
| 78730 | put4bytesqlite3Put4byte(pPrior, pgnoOvfl); | ||||
| 78731 | releasePage(pToRelease); | ||||
| 78732 | pToRelease = pOvfl; | ||||
| 78733 | pPrior = pOvfl->aData; | ||||
| 78734 | put4bytesqlite3Put4byte(pPrior, 0); | ||||
| 78735 | pPayload = &pOvfl->aData[4]; | ||||
| 78736 | spaceLeft = pBt->usableSize - 4; | ||||
| 78737 | } | ||||
| 78738 | } | ||||
| 78739 | releasePage(pToRelease); | ||||
| 78740 | return SQLITE_OK0; | ||||
| 78741 | } | ||||
| 78742 | |||||
| 78743 | /* | ||||
| 78744 | ** Remove the i-th cell from pPage. This routine effects pPage only. | ||||
| 78745 | ** The cell content is not freed or deallocated. It is assumed that | ||||
| 78746 | ** the cell content has been copied someplace else. This routine just | ||||
| 78747 | ** removes the reference to the cell from pPage. | ||||
| 78748 | ** | ||||
| 78749 | ** "sz" must be the number of bytes in the cell. | ||||
| 78750 | */ | ||||
| 78751 | static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ | ||||
| 78752 | u32 pc; /* Offset to cell content of cell being deleted */ | ||||
| 78753 | u8 *data; /* pPage->aData */ | ||||
| 78754 | u8 *ptr; /* Used to move bytes around within data[] */ | ||||
| 78755 | int rc; /* The return code */ | ||||
| 78756 | int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ | ||||
| 78757 | |||||
| 78758 | if( *pRC ) return; | ||||
| 78759 | assert( idx>=0 )((void) (0)); | ||||
| 78760 | assert( idx<pPage->nCell )((void) (0)); | ||||
| 78761 | assert( CORRUPT_DB || sz==cellSize(pPage, idx) )((void) (0)); | ||||
| 78762 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 78763 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 78764 | assert( pPage->nFree>=0 )((void) (0)); | ||||
| 78765 | data = pPage->aData; | ||||
| 78766 | ptr = &pPage->aCellIdx[2*idx]; | ||||
| 78767 | assert( pPage->pBt->usableSize > (u32)(ptr-data) )((void) (0)); | ||||
| 78768 | pc = get2byte(ptr)((ptr)[0]<<8 | (ptr)[1]); | ||||
| 78769 | hdr = pPage->hdrOffset; | ||||
| 78770 | testcase( pc==(u32)get2byte(&data[hdr+5]) ); | ||||
| 78771 | testcase( pc+sz==pPage->pBt->usableSize ); | ||||
| 78772 | if( pc+sz > pPage->pBt->usableSize ){ | ||||
| 78773 | *pRC = SQLITE_CORRUPT_BKPTsqlite3CorruptError(78773); | ||||
| 78774 | return; | ||||
| 78775 | } | ||||
| 78776 | rc = freeSpace(pPage, pc, sz); | ||||
| 78777 | if( rc ){ | ||||
| 78778 | *pRC = rc; | ||||
| 78779 | return; | ||||
| 78780 | } | ||||
| 78781 | pPage->nCell--; | ||||
| 78782 | if( pPage->nCell==0 ){ | ||||
| 78783 | memset(&data[hdr+1], 0, 4); | ||||
| 78784 | data[hdr+7] = 0; | ||||
| 78785 | put2byte(&data[hdr+5], pPage->pBt->usableSize)((&data[hdr+5])[0] = (u8)((pPage->pBt->usableSize)>> 8), (&data[hdr+5])[1] = (u8)(pPage->pBt->usableSize )); | ||||
| 78786 | pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset | ||||
| 78787 | - pPage->childPtrSize - 8; | ||||
| 78788 | }else{ | ||||
| 78789 | memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); | ||||
| 78790 | put2byte(&data[hdr+3], pPage->nCell)((&data[hdr+3])[0] = (u8)((pPage->nCell)>>8), (& data[hdr+3])[1] = (u8)(pPage->nCell)); | ||||
| 78791 | pPage->nFree += 2; | ||||
| 78792 | } | ||||
| 78793 | } | ||||
| 78794 | |||||
| 78795 | /* | ||||
| 78796 | ** Insert a new cell on pPage at cell index "i". pCell points to the | ||||
| 78797 | ** content of the cell. | ||||
| 78798 | ** | ||||
| 78799 | ** If the cell content will fit on the page, then put it there. If it | ||||
| 78800 | ** will not fit, then make a copy of the cell content into pTemp if | ||||
| 78801 | ** pTemp is not null. Regardless of pTemp, allocate a new entry | ||||
| 78802 | ** in pPage->apOvfl[] and make it point to the cell content (either | ||||
| 78803 | ** in pTemp or the original pCell) and also record its index. | ||||
| 78804 | ** Allocating a new entry in pPage->aCell[] implies that | ||||
| 78805 | ** pPage->nOverflow is incremented. | ||||
| 78806 | ** | ||||
| 78807 | ** The insertCellFast() routine below works exactly the same as | ||||
| 78808 | ** insertCell() except that it lacks the pTemp and iChild parameters | ||||
| 78809 | ** which are assumed zero. Other than that, the two routines are the | ||||
| 78810 | ** same. | ||||
| 78811 | ** | ||||
| 78812 | ** Fixes or enhancements to this routine should be reflected in | ||||
| 78813 | ** insertCellFast()! | ||||
| 78814 | */ | ||||
| 78815 | static int insertCell( | ||||
| 78816 | MemPage *pPage, /* Page into which we are copying */ | ||||
| 78817 | int i, /* New cell becomes the i-th cell of the page */ | ||||
| 78818 | u8 *pCell, /* Content of the new cell */ | ||||
| 78819 | int sz, /* Bytes of content in pCell */ | ||||
| 78820 | u8 *pTemp, /* Temp storage space for pCell, if needed */ | ||||
| 78821 | Pgno iChild /* If non-zero, replace first 4 bytes with this value */ | ||||
| 78822 | ){ | ||||
| 78823 | int idx = 0; /* Where to write new cell content in data[] */ | ||||
| 78824 | int j; /* Loop counter */ | ||||
| 78825 | u8 *data; /* The content of the whole page */ | ||||
| 78826 | u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ | ||||
| 78827 | |||||
| 78828 | assert( i>=0 && i<=pPage->nCell+pPage->nOverflow )((void) (0)); | ||||
| 78829 | assert( MX_CELL(pPage->pBt)<=10921 )((void) (0)); | ||||
| 78830 | assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB )((void) (0)); | ||||
| 78831 | assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) )((void) (0)); | ||||
| 78832 | assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) )((void) (0)); | ||||
| 78833 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 78834 | assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB )((void) (0)); | ||||
| 78835 | assert( pPage->nFree>=0 )((void) (0)); | ||||
| 78836 | assert( iChild>0 )((void) (0)); | ||||
| 78837 | if( pPage->nOverflow || sz+2>pPage->nFree ){ | ||||
| 78838 | if( pTemp ){ | ||||
| 78839 | memcpy(pTemp, pCell, sz); | ||||
| 78840 | pCell = pTemp; | ||||
| 78841 | } | ||||
| 78842 | put4bytesqlite3Put4byte(pCell, iChild); | ||||
| 78843 | j = pPage->nOverflow++; | ||||
| 78844 | /* Comparison against ArraySize-1 since we hold back one extra slot | ||||
| 78845 | ** as a contingency. In other words, never need more than 3 overflow | ||||
| 78846 | ** slots but 4 are allocated, just to be safe. */ | ||||
| 78847 | assert( j < ArraySize(pPage->apOvfl)-1 )((void) (0)); | ||||
| 78848 | pPage->apOvfl[j] = pCell; | ||||
| 78849 | pPage->aiOvfl[j] = (u16)i; | ||||
| 78850 | |||||
| 78851 | /* When multiple overflows occur, they are always sequential and in | ||||
| 78852 | ** sorted order. This invariants arise because multiple overflows can | ||||
| 78853 | ** only occur when inserting divider cells into the parent page during | ||||
| 78854 | ** balancing, and the dividers are adjacent and sorted. | ||||
| 78855 | */ | ||||
| 78856 | assert( j==0 || pPage->aiOvfl[j-1]<(u16)i )((void) (0)); /* Overflows in sorted order */ | ||||
| 78857 | assert( j==0 || i==pPage->aiOvfl[j-1]+1 )((void) (0)); /* Overflows are sequential */ | ||||
| 78858 | }else{ | ||||
| 78859 | int rc = sqlite3PagerWrite(pPage->pDbPage); | ||||
| 78860 | if( NEVER(rc!=SQLITE_OK)(rc!=0) ){ | ||||
| 78861 | return rc; | ||||
| 78862 | } | ||||
| 78863 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 78864 | data = pPage->aData; | ||||
| 78865 | assert( &data[pPage->cellOffset]==pPage->aCellIdx )((void) (0)); | ||||
| 78866 | rc = allocateSpace(pPage, sz, &idx); | ||||
| 78867 | if( rc ){ return rc; } | ||||
| 78868 | /* The allocateSpace() routine guarantees the following properties | ||||
| 78869 | ** if it returns successfully */ | ||||
| 78870 | assert( idx >= 0 )((void) (0)); | ||||
| 78871 | assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB )((void) (0)); | ||||
| 78872 | assert( idx+sz <= (int)pPage->pBt->usableSize )((void) (0)); | ||||
| 78873 | pPage->nFree -= (u16)(2 + sz); | ||||
| 78874 | /* In a corrupt database where an entry in the cell index section of | ||||
| 78875 | ** a btree page has a value of 3 or less, the pCell value might point | ||||
| 78876 | ** as many as 4 bytes in front of the start of the aData buffer for | ||||
| 78877 | ** the source page. Make sure this does not cause problems by not | ||||
| 78878 | ** reading the first 4 bytes */ | ||||
| 78879 | memcpy(&data[idx+4], pCell+4, sz-4); | ||||
| 78880 | put4bytesqlite3Put4byte(&data[idx], iChild); | ||||
| 78881 | pIns = pPage->aCellIdx + i*2; | ||||
| 78882 | memmove(pIns+2, pIns, 2*(pPage->nCell - i)); | ||||
| 78883 | put2byte(pIns, idx)((pIns)[0] = (u8)((idx)>>8), (pIns)[1] = (u8)(idx)); | ||||
| 78884 | pPage->nCell++; | ||||
| 78885 | /* increment the cell count */ | ||||
| 78886 | if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; | ||||
| 78887 | assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB )((void) (0)); | ||||
| 78888 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 78889 | if( pPage->pBt->autoVacuum ){ | ||||
| 78890 | int rc2 = SQLITE_OK0; | ||||
| 78891 | /* The cell may contain a pointer to an overflow page. If so, write | ||||
| 78892 | ** the entry for the overflow page into the pointer map. | ||||
| 78893 | */ | ||||
| 78894 | ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2); | ||||
| 78895 | if( rc2 ) return rc2; | ||||
| 78896 | } | ||||
| 78897 | #endif | ||||
| 78898 | } | ||||
| 78899 | return SQLITE_OK0; | ||||
| 78900 | } | ||||
| 78901 | |||||
| 78902 | /* | ||||
| 78903 | ** This variant of insertCell() assumes that the pTemp and iChild | ||||
| 78904 | ** parameters are both zero. Use this variant in sqlite3BtreeInsert() | ||||
| 78905 | ** for performance improvement, and also so that this variant is only | ||||
| 78906 | ** called from that one place, and is thus inlined, and thus runs must | ||||
| 78907 | ** faster. | ||||
| 78908 | ** | ||||
| 78909 | ** Fixes or enhancements to this routine should be reflected into | ||||
| 78910 | ** the insertCell() routine. | ||||
| 78911 | */ | ||||
| 78912 | static int insertCellFast( | ||||
| 78913 | MemPage *pPage, /* Page into which we are copying */ | ||||
| 78914 | int i, /* New cell becomes the i-th cell of the page */ | ||||
| 78915 | u8 *pCell, /* Content of the new cell */ | ||||
| 78916 | int sz /* Bytes of content in pCell */ | ||||
| 78917 | ){ | ||||
| 78918 | int idx = 0; /* Where to write new cell content in data[] */ | ||||
| 78919 | int j; /* Loop counter */ | ||||
| 78920 | u8 *data; /* The content of the whole page */ | ||||
| 78921 | u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ | ||||
| 78922 | |||||
| 78923 | assert( i>=0 && i<=pPage->nCell+pPage->nOverflow )((void) (0)); | ||||
| 78924 | assert( MX_CELL(pPage->pBt)<=10921 )((void) (0)); | ||||
| 78925 | assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB )((void) (0)); | ||||
| 78926 | assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) )((void) (0)); | ||||
| 78927 | assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) )((void) (0)); | ||||
| 78928 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 78929 | assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB )((void) (0)); | ||||
| 78930 | assert( pPage->nFree>=0 )((void) (0)); | ||||
| 78931 | assert( pPage->nOverflow==0 )((void) (0)); | ||||
| 78932 | if( sz+2>pPage->nFree ){ | ||||
| 78933 | j = pPage->nOverflow++; | ||||
| 78934 | /* Comparison against ArraySize-1 since we hold back one extra slot | ||||
| 78935 | ** as a contingency. In other words, never need more than 3 overflow | ||||
| 78936 | ** slots but 4 are allocated, just to be safe. */ | ||||
| 78937 | assert( j < ArraySize(pPage->apOvfl)-1 )((void) (0)); | ||||
| 78938 | pPage->apOvfl[j] = pCell; | ||||
| 78939 | pPage->aiOvfl[j] = (u16)i; | ||||
| 78940 | |||||
| 78941 | /* When multiple overflows occur, they are always sequential and in | ||||
| 78942 | ** sorted order. This invariants arise because multiple overflows can | ||||
| 78943 | ** only occur when inserting divider cells into the parent page during | ||||
| 78944 | ** balancing, and the dividers are adjacent and sorted. | ||||
| 78945 | */ | ||||
| 78946 | assert( j==0 || pPage->aiOvfl[j-1]<(u16)i )((void) (0)); /* Overflows in sorted order */ | ||||
| 78947 | assert( j==0 || i==pPage->aiOvfl[j-1]+1 )((void) (0)); /* Overflows are sequential */ | ||||
| 78948 | }else{ | ||||
| 78949 | int rc = sqlite3PagerWrite(pPage->pDbPage); | ||||
| 78950 | if( rc!=SQLITE_OK0 ){ | ||||
| 78951 | return rc; | ||||
| 78952 | } | ||||
| 78953 | assert( sqlite3PagerIswriteable(pPage->pDbPage) )((void) (0)); | ||||
| 78954 | data = pPage->aData; | ||||
| 78955 | assert( &data[pPage->cellOffset]==pPage->aCellIdx )((void) (0)); | ||||
| 78956 | rc = allocateSpace(pPage, sz, &idx); | ||||
| 78957 | if( rc ){ return rc; } | ||||
| 78958 | /* The allocateSpace() routine guarantees the following properties | ||||
| 78959 | ** if it returns successfully */ | ||||
| 78960 | assert( idx >= 0 )((void) (0)); | ||||
| 78961 | assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB )((void) (0)); | ||||
| 78962 | assert( idx+sz <= (int)pPage->pBt->usableSize )((void) (0)); | ||||
| 78963 | pPage->nFree -= (u16)(2 + sz); | ||||
| 78964 | memcpy(&data[idx], pCell, sz); | ||||
| 78965 | pIns = pPage->aCellIdx + i*2; | ||||
| 78966 | memmove(pIns+2, pIns, 2*(pPage->nCell - i)); | ||||
| 78967 | put2byte(pIns, idx)((pIns)[0] = (u8)((idx)>>8), (pIns)[1] = (u8)(idx)); | ||||
| 78968 | pPage->nCell++; | ||||
| 78969 | /* increment the cell count */ | ||||
| 78970 | if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; | ||||
| 78971 | assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB )((void) (0)); | ||||
| 78972 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 78973 | if( pPage->pBt->autoVacuum ){ | ||||
| 78974 | int rc2 = SQLITE_OK0; | ||||
| 78975 | /* The cell may contain a pointer to an overflow page. If so, write | ||||
| 78976 | ** the entry for the overflow page into the pointer map. | ||||
| 78977 | */ | ||||
| 78978 | ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2); | ||||
| 78979 | if( rc2 ) return rc2; | ||||
| 78980 | } | ||||
| 78981 | #endif | ||||
| 78982 | } | ||||
| 78983 | return SQLITE_OK0; | ||||
| 78984 | } | ||||
| 78985 | |||||
| 78986 | /* | ||||
| 78987 | ** The following parameters determine how many adjacent pages get involved | ||||
| 78988 | ** in a balancing operation. NN is the number of neighbors on either side | ||||
| 78989 | ** of the page that participate in the balancing operation. NB is the | ||||
| 78990 | ** total number of pages that participate, including the target page and | ||||
| 78991 | ** NN neighbors on either side. | ||||
| 78992 | ** | ||||
| 78993 | ** The minimum value of NN is 1 (of course). Increasing NN above 1 | ||||
| 78994 | ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance | ||||
| 78995 | ** in exchange for a larger degradation in INSERT and UPDATE performance. | ||||
| 78996 | ** The value of NN appears to give the best results overall. | ||||
| 78997 | ** | ||||
| 78998 | ** (Later:) The description above makes it seem as if these values are | ||||
| 78999 | ** tunable - as if you could change them and recompile and it would all work. | ||||
| 79000 | ** But that is unlikely. NB has been 3 since the inception of SQLite and | ||||
| 79001 | ** we have never tested any other value. | ||||
| 79002 | */ | ||||
| 79003 | #define NN1 1 /* Number of neighbors on either side of pPage */ | ||||
| 79004 | #define NB3 3 /* (NN*2+1): Total pages involved in the balance */ | ||||
| 79005 | |||||
| 79006 | /* | ||||
| 79007 | ** A CellArray object contains a cache of pointers and sizes for a | ||||
| 79008 | ** consecutive sequence of cells that might be held on multiple pages. | ||||
| 79009 | ** | ||||
| 79010 | ** The cells in this array are the divider cell or cells from the pParent | ||||
| 79011 | ** page plus up to three child pages. There are a total of nCell cells. | ||||
| 79012 | ** | ||||
| 79013 | ** pRef is a pointer to one of the pages that contributes cells. This is | ||||
| 79014 | ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize | ||||
| 79015 | ** which should be common to all pages that contribute cells to this array. | ||||
| 79016 | ** | ||||
| 79017 | ** apCell[] and szCell[] hold, respectively, pointers to the start of each | ||||
| 79018 | ** cell and the size of each cell. Some of the apCell[] pointers might refer | ||||
| 79019 | ** to overflow cells. In other words, some apCel[] pointers might not point | ||||
| 79020 | ** to content area of the pages. | ||||
| 79021 | ** | ||||
| 79022 | ** A szCell[] of zero means the size of that cell has not yet been computed. | ||||
| 79023 | ** | ||||
| 79024 | ** The cells come from as many as four different pages: | ||||
| 79025 | ** | ||||
| 79026 | ** ----------- | ||||
| 79027 | ** | Parent | | ||||
| 79028 | ** ----------- | ||||
| 79029 | ** / | \ | ||||
| 79030 | ** / | \ | ||||
| 79031 | ** --------- --------- --------- | ||||
| 79032 | ** |Child-1| |Child-2| |Child-3| | ||||
| 79033 | ** --------- --------- --------- | ||||
| 79034 | ** | ||||
| 79035 | ** The order of cells is in the array is for an index btree is: | ||||
| 79036 | ** | ||||
| 79037 | ** 1. All cells from Child-1 in order | ||||
| 79038 | ** 2. The first divider cell from Parent | ||||
| 79039 | ** 3. All cells from Child-2 in order | ||||
| 79040 | ** 4. The second divider cell from Parent | ||||
| 79041 | ** 5. All cells from Child-3 in order | ||||
| 79042 | ** | ||||
| 79043 | ** For a table-btree (with rowids) the items 2 and 4 are empty because | ||||
| 79044 | ** content exists only in leaves and there are no divider cells. | ||||
| 79045 | ** | ||||
| 79046 | ** For an index btree, the apEnd[] array holds pointer to the end of page | ||||
| 79047 | ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3, | ||||
| 79048 | ** respectively. The ixNx[] array holds the number of cells contained in | ||||
| 79049 | ** each of these 5 stages, and all stages to the left. Hence: | ||||
| 79050 | ** | ||||
| 79051 | ** ixNx[0] = Number of cells in Child-1. | ||||
| 79052 | ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider. | ||||
| 79053 | ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider. | ||||
| 79054 | ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells | ||||
| 79055 | ** ixNx[4] = Total number of cells. | ||||
| 79056 | ** | ||||
| 79057 | ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2] | ||||
| 79058 | ** are used and they point to the leaf pages only, and the ixNx value are: | ||||
| 79059 | ** | ||||
| 79060 | ** ixNx[0] = Number of cells in Child-1. | ||||
| 79061 | ** ixNx[1] = Number of cells in Child-1 and Child-2. | ||||
| 79062 | ** ixNx[2] = Total number of cells. | ||||
| 79063 | ** | ||||
| 79064 | ** Sometimes when deleting, a child page can have zero cells. In those | ||||
| 79065 | ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[] | ||||
| 79066 | ** entries, shift down. The end result is that each ixNx[] entry should | ||||
| 79067 | ** be larger than the previous | ||||
| 79068 | */ | ||||
| 79069 | typedef struct CellArray CellArray; | ||||
| 79070 | struct CellArray { | ||||
| 79071 | int nCell; /* Number of cells in apCell[] */ | ||||
| 79072 | MemPage *pRef; /* Reference page */ | ||||
| 79073 | u8 **apCell; /* All cells begin balanced */ | ||||
| 79074 | u16 *szCell; /* Local size of all cells in apCell[] */ | ||||
| 79075 | u8 *apEnd[NB3*2]; /* MemPage.aDataEnd values */ | ||||
| 79076 | int ixNx[NB3*2]; /* Index of at which we move to the next apEnd[] */ | ||||
| 79077 | }; | ||||
| 79078 | |||||
| 79079 | /* | ||||
| 79080 | ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been | ||||
| 79081 | ** computed. | ||||
| 79082 | */ | ||||
| 79083 | static void populateCellCache(CellArray *p, int idx, int N){ | ||||
| 79084 | MemPage *pRef = p->pRef; | ||||
| 79085 | u16 *szCell = p->szCell; | ||||
| 79086 | assert( idx>=0 && idx+N<=p->nCell )((void) (0)); | ||||
| 79087 | while( N>0 ){ | ||||
| 79088 | assert( p->apCell[idx]!=0 )((void) (0)); | ||||
| 79089 | if( szCell[idx]==0 ){ | ||||
| 79090 | szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]); | ||||
| 79091 | }else{ | ||||
| 79092 | assert( CORRUPT_DB ||((void) (0)) | ||||
| 79093 | szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) )((void) (0)); | ||||
| 79094 | } | ||||
| 79095 | idx++; | ||||
| 79096 | N--; | ||||
| 79097 | } | ||||
| 79098 | } | ||||
| 79099 | |||||
| 79100 | /* | ||||
| 79101 | ** Return the size of the Nth element of the cell array | ||||
| 79102 | */ | ||||
| 79103 | static SQLITE_NOINLINE__attribute__((noinline)) u16 computeCellSize(CellArray *p, int N){ | ||||
| 79104 | assert( N>=0 && N<p->nCell )((void) (0)); | ||||
| 79105 | assert( p->szCell[N]==0 )((void) (0)); | ||||
| 79106 | p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]); | ||||
| 79107 | return p->szCell[N]; | ||||
| 79108 | } | ||||
| 79109 | static u16 cachedCellSize(CellArray *p, int N){ | ||||
| 79110 | assert( N>=0 && N<p->nCell )((void) (0)); | ||||
| 79111 | if( p->szCell[N] ) return p->szCell[N]; | ||||
| 79112 | return computeCellSize(p, N); | ||||
| 79113 | } | ||||
| 79114 | |||||
| 79115 | /* | ||||
| 79116 | ** Array apCell[] contains pointers to nCell b-tree page cells. The | ||||
| 79117 | ** szCell[] array contains the size in bytes of each cell. This function | ||||
| 79118 | ** replaces the current contents of page pPg with the contents of the cell | ||||
| 79119 | ** array. | ||||
| 79120 | ** | ||||
| 79121 | ** Some of the cells in apCell[] may currently be stored in pPg. This | ||||
| 79122 | ** function works around problems caused by this by making a copy of any | ||||
| 79123 | ** such cells before overwriting the page data. | ||||
| 79124 | ** | ||||
| 79125 | ** The MemPage.nFree field is invalidated by this function. It is the | ||||
| 79126 | ** responsibility of the caller to set it correctly. | ||||
| 79127 | */ | ||||
| 79128 | static int rebuildPage( | ||||
| 79129 | CellArray *pCArray, /* Content to be added to page pPg */ | ||||
| 79130 | int iFirst, /* First cell in pCArray to use */ | ||||
| 79131 | int nCell, /* Final number of cells on page */ | ||||
| 79132 | MemPage *pPg /* The page to be reconstructed */ | ||||
| 79133 | ){ | ||||
| 79134 | const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ | ||||
| 79135 | u8 * const aData = pPg->aData; /* Pointer to data for pPg */ | ||||
| 79136 | const int usableSize = pPg->pBt->usableSize; | ||||
| 79137 | u8 * const pEnd = &aData[usableSize]; | ||||
| 79138 | int i = iFirst; /* Which cell to copy from pCArray*/ | ||||
| 79139 | u32 j; /* Start of cell content area */ | ||||
| 79140 | int iEnd = i+nCell; /* Loop terminator */ | ||||
| 79141 | u8 *pCellptr = pPg->aCellIdx; | ||||
| 79142 | u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); | ||||
| 79143 | u8 *pData; | ||||
| 79144 | int k; /* Current slot in pCArray->apEnd[] */ | ||||
| 79145 | u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */ | ||||
| 79146 | |||||
| 79147 | assert( nCell>0 )((void) (0)); | ||||
| 79148 | assert( i<iEnd )((void) (0)); | ||||
| 79149 | j = get2byte(&aData[hdr+5])((&aData[hdr+5])[0]<<8 | (&aData[hdr+5])[1]); | ||||
| 79150 | if( j>(u32)usableSize ){ j = 0; } | ||||
| 79151 | memcpy(&pTmp[j], &aData[j], usableSize - j); | ||||
| 79152 | |||||
| 79153 | assert( pCArray->ixNx[NB*2-1]>i )((void) (0)); | ||||
| 79154 | for(k=0; pCArray->ixNx[k]<=i; k++){} | ||||
| 79155 | pSrcEnd = pCArray->apEnd[k]; | ||||
| 79156 | |||||
| 79157 | pData = pEnd; | ||||
| 79158 | while( 1/*exit by break*/ ){ | ||||
| 79159 | u8 *pCell = pCArray->apCell[i]; | ||||
| 79160 | u16 sz = pCArray->szCell[i]; | ||||
| 79161 | assert( sz>0 )((void) (0)); | ||||
| 79162 | if( SQLITE_WITHIN(pCell,aData+j,pEnd)(((uptr)(pCell)>=(uptr)(aData+j))&&((uptr)(pCell)< (uptr)(pEnd))) ){ | ||||
| 79163 | if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(79163); | ||||
| 79164 | pCell = &pTmp[pCell - aData]; | ||||
| 79165 | }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd | ||||
| 79166 | && (uptr)(pCell)<(uptr)pSrcEnd | ||||
| 79167 | ){ | ||||
| 79168 | return SQLITE_CORRUPT_BKPTsqlite3CorruptError(79168); | ||||
| 79169 | } | ||||
| 79170 | |||||
| 79171 | pData -= sz; | ||||
| 79172 | put2byte(pCellptr, (pData - aData))((pCellptr)[0] = (u8)(((pData - aData))>>8), (pCellptr) [1] = (u8)((pData - aData))); | ||||
| 79173 | pCellptr += 2; | ||||
| 79174 | if( pData < pCellptr ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(79174); | ||||
| 79175 | memmove(pData, pCell, sz); | ||||
| 79176 | assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB )((void) (0)); | ||||
| 79177 | i++; | ||||
| 79178 | if( i>=iEnd ) break; | ||||
| 79179 | if( pCArray->ixNx[k]<=i ){ | ||||
| 79180 | k++; | ||||
| 79181 | pSrcEnd = pCArray->apEnd[k]; | ||||
| 79182 | } | ||||
| 79183 | } | ||||
| 79184 | |||||
| 79185 | /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ | ||||
| 79186 | assert( nCell < 10922 )((void) (0)); | ||||
| 79187 | pPg->nCell = (u16)nCell; | ||||
| 79188 | pPg->nOverflow = 0; | ||||
| 79189 | |||||
| 79190 | put2byte(&aData[hdr+1], 0)((&aData[hdr+1])[0] = (u8)((0)>>8), (&aData[hdr +1])[1] = (u8)(0)); | ||||
| 79191 | put2byte(&aData[hdr+3], pPg->nCell)((&aData[hdr+3])[0] = (u8)((pPg->nCell)>>8), (& aData[hdr+3])[1] = (u8)(pPg->nCell)); | ||||
| 79192 | put2byte(&aData[hdr+5], pData - aData)((&aData[hdr+5])[0] = (u8)((pData - aData)>>8), (& aData[hdr+5])[1] = (u8)(pData - aData)); | ||||
| 79193 | aData[hdr+7] = 0x00; | ||||
| 79194 | return SQLITE_OK0; | ||||
| 79195 | } | ||||
| 79196 | |||||
| 79197 | /* | ||||
| 79198 | ** The pCArray objects contains pointers to b-tree cells and the cell sizes. | ||||
| 79199 | ** This function attempts to add the cells stored in the array to page pPg. | ||||
| 79200 | ** If it cannot (because the page needs to be defragmented before the cells | ||||
| 79201 | ** will fit), non-zero is returned. Otherwise, if the cells are added | ||||
| 79202 | ** successfully, zero is returned. | ||||
| 79203 | ** | ||||
| 79204 | ** Argument pCellptr points to the first entry in the cell-pointer array | ||||
| 79205 | ** (part of page pPg) to populate. After cell apCell[0] is written to the | ||||
| 79206 | ** page body, a 16-bit offset is written to pCellptr. And so on, for each | ||||
| 79207 | ** cell in the array. It is the responsibility of the caller to ensure | ||||
| 79208 | ** that it is safe to overwrite this part of the cell-pointer array. | ||||
| 79209 | ** | ||||
| 79210 | ** When this function is called, *ppData points to the start of the | ||||
| 79211 | ** content area on page pPg. If the size of the content area is extended, | ||||
| 79212 | ** *ppData is updated to point to the new start of the content area | ||||
| 79213 | ** before returning. | ||||
| 79214 | ** | ||||
| 79215 | ** Finally, argument pBegin points to the byte immediately following the | ||||
| 79216 | ** end of the space required by this page for the cell-pointer area (for | ||||
| 79217 | ** all cells - not just those inserted by the current call). If the content | ||||
| 79218 | ** area must be extended to before this point in order to accommodate all | ||||
| 79219 | ** cells in apCell[], then the cells do not fit and non-zero is returned. | ||||
| 79220 | */ | ||||
| 79221 | static int pageInsertArray( | ||||
| 79222 | MemPage *pPg, /* Page to add cells to */ | ||||
| 79223 | u8 *pBegin, /* End of cell-pointer array */ | ||||
| 79224 | u8 **ppData, /* IN/OUT: Page content-area pointer */ | ||||
| 79225 | u8 *pCellptr, /* Pointer to cell-pointer area */ | ||||
| 79226 | int iFirst, /* Index of first cell to add */ | ||||
| 79227 | int nCell, /* Number of cells to add to pPg */ | ||||
| 79228 | CellArray *pCArray /* Array of cells */ | ||||
| 79229 | ){ | ||||
| 79230 | int i = iFirst; /* Loop counter - cell index to insert */ | ||||
| 79231 | u8 *aData = pPg->aData; /* Complete page */ | ||||
| 79232 | u8 *pData = *ppData; /* Content area. A subset of aData[] */ | ||||
| 79233 | int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */ | ||||
| 79234 | int k; /* Current slot in pCArray->apEnd[] */ | ||||
| 79235 | u8 *pEnd; /* Maximum extent of cell data */ | ||||
| 79236 | assert( CORRUPT_DB || pPg->hdrOffset==0 )((void) (0)); /* Never called on page 1 */ | ||||
| 79237 | if( iEnd<=iFirst ) return 0; | ||||
| 79238 | assert( pCArray->ixNx[NB*2-1]>i )((void) (0)); | ||||
| 79239 | for(k=0; pCArray->ixNx[k]<=i ; k++){} | ||||
| 79240 | pEnd = pCArray->apEnd[k]; | ||||
| 79241 | while( 1 /*Exit by break*/ ){ | ||||
| 79242 | int sz, rc; | ||||
| 79243 | u8 *pSlot; | ||||
| 79244 | assert( pCArray->szCell[i]!=0 )((void) (0)); | ||||
| 79245 | sz = pCArray->szCell[i]; | ||||
| 79246 | if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){ | ||||
| 79247 | if( (pData - pBegin)<sz ) return 1; | ||||
| 79248 | pData -= sz; | ||||
| 79249 | pSlot = pData; | ||||
| 79250 | } | ||||
| 79251 | /* pSlot and pCArray->apCell[i] will never overlap on a well-formed | ||||
| 79252 | ** database. But they might for a corrupt database. Hence use memmove() | ||||
| 79253 | ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */ | ||||
| 79254 | assert( (pSlot+sz)<=pCArray->apCell[i]((void) (0)) | ||||
| 79255 | || pSlot>=(pCArray->apCell[i]+sz)((void) (0)) | ||||
| 79256 | || CORRUPT_DB )((void) (0)); | ||||
| 79257 | if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd | ||||
| 79258 | && (uptr)(pCArray->apCell[i])<(uptr)pEnd | ||||
| 79259 | ){ | ||||
| 79260 | assert( CORRUPT_DB )((void) (0)); | ||||
| 79261 | (void)SQLITE_CORRUPT_BKPTsqlite3CorruptError(79261); | ||||
| 79262 | return 1; | ||||
| 79263 | } | ||||
| 79264 | memmove(pSlot, pCArray->apCell[i], sz); | ||||
| 79265 | put2byte(pCellptr, (pSlot - aData))((pCellptr)[0] = (u8)(((pSlot - aData))>>8), (pCellptr) [1] = (u8)((pSlot - aData))); | ||||
| 79266 | pCellptr += 2; | ||||
| 79267 | i++; | ||||
| 79268 | if( i>=iEnd ) break; | ||||
| 79269 | if( pCArray->ixNx[k]<=i ){ | ||||
| 79270 | k++; | ||||
| 79271 | pEnd = pCArray->apEnd[k]; | ||||
| 79272 | } | ||||
| 79273 | } | ||||
| 79274 | *ppData = pData; | ||||
| 79275 | return 0; | ||||
| 79276 | } | ||||
| 79277 | |||||
| 79278 | /* | ||||
| 79279 | ** The pCArray object contains pointers to b-tree cells and their sizes. | ||||
| 79280 | ** | ||||
| 79281 | ** This function adds the space associated with each cell in the array | ||||
| 79282 | ** that is currently stored within the body of pPg to the pPg free-list. | ||||
| 79283 | ** The cell-pointers and other fields of the page are not updated. | ||||
| 79284 | ** | ||||
| 79285 | ** This function returns the total number of cells added to the free-list. | ||||
| 79286 | */ | ||||
| 79287 | static int pageFreeArray( | ||||
| 79288 | MemPage *pPg, /* Page to edit */ | ||||
| 79289 | int iFirst, /* First cell to delete */ | ||||
| 79290 | int nCell, /* Cells to delete */ | ||||
| 79291 | CellArray *pCArray /* Array of cells */ | ||||
| 79292 | ){ | ||||
| 79293 | u8 * const aData = pPg->aData; | ||||
| 79294 | u8 * const pEnd = &aData[pPg->pBt->usableSize]; | ||||
| 79295 | u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize]; | ||||
| 79296 | int nRet = 0; | ||||
| 79297 | int i, j; | ||||
| 79298 | int iEnd = iFirst + nCell; | ||||
| 79299 | int nFree = 0; | ||||
| 79300 | int aOfst[10]; | ||||
| 79301 | int aAfter[10]; | ||||
| 79302 | |||||
| 79303 | for(i=iFirst; i<iEnd; i++){ | ||||
| 79304 | u8 *pCell = pCArray->apCell[i]; | ||||
| 79305 | if( SQLITE_WITHIN(pCell, pStart, pEnd)(((uptr)(pCell)>=(uptr)(pStart))&&((uptr)(pCell)< (uptr)(pEnd))) ){ | ||||
| 79306 | int sz; | ||||
| 79307 | int iAfter; | ||||
| 79308 | int iOfst; | ||||
| 79309 | /* No need to use cachedCellSize() here. The sizes of all cells that | ||||
| 79310 | ** are to be freed have already been computing while deciding which | ||||
| 79311 | ** cells need freeing */ | ||||
| 79312 | sz = pCArray->szCell[i]; assert( sz>0 )((void) (0)); | ||||
| 79313 | iOfst = (u16)(pCell - aData); | ||||
| 79314 | iAfter = iOfst+sz; | ||||
| 79315 | for(j=0; j<nFree; j++){ | ||||
| 79316 | if( aOfst[j]==iAfter ){ | ||||
| 79317 | aOfst[j] = iOfst; | ||||
| 79318 | break; | ||||
| 79319 | }else if( aAfter[j]==iOfst ){ | ||||
| 79320 | aAfter[j] = iAfter; | ||||
| 79321 | break; | ||||
| 79322 | } | ||||
| 79323 | } | ||||
| 79324 | if( j>=nFree ){ | ||||
| 79325 | if( nFree>=(int)(sizeof(aOfst)/sizeof(aOfst[0])) ){ | ||||
| 79326 | for(j=0; j<nFree; j++){ | ||||
| 79327 | freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]); | ||||
| 79328 | } | ||||
| 79329 | nFree = 0; | ||||
| 79330 | } | ||||
| 79331 | aOfst[nFree] = iOfst; | ||||
| 79332 | aAfter[nFree] = iAfter; | ||||
| 79333 | if( &aData[iAfter]>pEnd ) return 0; | ||||
| 79334 | nFree++; | ||||
| 79335 | } | ||||
| 79336 | nRet++; | ||||
| 79337 | } | ||||
| 79338 | } | ||||
| 79339 | for(j=0; j<nFree; j++){ | ||||
| 79340 | freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]); | ||||
| 79341 | } | ||||
| 79342 | return nRet; | ||||
| 79343 | } | ||||
| 79344 | |||||
| 79345 | /* | ||||
| 79346 | ** pCArray contains pointers to and sizes of all cells in the page being | ||||
| 79347 | ** balanced. The current page, pPg, has pPg->nCell cells starting with | ||||
| 79348 | ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells | ||||
| 79349 | ** starting at apCell[iNew]. | ||||
| 79350 | ** | ||||
| 79351 | ** This routine makes the necessary adjustments to pPg so that it contains | ||||
| 79352 | ** the correct cells after being balanced. | ||||
| 79353 | ** | ||||
| 79354 | ** The pPg->nFree field is invalid when this function returns. It is the | ||||
| 79355 | ** responsibility of the caller to set it correctly. | ||||
| 79356 | */ | ||||
| 79357 | static int editPage( | ||||
| 79358 | MemPage *pPg, /* Edit this page */ | ||||
| 79359 | int iOld, /* Index of first cell currently on page */ | ||||
| 79360 | int iNew, /* Index of new first cell on page */ | ||||
| 79361 | int nNew, /* Final number of cells on page */ | ||||
| 79362 | CellArray *pCArray /* Array of cells and sizes */ | ||||
| 79363 | ){ | ||||
| 79364 | u8 * const aData = pPg->aData; | ||||
| 79365 | const int hdr = pPg->hdrOffset; | ||||
| 79366 | u8 *pBegin = &pPg->aCellIdx[nNew * 2]; | ||||
| 79367 | int nCell = pPg->nCell; /* Cells stored on pPg */ | ||||
| 79368 | u8 *pData; | ||||
| 79369 | u8 *pCellptr; | ||||
| 79370 | int i; | ||||
| 79371 | int iOldEnd = iOld + pPg->nCell + pPg->nOverflow; | ||||
| 79372 | int iNewEnd = iNew + nNew; | ||||
| 79373 | |||||
| 79374 | #ifdef SQLITE_DEBUG | ||||
| 79375 | u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); | ||||
| 79376 | memcpy(pTmp, aData, pPg->pBt->usableSize); | ||||
| 79377 | #endif | ||||
| 79378 | |||||
| 79379 | /* Remove cells from the start and end of the page */ | ||||
| 79380 | assert( nCell>=0 )((void) (0)); | ||||
| 79381 | if( iOld<iNew ){ | ||||
| 79382 | int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray); | ||||
| 79383 | if( NEVER(nShift>nCell)(nShift>nCell) ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(79383); | ||||
| 79384 | memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); | ||||
| 79385 | nCell -= nShift; | ||||
| 79386 | } | ||||
| 79387 | if( iNewEnd < iOldEnd ){ | ||||
| 79388 | int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); | ||||
| 79389 | assert( nCell>=nTail )((void) (0)); | ||||
| 79390 | nCell -= nTail; | ||||
| 79391 | } | ||||
| 79392 | |||||
| 79393 | pData = &aData[get2byte(&aData[hdr+5])((&aData[hdr+5])[0]<<8 | (&aData[hdr+5])[1])]; | ||||
| 79394 | if( pData<pBegin ) goto editpage_fail; | ||||
| 79395 | if( NEVER(pData>pPg->aDataEnd)(pData>pPg->aDataEnd) ) goto editpage_fail; | ||||
| 79396 | |||||
| 79397 | /* Add cells to the start of the page */ | ||||
| 79398 | if( iNew<iOld ){ | ||||
| 79399 | int nAdd = MIN(nNew,iOld-iNew)((nNew)<(iOld-iNew)?(nNew):(iOld-iNew)); | ||||
| 79400 | assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB )((void) (0)); | ||||
| 79401 | assert( nAdd>=0 )((void) (0)); | ||||
| 79402 | pCellptr = pPg->aCellIdx; | ||||
| 79403 | memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); | ||||
| 79404 | if( pageInsertArray( | ||||
| 79405 | pPg, pBegin, &pData, pCellptr, | ||||
| 79406 | iNew, nAdd, pCArray | ||||
| 79407 | ) ) goto editpage_fail; | ||||
| 79408 | nCell += nAdd; | ||||
| 79409 | } | ||||
| 79410 | |||||
| 79411 | /* Add any overflow cells */ | ||||
| 79412 | for(i=0; i<pPg->nOverflow; i++){ | ||||
| 79413 | int iCell = (iOld + pPg->aiOvfl[i]) - iNew; | ||||
| 79414 | if( iCell>=0 && iCell<nNew ){ | ||||
| 79415 | pCellptr = &pPg->aCellIdx[iCell * 2]; | ||||
| 79416 | if( nCell>iCell ){ | ||||
| 79417 | memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); | ||||
| 79418 | } | ||||
| 79419 | nCell++; | ||||
| 79420 | cachedCellSize(pCArray, iCell+iNew); | ||||
| 79421 | if( pageInsertArray( | ||||
| 79422 | pPg, pBegin, &pData, pCellptr, | ||||
| 79423 | iCell+iNew, 1, pCArray | ||||
| 79424 | ) ) goto editpage_fail; | ||||
| 79425 | } | ||||
| 79426 | } | ||||
| 79427 | |||||
| 79428 | /* Append cells to the end of the page */ | ||||
| 79429 | assert( nCell>=0 )((void) (0)); | ||||
| 79430 | pCellptr = &pPg->aCellIdx[nCell*2]; | ||||
| 79431 | if( pageInsertArray( | ||||
| 79432 | pPg, pBegin, &pData, pCellptr, | ||||
| 79433 | iNew+nCell, nNew-nCell, pCArray | ||||
| 79434 | ) | ||||
| 79435 | ){ | ||||
| 79436 | goto editpage_fail; | ||||
| 79437 | } | ||||
| 79438 | |||||
| 79439 | assert( nNew < 10922 )((void) (0)); | ||||
| 79440 | pPg->nCell = (u16)nNew; | ||||
| 79441 | pPg->nOverflow = 0; | ||||
| 79442 | |||||
| 79443 | put2byte(&aData[hdr+3], pPg->nCell)((&aData[hdr+3])[0] = (u8)((pPg->nCell)>>8), (& aData[hdr+3])[1] = (u8)(pPg->nCell)); | ||||
| 79444 | put2byte(&aData[hdr+5], pData - aData)((&aData[hdr+5])[0] = (u8)((pData - aData)>>8), (& aData[hdr+5])[1] = (u8)(pData - aData)); | ||||
| 79445 | |||||
| 79446 | #ifdef SQLITE_DEBUG | ||||
| 79447 | for(i=0; i<nNew && !CORRUPT_DB(sqlite3Config.neverCorrupt==0); i++){ | ||||
| 79448 | u8 *pCell = pCArray->apCell[i+iNew]; | ||||
| 79449 | int iOff = get2byteAligned(&pPg->aCellIdx[i*2])((&pPg->aCellIdx[i*2])[0]<<8 | (&pPg->aCellIdx [i*2])[1]); | ||||
| 79450 | if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize])(((uptr)(pCell)>=(uptr)(aData))&&((uptr)(pCell)< (uptr)(&aData[pPg->pBt->usableSize]))) ){ | ||||
| 79451 | pCell = &pTmp[pCell - aData]; | ||||
| 79452 | } | ||||
| 79453 | assert( 0==memcmp(pCell, &aData[iOff],((void) (0)) | ||||
| 79454 | pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) )((void) (0)); | ||||
| 79455 | } | ||||
| 79456 | #endif | ||||
| 79457 | |||||
| 79458 | return SQLITE_OK0; | ||||
| 79459 | editpage_fail: | ||||
| 79460 | /* Unable to edit this page. Rebuild it from scratch instead. */ | ||||
| 79461 | if( nNew<1 ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(79461); | ||||
| 79462 | populateCellCache(pCArray, iNew, nNew); | ||||
| 79463 | return rebuildPage(pCArray, iNew, nNew, pPg); | ||||
| 79464 | } | ||||
| 79465 | |||||
| 79466 | |||||
| 79467 | #ifndef SQLITE_OMIT_QUICKBALANCE | ||||
| 79468 | /* | ||||
| 79469 | ** This version of balance() handles the common special case where | ||||
| 79470 | ** a new entry is being inserted on the extreme right-end of the | ||||
| 79471 | ** tree, in other words, when the new entry will become the largest | ||||
| 79472 | ** entry in the tree. | ||||
| 79473 | ** | ||||
| 79474 | ** Instead of trying to balance the 3 right-most leaf pages, just add | ||||
| 79475 | ** a new page to the right-hand side and put the one new entry in | ||||
| 79476 | ** that page. This leaves the right side of the tree somewhat | ||||
| 79477 | ** unbalanced. But odds are that we will be inserting new entries | ||||
| 79478 | ** at the end soon afterwards so the nearly empty page will quickly | ||||
| 79479 | ** fill up. On average. | ||||
| 79480 | ** | ||||
| 79481 | ** pPage is the leaf page which is the right-most page in the tree. | ||||
| 79482 | ** pParent is its parent. pPage must have a single overflow entry | ||||
| 79483 | ** which is also the right-most entry on the page. | ||||
| 79484 | ** | ||||
| 79485 | ** The pSpace buffer is used to store a temporary copy of the divider | ||||
| 79486 | ** cell that will be inserted into pParent. Such a cell consists of a 4 | ||||
| 79487 | ** byte page number followed by a variable length integer. In other | ||||
| 79488 | ** words, at most 13 bytes. Hence the pSpace buffer must be at | ||||
| 79489 | ** least 13 bytes in size. | ||||
| 79490 | */ | ||||
| 79491 | static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ | ||||
| 79492 | BtShared *const pBt = pPage->pBt; /* B-Tree Database */ | ||||
| 79493 | MemPage *pNew; /* Newly allocated page */ | ||||
| 79494 | int rc; /* Return Code */ | ||||
| 79495 | Pgno pgnoNew; /* Page number of pNew */ | ||||
| 79496 | |||||
| 79497 | assert( sqlite3_mutex_held(pPage->pBt->mutex) )((void) (0)); | ||||
| 79498 | assert( sqlite3PagerIswriteable(pParent->pDbPage) )((void) (0)); | ||||
| 79499 | assert( pPage->nOverflow==1 )((void) (0)); | ||||
| 79500 | |||||
| 79501 | if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPTsqlite3CorruptError(79501); /* dbfuzz001.test */ | ||||
| 79502 | assert( pPage->nFree>=0 )((void) (0)); | ||||
| 79503 | assert( pParent->nFree>=0 )((void) (0)); | ||||
| 79504 | |||||
| 79505 | /* Allocate a new page. This page will become the right-sibling of | ||||
| 79506 | ** pPage. Make the parent page writable, so that the new divider cell | ||||
| 79507 | ** may be inserted. If both these operations are successful, proceed. | ||||
| 79508 | */ | ||||
| 79509 | rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); | ||||
| 79510 | |||||
| 79511 | if( rc==SQLITE_OK0 ){ | ||||
| 79512 | |||||
| 79513 | u8 *pOut = &pSpace[4]; | ||||
| 79514 | u8 *pCell = pPage->apOvfl[0]; | ||||
| 79515 | u16 szCell = pPage->xCellSize(pPage, pCell); | ||||
| 79516 | u8 *pStop; | ||||
| 79517 | CellArray b; | ||||
| 79518 | |||||
| 79519 | assert( sqlite3PagerIswriteable(pNew->pDbPage) )((void) (0)); | ||||
| 79520 | assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) )((void) (0)); | ||||
| 79521 | zeroPage(pNew, PTF_INTKEY0x01|PTF_LEAFDATA0x04|PTF_LEAF0x08); | ||||
| 79522 | b.nCell = 1; | ||||
| 79523 | b.pRef = pPage; | ||||
| 79524 | b.apCell = &pCell; | ||||
| 79525 | b.szCell = &szCell; | ||||
| 79526 | b.apEnd[0] = pPage->aDataEnd; | ||||
| 79527 | b.ixNx[0] = 2; | ||||
| 79528 | b.ixNx[NB3*2-1] = 0x7fffffff; | ||||
| 79529 | rc = rebuildPage(&b, 0, 1, pNew); | ||||
| 79530 | if( NEVER(rc)(rc) ){ | ||||
| 79531 | releasePage(pNew); | ||||
| 79532 | return rc; | ||||
| 79533 | } | ||||
| 79534 | pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; | ||||
| 79535 | |||||
| 79536 | /* If this is an auto-vacuum database, update the pointer map | ||||
| 79537 | ** with entries for the new page, and any pointer from the | ||||
| 79538 | ** cell on the page to an overflow page. If either of these | ||||
| 79539 | ** operations fails, the return code is set, but the contents | ||||
| 79540 | ** of the parent page are still manipulated by the code below. | ||||
| 79541 | ** That is Ok, at this point the parent page is guaranteed to | ||||
| 79542 | ** be marked as dirty. Returning an error code will cause a | ||||
| 79543 | ** rollback, undoing any changes made to the parent page. | ||||
| 79544 | */ | ||||
| 79545 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) ){ | ||||
| 79546 | ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE5, pParent->pgno, &rc); | ||||
| 79547 | if( szCell>pNew->minLocal ){ | ||||
| 79548 | ptrmapPutOvflPtr(pNew, pNew, pCell, &rc); | ||||
| 79549 | } | ||||
| 79550 | } | ||||
| 79551 | |||||
| 79552 | /* Create a divider cell to insert into pParent. The divider cell | ||||
| 79553 | ** consists of a 4-byte page number (the page number of pPage) and | ||||
| 79554 | ** a variable length key value (which must be the same value as the | ||||
| 79555 | ** largest key on pPage). | ||||
| 79556 | ** | ||||
| 79557 | ** To find the largest key value on pPage, first find the right-most | ||||
| 79558 | ** cell on pPage. The first two fields of this cell are the | ||||
| 79559 | ** record-length (a variable length integer at most 32-bits in size) | ||||
| 79560 | ** and the key value (a variable length integer, may have any value). | ||||
| 79561 | ** The first of the while(...) loops below skips over the record-length | ||||
| 79562 | ** field. The second while(...) loop copies the key value from the | ||||
| 79563 | ** cell on pPage into the pSpace buffer. | ||||
| 79564 | */ | ||||
| 79565 | pCell = findCell(pPage, pPage->nCell-1)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(pPage->nCell-1)])[0]<<8 | (&(pPage )->aCellIdx[2*(pPage->nCell-1)])[1]))); | ||||
| 79566 | pStop = &pCell[9]; | ||||
| 79567 | while( (*(pCell++)&0x80) && pCell<pStop ); | ||||
| 79568 | pStop = &pCell[9]; | ||||
| 79569 | while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop ); | ||||
| 79570 | |||||
| 79571 | /* Insert the new divider cell into pParent. */ | ||||
| 79572 | if( rc==SQLITE_OK0 ){ | ||||
| 79573 | rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace), | ||||
| 79574 | 0, pPage->pgno); | ||||
| 79575 | } | ||||
| 79576 | |||||
| 79577 | /* Set the right-child pointer of pParent to point to the new page. */ | ||||
| 79578 | put4bytesqlite3Put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); | ||||
| 79579 | |||||
| 79580 | /* Release the reference to the new page. */ | ||||
| 79581 | releasePage(pNew); | ||||
| 79582 | } | ||||
| 79583 | |||||
| 79584 | return rc; | ||||
| 79585 | } | ||||
| 79586 | #endif /* SQLITE_OMIT_QUICKBALANCE */ | ||||
| 79587 | |||||
| 79588 | #if 0 | ||||
| 79589 | /* | ||||
| 79590 | ** This function does not contribute anything to the operation of SQLite. | ||||
| 79591 | ** it is sometimes activated temporarily while debugging code responsible | ||||
| 79592 | ** for setting pointer-map entries. | ||||
| 79593 | */ | ||||
| 79594 | static int ptrmapCheckPages(MemPage **apPage, int nPage){ | ||||
| 79595 | int i, j; | ||||
| 79596 | for(i=0; i<nPage; i++){ | ||||
| 79597 | Pgno n; | ||||
| 79598 | u8 e; | ||||
| 79599 | MemPage *pPage = apPage[i]; | ||||
| 79600 | BtShared *pBt = pPage->pBt; | ||||
| 79601 | assert( pPage->isInit )((void) (0)); | ||||
| 79602 | |||||
| 79603 | for(j=0; j<pPage->nCell; j++){ | ||||
| 79604 | CellInfo info; | ||||
| 79605 | u8 *z; | ||||
| 79606 | |||||
| 79607 | z = findCell(pPage, j)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(j)])[0]<<8 | (&(pPage)->aCellIdx [2*(j)])[1]))); | ||||
| 79608 | pPage->xParseCell(pPage, z, &info); | ||||
| 79609 | if( info.nLocal<info.nPayload ){ | ||||
| 79610 | Pgno ovfl = get4bytesqlite3Get4byte(&z[info.nSize-4]); | ||||
| 79611 | ptrmapGet(pBt, ovfl, &e, &n); | ||||
| 79612 | assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 )((void) (0)); | ||||
| 79613 | } | ||||
| 79614 | if( !pPage->leaf ){ | ||||
| 79615 | Pgno child = get4bytesqlite3Get4byte(z); | ||||
| 79616 | ptrmapGet(pBt, child, &e, &n); | ||||
| 79617 | assert( n==pPage->pgno && e==PTRMAP_BTREE )((void) (0)); | ||||
| 79618 | } | ||||
| 79619 | } | ||||
| 79620 | if( !pPage->leaf ){ | ||||
| 79621 | Pgno child = get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8]); | ||||
| 79622 | ptrmapGet(pBt, child, &e, &n); | ||||
| 79623 | assert( n==pPage->pgno && e==PTRMAP_BTREE )((void) (0)); | ||||
| 79624 | } | ||||
| 79625 | } | ||||
| 79626 | return 1; | ||||
| 79627 | } | ||||
| 79628 | #endif | ||||
| 79629 | |||||
| 79630 | /* | ||||
| 79631 | ** This function is used to copy the contents of the b-tree node stored | ||||
| 79632 | ** on page pFrom to page pTo. If page pFrom was not a leaf page, then | ||||
| 79633 | ** the pointer-map entries for each child page are updated so that the | ||||
| 79634 | ** parent page stored in the pointer map is page pTo. If pFrom contained | ||||
| 79635 | ** any cells with overflow page pointers, then the corresponding pointer | ||||
| 79636 | ** map entries are also updated so that the parent page is page pTo. | ||||
| 79637 | ** | ||||
| 79638 | ** If pFrom is currently carrying any overflow cells (entries in the | ||||
| 79639 | ** MemPage.apOvfl[] array), they are not copied to pTo. | ||||
| 79640 | ** | ||||
| 79641 | ** Before returning, page pTo is reinitialized using btreeInitPage(). | ||||
| 79642 | ** | ||||
| 79643 | ** The performance of this function is not critical. It is only used by | ||||
| 79644 | ** the balance_shallower() and balance_deeper() procedures, neither of | ||||
| 79645 | ** which are called often under normal circumstances. | ||||
| 79646 | */ | ||||
| 79647 | static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ | ||||
| 79648 | if( (*pRC)==SQLITE_OK0 ){ | ||||
| 79649 | BtShared * const pBt = pFrom->pBt; | ||||
| 79650 | u8 * const aFrom = pFrom->aData; | ||||
| 79651 | u8 * const aTo = pTo->aData; | ||||
| 79652 | int const iFromHdr = pFrom->hdrOffset; | ||||
| 79653 | int const iToHdr = ((pTo->pgno==1) ? 100 : 0); | ||||
| 79654 | int rc; | ||||
| 79655 | int iData; | ||||
| 79656 | |||||
| 79657 | |||||
| 79658 | assert( pFrom->isInit )((void) (0)); | ||||
| 79659 | assert( pFrom->nFree>=iToHdr )((void) (0)); | ||||
| 79660 | assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize )((void) (0)); | ||||
| 79661 | |||||
| 79662 | /* Copy the b-tree node content from page pFrom to page pTo. */ | ||||
| 79663 | iData = get2byte(&aFrom[iFromHdr+5])((&aFrom[iFromHdr+5])[0]<<8 | (&aFrom[iFromHdr+ 5])[1]); | ||||
| 79664 | memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); | ||||
| 79665 | memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); | ||||
| 79666 | |||||
| 79667 | /* Reinitialize page pTo so that the contents of the MemPage structure | ||||
| 79668 | ** match the new data. The initialization of pTo can actually fail under | ||||
| 79669 | ** fairly obscure circumstances, even though it is a copy of initialized | ||||
| 79670 | ** page pFrom. | ||||
| 79671 | */ | ||||
| 79672 | pTo->isInit = 0; | ||||
| 79673 | rc = btreeInitPage(pTo); | ||||
| 79674 | if( rc==SQLITE_OK0 ) rc = btreeComputeFreeSpace(pTo); | ||||
| 79675 | if( rc!=SQLITE_OK0 ){ | ||||
| 79676 | *pRC = rc; | ||||
| 79677 | return; | ||||
| 79678 | } | ||||
| 79679 | |||||
| 79680 | /* If this is an auto-vacuum database, update the pointer-map entries | ||||
| 79681 | ** for any b-tree or overflow pages that pTo now contains the pointers to. | ||||
| 79682 | */ | ||||
| 79683 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) ){ | ||||
| 79684 | *pRC = setChildPtrmaps(pTo); | ||||
| 79685 | } | ||||
| 79686 | } | ||||
| 79687 | } | ||||
| 79688 | |||||
| 79689 | /* | ||||
| 79690 | ** This routine redistributes cells on the iParentIdx'th child of pParent | ||||
| 79691 | ** (hereafter "the page") and up to 2 siblings so that all pages have about the | ||||
| 79692 | ** same amount of free space. Usually a single sibling on either side of the | ||||
| 79693 | ** page are used in the balancing, though both siblings might come from one | ||||
| 79694 | ** side if the page is the first or last child of its parent. If the page | ||||
| 79695 | ** has fewer than 2 siblings (something which can only happen if the page | ||||
| 79696 | ** is a root page or a child of a root page) then all available siblings | ||||
| 79697 | ** participate in the balancing. | ||||
| 79698 | ** | ||||
| 79699 | ** The number of siblings of the page might be increased or decreased by | ||||
| 79700 | ** one or two in an effort to keep pages nearly full but not over full. | ||||
| 79701 | ** | ||||
| 79702 | ** Note that when this routine is called, some of the cells on the page | ||||
| 79703 | ** might not actually be stored in MemPage.aData[]. This can happen | ||||
| 79704 | ** if the page is overfull. This routine ensures that all cells allocated | ||||
| 79705 | ** to the page and its siblings fit into MemPage.aData[] before returning. | ||||
| 79706 | ** | ||||
| 79707 | ** In the course of balancing the page and its siblings, cells may be | ||||
| 79708 | ** inserted into or removed from the parent page (pParent). Doing so | ||||
| 79709 | ** may cause the parent page to become overfull or underfull. If this | ||||
| 79710 | ** happens, it is the responsibility of the caller to invoke the correct | ||||
| 79711 | ** balancing routine to fix this problem (see the balance() routine). | ||||
| 79712 | ** | ||||
| 79713 | ** If this routine fails for any reason, it might leave the database | ||||
| 79714 | ** in a corrupted state. So if this routine fails, the database should | ||||
| 79715 | ** be rolled back. | ||||
| 79716 | ** | ||||
| 79717 | ** The third argument to this function, aOvflSpace, is a pointer to a | ||||
| 79718 | ** buffer big enough to hold one page. If while inserting cells into the parent | ||||
| 79719 | ** page (pParent) the parent page becomes overfull, this buffer is | ||||
| 79720 | ** used to store the parent's overflow cells. Because this function inserts | ||||
| 79721 | ** a maximum of four divider cells into the parent page, and the maximum | ||||
| 79722 | ** size of a cell stored within an internal node is always less than 1/4 | ||||
| 79723 | ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large | ||||
| 79724 | ** enough for all overflow cells. | ||||
| 79725 | ** | ||||
| 79726 | ** If aOvflSpace is set to a null pointer, this function returns | ||||
| 79727 | ** SQLITE_NOMEM. | ||||
| 79728 | */ | ||||
| 79729 | static int balance_nonroot( | ||||
| 79730 | MemPage *pParent, /* Parent page of siblings being balanced */ | ||||
| 79731 | int iParentIdx, /* Index of "the page" in pParent */ | ||||
| 79732 | u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ | ||||
| 79733 | int isRoot, /* True if pParent is a root-page */ | ||||
| 79734 | int bBulk /* True if this call is part of a bulk load */ | ||||
| 79735 | ){ | ||||
| 79736 | BtShared *pBt; /* The whole database */ | ||||
| 79737 | int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ | ||||
| 79738 | int nNew = 0; /* Number of pages in apNew[] */ | ||||
| 79739 | int nOld; /* Number of pages in apOld[] */ | ||||
| 79740 | int i, j, k; /* Loop counters */ | ||||
| 79741 | int nxDiv; /* Next divider slot in pParent->aCell[] */ | ||||
| 79742 | int rc = SQLITE_OK0; /* The return code */ | ||||
| 79743 | u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ | ||||
| 79744 | int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ | ||||
| 79745 | int usableSpace; /* Bytes in pPage beyond the header */ | ||||
| 79746 | int pageFlags; /* Value of pPage->aData[0] */ | ||||
| 79747 | int iSpace1 = 0; /* First unused byte of aSpace1[] */ | ||||
| 79748 | int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ | ||||
| 79749 | u64 szScratch; /* Size of scratch memory requested */ | ||||
| 79750 | MemPage *apOld[NB3]; /* pPage and up to two siblings */ | ||||
| 79751 | MemPage *apNew[NB3+2]; /* pPage and up to NB siblings after balancing */ | ||||
| 79752 | u8 *pRight; /* Location in parent of right-sibling pointer */ | ||||
| 79753 | u8 *apDiv[NB3-1]; /* Divider cells in pParent */ | ||||
| 79754 | int cntNew[NB3+2]; /* Index in b.paCell[] of cell after i-th page */ | ||||
| 79755 | int cntOld[NB3+2]; /* Old index in b.apCell[] */ | ||||
| 79756 | int szNew[NB3+2]; /* Combined size of cells placed on i-th page */ | ||||
| 79757 | u8 *aSpace1; /* Space for copies of dividers cells */ | ||||
| 79758 | Pgno pgno; /* Temp var to store a page number in */ | ||||
| 79759 | u8 abDone[NB3+2]; /* True after i'th new page is populated */ | ||||
| 79760 | Pgno aPgno[NB3+2]; /* Page numbers of new pages before shuffling */ | ||||
| 79761 | CellArray b; /* Parsed information on cells being balanced */ | ||||
| 79762 | |||||
| 79763 | memset(abDone, 0, sizeof(abDone)); | ||||
| 79764 | assert( sizeof(b) - sizeof(b.ixNx) == offsetof(CellArray,ixNx) )((void) (0)); | ||||
| 79765 | memset(&b, 0, sizeof(b)-sizeof(b.ixNx[0])); | ||||
| 79766 | b.ixNx[NB3*2-1] = 0x7fffffff; | ||||
| 79767 | pBt = pParent->pBt; | ||||
| 79768 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 79769 | assert( sqlite3PagerIswriteable(pParent->pDbPage) )((void) (0)); | ||||
| 79770 | |||||
| 79771 | /* At this point pParent may have at most one overflow cell. And if | ||||
| 79772 | ** this overflow cell is present, it must be the cell with | ||||
| 79773 | ** index iParentIdx. This scenario comes about when this function | ||||
| 79774 | ** is called (indirectly) from sqlite3BtreeDelete(). | ||||
| 79775 | */ | ||||
| 79776 | assert( pParent->nOverflow==0 || pParent->nOverflow==1 )((void) (0)); | ||||
| 79777 | assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx )((void) (0)); | ||||
| 79778 | |||||
| 79779 | if( !aOvflSpace ){ | ||||
| 79780 | return SQLITE_NOMEM_BKPT7; | ||||
| 79781 | } | ||||
| 79782 | assert( pParent->nFree>=0 )((void) (0)); | ||||
| 79783 | |||||
| 79784 | /* Find the sibling pages to balance. Also locate the cells in pParent | ||||
| 79785 | ** that divide the siblings. An attempt is made to find NN siblings on | ||||
| 79786 | ** either side of pPage. More siblings are taken from one side, however, | ||||
| 79787 | ** if there are fewer than NN siblings on the other side. If pParent | ||||
| 79788 | ** has NB or fewer children then all children of pParent are taken. | ||||
| 79789 | ** | ||||
| 79790 | ** This loop also drops the divider cells from the parent page. This | ||||
| 79791 | ** way, the remainder of the function does not have to deal with any | ||||
| 79792 | ** overflow cells in the parent page, since if any existed they will | ||||
| 79793 | ** have already been removed. | ||||
| 79794 | */ | ||||
| 79795 | i = pParent->nOverflow + pParent->nCell; | ||||
| 79796 | if( i<2 ){ | ||||
| 79797 | nxDiv = 0; | ||||
| 79798 | }else{ | ||||
| 79799 | assert( bBulk==0 || bBulk==1 )((void) (0)); | ||||
| 79800 | if( iParentIdx==0 ){ | ||||
| 79801 | nxDiv = 0; | ||||
| 79802 | }else if( iParentIdx==i ){ | ||||
| 79803 | nxDiv = i-2+bBulk; | ||||
| 79804 | }else{ | ||||
| 79805 | nxDiv = iParentIdx-1; | ||||
| 79806 | } | ||||
| 79807 | i = 2-bBulk; | ||||
| 79808 | } | ||||
| 79809 | nOld = i+1; | ||||
| 79810 | if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ | ||||
| 79811 | pRight = &pParent->aData[pParent->hdrOffset+8]; | ||||
| 79812 | }else{ | ||||
| 79813 | pRight = findCell(pParent, i+nxDiv-pParent->nOverflow)((pParent)->aData + ((pParent)->maskPage & ((&( pParent)->aCellIdx[2*(i+nxDiv-pParent->nOverflow)])[0]<< 8 | (&(pParent)->aCellIdx[2*(i+nxDiv-pParent->nOverflow )])[1]))); | ||||
| 79814 | } | ||||
| 79815 | pgno = get4bytesqlite3Get4byte(pRight); | ||||
| 79816 | while( 1 ){ | ||||
| 79817 | if( rc==SQLITE_OK0 ){ | ||||
| 79818 | rc = getAndInitPage(pBt, pgno, &apOld[i], 0); | ||||
| 79819 | } | ||||
| 79820 | if( rc ){ | ||||
| 79821 | memset(apOld, 0, (i+1)*sizeof(MemPage*)); | ||||
| 79822 | goto balance_cleanup; | ||||
| 79823 | } | ||||
| 79824 | if( apOld[i]->nFree<0 ){ | ||||
| 79825 | rc = btreeComputeFreeSpace(apOld[i]); | ||||
| 79826 | if( rc ){ | ||||
| 79827 | memset(apOld, 0, (i)*sizeof(MemPage*)); | ||||
| 79828 | goto balance_cleanup; | ||||
| 79829 | } | ||||
| 79830 | } | ||||
| 79831 | nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl)((int)(sizeof(pParent->apOvfl)/sizeof(pParent->apOvfl[0 ]))); | ||||
| 79832 | if( (i--)==0 ) break; | ||||
| 79833 | |||||
| 79834 | if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){ | ||||
| 79835 | apDiv[i] = pParent->apOvfl[0]; | ||||
| 79836 | pgno = get4bytesqlite3Get4byte(apDiv[i]); | ||||
| 79837 | szNew[i] = pParent->xCellSize(pParent, apDiv[i]); | ||||
| 79838 | pParent->nOverflow = 0; | ||||
| 79839 | }else{ | ||||
| 79840 | apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow)((pParent)->aData + ((pParent)->maskPage & ((&( pParent)->aCellIdx[2*(i+nxDiv-pParent->nOverflow)])[0]<< 8 | (&(pParent)->aCellIdx[2*(i+nxDiv-pParent->nOverflow )])[1]))); | ||||
| 79841 | pgno = get4bytesqlite3Get4byte(apDiv[i]); | ||||
| 79842 | szNew[i] = pParent->xCellSize(pParent, apDiv[i]); | ||||
| 79843 | |||||
| 79844 | /* Drop the cell from the parent page. apDiv[i] still points to | ||||
| 79845 | ** the cell within the parent, even though it has been dropped. | ||||
| 79846 | ** This is safe because dropping a cell only overwrites the first | ||||
| 79847 | ** four bytes of it, and this function does not need the first | ||||
| 79848 | ** four bytes of the divider cell. So the pointer is safe to use | ||||
| 79849 | ** later on. | ||||
| 79850 | ** | ||||
| 79851 | ** But not if we are in secure-delete mode. In secure-delete mode, | ||||
| 79852 | ** the dropCell() routine will overwrite the entire cell with zeroes. | ||||
| 79853 | ** In this case, temporarily copy the cell into the aOvflSpace[] | ||||
| 79854 | ** buffer. It will be copied out again as soon as the aSpace[] buffer | ||||
| 79855 | ** is allocated. */ | ||||
| 79856 | if( pBt->btsFlags & BTS_FAST_SECURE0x000c ){ | ||||
| 79857 | int iOff; | ||||
| 79858 | |||||
| 79859 | /* If the following if() condition is not true, the db is corrupted. | ||||
| 79860 | ** The call to dropCell() below will detect this. */ | ||||
| 79861 | iOff = SQLITE_PTR_TO_INT(apDiv[i])((int)(long int)(apDiv[i])) - SQLITE_PTR_TO_INT(pParent->aData)((int)(long int)(pParent->aData)); | ||||
| 79862 | if( (iOff+szNew[i])<=(int)pBt->usableSize ){ | ||||
| 79863 | memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); | ||||
| 79864 | apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; | ||||
| 79865 | } | ||||
| 79866 | } | ||||
| 79867 | dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); | ||||
| 79868 | } | ||||
| 79869 | } | ||||
| 79870 | |||||
| 79871 | /* Make nMaxCells a multiple of 4 in order to preserve 8-byte | ||||
| 79872 | ** alignment */ | ||||
| 79873 | nMaxCells = (nMaxCells + 3)&~3; | ||||
| 79874 | |||||
| 79875 | /* | ||||
| 79876 | ** Allocate space for memory structures | ||||
| 79877 | */ | ||||
| 79878 | szScratch = | ||||
| 79879 | nMaxCells*sizeof(u8*) /* b.apCell */ | ||||
| 79880 | + nMaxCells*sizeof(u16) /* b.szCell */ | ||||
| 79881 | + pBt->pageSize; /* aSpace1 */ | ||||
| 79882 | |||||
| 79883 | assert( szScratch<=7*(int)pBt->pageSize )((void) (0)); | ||||
| 79884 | b.apCell = sqlite3StackAllocRaw(0, szScratch )sqlite3DbMallocRaw(0,szScratch); | ||||
| 79885 | if( b.apCell==0 ){ | ||||
| 79886 | rc = SQLITE_NOMEM_BKPT7; | ||||
| 79887 | goto balance_cleanup; | ||||
| 79888 | } | ||||
| 79889 | b.szCell = (u16*)&b.apCell[nMaxCells]; | ||||
| 79890 | aSpace1 = (u8*)&b.szCell[nMaxCells]; | ||||
| 79891 | assert( EIGHT_BYTE_ALIGNMENT(aSpace1) )((void) (0)); | ||||
| 79892 | |||||
| 79893 | /* | ||||
| 79894 | ** Load pointers to all cells on sibling pages and the divider cells | ||||
| 79895 | ** into the local b.apCell[] array. Make copies of the divider cells | ||||
| 79896 | ** into space obtained from aSpace1[]. The divider cells have already | ||||
| 79897 | ** been removed from pParent. | ||||
| 79898 | ** | ||||
| 79899 | ** If the siblings are on leaf pages, then the child pointers of the | ||||
| 79900 | ** divider cells are stripped from the cells before they are copied | ||||
| 79901 | ** into aSpace1[]. In this way, all cells in b.apCell[] are without | ||||
| 79902 | ** child pointers. If siblings are not leaves, then all cell in | ||||
| 79903 | ** b.apCell[] include child pointers. Either way, all cells in b.apCell[] | ||||
| 79904 | ** are alike. | ||||
| 79905 | ** | ||||
| 79906 | ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. | ||||
| 79907 | ** leafData: 1 if pPage holds key+data and pParent holds only keys. | ||||
| 79908 | */ | ||||
| 79909 | b.pRef = apOld[0]; | ||||
| 79910 | leafCorrection = b.pRef->leaf*4; | ||||
| 79911 | leafData = b.pRef->intKeyLeaf; | ||||
| 79912 | for(i=0; i<nOld; i++){ | ||||
| 79913 | MemPage *pOld = apOld[i]; | ||||
| 79914 | int limit = pOld->nCell; | ||||
| 79915 | u8 *aData = pOld->aData; | ||||
| 79916 | u16 maskPage = pOld->maskPage; | ||||
| 79917 | u8 *piCell = aData + pOld->cellOffset; | ||||
| 79918 | u8 *piEnd; | ||||
| 79919 | VVA_ONLY( int nCellAtStart = b.nCell; ) | ||||
| 79920 | |||||
| 79921 | /* Verify that all sibling pages are of the same "type" (table-leaf, | ||||
| 79922 | ** table-interior, index-leaf, or index-interior). | ||||
| 79923 | */ | ||||
| 79924 | if( pOld->aData[0]!=apOld[0]->aData[0] ){ | ||||
| 79925 | rc = SQLITE_CORRUPT_PAGE(pOld)sqlite3CorruptError(79925); | ||||
| 79926 | goto balance_cleanup; | ||||
| 79927 | } | ||||
| 79928 | |||||
| 79929 | /* Load b.apCell[] with pointers to all cells in pOld. If pOld | ||||
| 79930 | ** contains overflow cells, include them in the b.apCell[] array | ||||
| 79931 | ** in the correct spot. | ||||
| 79932 | ** | ||||
| 79933 | ** Note that when there are multiple overflow cells, it is always the | ||||
| 79934 | ** case that they are sequential and adjacent. This invariant arises | ||||
| 79935 | ** because multiple overflows can only occurs when inserting divider | ||||
| 79936 | ** cells into a parent on a prior balance, and divider cells are always | ||||
| 79937 | ** adjacent and are inserted in order. There is an assert() tagged | ||||
| 79938 | ** with "NOTE 1" in the overflow cell insertion loop to prove this | ||||
| 79939 | ** invariant. | ||||
| 79940 | ** | ||||
| 79941 | ** This must be done in advance. Once the balance starts, the cell | ||||
| 79942 | ** offset section of the btree page will be overwritten and we will no | ||||
| 79943 | ** long be able to find the cells if a pointer to each cell is not saved | ||||
| 79944 | ** first. | ||||
| 79945 | */ | ||||
| 79946 | memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow)); | ||||
| 79947 | if( pOld->nOverflow>0 ){ | ||||
| 79948 | if( NEVER(limit<pOld->aiOvfl[0])(limit<pOld->aiOvfl[0]) ){ | ||||
| 79949 | rc = SQLITE_CORRUPT_PAGE(pOld)sqlite3CorruptError(79949); | ||||
| 79950 | goto balance_cleanup; | ||||
| 79951 | } | ||||
| 79952 | limit = pOld->aiOvfl[0]; | ||||
| 79953 | for(j=0; j<limit; j++){ | ||||
| 79954 | b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)((piCell)[0]<<8 | (piCell)[1])); | ||||
| 79955 | piCell += 2; | ||||
| 79956 | b.nCell++; | ||||
| 79957 | } | ||||
| 79958 | for(k=0; k<pOld->nOverflow; k++){ | ||||
| 79959 | assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] )((void) (0));/* NOTE 1 */ | ||||
| 79960 | b.apCell[b.nCell] = pOld->apOvfl[k]; | ||||
| 79961 | b.nCell++; | ||||
| 79962 | } | ||||
| 79963 | } | ||||
| 79964 | piEnd = aData + pOld->cellOffset + 2*pOld->nCell; | ||||
| 79965 | while( piCell<piEnd ){ | ||||
| 79966 | assert( b.nCell<nMaxCells )((void) (0)); | ||||
| 79967 | b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell)((piCell)[0]<<8 | (piCell)[1])); | ||||
| 79968 | piCell += 2; | ||||
| 79969 | b.nCell++; | ||||
| 79970 | } | ||||
| 79971 | assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) )((void) (0)); | ||||
| 79972 | |||||
| 79973 | cntOld[i] = b.nCell; | ||||
| 79974 | if( i<nOld-1 && !leafData){ | ||||
| 79975 | u16 sz = (u16)szNew[i]; | ||||
| 79976 | u8 *pTemp; | ||||
| 79977 | assert( b.nCell<nMaxCells )((void) (0)); | ||||
| 79978 | b.szCell[b.nCell] = sz; | ||||
| 79979 | pTemp = &aSpace1[iSpace1]; | ||||
| 79980 | iSpace1 += sz; | ||||
| 79981 | assert( sz<=pBt->maxLocal+23 )((void) (0)); | ||||
| 79982 | assert( iSpace1 <= (int)pBt->pageSize )((void) (0)); | ||||
| 79983 | memcpy(pTemp, apDiv[i], sz); | ||||
| 79984 | b.apCell[b.nCell] = pTemp+leafCorrection; | ||||
| 79985 | assert( leafCorrection==0 || leafCorrection==4 )((void) (0)); | ||||
| 79986 | b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; | ||||
| 79987 | if( !pOld->leaf ){ | ||||
| 79988 | assert( leafCorrection==0 )((void) (0)); | ||||
| 79989 | assert( pOld->hdrOffset==0 || CORRUPT_DB )((void) (0)); | ||||
| 79990 | /* The right pointer of the child page pOld becomes the left | ||||
| 79991 | ** pointer of the divider cell */ | ||||
| 79992 | memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); | ||||
| 79993 | }else{ | ||||
| 79994 | assert( leafCorrection==4 )((void) (0)); | ||||
| 79995 | while( b.szCell[b.nCell]<4 ){ | ||||
| 79996 | /* Do not allow any cells smaller than 4 bytes. If a smaller cell | ||||
| 79997 | ** does exist, pad it with 0x00 bytes. */ | ||||
| 79998 | assert( b.szCell[b.nCell]==3 || CORRUPT_DB )((void) (0)); | ||||
| 79999 | assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB )((void) (0)); | ||||
| 80000 | aSpace1[iSpace1++] = 0x00; | ||||
| 80001 | b.szCell[b.nCell]++; | ||||
| 80002 | } | ||||
| 80003 | } | ||||
| 80004 | b.nCell++; | ||||
| 80005 | } | ||||
| 80006 | } | ||||
| 80007 | |||||
| 80008 | /* | ||||
| 80009 | ** Figure out the number of pages needed to hold all b.nCell cells. | ||||
| 80010 | ** Store this number in "k". Also compute szNew[] which is the total | ||||
| 80011 | ** size of all cells on the i-th page and cntNew[] which is the index | ||||
| 80012 | ** in b.apCell[] of the cell that divides page i from page i+1. | ||||
| 80013 | ** cntNew[k] should equal b.nCell. | ||||
| 80014 | ** | ||||
| 80015 | ** Values computed by this block: | ||||
| 80016 | ** | ||||
| 80017 | ** k: The total number of sibling pages | ||||
| 80018 | ** szNew[i]: Spaced used on the i-th sibling page. | ||||
| 80019 | ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to | ||||
| 80020 | ** the right of the i-th sibling page. | ||||
| 80021 | ** usableSpace: Number of bytes of space available on each sibling. | ||||
| 80022 | ** | ||||
| 80023 | */ | ||||
| 80024 | usableSpace = pBt->usableSize - 12 + leafCorrection; | ||||
| 80025 | for(i=k=0; i<nOld; i++, k++){ | ||||
| 80026 | MemPage *p = apOld[i]; | ||||
| 80027 | b.apEnd[k] = p->aDataEnd; | ||||
| 80028 | b.ixNx[k] = cntOld[i]; | ||||
| 80029 | if( k && b.ixNx[k]==b.ixNx[k-1] ){ | ||||
| 80030 | k--; /* Omit b.ixNx[] entry for child pages with no cells */ | ||||
| 80031 | } | ||||
| 80032 | if( !leafData ){ | ||||
| 80033 | k++; | ||||
| 80034 | b.apEnd[k] = pParent->aDataEnd; | ||||
| 80035 | b.ixNx[k] = cntOld[i]+1; | ||||
| 80036 | } | ||||
| 80037 | assert( p->nFree>=0 )((void) (0)); | ||||
| 80038 | szNew[i] = usableSpace - p->nFree; | ||||
| 80039 | for(j=0; j<p->nOverflow; j++){ | ||||
| 80040 | szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); | ||||
| 80041 | } | ||||
| 80042 | cntNew[i] = cntOld[i]; | ||||
| 80043 | } | ||||
| 80044 | k = nOld; | ||||
| 80045 | for(i=0; i<k; i++){ | ||||
| 80046 | int sz; | ||||
| 80047 | while( szNew[i]>usableSpace ){ | ||||
| 80048 | if( i+1>=k ){ | ||||
| 80049 | k = i+2; | ||||
| 80050 | if( k>NB3+2 ){ rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(80050); goto balance_cleanup; } | ||||
| 80051 | szNew[k-1] = 0; | ||||
| 80052 | cntNew[k-1] = b.nCell; | ||||
| 80053 | } | ||||
| 80054 | sz = 2 + cachedCellSize(&b, cntNew[i]-1); | ||||
| 80055 | szNew[i] -= sz; | ||||
| 80056 | if( !leafData ){ | ||||
| 80057 | if( cntNew[i]<b.nCell ){ | ||||
| 80058 | sz = 2 + cachedCellSize(&b, cntNew[i]); | ||||
| 80059 | }else{ | ||||
| 80060 | sz = 0; | ||||
| 80061 | } | ||||
| 80062 | } | ||||
| 80063 | szNew[i+1] += sz; | ||||
| 80064 | cntNew[i]--; | ||||
| 80065 | } | ||||
| 80066 | while( cntNew[i]<b.nCell ){ | ||||
| 80067 | sz = 2 + cachedCellSize(&b, cntNew[i]); | ||||
| 80068 | if( szNew[i]+sz>usableSpace ) break; | ||||
| 80069 | szNew[i] += sz; | ||||
| 80070 | cntNew[i]++; | ||||
| 80071 | if( !leafData ){ | ||||
| 80072 | if( cntNew[i]<b.nCell ){ | ||||
| 80073 | sz = 2 + cachedCellSize(&b, cntNew[i]); | ||||
| 80074 | }else{ | ||||
| 80075 | sz = 0; | ||||
| 80076 | } | ||||
| 80077 | } | ||||
| 80078 | szNew[i+1] -= sz; | ||||
| 80079 | } | ||||
| 80080 | if( cntNew[i]>=b.nCell ){ | ||||
| 80081 | k = i+1; | ||||
| 80082 | }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){ | ||||
| 80083 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(80083); | ||||
| 80084 | goto balance_cleanup; | ||||
| 80085 | } | ||||
| 80086 | } | ||||
| 80087 | |||||
| 80088 | /* | ||||
| 80089 | ** The packing computed by the previous block is biased toward the siblings | ||||
| 80090 | ** on the left side (siblings with smaller keys). The left siblings are | ||||
| 80091 | ** always nearly full, while the right-most sibling might be nearly empty. | ||||
| 80092 | ** The next block of code attempts to adjust the packing of siblings to | ||||
| 80093 | ** get a better balance. | ||||
| 80094 | ** | ||||
| 80095 | ** This adjustment is more than an optimization. The packing above might | ||||
| 80096 | ** be so out of balance as to be illegal. For example, the right-most | ||||
| 80097 | ** sibling might be completely empty. This adjustment is not optional. | ||||
| 80098 | */ | ||||
| 80099 | for(i=k-1; i>0; i--){ | ||||
| 80100 | int szRight = szNew[i]; /* Size of sibling on the right */ | ||||
| 80101 | int szLeft = szNew[i-1]; /* Size of sibling on the left */ | ||||
| 80102 | int r; /* Index of right-most cell in left sibling */ | ||||
| 80103 | int d; /* Index of first cell to the left of right sibling */ | ||||
| 80104 | |||||
| 80105 | r = cntNew[i-1] - 1; | ||||
| 80106 | d = r + 1 - leafData; | ||||
| 80107 | (void)cachedCellSize(&b, d); | ||||
| 80108 | do{ | ||||
| 80109 | int szR, szD; | ||||
| 80110 | assert( d<nMaxCells )((void) (0)); | ||||
| 80111 | assert( r<nMaxCells )((void) (0)); | ||||
| 80112 | szR = cachedCellSize(&b, r); | ||||
| 80113 | szD = b.szCell[d]; | ||||
| 80114 | if( szRight!=0 | ||||
| 80115 | && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){ | ||||
| 80116 | break; | ||||
| 80117 | } | ||||
| 80118 | szRight += szD + 2; | ||||
| 80119 | szLeft -= szR + 2; | ||||
| 80120 | cntNew[i-1] = r; | ||||
| 80121 | r--; | ||||
| 80122 | d--; | ||||
| 80123 | }while( r>=0 ); | ||||
| 80124 | szNew[i] = szRight; | ||||
| 80125 | szNew[i-1] = szLeft; | ||||
| 80126 | if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){ | ||||
| 80127 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(80127); | ||||
| 80128 | goto balance_cleanup; | ||||
| 80129 | } | ||||
| 80130 | } | ||||
| 80131 | |||||
| 80132 | /* Sanity check: For a non-corrupt database file one of the following | ||||
| 80133 | ** must be true: | ||||
| 80134 | ** (1) We found one or more cells (cntNew[0])>0), or | ||||
| 80135 | ** (2) pPage is a virtual root page. A virtual root page is when | ||||
| 80136 | ** the real root page is page 1 and we are the only child of | ||||
| 80137 | ** that page. | ||||
| 80138 | */ | ||||
| 80139 | assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB)((void) (0)); | ||||
| 80140 | TRACE(("BALANCE: old: %u(nc=%u) %u(nc=%u) %u(nc=%u)\n", | ||||
| 80141 | apOld[0]->pgno, apOld[0]->nCell, | ||||
| 80142 | nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0, | ||||
| 80143 | nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0 | ||||
| 80144 | )); | ||||
| 80145 | |||||
| 80146 | /* | ||||
| 80147 | ** Allocate k new pages. Reuse old pages where possible. | ||||
| 80148 | */ | ||||
| 80149 | pageFlags = apOld[0]->aData[0]; | ||||
| 80150 | for(i=0; i<k; i++){ | ||||
| 80151 | MemPage *pNew; | ||||
| 80152 | if( i<nOld ){ | ||||
| 80153 | pNew = apNew[i] = apOld[i]; | ||||
| 80154 | apOld[i] = 0; | ||||
| 80155 | rc = sqlite3PagerWrite(pNew->pDbPage); | ||||
| 80156 | nNew++; | ||||
| 80157 | if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv)) | ||||
| 80158 | && rc==SQLITE_OK0 | ||||
| 80159 | ){ | ||||
| 80160 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(80160); | ||||
| 80161 | } | ||||
| 80162 | if( rc ) goto balance_cleanup; | ||||
| 80163 | }else{ | ||||
| 80164 | assert( i>0 )((void) (0)); | ||||
| 80165 | rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); | ||||
| 80166 | if( rc ) goto balance_cleanup; | ||||
| 80167 | zeroPage(pNew, pageFlags); | ||||
| 80168 | apNew[i] = pNew; | ||||
| 80169 | nNew++; | ||||
| 80170 | cntOld[i] = b.nCell; | ||||
| 80171 | |||||
| 80172 | /* Set the pointer-map entry for the new sibling page. */ | ||||
| 80173 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) ){ | ||||
| 80174 | ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE5, pParent->pgno, &rc); | ||||
| 80175 | if( rc!=SQLITE_OK0 ){ | ||||
| 80176 | goto balance_cleanup; | ||||
| 80177 | } | ||||
| 80178 | } | ||||
| 80179 | } | ||||
| 80180 | } | ||||
| 80181 | |||||
| 80182 | /* | ||||
| 80183 | ** Reassign page numbers so that the new pages are in ascending order. | ||||
| 80184 | ** This helps to keep entries in the disk file in order so that a scan | ||||
| 80185 | ** of the table is closer to a linear scan through the file. That in turn | ||||
| 80186 | ** helps the operating system to deliver pages from the disk more rapidly. | ||||
| 80187 | ** | ||||
| 80188 | ** An O(N*N) sort algorithm is used, but since N is never more than NB+2 | ||||
| 80189 | ** (5), that is not a performance concern. | ||||
| 80190 | ** | ||||
| 80191 | ** When NB==3, this one optimization makes the database about 25% faster | ||||
| 80192 | ** for large insertions and deletions. | ||||
| 80193 | */ | ||||
| 80194 | for(i=0; i<nNew; i++){ | ||||
| 80195 | aPgno[i] = apNew[i]->pgno; | ||||
| 80196 | assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE )((void) (0)); | ||||
| 80197 | assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY )((void) (0)); | ||||
| 80198 | } | ||||
| 80199 | for(i=0; i<nNew-1; i++){ | ||||
| 80200 | int iB = i; | ||||
| 80201 | for(j=i+1; j<nNew; j++){ | ||||
| 80202 | if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j; | ||||
| 80203 | } | ||||
| 80204 | |||||
| 80205 | /* If apNew[i] has a page number that is bigger than any of the | ||||
| 80206 | ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent | ||||
| 80207 | ** entry that has the smallest page number (which we know to be | ||||
| 80208 | ** entry apNew[iB]). | ||||
| 80209 | */ | ||||
| 80210 | if( iB!=i ){ | ||||
| 80211 | Pgno pgnoA = apNew[i]->pgno; | ||||
| 80212 | Pgno pgnoB = apNew[iB]->pgno; | ||||
| 80213 | Pgno pgnoTemp = (PENDING_BYTEsqlite3PendingByte/pBt->pageSize)+1; | ||||
| 80214 | u16 fgA = apNew[i]->pDbPage->flags; | ||||
| 80215 | u16 fgB = apNew[iB]->pDbPage->flags; | ||||
| 80216 | sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB); | ||||
| 80217 | sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA); | ||||
| 80218 | sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB); | ||||
| 80219 | apNew[i]->pgno = pgnoB; | ||||
| 80220 | apNew[iB]->pgno = pgnoA; | ||||
| 80221 | } | ||||
| 80222 | } | ||||
| 80223 | |||||
| 80224 | TRACE(("BALANCE: new: %u(%u nc=%u) %u(%u nc=%u) %u(%u nc=%u) " | ||||
| 80225 | "%u(%u nc=%u) %u(%u nc=%u)\n", | ||||
| 80226 | apNew[0]->pgno, szNew[0], cntNew[0], | ||||
| 80227 | nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, | ||||
| 80228 | nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0, | ||||
| 80229 | nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, | ||||
| 80230 | nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0, | ||||
| 80231 | nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, | ||||
| 80232 | nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0, | ||||
| 80233 | nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0, | ||||
| 80234 | nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 | ||||
| 80235 | )); | ||||
| 80236 | |||||
| 80237 | assert( sqlite3PagerIswriteable(pParent->pDbPage) )((void) (0)); | ||||
| 80238 | assert( nNew>=1 && nNew<=ArraySize(apNew) )((void) (0)); | ||||
| 80239 | assert( apNew[nNew-1]!=0 )((void) (0)); | ||||
| 80240 | put4bytesqlite3Put4byte(pRight, apNew[nNew-1]->pgno); | ||||
| 80241 | |||||
| 80242 | /* If the sibling pages are not leaves, ensure that the right-child pointer | ||||
| 80243 | ** of the right-most new sibling page is set to the value that was | ||||
| 80244 | ** originally in the same field of the right-most old sibling page. */ | ||||
| 80245 | if( (pageFlags & PTF_LEAF0x08)==0 && nOld!=nNew ){ | ||||
| 80246 | MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; | ||||
| 80247 | memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); | ||||
| 80248 | } | ||||
| 80249 | |||||
| 80250 | /* Make any required updates to pointer map entries associated with | ||||
| 80251 | ** cells stored on sibling pages following the balance operation. Pointer | ||||
| 80252 | ** map entries associated with divider cells are set by the insertCell() | ||||
| 80253 | ** routine. The associated pointer map entries are: | ||||
| 80254 | ** | ||||
| 80255 | ** a) if the cell contains a reference to an overflow chain, the | ||||
| 80256 | ** entry associated with the first page in the overflow chain, and | ||||
| 80257 | ** | ||||
| 80258 | ** b) if the sibling pages are not leaves, the child page associated | ||||
| 80259 | ** with the cell. | ||||
| 80260 | ** | ||||
| 80261 | ** If the sibling pages are not leaves, then the pointer map entry | ||||
| 80262 | ** associated with the right-child of each sibling may also need to be | ||||
| 80263 | ** updated. This happens below, after the sibling pages have been | ||||
| 80264 | ** populated, not here. | ||||
| 80265 | */ | ||||
| 80266 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) ){ | ||||
| 80267 | MemPage *pOld; | ||||
| 80268 | MemPage *pNew = pOld = apNew[0]; | ||||
| 80269 | int cntOldNext = pNew->nCell + pNew->nOverflow; | ||||
| 80270 | int iNew = 0; | ||||
| 80271 | int iOld = 0; | ||||
| 80272 | |||||
| 80273 | for(i=0; i<b.nCell; i++){ | ||||
| 80274 | u8 *pCell = b.apCell[i]; | ||||
| 80275 | while( i==cntOldNext ){ | ||||
| 80276 | iOld++; | ||||
| 80277 | assert( iOld<nNew || iOld<nOld )((void) (0)); | ||||
| 80278 | assert( iOld>=0 && iOld<NB )((void) (0)); | ||||
| 80279 | pOld = iOld<nNew ? apNew[iOld] : apOld[iOld]; | ||||
| 80280 | cntOldNext += pOld->nCell + pOld->nOverflow + !leafData; | ||||
| 80281 | } | ||||
| 80282 | if( i==cntNew[iNew] ){ | ||||
| 80283 | pNew = apNew[++iNew]; | ||||
| 80284 | if( !leafData ) continue; | ||||
| 80285 | } | ||||
| 80286 | |||||
| 80287 | /* Cell pCell is destined for new sibling page pNew. Originally, it | ||||
| 80288 | ** was either part of sibling page iOld (possibly an overflow cell), | ||||
| 80289 | ** or else the divider cell to the left of sibling page iOld. So, | ||||
| 80290 | ** if sibling page iOld had the same page number as pNew, and if | ||||
| 80291 | ** pCell really was a part of sibling page iOld (not a divider or | ||||
| 80292 | ** overflow cell), we can skip updating the pointer map entries. */ | ||||
| 80293 | if( iOld>=nNew | ||||
| 80294 | || pNew->pgno!=aPgno[iOld] | ||||
| 80295 | || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)(((uptr)(pCell)>=(uptr)(pOld->aData))&&((uptr)( pCell)<(uptr)(pOld->aDataEnd))) | ||||
| 80296 | ){ | ||||
| 80297 | if( !leafCorrection ){ | ||||
| 80298 | ptrmapPut(pBt, get4bytesqlite3Get4byte(pCell), PTRMAP_BTREE5, pNew->pgno, &rc); | ||||
| 80299 | } | ||||
| 80300 | if( cachedCellSize(&b,i)>pNew->minLocal ){ | ||||
| 80301 | ptrmapPutOvflPtr(pNew, pOld, pCell, &rc); | ||||
| 80302 | } | ||||
| 80303 | if( rc ) goto balance_cleanup; | ||||
| 80304 | } | ||||
| 80305 | } | ||||
| 80306 | } | ||||
| 80307 | |||||
| 80308 | /* Insert new divider cells into pParent. */ | ||||
| 80309 | for(i=0; i<nNew-1; i++){ | ||||
| 80310 | u8 *pCell; | ||||
| 80311 | u8 *pTemp; | ||||
| 80312 | int sz; | ||||
| 80313 | u8 *pSrcEnd; | ||||
| 80314 | MemPage *pNew = apNew[i]; | ||||
| 80315 | j = cntNew[i]; | ||||
| 80316 | |||||
| 80317 | assert( j<nMaxCells )((void) (0)); | ||||
| 80318 | assert( b.apCell[j]!=0 )((void) (0)); | ||||
| 80319 | pCell = b.apCell[j]; | ||||
| 80320 | sz = b.szCell[j] + leafCorrection; | ||||
| 80321 | pTemp = &aOvflSpace[iOvflSpace]; | ||||
| 80322 | if( !pNew->leaf ){ | ||||
| 80323 | memcpy(&pNew->aData[8], pCell, 4); | ||||
| 80324 | }else if( leafData ){ | ||||
| 80325 | /* If the tree is a leaf-data tree, and the siblings are leaves, | ||||
| 80326 | ** then there is no divider cell in b.apCell[]. Instead, the divider | ||||
| 80327 | ** cell consists of the integer key for the right-most cell of | ||||
| 80328 | ** the sibling-page assembled above only. | ||||
| 80329 | */ | ||||
| 80330 | CellInfo info; | ||||
| 80331 | j--; | ||||
| 80332 | pNew->xParseCell(pNew, b.apCell[j], &info); | ||||
| 80333 | pCell = pTemp; | ||||
| 80334 | sz = 4 + putVarintsqlite3PutVarint(&pCell[4], info.nKey); | ||||
| 80335 | pTemp = 0; | ||||
| 80336 | }else{ | ||||
| 80337 | pCell -= 4; | ||||
| 80338 | /* Obscure case for non-leaf-data trees: If the cell at pCell was | ||||
| 80339 | ** previously stored on a leaf node, and its reported size was 4 | ||||
| 80340 | ** bytes, then it may actually be smaller than this | ||||
| 80341 | ** (see btreeParseCellPtr(), 4 bytes is the minimum size of | ||||
| 80342 | ** any cell). But it is important to pass the correct size to | ||||
| 80343 | ** insertCell(), so reparse the cell now. | ||||
| 80344 | ** | ||||
| 80345 | ** This can only happen for b-trees used to evaluate "IN (SELECT ...)" | ||||
| 80346 | ** and WITHOUT ROWID tables with exactly one column which is the | ||||
| 80347 | ** primary key. | ||||
| 80348 | */ | ||||
| 80349 | if( b.szCell[j]==4 ){ | ||||
| 80350 | assert(leafCorrection==4)((void) (0)); | ||||
| 80351 | sz = pParent->xCellSize(pParent, pCell); | ||||
| 80352 | } | ||||
| 80353 | } | ||||
| 80354 | iOvflSpace += sz; | ||||
| 80355 | assert( sz<=pBt->maxLocal+23 )((void) (0)); | ||||
| 80356 | assert( iOvflSpace <= (int)pBt->pageSize )((void) (0)); | ||||
| 80357 | assert( b.ixNx[NB*2-1]>j )((void) (0)); | ||||
| 80358 | for(k=0; b.ixNx[k]<=j; k++){} | ||||
| 80359 | pSrcEnd = b.apEnd[k]; | ||||
| 80360 | if( SQLITE_OVERFLOW(pSrcEnd, pCell, pCell+sz)(((uptr)(pCell)<(uptr)(pSrcEnd))&&((uptr)(pCell+sz )>(uptr)(pSrcEnd))) ){ | ||||
| 80361 | rc = SQLITE_CORRUPT_BKPTsqlite3CorruptError(80361); | ||||
| 80362 | goto balance_cleanup; | ||||
| 80363 | } | ||||
| 80364 | rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno); | ||||
| 80365 | if( rc!=SQLITE_OK0 ) goto balance_cleanup; | ||||
| 80366 | assert( sqlite3PagerIswriteable(pParent->pDbPage) )((void) (0)); | ||||
| 80367 | } | ||||
| 80368 | |||||
| 80369 | /* Now update the actual sibling pages. The order in which they are updated | ||||
| 80370 | ** is important, as this code needs to avoid disrupting any page from which | ||||
| 80371 | ** cells may still to be read. In practice, this means: | ||||
| 80372 | ** | ||||
| 80373 | ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1]) | ||||
| 80374 | ** then it is not safe to update page apNew[iPg] until after | ||||
| 80375 | ** the left-hand sibling apNew[iPg-1] has been updated. | ||||
| 80376 | ** | ||||
| 80377 | ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1]) | ||||
| 80378 | ** then it is not safe to update page apNew[iPg] until after | ||||
| 80379 | ** the right-hand sibling apNew[iPg+1] has been updated. | ||||
| 80380 | ** | ||||
| 80381 | ** If neither of the above apply, the page is safe to update. | ||||
| 80382 | ** | ||||
| 80383 | ** The iPg value in the following loop starts at nNew-1 goes down | ||||
| 80384 | ** to 0, then back up to nNew-1 again, thus making two passes over | ||||
| 80385 | ** the pages. On the initial downward pass, only condition (1) above | ||||
| 80386 | ** needs to be tested because (2) will always be true from the previous | ||||
| 80387 | ** step. On the upward pass, both conditions are always true, so the | ||||
| 80388 | ** upwards pass simply processes pages that were missed on the downward | ||||
| 80389 | ** pass. | ||||
| 80390 | */ | ||||
| 80391 | for(i=1-nNew; i<nNew; i++){ | ||||
| 80392 | int iPg = i<0 ? -i : i; | ||||
| 80393 | assert( iPg>=0 && iPg<nNew )((void) (0)); | ||||
| 80394 | assert( iPg>=1 || i>=0 )((void) (0)); | ||||
| 80395 | assert( iPg<ArraySize(cntOld) )((void) (0)); | ||||
| 80396 | if( abDone[iPg] ) continue; /* Skip pages already processed */ | ||||
| 80397 | if( i>=0 /* On the upwards pass, or... */ | ||||
| 80398 | || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */ | ||||
| 80399 | ){ | ||||
| 80400 | int iNew; | ||||
| 80401 | int iOld; | ||||
| 80402 | int nNewCell; | ||||
| 80403 | |||||
| 80404 | /* Verify condition (1): If cells are moving left, update iPg | ||||
| 80405 | ** only after iPg-1 has already been updated. */ | ||||
| 80406 | assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] )((void) (0)); | ||||
| 80407 | |||||
| 80408 | /* Verify condition (2): If cells are moving right, update iPg | ||||
| 80409 | ** only after iPg+1 has already been updated. */ | ||||
| 80410 | assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] )((void) (0)); | ||||
| 80411 | |||||
| 80412 | if( iPg==0 ){ | ||||
| 80413 | iNew = iOld = 0; | ||||
| 80414 | nNewCell = cntNew[0]; | ||||
| 80415 | }else{ | ||||
| 80416 | iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell; | ||||
| 80417 | iNew = cntNew[iPg-1] + !leafData; | ||||
| 80418 | nNewCell = cntNew[iPg] - iNew; | ||||
| 80419 | } | ||||
| 80420 | |||||
| 80421 | rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b); | ||||
| 80422 | if( rc ) goto balance_cleanup; | ||||
| 80423 | abDone[iPg]++; | ||||
| 80424 | apNew[iPg]->nFree = usableSpace-szNew[iPg]; | ||||
| 80425 | assert( apNew[iPg]->nOverflow==0 )((void) (0)); | ||||
| 80426 | assert( apNew[iPg]->nCell==nNewCell )((void) (0)); | ||||
| 80427 | } | ||||
| 80428 | } | ||||
| 80429 | |||||
| 80430 | /* All pages have been processed exactly once */ | ||||
| 80431 | assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 )((void) (0)); | ||||
| 80432 | |||||
| 80433 | assert( nOld>0 )((void) (0)); | ||||
| 80434 | assert( nNew>0 )((void) (0)); | ||||
| 80435 | |||||
| 80436 | if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ | ||||
| 80437 | /* The root page of the b-tree now contains no cells. The only sibling | ||||
| 80438 | ** page is the right-child of the parent. Copy the contents of the | ||||
| 80439 | ** child page into the parent, decreasing the overall height of the | ||||
| 80440 | ** b-tree structure by one. This is described as the "balance-shallower" | ||||
| 80441 | ** sub-algorithm in some documentation. | ||||
| 80442 | ** | ||||
| 80443 | ** If this is an auto-vacuum database, the call to copyNodeContent() | ||||
| 80444 | ** sets all pointer-map entries corresponding to database image pages | ||||
| 80445 | ** for which the pointer is stored within the content being copied. | ||||
| 80446 | ** | ||||
| 80447 | ** It is critical that the child page be defragmented before being | ||||
| 80448 | ** copied into the parent, because if the parent is page 1 then it will | ||||
| 80449 | ** by smaller than the child due to the database header, and so all the | ||||
| 80450 | ** free space needs to be up front. | ||||
| 80451 | */ | ||||
| 80452 | assert( nNew==1 || CORRUPT_DB )((void) (0)); | ||||
| 80453 | rc = defragmentPage(apNew[0], -1); | ||||
| 80454 | testcase( rc!=SQLITE_OK ); | ||||
| 80455 | assert( apNew[0]->nFree ==((void) (0)) | ||||
| 80456 | (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset((void) (0)) | ||||
| 80457 | - apNew[0]->nCell*2)((void) (0)) | ||||
| 80458 | || rc!=SQLITE_OK((void) (0)) | ||||
| 80459 | )((void) (0)); | ||||
| 80460 | copyNodeContent(apNew[0], pParent, &rc); | ||||
| 80461 | freePage(apNew[0], &rc); | ||||
| 80462 | }else if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) && !leafCorrection ){ | ||||
| 80463 | /* Fix the pointer map entries associated with the right-child of each | ||||
| 80464 | ** sibling page. All other pointer map entries have already been taken | ||||
| 80465 | ** care of. */ | ||||
| 80466 | for(i=0; i<nNew; i++){ | ||||
| 80467 | u32 key = get4bytesqlite3Get4byte(&apNew[i]->aData[8]); | ||||
| 80468 | ptrmapPut(pBt, key, PTRMAP_BTREE5, apNew[i]->pgno, &rc); | ||||
| 80469 | } | ||||
| 80470 | } | ||||
| 80471 | |||||
| 80472 | assert( pParent->isInit )((void) (0)); | ||||
| 80473 | TRACE(("BALANCE: finished: old=%u new=%u cells=%u\n", | ||||
| 80474 | nOld, nNew, b.nCell)); | ||||
| 80475 | |||||
| 80476 | /* Free any old pages that were not reused as new pages. | ||||
| 80477 | */ | ||||
| 80478 | for(i=nNew; i<nOld; i++){ | ||||
| 80479 | freePage(apOld[i], &rc); | ||||
| 80480 | } | ||||
| 80481 | |||||
| 80482 | #if 0 | ||||
| 80483 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) && rc==SQLITE_OK0 && apNew[0]->isInit ){ | ||||
| 80484 | /* The ptrmapCheckPages() contains assert() statements that verify that | ||||
| 80485 | ** all pointer map pages are set correctly. This is helpful while | ||||
| 80486 | ** debugging. This is usually disabled because a corrupt database may | ||||
| 80487 | ** cause an assert() statement to fail. */ | ||||
| 80488 | ptrmapCheckPages(apNew, nNew); | ||||
| 80489 | ptrmapCheckPages(&pParent, 1); | ||||
| 80490 | } | ||||
| 80491 | #endif | ||||
| 80492 | |||||
| 80493 | /* | ||||
| 80494 | ** Cleanup before returning. | ||||
| 80495 | */ | ||||
| 80496 | balance_cleanup: | ||||
| 80497 | sqlite3StackFree(0, b.apCell)sqlite3DbFree(0,b.apCell); | ||||
| 80498 | for(i=0; i<nOld; i++){ | ||||
| 80499 | releasePage(apOld[i]); | ||||
| 80500 | } | ||||
| 80501 | for(i=0; i<nNew; i++){ | ||||
| 80502 | releasePage(apNew[i]); | ||||
| 80503 | } | ||||
| 80504 | |||||
| 80505 | return rc; | ||||
| 80506 | } | ||||
| 80507 | |||||
| 80508 | |||||
| 80509 | /* | ||||
| 80510 | ** This function is called when the root page of a b-tree structure is | ||||
| 80511 | ** overfull (has one or more overflow pages). | ||||
| 80512 | ** | ||||
| 80513 | ** A new child page is allocated and the contents of the current root | ||||
| 80514 | ** page, including overflow cells, are copied into the child. The root | ||||
| 80515 | ** page is then overwritten to make it an empty page with the right-child | ||||
| 80516 | ** pointer pointing to the new page. | ||||
| 80517 | ** | ||||
| 80518 | ** Before returning, all pointer-map entries corresponding to pages | ||||
| 80519 | ** that the new child-page now contains pointers to are updated. The | ||||
| 80520 | ** entry corresponding to the new right-child pointer of the root | ||||
| 80521 | ** page is also updated. | ||||
| 80522 | ** | ||||
| 80523 | ** If successful, *ppChild is set to contain a reference to the child | ||||
| 80524 | ** page and SQLITE_OK is returned. In this case the caller is required | ||||
| 80525 | ** to call releasePage() on *ppChild exactly once. If an error occurs, | ||||
| 80526 | ** an error code is returned and *ppChild is set to 0. | ||||
| 80527 | */ | ||||
| 80528 | static int balance_deeper(MemPage *pRoot, MemPage **ppChild){ | ||||
| 80529 | int rc; /* Return value from subprocedures */ | ||||
| 80530 | MemPage *pChild = 0; /* Pointer to a new child page */ | ||||
| 80531 | Pgno pgnoChild = 0; /* Page number of the new child page */ | ||||
| 80532 | BtShared *pBt = pRoot->pBt; /* The BTree */ | ||||
| 80533 | |||||
| 80534 | assert( pRoot->nOverflow>0 )((void) (0)); | ||||
| 80535 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 80536 | |||||
| 80537 | /* Make pRoot, the root page of the b-tree, writable. Allocate a new | ||||
| 80538 | ** page that will become the new right-child of pPage. Copy the contents | ||||
| 80539 | ** of the node stored on pRoot into the new child page. | ||||
| 80540 | */ | ||||
| 80541 | rc = sqlite3PagerWrite(pRoot->pDbPage); | ||||
| 80542 | if( rc==SQLITE_OK0 ){ | ||||
| 80543 | rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); | ||||
| 80544 | copyNodeContent(pRoot, pChild, &rc); | ||||
| 80545 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) ){ | ||||
| 80546 | ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE5, pRoot->pgno, &rc); | ||||
| 80547 | } | ||||
| 80548 | } | ||||
| 80549 | if( rc ){ | ||||
| 80550 | *ppChild = 0; | ||||
| 80551 | releasePage(pChild); | ||||
| 80552 | return rc; | ||||
| 80553 | } | ||||
| 80554 | assert( sqlite3PagerIswriteable(pChild->pDbPage) )((void) (0)); | ||||
| 80555 | assert( sqlite3PagerIswriteable(pRoot->pDbPage) )((void) (0)); | ||||
| 80556 | assert( pChild->nCell==pRoot->nCell || CORRUPT_DB )((void) (0)); | ||||
| 80557 | |||||
| 80558 | TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno)); | ||||
| 80559 | |||||
| 80560 | /* Copy the overflow cells from pRoot to pChild */ | ||||
| 80561 | memcpy(pChild->aiOvfl, pRoot->aiOvfl, | ||||
| 80562 | pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); | ||||
| 80563 | memcpy(pChild->apOvfl, pRoot->apOvfl, | ||||
| 80564 | pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); | ||||
| 80565 | pChild->nOverflow = pRoot->nOverflow; | ||||
| 80566 | |||||
| 80567 | /* Zero the contents of pRoot. Then install pChild as the right-child. */ | ||||
| 80568 | zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF0x08); | ||||
| 80569 | put4bytesqlite3Put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); | ||||
| 80570 | |||||
| 80571 | *ppChild = pChild; | ||||
| 80572 | return SQLITE_OK0; | ||||
| 80573 | } | ||||
| 80574 | |||||
| 80575 | /* | ||||
| 80576 | ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid | ||||
| 80577 | ** on the same B-tree as pCur. | ||||
| 80578 | ** | ||||
| 80579 | ** This can occur if a database is corrupt with two or more SQL tables | ||||
| 80580 | ** pointing to the same b-tree. If an insert occurs on one SQL table | ||||
| 80581 | ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL | ||||
| 80582 | ** table linked to the same b-tree. If the secondary insert causes a | ||||
| 80583 | ** rebalance, that can change content out from under the cursor on the | ||||
| 80584 | ** first SQL table, violating invariants on the first insert. | ||||
| 80585 | */ | ||||
| 80586 | static int anotherValidCursor(BtCursor *pCur){ | ||||
| 80587 | BtCursor *pOther; | ||||
| 80588 | for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){ | ||||
| 80589 | if( pOther!=pCur | ||||
| 80590 | && pOther->eState==CURSOR_VALID0 | ||||
| 80591 | && pOther->pPage==pCur->pPage | ||||
| 80592 | ){ | ||||
| 80593 | return SQLITE_CORRUPT_PAGE(pCur->pPage)sqlite3CorruptError(80593); | ||||
| 80594 | } | ||||
| 80595 | } | ||||
| 80596 | return SQLITE_OK0; | ||||
| 80597 | } | ||||
| 80598 | |||||
| 80599 | /* | ||||
| 80600 | ** The page that pCur currently points to has just been modified in | ||||
| 80601 | ** some way. This function figures out if this modification means the | ||||
| 80602 | ** tree needs to be balanced, and if so calls the appropriate balancing | ||||
| 80603 | ** routine. Balancing routines are: | ||||
| 80604 | ** | ||||
| 80605 | ** balance_quick() | ||||
| 80606 | ** balance_deeper() | ||||
| 80607 | ** balance_nonroot() | ||||
| 80608 | */ | ||||
| 80609 | static int balance(BtCursor *pCur){ | ||||
| 80610 | int rc = SQLITE_OK0; | ||||
| 80611 | u8 aBalanceQuickSpace[13]; | ||||
| 80612 | u8 *pFree = 0; | ||||
| 80613 | |||||
| 80614 | VVA_ONLY( int balance_quick_called = 0 ); | ||||
| 80615 | VVA_ONLY( int balance_deeper_called = 0 ); | ||||
| 80616 | |||||
| 80617 | do { | ||||
| 80618 | int iPage; | ||||
| 80619 | MemPage *pPage = pCur->pPage; | ||||
| 80620 | |||||
| 80621 | if( NEVER(pPage->nFree<0)(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break; | ||||
| 80622 | if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){ | ||||
| 80623 | /* No rebalance required as long as: | ||||
| 80624 | ** (1) There are no overflow cells | ||||
| 80625 | ** (2) The amount of free space on the page is less than 2/3rds of | ||||
| 80626 | ** the total usable space on the page. */ | ||||
| 80627 | break; | ||||
| 80628 | }else if( (iPage = pCur->iPage)==0 ){ | ||||
| 80629 | if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK0 ){ | ||||
| 80630 | /* The root page of the b-tree is overfull. In this case call the | ||||
| 80631 | ** balance_deeper() function to create a new child for the root-page | ||||
| 80632 | ** and copy the current contents of the root-page to it. The | ||||
| 80633 | ** next iteration of the do-loop will balance the child page. | ||||
| 80634 | */ | ||||
| 80635 | assert( balance_deeper_called==0 )((void) (0)); | ||||
| 80636 | VVA_ONLY( balance_deeper_called++ ); | ||||
| 80637 | rc = balance_deeper(pPage, &pCur->apPage[1]); | ||||
| 80638 | if( rc==SQLITE_OK0 ){ | ||||
| 80639 | pCur->iPage = 1; | ||||
| 80640 | pCur->ix = 0; | ||||
| 80641 | pCur->aiIdx[0] = 0; | ||||
| 80642 | pCur->apPage[0] = pPage; | ||||
| 80643 | pCur->pPage = pCur->apPage[1]; | ||||
| 80644 | assert( pCur->pPage->nOverflow )((void) (0)); | ||||
| 80645 | } | ||||
| 80646 | }else{ | ||||
| 80647 | break; | ||||
| 80648 | } | ||||
| 80649 | }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){ | ||||
| 80650 | /* The page being written is not a root page, and there is currently | ||||
| 80651 | ** more than one reference to it. This only happens if the page is one | ||||
| 80652 | ** of its own ancestor pages. Corruption. */ | ||||
| 80653 | rc = SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(80653); | ||||
| 80654 | }else{ | ||||
| 80655 | MemPage * const pParent = pCur->apPage[iPage-1]; | ||||
| 80656 | int const iIdx = pCur->aiIdx[iPage-1]; | ||||
| 80657 | |||||
| 80658 | rc = sqlite3PagerWrite(pParent->pDbPage); | ||||
| 80659 | if( rc==SQLITE_OK0 && pParent->nFree<0 ){ | ||||
| 80660 | rc = btreeComputeFreeSpace(pParent); | ||||
| 80661 | } | ||||
| 80662 | if( rc==SQLITE_OK0 ){ | ||||
| 80663 | #ifndef SQLITE_OMIT_QUICKBALANCE | ||||
| 80664 | if( pPage->intKeyLeaf | ||||
| 80665 | && pPage->nOverflow==1 | ||||
| 80666 | && pPage->aiOvfl[0]==pPage->nCell | ||||
| 80667 | && pParent->pgno!=1 | ||||
| 80668 | && pParent->nCell==iIdx | ||||
| 80669 | ){ | ||||
| 80670 | /* Call balance_quick() to create a new sibling of pPage on which | ||||
| 80671 | ** to store the overflow cell. balance_quick() inserts a new cell | ||||
| 80672 | ** into pParent, which may cause pParent overflow. If this | ||||
| 80673 | ** happens, the next iteration of the do-loop will balance pParent | ||||
| 80674 | ** use either balance_nonroot() or balance_deeper(). Until this | ||||
| 80675 | ** happens, the overflow cell is stored in the aBalanceQuickSpace[] | ||||
| 80676 | ** buffer. | ||||
| 80677 | ** | ||||
| 80678 | ** The purpose of the following assert() is to check that only a | ||||
| 80679 | ** single call to balance_quick() is made for each call to this | ||||
| 80680 | ** function. If this were not verified, a subtle bug involving reuse | ||||
| 80681 | ** of the aBalanceQuickSpace[] might sneak in. | ||||
| 80682 | */ | ||||
| 80683 | assert( balance_quick_called==0 )((void) (0)); | ||||
| 80684 | VVA_ONLY( balance_quick_called++ ); | ||||
| 80685 | rc = balance_quick(pParent, pPage, aBalanceQuickSpace); | ||||
| 80686 | }else | ||||
| 80687 | #endif | ||||
| 80688 | { | ||||
| 80689 | /* In this case, call balance_nonroot() to redistribute cells | ||||
| 80690 | ** between pPage and up to 2 of its sibling pages. This involves | ||||
| 80691 | ** modifying the contents of pParent, which may cause pParent to | ||||
| 80692 | ** become overfull or underfull. The next iteration of the do-loop | ||||
| 80693 | ** will balance the parent page to correct this. | ||||
| 80694 | ** | ||||
| 80695 | ** If the parent page becomes overfull, the overflow cell or cells | ||||
| 80696 | ** are stored in the pSpace buffer allocated immediately below. | ||||
| 80697 | ** A subsequent iteration of the do-loop will deal with this by | ||||
| 80698 | ** calling balance_nonroot() (balance_deeper() may be called first, | ||||
| 80699 | ** but it doesn't deal with overflow cells - just moves them to a | ||||
| 80700 | ** different page). Once this subsequent call to balance_nonroot() | ||||
| 80701 | ** has completed, it is safe to release the pSpace buffer used by | ||||
| 80702 | ** the previous call, as the overflow cell data will have been | ||||
| 80703 | ** copied either into the body of a database page or into the new | ||||
| 80704 | ** pSpace buffer passed to the latter call to balance_nonroot(). | ||||
| 80705 | */ | ||||
| 80706 | u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); | ||||
| 80707 | rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, | ||||
| 80708 | pCur->hints&BTREE_BULKLOAD0x00000001); | ||||
| 80709 | if( pFree ){ | ||||
| 80710 | /* If pFree is not NULL, it points to the pSpace buffer used | ||||
| 80711 | ** by a previous call to balance_nonroot(). Its contents are | ||||
| 80712 | ** now stored either on real database pages or within the | ||||
| 80713 | ** new pSpace buffer, so it may be safely freed here. */ | ||||
| 80714 | sqlite3PageFree(pFree); | ||||
| 80715 | } | ||||
| 80716 | |||||
| 80717 | /* The pSpace buffer will be freed after the next call to | ||||
| 80718 | ** balance_nonroot(), or just before this function returns, whichever | ||||
| 80719 | ** comes first. */ | ||||
| 80720 | pFree = pSpace; | ||||
| 80721 | } | ||||
| 80722 | } | ||||
| 80723 | |||||
| 80724 | pPage->nOverflow = 0; | ||||
| 80725 | |||||
| 80726 | /* The next iteration of the do-loop balances the parent page. */ | ||||
| 80727 | releasePage(pPage); | ||||
| 80728 | pCur->iPage--; | ||||
| 80729 | assert( pCur->iPage>=0 )((void) (0)); | ||||
| 80730 | pCur->pPage = pCur->apPage[pCur->iPage]; | ||||
| 80731 | } | ||||
| 80732 | }while( rc==SQLITE_OK0 ); | ||||
| 80733 | |||||
| 80734 | if( pFree ){ | ||||
| 80735 | sqlite3PageFree(pFree); | ||||
| 80736 | } | ||||
| 80737 | return rc; | ||||
| 80738 | } | ||||
| 80739 | |||||
| 80740 | /* Overwrite content from pX into pDest. Only do the write if the | ||||
| 80741 | ** content is different from what is already there. | ||||
| 80742 | */ | ||||
| 80743 | static int btreeOverwriteContent( | ||||
| 80744 | MemPage *pPage, /* MemPage on which writing will occur */ | ||||
| 80745 | u8 *pDest, /* Pointer to the place to start writing */ | ||||
| 80746 | const BtreePayload *pX, /* Source of data to write */ | ||||
| 80747 | int iOffset, /* Offset of first byte to write */ | ||||
| 80748 | int iAmt /* Number of bytes to be written */ | ||||
| 80749 | ){ | ||||
| 80750 | int nData = pX->nData - iOffset; | ||||
| 80751 | if( nData<=0 ){ | ||||
| 80752 | /* Overwriting with zeros */ | ||||
| 80753 | int i; | ||||
| 80754 | for(i=0; i<iAmt && pDest[i]==0; i++){} | ||||
| 80755 | if( i<iAmt ){ | ||||
| 80756 | int rc = sqlite3PagerWrite(pPage->pDbPage); | ||||
| 80757 | if( rc ) return rc; | ||||
| 80758 | memset(pDest + i, 0, iAmt - i); | ||||
| 80759 | } | ||||
| 80760 | }else{ | ||||
| 80761 | if( nData<iAmt ){ | ||||
| 80762 | /* Mixed read data and zeros at the end. Make a recursive call | ||||
| 80763 | ** to write the zeros then fall through to write the real data */ | ||||
| 80764 | int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData, | ||||
| 80765 | iAmt-nData); | ||||
| 80766 | if( rc ) return rc; | ||||
| 80767 | iAmt = nData; | ||||
| 80768 | } | ||||
| 80769 | if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){ | ||||
| 80770 | int rc = sqlite3PagerWrite(pPage->pDbPage); | ||||
| 80771 | if( rc ) return rc; | ||||
| 80772 | /* In a corrupt database, it is possible for the source and destination | ||||
| 80773 | ** buffers to overlap. This is harmless since the database is already | ||||
| 80774 | ** corrupt but it does cause valgrind and ASAN warnings. So use | ||||
| 80775 | ** memmove(). */ | ||||
| 80776 | memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt); | ||||
| 80777 | } | ||||
| 80778 | } | ||||
| 80779 | return SQLITE_OK0; | ||||
| 80780 | } | ||||
| 80781 | |||||
| 80782 | /* | ||||
| 80783 | ** Overwrite the cell that cursor pCur is pointing to with fresh content | ||||
| 80784 | ** contained in pX. In this variant, pCur is pointing to an overflow | ||||
| 80785 | ** cell. | ||||
| 80786 | */ | ||||
| 80787 | static SQLITE_NOINLINE__attribute__((noinline)) int btreeOverwriteOverflowCell( | ||||
| 80788 | BtCursor *pCur, /* Cursor pointing to cell to overwrite */ | ||||
| 80789 | const BtreePayload *pX /* Content to write into the cell */ | ||||
| 80790 | ){ | ||||
| 80791 | int iOffset; /* Next byte of pX->pData to write */ | ||||
| 80792 | int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */ | ||||
| 80793 | int rc; /* Return code */ | ||||
| 80794 | MemPage *pPage = pCur->pPage; /* Page being written */ | ||||
| 80795 | BtShared *pBt; /* Btree */ | ||||
| 80796 | Pgno ovflPgno; /* Next overflow page to write */ | ||||
| 80797 | u32 ovflPageSize; /* Size to write on overflow page */ | ||||
| 80798 | |||||
| 80799 | assert( pCur->info.nLocal<nTotal )((void) (0)); /* pCur is an overflow cell */ | ||||
| 80800 | |||||
| 80801 | /* Overwrite the local portion first */ | ||||
| 80802 | rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX, | ||||
| 80803 | 0, pCur->info.nLocal); | ||||
| 80804 | if( rc ) return rc; | ||||
| 80805 | |||||
| 80806 | /* Now overwrite the overflow pages */ | ||||
| 80807 | iOffset = pCur->info.nLocal; | ||||
| 80808 | assert( nTotal>=0 )((void) (0)); | ||||
| 80809 | assert( iOffset>=0 )((void) (0)); | ||||
| 80810 | ovflPgno = get4bytesqlite3Get4byte(pCur->info.pPayload + iOffset); | ||||
| 80811 | pBt = pPage->pBt; | ||||
| 80812 | ovflPageSize = pBt->usableSize - 4; | ||||
| 80813 | do{ | ||||
| 80814 | rc = btreeGetPage(pBt, ovflPgno, &pPage, 0); | ||||
| 80815 | if( rc ) return rc; | ||||
| 80816 | if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){ | ||||
| 80817 | rc = SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(80817); | ||||
| 80818 | }else{ | ||||
| 80819 | if( iOffset+ovflPageSize<(u32)nTotal ){ | ||||
| 80820 | ovflPgno = get4bytesqlite3Get4byte(pPage->aData); | ||||
| 80821 | }else{ | ||||
| 80822 | ovflPageSize = nTotal - iOffset; | ||||
| 80823 | } | ||||
| 80824 | rc = btreeOverwriteContent(pPage, pPage->aData+4, pX, | ||||
| 80825 | iOffset, ovflPageSize); | ||||
| 80826 | } | ||||
| 80827 | sqlite3PagerUnref(pPage->pDbPage); | ||||
| 80828 | if( rc ) return rc; | ||||
| 80829 | iOffset += ovflPageSize; | ||||
| 80830 | }while( iOffset<nTotal ); | ||||
| 80831 | return SQLITE_OK0; | ||||
| 80832 | } | ||||
| 80833 | |||||
| 80834 | /* | ||||
| 80835 | ** Overwrite the cell that cursor pCur is pointing to with fresh content | ||||
| 80836 | ** contained in pX. | ||||
| 80837 | */ | ||||
| 80838 | static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){ | ||||
| 80839 | int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */ | ||||
| 80840 | MemPage *pPage = pCur->pPage; /* Page being written */ | ||||
| 80841 | |||||
| 80842 | if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd | ||||
| 80843 | || pCur->info.pPayload < pPage->aData + pPage->cellOffset | ||||
| 80844 | ){ | ||||
| 80845 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(80845); | ||||
| 80846 | } | ||||
| 80847 | if( pCur->info.nLocal==nTotal ){ | ||||
| 80848 | /* The entire cell is local */ | ||||
| 80849 | return btreeOverwriteContent(pPage, pCur->info.pPayload, pX, | ||||
| 80850 | 0, pCur->info.nLocal); | ||||
| 80851 | }else{ | ||||
| 80852 | /* The cell contains overflow content */ | ||||
| 80853 | return btreeOverwriteOverflowCell(pCur, pX); | ||||
| 80854 | } | ||||
| 80855 | } | ||||
| 80856 | |||||
| 80857 | |||||
| 80858 | /* | ||||
| 80859 | ** Insert a new record into the BTree. The content of the new record | ||||
| 80860 | ** is described by the pX object. The pCur cursor is used only to | ||||
| 80861 | ** define what table the record should be inserted into, and is left | ||||
| 80862 | ** pointing at a random location. | ||||
| 80863 | ** | ||||
| 80864 | ** For a table btree (used for rowid tables), only the pX.nKey value of | ||||
| 80865 | ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the | ||||
| 80866 | ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields | ||||
| 80867 | ** hold the content of the row. | ||||
| 80868 | ** | ||||
| 80869 | ** For an index btree (used for indexes and WITHOUT ROWID tables), the | ||||
| 80870 | ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The | ||||
| 80871 | ** pX.pData,nData,nZero fields must be zero. | ||||
| 80872 | ** | ||||
| 80873 | ** If the seekResult parameter is non-zero, then a successful call to | ||||
| 80874 | ** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already | ||||
| 80875 | ** been performed. In other words, if seekResult!=0 then the cursor | ||||
| 80876 | ** is currently pointing to a cell that will be adjacent to the cell | ||||
| 80877 | ** to be inserted. If seekResult<0 then pCur points to a cell that is | ||||
| 80878 | ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell | ||||
| 80879 | ** that is larger than (pKey,nKey). | ||||
| 80880 | ** | ||||
| 80881 | ** If seekResult==0, that means pCur is pointing at some unknown location. | ||||
| 80882 | ** In that case, this routine must seek the cursor to the correct insertion | ||||
| 80883 | ** point for (pKey,nKey) before doing the insertion. For index btrees, | ||||
| 80884 | ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked | ||||
| 80885 | ** key values and pX->aMem can be used instead of pX->pKey to avoid having | ||||
| 80886 | ** to decode the key. | ||||
| 80887 | */ | ||||
| 80888 | SQLITE_PRIVATEstatic int sqlite3BtreeInsert( | ||||
| 80889 | BtCursor *pCur, /* Insert data into the table of this cursor */ | ||||
| 80890 | const BtreePayload *pX, /* Content of the row to be inserted */ | ||||
| 80891 | int flags, /* True if this is likely an append */ | ||||
| 80892 | int seekResult /* Result of prior IndexMoveto() call */ | ||||
| 80893 | ){ | ||||
| 80894 | int rc; | ||||
| 80895 | int loc = seekResult; /* -1: before desired location +1: after */ | ||||
| 80896 | int szNew = 0; | ||||
| 80897 | int idx; | ||||
| 80898 | MemPage *pPage; | ||||
| 80899 | Btree *p = pCur->pBtree; | ||||
| 80900 | unsigned char *oldCell; | ||||
| 80901 | unsigned char *newCell = 0; | ||||
| 80902 | |||||
| 80903 | assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags )((void) (0)); | ||||
| 80904 | assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 )((void) (0)); | ||||
| 80905 | |||||
| 80906 | /* Save the positions of any other cursors open on this table. | ||||
| 80907 | ** | ||||
| 80908 | ** In some cases, the call to btreeMoveto() below is a no-op. For | ||||
| 80909 | ** example, when inserting data into a table with auto-generated integer | ||||
| 80910 | ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the | ||||
| 80911 | ** integer key to use. It then calls this function to actually insert the | ||||
| 80912 | ** data into the intkey B-Tree. In this case btreeMoveto() recognizes | ||||
| 80913 | ** that the cursor is already where it needs to be and returns without | ||||
| 80914 | ** doing any work. To avoid thwarting these optimizations, it is important | ||||
| 80915 | ** not to clear the cursor here. | ||||
| 80916 | */ | ||||
| 80917 | if( pCur->curFlags & BTCF_Multiple0x20 ){ | ||||
| 80918 | rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur); | ||||
| 80919 | if( rc ) return rc; | ||||
| 80920 | if( loc && pCur->iPage<0 ){ | ||||
| 80921 | /* This can only happen if the schema is corrupt such that there is more | ||||
| 80922 | ** than one table or index with the same root page as used by the cursor. | ||||
| 80923 | ** Which can only happen if the SQLITE_NoSchemaError flag was set when | ||||
| 80924 | ** the schema was loaded. This cannot be asserted though, as a user might | ||||
| 80925 | ** set the flag, load the schema, and then unset the flag. */ | ||||
| 80926 | return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot)sqlite3CorruptError(80926); | ||||
| 80927 | } | ||||
| 80928 | } | ||||
| 80929 | |||||
| 80930 | /* Ensure that the cursor is not in the CURSOR_FAULT state and that it | ||||
| 80931 | ** points to a valid cell. | ||||
| 80932 | */ | ||||
| 80933 | if( pCur->eState>=CURSOR_REQUIRESEEK3 ){ | ||||
| 80934 | testcase( pCur->eState==CURSOR_REQUIRESEEK ); | ||||
| 80935 | testcase( pCur->eState==CURSOR_FAULT ); | ||||
| 80936 | rc = moveToRoot(pCur); | ||||
| 80937 | if( rc && rc!=SQLITE_EMPTY16 ) return rc; | ||||
| 80938 | } | ||||
| 80939 | |||||
| 80940 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 80941 | assert( (pCur->curFlags & BTCF_WriteFlag)!=0((void) (0)) | ||||
| 80942 | && p->pBt->inTransaction==TRANS_WRITE((void) (0)) | ||||
| 80943 | && (p->pBt->btsFlags & BTS_READ_ONLY)==0 )((void) (0)); | ||||
| 80944 | assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) )((void) (0)); | ||||
| 80945 | |||||
| 80946 | /* Assert that the caller has been consistent. If this cursor was opened | ||||
| 80947 | ** expecting an index b-tree, then the caller should be inserting blob | ||||
| 80948 | ** keys with no associated data. If the cursor was opened expecting an | ||||
| 80949 | ** intkey table, the caller should be inserting integer keys with a | ||||
| 80950 | ** blob of associated data. */ | ||||
| 80951 | assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) )((void) (0)); | ||||
| 80952 | |||||
| 80953 | if( pCur->pKeyInfo==0 ){ | ||||
| 80954 | assert( pX->pKey==0 )((void) (0)); | ||||
| 80955 | /* If this is an insert into a table b-tree, invalidate any incrblob | ||||
| 80956 | ** cursors open on the row being replaced */ | ||||
| 80957 | if( p->hasIncrblobCur ){ | ||||
| 80958 | invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0); | ||||
| 80959 | } | ||||
| 80960 | |||||
| 80961 | /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing | ||||
| 80962 | ** to a row with the same key as the new entry being inserted. | ||||
| 80963 | */ | ||||
| 80964 | #ifdef SQLITE_DEBUG | ||||
| 80965 | if( flags & BTREE_SAVEPOSITION0x02 ){ | ||||
| 80966 | assert( pCur->curFlags & BTCF_ValidNKey )((void) (0)); | ||||
| 80967 | assert( pX->nKey==pCur->info.nKey )((void) (0)); | ||||
| 80968 | assert( loc==0 )((void) (0)); | ||||
| 80969 | } | ||||
| 80970 | #endif | ||||
| 80971 | |||||
| 80972 | /* On the other hand, BTREE_SAVEPOSITION==0 does not imply | ||||
| 80973 | ** that the cursor is not pointing to a row to be overwritten. | ||||
| 80974 | ** So do a complete check. | ||||
| 80975 | */ | ||||
| 80976 | if( (pCur->curFlags&BTCF_ValidNKey0x02)!=0 && pX->nKey==pCur->info.nKey ){ | ||||
| 80977 | /* The cursor is pointing to the entry that is to be | ||||
| 80978 | ** overwritten */ | ||||
| 80979 | assert( pX->nData>=0 && pX->nZero>=0 )((void) (0)); | ||||
| 80980 | if( pCur->info.nSize!=0 | ||||
| 80981 | && pCur->info.nPayload==(u32)pX->nData+pX->nZero | ||||
| 80982 | ){ | ||||
| 80983 | /* New entry is the same size as the old. Do an overwrite */ | ||||
| 80984 | return btreeOverwriteCell(pCur, pX); | ||||
| 80985 | } | ||||
| 80986 | assert( loc==0 )((void) (0)); | ||||
| 80987 | }else if( loc==0 ){ | ||||
| 80988 | /* The cursor is *not* pointing to the cell to be overwritten, nor | ||||
| 80989 | ** to an adjacent cell. Move the cursor so that it is pointing either | ||||
| 80990 | ** to the cell to be overwritten or an adjacent cell. | ||||
| 80991 | */ | ||||
| 80992 | rc = sqlite3BtreeTableMoveto(pCur, pX->nKey, | ||||
| 80993 | (flags & BTREE_APPEND0x08)!=0, &loc); | ||||
| 80994 | if( rc ) return rc; | ||||
| 80995 | } | ||||
| 80996 | }else{ | ||||
| 80997 | /* This is an index or a WITHOUT ROWID table */ | ||||
| 80998 | |||||
| 80999 | /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing | ||||
| 81000 | ** to a row with the same key as the new entry being inserted. | ||||
| 81001 | */ | ||||
| 81002 | assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 )((void) (0)); | ||||
| 81003 | |||||
| 81004 | /* If the cursor is not already pointing either to the cell to be | ||||
| 81005 | ** overwritten, or if a new cell is being inserted, if the cursor is | ||||
| 81006 | ** not pointing to an immediately adjacent cell, then move the cursor | ||||
| 81007 | ** so that it does. | ||||
| 81008 | */ | ||||
| 81009 | if( loc==0 && (flags & BTREE_SAVEPOSITION0x02)==0 ){ | ||||
| 81010 | if( pX->nMem ){ | ||||
| 81011 | UnpackedRecord r; | ||||
| 81012 | r.pKeyInfo = pCur->pKeyInfo; | ||||
| 81013 | r.aMem = pX->aMem; | ||||
| 81014 | r.nField = pX->nMem; | ||||
| 81015 | r.default_rc = 0; | ||||
| 81016 | r.eqSeen = 0; | ||||
| 81017 | rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc); | ||||
| 81018 | }else{ | ||||
| 81019 | rc = btreeMoveto(pCur, pX->pKey, pX->nKey, | ||||
| 81020 | (flags & BTREE_APPEND0x08)!=0, &loc); | ||||
| 81021 | } | ||||
| 81022 | if( rc ) return rc; | ||||
| 81023 | } | ||||
| 81024 | |||||
| 81025 | /* If the cursor is currently pointing to an entry to be overwritten | ||||
| 81026 | ** and the new content is the same as as the old, then use the | ||||
| 81027 | ** overwrite optimization. | ||||
| 81028 | */ | ||||
| 81029 | if( loc==0 ){ | ||||
| 81030 | getCellInfo(pCur); | ||||
| 81031 | if( pCur->info.nKey==pX->nKey ){ | ||||
| 81032 | BtreePayload x2; | ||||
| 81033 | x2.pData = pX->pKey; | ||||
| 81034 | x2.nData = (int)pX->nKey; assert( pX->nKey<=0x7fffffff )((void) (0)); | ||||
| 81035 | x2.nZero = 0; | ||||
| 81036 | return btreeOverwriteCell(pCur, &x2); | ||||
| 81037 | } | ||||
| 81038 | } | ||||
| 81039 | } | ||||
| 81040 | assert( pCur->eState==CURSOR_VALID((void) (0)) | ||||
| 81041 | || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB )((void) (0)); | ||||
| 81042 | |||||
| 81043 | pPage = pCur->pPage; | ||||
| 81044 | assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) )((void) (0)); | ||||
| 81045 | assert( pPage->leaf || !pPage->intKey )((void) (0)); | ||||
| 81046 | if( pPage->nFree<0 ){ | ||||
| 81047 | if( NEVER(pCur->eState>CURSOR_INVALID)(pCur->eState>1) ){ | ||||
| 81048 | /* ^^^^^--- due to the moveToRoot() call above */ | ||||
| 81049 | rc = SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81049); | ||||
| 81050 | }else{ | ||||
| 81051 | rc = btreeComputeFreeSpace(pPage); | ||||
| 81052 | } | ||||
| 81053 | if( rc ) return rc; | ||||
| 81054 | } | ||||
| 81055 | |||||
| 81056 | TRACE(("INSERT: table=%u nkey=%lld ndata=%u page=%u %s\n", | ||||
| 81057 | pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno, | ||||
| 81058 | loc==0 ? "overwrite" : "new entry")); | ||||
| 81059 | assert( pPage->isInit || CORRUPT_DB )((void) (0)); | ||||
| 81060 | newCell = p->pBt->pTmpSpace; | ||||
| 81061 | assert( newCell!=0 )((void) (0)); | ||||
| 81062 | assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT )((void) (0)); | ||||
| 81063 | if( flags & BTREE_PREFORMAT0x80 ){ | ||||
| 81064 | rc = SQLITE_OK0; | ||||
| 81065 | szNew = p->pBt->nPreformatSize; | ||||
| 81066 | if( szNew<4 ){ | ||||
| 81067 | szNew = 4; | ||||
| 81068 | newCell[3] = 0; | ||||
| 81069 | } | ||||
| 81070 | if( ISAUTOVACUUM(p->pBt)(p->pBt->autoVacuum) && szNew>pPage->maxLocal ){ | ||||
| 81071 | CellInfo info; | ||||
| 81072 | pPage->xParseCell(pPage, newCell, &info); | ||||
| 81073 | if( info.nPayload!=info.nLocal ){ | ||||
| 81074 | Pgno ovfl = get4bytesqlite3Get4byte(&newCell[szNew-4]); | ||||
| 81075 | ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW13, pPage->pgno, &rc); | ||||
| 81076 | if( NEVER(rc)(rc) ) goto end_insert; | ||||
| 81077 | } | ||||
| 81078 | } | ||||
| 81079 | }else{ | ||||
| 81080 | rc = fillInCell(pPage, newCell, pX, &szNew); | ||||
| 81081 | if( rc ) goto end_insert; | ||||
| 81082 | } | ||||
| 81083 | assert( szNew==pPage->xCellSize(pPage, newCell) )((void) (0)); | ||||
| 81084 | assert( szNew <= MX_CELL_SIZE(p->pBt) )((void) (0)); | ||||
| 81085 | idx = pCur->ix; | ||||
| 81086 | pCur->info.nSize = 0; | ||||
| 81087 | if( loc==0 ){ | ||||
| 81088 | CellInfo info; | ||||
| 81089 | assert( idx>=0 )((void) (0)); | ||||
| 81090 | if( idx>=pPage->nCell ){ | ||||
| 81091 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81091); | ||||
| 81092 | } | ||||
| 81093 | rc = sqlite3PagerWrite(pPage->pDbPage); | ||||
| 81094 | if( rc ){ | ||||
| 81095 | goto end_insert; | ||||
| 81096 | } | ||||
| 81097 | oldCell = findCell(pPage, idx)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(idx)])[0]<<8 | (&(pPage)->aCellIdx [2*(idx)])[1]))); | ||||
| 81098 | if( !pPage->leaf ){ | ||||
| 81099 | memcpy(newCell, oldCell, 4); | ||||
| 81100 | } | ||||
| 81101 | BTREE_CLEAR_CELL(rc, pPage, oldCell, info)pPage->xParseCell(pPage, oldCell, &info); if( info.nLocal !=info.nPayload ){ rc = clearCellOverflow(pPage, oldCell, & info); }else{ rc = 0; }; | ||||
| 81102 | testcase( pCur->curFlags & BTCF_ValidOvfl ); | ||||
| 81103 | invalidateOverflowCache(pCur)(pCur->curFlags &= ~0x04); | ||||
| 81104 | if( info.nSize==szNew && info.nLocal==info.nPayload | ||||
| 81105 | && (!ISAUTOVACUUM(p->pBt)(p->pBt->autoVacuum) || szNew<pPage->minLocal) | ||||
| 81106 | ){ | ||||
| 81107 | /* Overwrite the old cell with the new if they are the same size. | ||||
| 81108 | ** We could also try to do this if the old cell is smaller, then add | ||||
| 81109 | ** the leftover space to the free list. But experiments show that | ||||
| 81110 | ** doing that is no faster then skipping this optimization and just | ||||
| 81111 | ** calling dropCell() and insertCell(). | ||||
| 81112 | ** | ||||
| 81113 | ** This optimization cannot be used on an autovacuum database if the | ||||
| 81114 | ** new entry uses overflow pages, as the insertCell() call below is | ||||
| 81115 | ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */ | ||||
| 81116 | assert( rc==SQLITE_OK )((void) (0)); /* clearCell never fails when nLocal==nPayload */ | ||||
| 81117 | if( oldCell < pPage->aData+pPage->hdrOffset+10 ){ | ||||
| 81118 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81118); | ||||
| 81119 | } | ||||
| 81120 | if( oldCell+szNew > pPage->aDataEnd ){ | ||||
| 81121 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81121); | ||||
| 81122 | } | ||||
| 81123 | memcpy(oldCell, newCell, szNew); | ||||
| 81124 | return SQLITE_OK0; | ||||
| 81125 | } | ||||
| 81126 | dropCell(pPage, idx, info.nSize, &rc); | ||||
| 81127 | if( rc ) goto end_insert; | ||||
| 81128 | }else if( loc<0 && pPage->nCell>0 ){ | ||||
| 81129 | assert( pPage->leaf )((void) (0)); | ||||
| 81130 | idx = ++pCur->ix; | ||||
| 81131 | pCur->curFlags &= ~(BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04); | ||||
| 81132 | }else{ | ||||
| 81133 | assert( pPage->leaf )((void) (0)); | ||||
| 81134 | } | ||||
| 81135 | rc = insertCellFast(pPage, idx, newCell, szNew); | ||||
| 81136 | assert( pPage->nOverflow==0 || rc==SQLITE_OK )((void) (0)); | ||||
| 81137 | assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 )((void) (0)); | ||||
| 81138 | |||||
| 81139 | /* If no error has occurred and pPage has an overflow cell, call balance() | ||||
| 81140 | ** to redistribute the cells within the tree. Since balance() may move | ||||
| 81141 | ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey | ||||
| 81142 | ** variables. | ||||
| 81143 | ** | ||||
| 81144 | ** Previous versions of SQLite called moveToRoot() to move the cursor | ||||
| 81145 | ** back to the root page as balance() used to invalidate the contents | ||||
| 81146 | ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, | ||||
| 81147 | ** set the cursor state to "invalid". This makes common insert operations | ||||
| 81148 | ** slightly faster. | ||||
| 81149 | ** | ||||
| 81150 | ** There is a subtle but important optimization here too. When inserting | ||||
| 81151 | ** multiple records into an intkey b-tree using a single cursor (as can | ||||
| 81152 | ** happen while processing an "INSERT INTO ... SELECT" statement), it | ||||
| 81153 | ** is advantageous to leave the cursor pointing to the last entry in | ||||
| 81154 | ** the b-tree if possible. If the cursor is left pointing to the last | ||||
| 81155 | ** entry in the table, and the next row inserted has an integer key | ||||
| 81156 | ** larger than the largest existing key, it is possible to insert the | ||||
| 81157 | ** row without seeking the cursor. This can be a big performance boost. | ||||
| 81158 | */ | ||||
| 81159 | if( pPage->nOverflow ){ | ||||
| 81160 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 81161 | pCur->curFlags &= ~(BTCF_ValidNKey0x02|BTCF_ValidOvfl0x04); | ||||
| 81162 | rc = balance(pCur); | ||||
| 81163 | |||||
| 81164 | /* Must make sure nOverflow is reset to zero even if the balance() | ||||
| 81165 | ** fails. Internal data structure corruption will result otherwise. | ||||
| 81166 | ** Also, set the cursor state to invalid. This stops saveCursorPosition() | ||||
| 81167 | ** from trying to save the current position of the cursor. */ | ||||
| 81168 | pCur->pPage->nOverflow = 0; | ||||
| 81169 | pCur->eState = CURSOR_INVALID1; | ||||
| 81170 | if( (flags & BTREE_SAVEPOSITION0x02) && rc==SQLITE_OK0 ){ | ||||
| 81171 | btreeReleaseAllCursorPages(pCur); | ||||
| 81172 | if( pCur->pKeyInfo ){ | ||||
| 81173 | assert( pCur->pKey==0 )((void) (0)); | ||||
| 81174 | pCur->pKey = sqlite3Malloc( pX->nKey ); | ||||
| 81175 | if( pCur->pKey==0 ){ | ||||
| 81176 | rc = SQLITE_NOMEM7; | ||||
| 81177 | }else{ | ||||
| 81178 | memcpy(pCur->pKey, pX->pKey, pX->nKey); | ||||
| 81179 | } | ||||
| 81180 | } | ||||
| 81181 | pCur->eState = CURSOR_REQUIRESEEK3; | ||||
| 81182 | pCur->nKey = pX->nKey; | ||||
| 81183 | } | ||||
| 81184 | } | ||||
| 81185 | assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 )((void) (0)); | ||||
| 81186 | |||||
| 81187 | end_insert: | ||||
| 81188 | return rc; | ||||
| 81189 | } | ||||
| 81190 | |||||
| 81191 | /* | ||||
| 81192 | ** This function is used as part of copying the current row from cursor | ||||
| 81193 | ** pSrc into cursor pDest. If the cursors are open on intkey tables, then | ||||
| 81194 | ** parameter iKey is used as the rowid value when the record is copied | ||||
| 81195 | ** into pDest. Otherwise, the record is copied verbatim. | ||||
| 81196 | ** | ||||
| 81197 | ** This function does not actually write the new value to cursor pDest. | ||||
| 81198 | ** Instead, it creates and populates any required overflow pages and | ||||
| 81199 | ** writes the data for the new cell into the BtShared.pTmpSpace buffer | ||||
| 81200 | ** for the destination database. The size of the cell, in bytes, is left | ||||
| 81201 | ** in BtShared.nPreformatSize. The caller completes the insertion by | ||||
| 81202 | ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified. | ||||
| 81203 | ** | ||||
| 81204 | ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. | ||||
| 81205 | */ | ||||
| 81206 | SQLITE_PRIVATEstatic int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){ | ||||
| 81207 | BtShared *pBt = pDest->pBt; | ||||
| 81208 | u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */ | ||||
| 81209 | const u8 *aIn; /* Pointer to next input buffer */ | ||||
| 81210 | u32 nIn; /* Size of input buffer aIn[] */ | ||||
| 81211 | u32 nRem; /* Bytes of data still to copy */ | ||||
| 81212 | |||||
| 81213 | getCellInfo(pSrc); | ||||
| 81214 | if( pSrc->info.nPayload<0x80 ){ | ||||
| 81215 | *(aOut++) = (u8)pSrc->info.nPayload; | ||||
| 81216 | }else{ | ||||
| 81217 | aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload); | ||||
| 81218 | } | ||||
| 81219 | if( pDest->pKeyInfo==0 ) aOut += putVarintsqlite3PutVarint(aOut, iKey); | ||||
| 81220 | nIn = pSrc->info.nLocal; | ||||
| 81221 | aIn = pSrc->info.pPayload; | ||||
| 81222 | if( aIn+nIn>pSrc->pPage->aDataEnd ){ | ||||
| 81223 | return SQLITE_CORRUPT_PAGE(pSrc->pPage)sqlite3CorruptError(81223); | ||||
| 81224 | } | ||||
| 81225 | nRem = pSrc->info.nPayload; | ||||
| 81226 | if( nIn==nRem && nIn<pDest->pPage->maxLocal ){ | ||||
| 81227 | memcpy(aOut, aIn, nIn); | ||||
| 81228 | pBt->nPreformatSize = nIn + (int)(aOut - pBt->pTmpSpace); | ||||
| 81229 | return SQLITE_OK0; | ||||
| 81230 | }else{ | ||||
| 81231 | int rc = SQLITE_OK0; | ||||
| 81232 | Pager *pSrcPager = pSrc->pBt->pPager; | ||||
| 81233 | u8 *pPgnoOut = 0; | ||||
| 81234 | Pgno ovflIn = 0; | ||||
| 81235 | DbPage *pPageIn = 0; | ||||
| 81236 | MemPage *pPageOut = 0; | ||||
| 81237 | u32 nOut; /* Size of output buffer aOut[] */ | ||||
| 81238 | |||||
| 81239 | nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload); | ||||
| 81240 | pBt->nPreformatSize = (int)nOut + (int)(aOut - pBt->pTmpSpace); | ||||
| 81241 | if( nOut<pSrc->info.nPayload ){ | ||||
| 81242 | pPgnoOut = &aOut[nOut]; | ||||
| 81243 | pBt->nPreformatSize += 4; | ||||
| 81244 | } | ||||
| 81245 | |||||
| 81246 | if( nRem>nIn ){ | ||||
| 81247 | if( aIn+nIn+4>pSrc->pPage->aDataEnd ){ | ||||
| 81248 | return SQLITE_CORRUPT_PAGE(pSrc->pPage)sqlite3CorruptError(81248); | ||||
| 81249 | } | ||||
| 81250 | ovflIn = get4bytesqlite3Get4byte(&pSrc->info.pPayload[nIn]); | ||||
| 81251 | } | ||||
| 81252 | |||||
| 81253 | do { | ||||
| 81254 | nRem -= nOut; | ||||
| 81255 | do{ | ||||
| 81256 | assert( nOut>0 )((void) (0)); | ||||
| 81257 | if( nIn>0 ){ | ||||
| 81258 | int nCopy = MIN(nOut, nIn)((nOut)<(nIn)?(nOut):(nIn)); | ||||
| 81259 | memcpy(aOut, aIn, nCopy); | ||||
| 81260 | nOut -= nCopy; | ||||
| 81261 | nIn -= nCopy; | ||||
| 81262 | aOut += nCopy; | ||||
| 81263 | aIn += nCopy; | ||||
| 81264 | } | ||||
| 81265 | if( nOut>0 ){ | ||||
| 81266 | sqlite3PagerUnref(pPageIn); | ||||
| 81267 | pPageIn = 0; | ||||
| 81268 | rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY0x02); | ||||
| 81269 | if( rc==SQLITE_OK0 ){ | ||||
| 81270 | aIn = (const u8*)sqlite3PagerGetData(pPageIn); | ||||
| 81271 | ovflIn = get4bytesqlite3Get4byte(aIn); | ||||
| 81272 | aIn += 4; | ||||
| 81273 | nIn = pSrc->pBt->usableSize - 4; | ||||
| 81274 | } | ||||
| 81275 | } | ||||
| 81276 | }while( rc==SQLITE_OK0 && nOut>0 ); | ||||
| 81277 | |||||
| 81278 | if( rc==SQLITE_OK0 && nRem>0 && ALWAYS(pPgnoOut)(pPgnoOut) ){ | ||||
| 81279 | Pgno pgnoNew; | ||||
| 81280 | MemPage *pNew = 0; | ||||
| 81281 | rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); | ||||
| 81282 | put4bytesqlite3Put4byte(pPgnoOut, pgnoNew); | ||||
| 81283 | if( ISAUTOVACUUM(pBt)(pBt->autoVacuum) && pPageOut ){ | ||||
| 81284 | ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW24, pPageOut->pgno, &rc); | ||||
| 81285 | } | ||||
| 81286 | releasePage(pPageOut); | ||||
| 81287 | pPageOut = pNew; | ||||
| 81288 | if( pPageOut ){ | ||||
| 81289 | pPgnoOut = pPageOut->aData; | ||||
| 81290 | put4bytesqlite3Put4byte(pPgnoOut, 0); | ||||
| 81291 | aOut = &pPgnoOut[4]; | ||||
| 81292 | nOut = MIN(pBt->usableSize - 4, nRem)((pBt->usableSize - 4)<(nRem)?(pBt->usableSize - 4): (nRem)); | ||||
| 81293 | } | ||||
| 81294 | } | ||||
| 81295 | }while( nRem>0 && rc==SQLITE_OK0 ); | ||||
| 81296 | |||||
| 81297 | releasePage(pPageOut); | ||||
| 81298 | sqlite3PagerUnref(pPageIn); | ||||
| 81299 | return rc; | ||||
| 81300 | } | ||||
| 81301 | } | ||||
| 81302 | |||||
| 81303 | /* | ||||
| 81304 | ** Delete the entry that the cursor is pointing to. | ||||
| 81305 | ** | ||||
| 81306 | ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then | ||||
| 81307 | ** the cursor is left pointing at an arbitrary location after the delete. | ||||
| 81308 | ** But if that bit is set, then the cursor is left in a state such that | ||||
| 81309 | ** the next call to BtreeNext() or BtreePrev() moves it to the same row | ||||
| 81310 | ** as it would have been on if the call to BtreeDelete() had been omitted. | ||||
| 81311 | ** | ||||
| 81312 | ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes | ||||
| 81313 | ** associated with a single table entry and its indexes. Only one of those | ||||
| 81314 | ** deletes is considered the "primary" delete. The primary delete occurs | ||||
| 81315 | ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete | ||||
| 81316 | ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag. | ||||
| 81317 | ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation, | ||||
| 81318 | ** but which might be used by alternative storage engines. | ||||
| 81319 | */ | ||||
| 81320 | SQLITE_PRIVATEstatic int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ | ||||
| 81321 | Btree *p = pCur->pBtree; | ||||
| 81322 | BtShared *pBt = p->pBt; | ||||
| 81323 | int rc; /* Return code */ | ||||
| 81324 | MemPage *pPage; /* Page to delete cell from */ | ||||
| 81325 | unsigned char *pCell; /* Pointer to cell to delete */ | ||||
| 81326 | int iCellIdx; /* Index of cell to delete */ | ||||
| 81327 | int iCellDepth; /* Depth of node containing pCell */ | ||||
| 81328 | CellInfo info; /* Size of the cell being deleted */ | ||||
| 81329 | u8 bPreserve; /* Keep cursor valid. 2 for CURSOR_SKIPNEXT */ | ||||
| 81330 | |||||
| 81331 | assert( cursorOwnsBtShared(pCur) )((void) (0)); | ||||
| 81332 | assert( pBt->inTransaction==TRANS_WRITE )((void) (0)); | ||||
| 81333 | assert( (pBt->btsFlags & BTS_READ_ONLY)==0 )((void) (0)); | ||||
| 81334 | assert( pCur->curFlags & BTCF_WriteFlag )((void) (0)); | ||||
| 81335 | assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) )((void) (0)); | ||||
| 81336 | assert( !hasReadConflicts(p, pCur->pgnoRoot) )((void) (0)); | ||||
| 81337 | assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 )((void) (0)); | ||||
| 81338 | if( pCur->eState!=CURSOR_VALID0 ){ | ||||
| 81339 | if( pCur->eState>=CURSOR_REQUIRESEEK3 ){ | ||||
| 81340 | rc = btreeRestoreCursorPosition(pCur); | ||||
| 81341 | assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 81342 | if( rc || pCur->eState!=CURSOR_VALID0 ) return rc; | ||||
| 81343 | }else{ | ||||
| 81344 | return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot)sqlite3CorruptError(81344); | ||||
| 81345 | } | ||||
| 81346 | } | ||||
| 81347 | assert( pCur->eState==CURSOR_VALID )((void) (0)); | ||||
| 81348 | |||||
| 81349 | iCellDepth = pCur->iPage; | ||||
| 81350 | iCellIdx = pCur->ix; | ||||
| 81351 | pPage = pCur->pPage; | ||||
| 81352 | if( pPage->nCell<=iCellIdx ){ | ||||
| 81353 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81353); | ||||
| 81354 | } | ||||
| 81355 | pCell = findCell(pPage, iCellIdx)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(iCellIdx)])[0]<<8 | (&(pPage)-> aCellIdx[2*(iCellIdx)])[1]))); | ||||
| 81356 | if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){ | ||||
| 81357 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81357); | ||||
| 81358 | } | ||||
| 81359 | if( pCell<&pPage->aCellIdx[pPage->nCell] ){ | ||||
| 81360 | return SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81360); | ||||
| 81361 | } | ||||
| 81362 | |||||
| 81363 | /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must | ||||
| 81364 | ** be preserved following this delete operation. If the current delete | ||||
| 81365 | ** will cause a b-tree rebalance, then this is done by saving the cursor | ||||
| 81366 | ** key and leaving the cursor in CURSOR_REQUIRESEEK state before | ||||
| 81367 | ** returning. | ||||
| 81368 | ** | ||||
| 81369 | ** If the current delete will not cause a rebalance, then the cursor | ||||
| 81370 | ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately | ||||
| 81371 | ** before or after the deleted entry. | ||||
| 81372 | ** | ||||
| 81373 | ** The bPreserve value records which path is required: | ||||
| 81374 | ** | ||||
| 81375 | ** bPreserve==0 Not necessary to save the cursor position | ||||
| 81376 | ** bPreserve==1 Use CURSOR_REQUIRESEEK to save the cursor position | ||||
| 81377 | ** bPreserve==2 Cursor won't move. Set CURSOR_SKIPNEXT. | ||||
| 81378 | */ | ||||
| 81379 | bPreserve = (flags & BTREE_SAVEPOSITION0x02)!=0; | ||||
| 81380 | if( bPreserve ){ | ||||
| 81381 | if( !pPage->leaf | ||||
| 81382 | || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) > | ||||
| 81383 | (int)(pBt->usableSize*2/3) | ||||
| 81384 | || pPage->nCell==1 /* See dbfuzz001.test for a test case */ | ||||
| 81385 | ){ | ||||
| 81386 | /* A b-tree rebalance will be required after deleting this entry. | ||||
| 81387 | ** Save the cursor key. */ | ||||
| 81388 | rc = saveCursorKey(pCur); | ||||
| 81389 | if( rc ) return rc; | ||||
| 81390 | }else{ | ||||
| 81391 | bPreserve = 2; | ||||
| 81392 | } | ||||
| 81393 | } | ||||
| 81394 | |||||
| 81395 | /* If the page containing the entry to delete is not a leaf page, move | ||||
| 81396 | ** the cursor to the largest entry in the tree that is smaller than | ||||
| 81397 | ** the entry being deleted. This cell will replace the cell being deleted | ||||
| 81398 | ** from the internal node. The 'previous' entry is used for this instead | ||||
| 81399 | ** of the 'next' entry, as the previous entry is always a part of the | ||||
| 81400 | ** sub-tree headed by the child page of the cell being deleted. This makes | ||||
| 81401 | ** balancing the tree following the delete operation easier. */ | ||||
| 81402 | if( !pPage->leaf ){ | ||||
| 81403 | rc = sqlite3BtreePrevious(pCur, 0); | ||||
| 81404 | assert( rc!=SQLITE_DONE )((void) (0)); | ||||
| 81405 | if( rc ) return rc; | ||||
| 81406 | } | ||||
| 81407 | |||||
| 81408 | /* Save the positions of any other cursors open on this table before | ||||
| 81409 | ** making any modifications. */ | ||||
| 81410 | if( pCur->curFlags & BTCF_Multiple0x20 ){ | ||||
| 81411 | rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); | ||||
| 81412 | if( rc ) return rc; | ||||
| 81413 | } | ||||
| 81414 | |||||
| 81415 | /* If this is a delete operation to remove a row from a table b-tree, | ||||
| 81416 | ** invalidate any incrblob cursors open on the row being deleted. */ | ||||
| 81417 | if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){ | ||||
| 81418 | invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0); | ||||
| 81419 | } | ||||
| 81420 | |||||
| 81421 | /* Make the page containing the entry to be deleted writable. Then free any | ||||
| 81422 | ** overflow pages associated with the entry and finally remove the cell | ||||
| 81423 | ** itself from within the page. */ | ||||
| 81424 | rc = sqlite3PagerWrite(pPage->pDbPage); | ||||
| 81425 | if( rc ) return rc; | ||||
| 81426 | BTREE_CLEAR_CELL(rc, pPage, pCell, info)pPage->xParseCell(pPage, pCell, &info); if( info.nLocal !=info.nPayload ){ rc = clearCellOverflow(pPage, pCell, & info); }else{ rc = 0; }; | ||||
| 81427 | dropCell(pPage, iCellIdx, info.nSize, &rc); | ||||
| 81428 | if( rc ) return rc; | ||||
| 81429 | |||||
| 81430 | /* If the cell deleted was not located on a leaf page, then the cursor | ||||
| 81431 | ** is currently pointing to the largest entry in the sub-tree headed | ||||
| 81432 | ** by the child-page of the cell that was just deleted from an internal | ||||
| 81433 | ** node. The cell from the leaf node needs to be moved to the internal | ||||
| 81434 | ** node to replace the deleted cell. */ | ||||
| 81435 | if( !pPage->leaf ){ | ||||
| 81436 | MemPage *pLeaf = pCur->pPage; | ||||
| 81437 | int nCell; | ||||
| 81438 | Pgno n; | ||||
| 81439 | unsigned char *pTmp; | ||||
| 81440 | |||||
| 81441 | if( pLeaf->nFree<0 ){ | ||||
| 81442 | rc = btreeComputeFreeSpace(pLeaf); | ||||
| 81443 | if( rc ) return rc; | ||||
| 81444 | } | ||||
| 81445 | if( iCellDepth<pCur->iPage-1 ){ | ||||
| 81446 | n = pCur->apPage[iCellDepth+1]->pgno; | ||||
| 81447 | }else{ | ||||
| 81448 | n = pCur->pPage->pgno; | ||||
| 81449 | } | ||||
| 81450 | pCell = findCell(pLeaf, pLeaf->nCell-1)((pLeaf)->aData + ((pLeaf)->maskPage & ((&(pLeaf )->aCellIdx[2*(pLeaf->nCell-1)])[0]<<8 | (&(pLeaf )->aCellIdx[2*(pLeaf->nCell-1)])[1]))); | ||||
| 81451 | if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_PAGE(pLeaf)sqlite3CorruptError(81451); | ||||
| 81452 | nCell = pLeaf->xCellSize(pLeaf, pCell); | ||||
| 81453 | assert( MX_CELL_SIZE(pBt) >= nCell )((void) (0)); | ||||
| 81454 | pTmp = pBt->pTmpSpace; | ||||
| 81455 | assert( pTmp!=0 )((void) (0)); | ||||
| 81456 | rc = sqlite3PagerWrite(pLeaf->pDbPage); | ||||
| 81457 | if( rc==SQLITE_OK0 ){ | ||||
| 81458 | rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n); | ||||
| 81459 | } | ||||
| 81460 | dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); | ||||
| 81461 | if( rc ) return rc; | ||||
| 81462 | } | ||||
| 81463 | |||||
| 81464 | /* Balance the tree. If the entry deleted was located on a leaf page, | ||||
| 81465 | ** then the cursor still points to that page. In this case the first | ||||
| 81466 | ** call to balance() repairs the tree, and the if(...) condition is | ||||
| 81467 | ** never true. | ||||
| 81468 | ** | ||||
| 81469 | ** Otherwise, if the entry deleted was on an internal node page, then | ||||
| 81470 | ** pCur is pointing to the leaf page from which a cell was removed to | ||||
| 81471 | ** replace the cell deleted from the internal node. This is slightly | ||||
| 81472 | ** tricky as the leaf node may be underfull, and the internal node may | ||||
| 81473 | ** be either under or overfull. In this case run the balancing algorithm | ||||
| 81474 | ** on the leaf node first. If the balance proceeds far enough up the | ||||
| 81475 | ** tree that we can be sure that any problem in the internal node has | ||||
| 81476 | ** been corrected, so be it. Otherwise, after balancing the leaf node, | ||||
| 81477 | ** walk the cursor up the tree to the internal node and balance it as | ||||
| 81478 | ** well. */ | ||||
| 81479 | assert( pCur->pPage->nOverflow==0 )((void) (0)); | ||||
| 81480 | assert( pCur->pPage->nFree>=0 )((void) (0)); | ||||
| 81481 | if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){ | ||||
| 81482 | /* Optimization: If the free space is less than 2/3rds of the page, | ||||
| 81483 | ** then balance() will always be a no-op. No need to invoke it. */ | ||||
| 81484 | rc = SQLITE_OK0; | ||||
| 81485 | }else{ | ||||
| 81486 | rc = balance(pCur); | ||||
| 81487 | } | ||||
| 81488 | if( rc==SQLITE_OK0 && pCur->iPage>iCellDepth ){ | ||||
| 81489 | releasePageNotNull(pCur->pPage); | ||||
| 81490 | pCur->iPage--; | ||||
| 81491 | while( pCur->iPage>iCellDepth ){ | ||||
| 81492 | releasePage(pCur->apPage[pCur->iPage--]); | ||||
| 81493 | } | ||||
| 81494 | pCur->pPage = pCur->apPage[pCur->iPage]; | ||||
| 81495 | rc = balance(pCur); | ||||
| 81496 | } | ||||
| 81497 | |||||
| 81498 | if( rc==SQLITE_OK0 ){ | ||||
| 81499 | if( bPreserve>1 ){ | ||||
| 81500 | assert( (pCur->iPage==iCellDepth || CORRUPT_DB) )((void) (0)); | ||||
| 81501 | assert( pPage==pCur->pPage || CORRUPT_DB )((void) (0)); | ||||
| 81502 | assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell )((void) (0)); | ||||
| 81503 | pCur->eState = CURSOR_SKIPNEXT2; | ||||
| 81504 | if( iCellIdx>=pPage->nCell ){ | ||||
| 81505 | pCur->skipNext = -1; | ||||
| 81506 | pCur->ix = pPage->nCell-1; | ||||
| 81507 | }else{ | ||||
| 81508 | pCur->skipNext = 1; | ||||
| 81509 | } | ||||
| 81510 | }else{ | ||||
| 81511 | rc = moveToRoot(pCur); | ||||
| 81512 | if( bPreserve ){ | ||||
| 81513 | btreeReleaseAllCursorPages(pCur); | ||||
| 81514 | pCur->eState = CURSOR_REQUIRESEEK3; | ||||
| 81515 | } | ||||
| 81516 | if( rc==SQLITE_EMPTY16 ) rc = SQLITE_OK0; | ||||
| 81517 | } | ||||
| 81518 | } | ||||
| 81519 | return rc; | ||||
| 81520 | } | ||||
| 81521 | |||||
| 81522 | /* | ||||
| 81523 | ** Create a new BTree table. Write into *piTable the page | ||||
| 81524 | ** number for the root page of the new table. | ||||
| 81525 | ** | ||||
| 81526 | ** The type of type is determined by the flags parameter. Only the | ||||
| 81527 | ** following values of flags are currently in use. Other values for | ||||
| 81528 | ** flags might not work: | ||||
| 81529 | ** | ||||
| 81530 | ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys | ||||
| 81531 | ** BTREE_ZERODATA Used for SQL indices | ||||
| 81532 | */ | ||||
| 81533 | static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){ | ||||
| 81534 | BtShared *pBt = p->pBt; | ||||
| 81535 | MemPage *pRoot; | ||||
| 81536 | Pgno pgnoRoot; | ||||
| 81537 | int rc; | ||||
| 81538 | int ptfFlags; /* Page-type flags for the root page of new table */ | ||||
| 81539 | |||||
| 81540 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 81541 | assert( pBt->inTransaction==TRANS_WRITE )((void) (0)); | ||||
| 81542 | assert( (pBt->btsFlags & BTS_READ_ONLY)==0 )((void) (0)); | ||||
| 81543 | |||||
| 81544 | #ifdef SQLITE_OMIT_AUTOVACUUM | ||||
| 81545 | rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); | ||||
| 81546 | if( rc ){ | ||||
| 81547 | return rc; | ||||
| 81548 | } | ||||
| 81549 | #else | ||||
| 81550 | if( pBt->autoVacuum ){ | ||||
| 81551 | Pgno pgnoMove; /* Move a page here to make room for the root-page */ | ||||
| 81552 | MemPage *pPageMove; /* The page to move to. */ | ||||
| 81553 | |||||
| 81554 | /* Creating a new table may probably require moving an existing database | ||||
| 81555 | ** to make room for the new tables root page. In case this page turns | ||||
| 81556 | ** out to be an overflow page, delete all overflow page-map caches | ||||
| 81557 | ** held by open cursors. | ||||
| 81558 | */ | ||||
| 81559 | invalidateAllOverflowCache(pBt); | ||||
| 81560 | |||||
| 81561 | /* Read the value of meta[3] from the database to determine where the | ||||
| 81562 | ** root page of the new table should go. meta[3] is the largest root-page | ||||
| 81563 | ** created so far, so the new root-page is (meta[3]+1). | ||||
| 81564 | */ | ||||
| 81565 | sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE4, &pgnoRoot); | ||||
| 81566 | if( pgnoRoot>btreePagecount(pBt) ){ | ||||
| 81567 | return SQLITE_CORRUPT_PGNO(pgnoRoot)sqlite3CorruptError(81567); | ||||
| 81568 | } | ||||
| 81569 | pgnoRoot++; | ||||
| 81570 | |||||
| 81571 | /* The new root-page may not be allocated on a pointer-map page, or the | ||||
| 81572 | ** PENDING_BYTE page. | ||||
| 81573 | */ | ||||
| 81574 | while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot)ptrmapPageno(pBt, pgnoRoot) || | ||||
| 81575 | pgnoRoot==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) ){ | ||||
| 81576 | pgnoRoot++; | ||||
| 81577 | } | ||||
| 81578 | assert( pgnoRoot>=3 )((void) (0)); | ||||
| 81579 | |||||
| 81580 | /* Allocate a page. The page that currently resides at pgnoRoot will | ||||
| 81581 | ** be moved to the allocated page (unless the allocated page happens | ||||
| 81582 | ** to reside at pgnoRoot). | ||||
| 81583 | */ | ||||
| 81584 | rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT1); | ||||
| 81585 | if( rc!=SQLITE_OK0 ){ | ||||
| 81586 | return rc; | ||||
| 81587 | } | ||||
| 81588 | |||||
| 81589 | if( pgnoMove!=pgnoRoot ){ | ||||
| 81590 | /* pgnoRoot is the page that will be used for the root-page of | ||||
| 81591 | ** the new table (assuming an error did not occur). But we were | ||||
| 81592 | ** allocated pgnoMove. If required (i.e. if it was not allocated | ||||
| 81593 | ** by extending the file), the current page at position pgnoMove | ||||
| 81594 | ** is already journaled. | ||||
| 81595 | */ | ||||
| 81596 | u8 eType = 0; | ||||
| 81597 | Pgno iPtrPage = 0; | ||||
| 81598 | |||||
| 81599 | /* Save the positions of any open cursors. This is required in | ||||
| 81600 | ** case they are holding a reference to an xFetch reference | ||||
| 81601 | ** corresponding to page pgnoRoot. */ | ||||
| 81602 | rc = saveAllCursors(pBt, 0, 0); | ||||
| 81603 | releasePage(pPageMove); | ||||
| 81604 | if( rc!=SQLITE_OK0 ){ | ||||
| 81605 | return rc; | ||||
| 81606 | } | ||||
| 81607 | |||||
| 81608 | /* Move the page currently at pgnoRoot to pgnoMove. */ | ||||
| 81609 | rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); | ||||
| 81610 | if( rc!=SQLITE_OK0 ){ | ||||
| 81611 | return rc; | ||||
| 81612 | } | ||||
| 81613 | rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); | ||||
| 81614 | if( eType==PTRMAP_ROOTPAGE1 || eType==PTRMAP_FREEPAGE2 ){ | ||||
| 81615 | rc = SQLITE_CORRUPT_PGNO(pgnoRoot)sqlite3CorruptError(81615); | ||||
| 81616 | } | ||||
| 81617 | if( rc!=SQLITE_OK0 ){ | ||||
| 81618 | releasePage(pRoot); | ||||
| 81619 | return rc; | ||||
| 81620 | } | ||||
| 81621 | assert( eType!=PTRMAP_ROOTPAGE )((void) (0)); | ||||
| 81622 | assert( eType!=PTRMAP_FREEPAGE )((void) (0)); | ||||
| 81623 | rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); | ||||
| 81624 | releasePage(pRoot); | ||||
| 81625 | |||||
| 81626 | /* Obtain the page at pgnoRoot */ | ||||
| 81627 | if( rc!=SQLITE_OK0 ){ | ||||
| 81628 | return rc; | ||||
| 81629 | } | ||||
| 81630 | rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); | ||||
| 81631 | if( rc!=SQLITE_OK0 ){ | ||||
| 81632 | return rc; | ||||
| 81633 | } | ||||
| 81634 | rc = sqlite3PagerWrite(pRoot->pDbPage); | ||||
| 81635 | if( rc!=SQLITE_OK0 ){ | ||||
| 81636 | releasePage(pRoot); | ||||
| 81637 | return rc; | ||||
| 81638 | } | ||||
| 81639 | }else{ | ||||
| 81640 | pRoot = pPageMove; | ||||
| 81641 | } | ||||
| 81642 | |||||
| 81643 | /* Update the pointer-map and meta-data with the new root-page number. */ | ||||
| 81644 | ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE1, 0, &rc); | ||||
| 81645 | if( rc ){ | ||||
| 81646 | releasePage(pRoot); | ||||
| 81647 | return rc; | ||||
| 81648 | } | ||||
| 81649 | |||||
| 81650 | /* When the new root page was allocated, page 1 was made writable in | ||||
| 81651 | ** order either to increase the database filesize, or to decrement the | ||||
| 81652 | ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. | ||||
| 81653 | */ | ||||
| 81654 | assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) )((void) (0)); | ||||
| 81655 | rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); | ||||
| 81656 | if( NEVER(rc)(rc) ){ | ||||
| 81657 | releasePage(pRoot); | ||||
| 81658 | return rc; | ||||
| 81659 | } | ||||
| 81660 | |||||
| 81661 | }else{ | ||||
| 81662 | rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); | ||||
| 81663 | if( rc ) return rc; | ||||
| 81664 | } | ||||
| 81665 | #endif | ||||
| 81666 | assert( sqlite3PagerIswriteable(pRoot->pDbPage) )((void) (0)); | ||||
| 81667 | if( createTabFlags & BTREE_INTKEY1 ){ | ||||
| 81668 | ptfFlags = PTF_INTKEY0x01 | PTF_LEAFDATA0x04 | PTF_LEAF0x08; | ||||
| 81669 | }else{ | ||||
| 81670 | ptfFlags = PTF_ZERODATA0x02 | PTF_LEAF0x08; | ||||
| 81671 | } | ||||
| 81672 | zeroPage(pRoot, ptfFlags); | ||||
| 81673 | sqlite3PagerUnref(pRoot->pDbPage); | ||||
| 81674 | assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 )((void) (0)); | ||||
| 81675 | *piTable = pgnoRoot; | ||||
| 81676 | return SQLITE_OK0; | ||||
| 81677 | } | ||||
| 81678 | SQLITE_PRIVATEstatic int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){ | ||||
| 81679 | int rc; | ||||
| 81680 | sqlite3BtreeEnter(p); | ||||
| 81681 | rc = btreeCreateTable(p, piTable, flags); | ||||
| 81682 | sqlite3BtreeLeave(p); | ||||
| 81683 | return rc; | ||||
| 81684 | } | ||||
| 81685 | |||||
| 81686 | /* | ||||
| 81687 | ** Erase the given database page and all its children. Return | ||||
| 81688 | ** the page to the freelist. | ||||
| 81689 | */ | ||||
| 81690 | static int clearDatabasePage( | ||||
| 81691 | BtShared *pBt, /* The BTree that contains the table */ | ||||
| 81692 | Pgno pgno, /* Page number to clear */ | ||||
| 81693 | int freePageFlag, /* Deallocate page if true */ | ||||
| 81694 | i64 *pnChange /* Add number of Cells freed to this counter */ | ||||
| 81695 | ){ | ||||
| 81696 | MemPage *pPage; | ||||
| 81697 | int rc; | ||||
| 81698 | unsigned char *pCell; | ||||
| 81699 | int i; | ||||
| 81700 | int hdr; | ||||
| 81701 | CellInfo info; | ||||
| 81702 | |||||
| 81703 | assert( sqlite3_mutex_held(pBt->mutex) )((void) (0)); | ||||
| 81704 | if( pgno>btreePagecount(pBt) ){ | ||||
| 81705 | return SQLITE_CORRUPT_PGNO(pgno)sqlite3CorruptError(81705); | ||||
| 81706 | } | ||||
| 81707 | rc = getAndInitPage(pBt, pgno, &pPage, 0); | ||||
| 81708 | if( rc ) return rc; | ||||
| 81709 | if( (pBt->openFlags & BTREE_SINGLE4)==0 | ||||
| 81710 | && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1)) | ||||
| 81711 | ){ | ||||
| 81712 | rc = SQLITE_CORRUPT_PAGE(pPage)sqlite3CorruptError(81712); | ||||
| 81713 | goto cleardatabasepage_out; | ||||
| 81714 | } | ||||
| 81715 | hdr = pPage->hdrOffset; | ||||
| 81716 | for(i=0; i<pPage->nCell; i++){ | ||||
| 81717 | pCell = findCell(pPage, i)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(i)])[0]<<8 | (&(pPage)->aCellIdx [2*(i)])[1]))); | ||||
| 81718 | if( !pPage->leaf ){ | ||||
| 81719 | rc = clearDatabasePage(pBt, get4bytesqlite3Get4byte(pCell), 1, pnChange); | ||||
| 81720 | if( rc ) goto cleardatabasepage_out; | ||||
| 81721 | } | ||||
| 81722 | BTREE_CLEAR_CELL(rc, pPage, pCell, info)pPage->xParseCell(pPage, pCell, &info); if( info.nLocal !=info.nPayload ){ rc = clearCellOverflow(pPage, pCell, & info); }else{ rc = 0; }; | ||||
| 81723 | if( rc ) goto cleardatabasepage_out; | ||||
| 81724 | } | ||||
| 81725 | if( !pPage->leaf ){ | ||||
| 81726 | rc = clearDatabasePage(pBt, get4bytesqlite3Get4byte(&pPage->aData[hdr+8]), 1, pnChange); | ||||
| 81727 | if( rc ) goto cleardatabasepage_out; | ||||
| 81728 | if( pPage->intKey ) pnChange = 0; | ||||
| 81729 | } | ||||
| 81730 | if( pnChange ){ | ||||
| 81731 | testcase( !pPage->intKey ); | ||||
| 81732 | *pnChange += pPage->nCell; | ||||
| 81733 | } | ||||
| 81734 | if( freePageFlag ){ | ||||
| 81735 | freePage(pPage, &rc); | ||||
| 81736 | }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ | ||||
| 81737 | zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF0x08); | ||||
| 81738 | } | ||||
| 81739 | |||||
| 81740 | cleardatabasepage_out: | ||||
| 81741 | releasePage(pPage); | ||||
| 81742 | return rc; | ||||
| 81743 | } | ||||
| 81744 | |||||
| 81745 | /* | ||||
| 81746 | ** Delete all information from a single table in the database. iTable is | ||||
| 81747 | ** the page number of the root of the table. After this routine returns, | ||||
| 81748 | ** the root page is empty, but still exists. | ||||
| 81749 | ** | ||||
| 81750 | ** This routine will fail with SQLITE_LOCKED if there are any open | ||||
| 81751 | ** read cursors on the table. Open write cursors are moved to the | ||||
| 81752 | ** root of the table. | ||||
| 81753 | ** | ||||
| 81754 | ** If pnChange is not NULL, then the integer value pointed to by pnChange | ||||
| 81755 | ** is incremented by the number of entries in the table. | ||||
| 81756 | */ | ||||
| 81757 | SQLITE_PRIVATEstatic int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){ | ||||
| 81758 | int rc; | ||||
| 81759 | BtShared *pBt = p->pBt; | ||||
| 81760 | sqlite3BtreeEnter(p); | ||||
| 81761 | assert( p->inTrans==TRANS_WRITE )((void) (0)); | ||||
| 81762 | |||||
| 81763 | rc = saveAllCursors(pBt, (Pgno)iTable, 0); | ||||
| 81764 | |||||
| 81765 | if( SQLITE_OK0==rc ){ | ||||
| 81766 | /* Invalidate all incrblob cursors open on table iTable (assuming iTable | ||||
| 81767 | ** is the root of a table b-tree - if it is not, the following call is | ||||
| 81768 | ** a no-op). */ | ||||
| 81769 | if( p->hasIncrblobCur ){ | ||||
| 81770 | invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1); | ||||
| 81771 | } | ||||
| 81772 | rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); | ||||
| 81773 | } | ||||
| 81774 | sqlite3BtreeLeave(p); | ||||
| 81775 | return rc; | ||||
| 81776 | } | ||||
| 81777 | |||||
| 81778 | /* | ||||
| 81779 | ** Delete all information from the single table that pCur is open on. | ||||
| 81780 | ** | ||||
| 81781 | ** This routine only work for pCur on an ephemeral table. | ||||
| 81782 | */ | ||||
| 81783 | SQLITE_PRIVATEstatic int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ | ||||
| 81784 | return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); | ||||
| 81785 | } | ||||
| 81786 | |||||
| 81787 | /* | ||||
| 81788 | ** Erase all information in a table and add the root of the table to | ||||
| 81789 | ** the freelist. Except, the root of the principle table (the one on | ||||
| 81790 | ** page 1) is never added to the freelist. | ||||
| 81791 | ** | ||||
| 81792 | ** This routine will fail with SQLITE_LOCKED if there are any open | ||||
| 81793 | ** cursors on the table. | ||||
| 81794 | ** | ||||
| 81795 | ** If AUTOVACUUM is enabled and the page at iTable is not the last | ||||
| 81796 | ** root page in the database file, then the last root page | ||||
| 81797 | ** in the database file is moved into the slot formerly occupied by | ||||
| 81798 | ** iTable and that last slot formerly occupied by the last root page | ||||
| 81799 | ** is added to the freelist instead of iTable. In this say, all | ||||
| 81800 | ** root pages are kept at the beginning of the database file, which | ||||
| 81801 | ** is necessary for AUTOVACUUM to work right. *piMoved is set to the | ||||
| 81802 | ** page number that used to be the last root page in the file before | ||||
| 81803 | ** the move. If no page gets moved, *piMoved is set to 0. | ||||
| 81804 | ** The last root page is recorded in meta[3] and the value of | ||||
| 81805 | ** meta[3] is updated by this procedure. | ||||
| 81806 | */ | ||||
| 81807 | static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ | ||||
| 81808 | int rc; | ||||
| 81809 | MemPage *pPage = 0; | ||||
| 81810 | BtShared *pBt = p->pBt; | ||||
| 81811 | |||||
| 81812 | assert( sqlite3BtreeHoldsMutex(p) )((void) (0)); | ||||
| 81813 | assert( p->inTrans==TRANS_WRITE )((void) (0)); | ||||
| 81814 | assert( iTable>=2 )((void) (0)); | ||||
| 81815 | if( iTable>btreePagecount(pBt) ){ | ||||
| 81816 | return SQLITE_CORRUPT_PGNO(iTable)sqlite3CorruptError(81816); | ||||
| 81817 | } | ||||
| 81818 | |||||
| 81819 | rc = sqlite3BtreeClearTable(p, iTable, 0); | ||||
| 81820 | if( rc ) return rc; | ||||
| 81821 | rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); | ||||
| 81822 | if( NEVER(rc)(rc) ){ | ||||
| 81823 | releasePage(pPage); | ||||
| 81824 | return rc; | ||||
| 81825 | } | ||||
| 81826 | |||||
| 81827 | *piMoved = 0; | ||||
| 81828 | |||||
| 81829 | #ifdef SQLITE_OMIT_AUTOVACUUM | ||||
| 81830 | freePage(pPage, &rc); | ||||
| 81831 | releasePage(pPage); | ||||
| 81832 | #else | ||||
| 81833 | if( pBt->autoVacuum ){ | ||||
| 81834 | Pgno maxRootPgno; | ||||
| 81835 | sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE4, &maxRootPgno); | ||||
| 81836 | |||||
| 81837 | if( iTable==maxRootPgno ){ | ||||
| 81838 | /* If the table being dropped is the table with the largest root-page | ||||
| 81839 | ** number in the database, put the root page on the free list. | ||||
| 81840 | */ | ||||
| 81841 | freePage(pPage, &rc); | ||||
| 81842 | releasePage(pPage); | ||||
| 81843 | if( rc!=SQLITE_OK0 ){ | ||||
| 81844 | return rc; | ||||
| 81845 | } | ||||
| 81846 | }else{ | ||||
| 81847 | /* The table being dropped does not have the largest root-page | ||||
| 81848 | ** number in the database. So move the page that does into the | ||||
| 81849 | ** gap left by the deleted root-page. | ||||
| 81850 | */ | ||||
| 81851 | MemPage *pMove; | ||||
| 81852 | releasePage(pPage); | ||||
| 81853 | rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); | ||||
| 81854 | if( rc!=SQLITE_OK0 ){ | ||||
| 81855 | return rc; | ||||
| 81856 | } | ||||
| 81857 | rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE1, 0, iTable, 0); | ||||
| 81858 | releasePage(pMove); | ||||
| 81859 | if( rc!=SQLITE_OK0 ){ | ||||
| 81860 | return rc; | ||||
| 81861 | } | ||||
| 81862 | pMove = 0; | ||||
| 81863 | rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); | ||||
| 81864 | freePage(pMove, &rc); | ||||
| 81865 | releasePage(pMove); | ||||
| 81866 | if( rc!=SQLITE_OK0 ){ | ||||
| 81867 | return rc; | ||||
| 81868 | } | ||||
| 81869 | *piMoved = maxRootPgno; | ||||
| 81870 | } | ||||
| 81871 | |||||
| 81872 | /* Set the new 'max-root-page' value in the database header. This | ||||
| 81873 | ** is the old value less one, less one more if that happens to | ||||
| 81874 | ** be a root-page number, less one again if that is the | ||||
| 81875 | ** PENDING_BYTE_PAGE. | ||||
| 81876 | */ | ||||
| 81877 | maxRootPgno--; | ||||
| 81878 | while( maxRootPgno==PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)) | ||||
| 81879 | || PTRMAP_ISPAGE(pBt, maxRootPgno)(ptrmapPageno((pBt), (maxRootPgno))==(maxRootPgno)) ){ | ||||
| 81880 | maxRootPgno--; | ||||
| 81881 | } | ||||
| 81882 | assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) )((void) (0)); | ||||
| 81883 | |||||
| 81884 | rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); | ||||
| 81885 | }else{ | ||||
| 81886 | freePage(pPage, &rc); | ||||
| 81887 | releasePage(pPage); | ||||
| 81888 | } | ||||
| 81889 | #endif | ||||
| 81890 | return rc; | ||||
| 81891 | } | ||||
| 81892 | SQLITE_PRIVATEstatic int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ | ||||
| 81893 | int rc; | ||||
| 81894 | sqlite3BtreeEnter(p); | ||||
| 81895 | rc = btreeDropTable(p, iTable, piMoved); | ||||
| 81896 | sqlite3BtreeLeave(p); | ||||
| 81897 | return rc; | ||||
| 81898 | } | ||||
| 81899 | |||||
| 81900 | |||||
| 81901 | /* | ||||
| 81902 | ** This function may only be called if the b-tree connection already | ||||
| 81903 | ** has a read or write transaction open on the database. | ||||
| 81904 | ** | ||||
| 81905 | ** Read the meta-information out of a database file. Meta[0] | ||||
| 81906 | ** is the number of free pages currently in the database. Meta[1] | ||||
| 81907 | ** through meta[15] are available for use by higher layers. Meta[0] | ||||
| 81908 | ** is read-only, the others are read/write. | ||||
| 81909 | ** | ||||
| 81910 | ** The schema layer numbers meta values differently. At the schema | ||||
| 81911 | ** layer (and the SetCookie and ReadCookie opcodes) the number of | ||||
| 81912 | ** free pages is not visible. So Cookie[0] is the same as Meta[1]. | ||||
| 81913 | ** | ||||
| 81914 | ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead | ||||
| 81915 | ** of reading the value out of the header, it instead loads the "DataVersion" | ||||
| 81916 | ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the | ||||
| 81917 | ** database file. It is a number computed by the pager. But its access | ||||
| 81918 | ** pattern is the same as header meta values, and so it is convenient to | ||||
| 81919 | ** read it from this routine. | ||||
| 81920 | */ | ||||
| 81921 | SQLITE_PRIVATEstatic void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ | ||||
| 81922 | BtShared *pBt = p->pBt; | ||||
| 81923 | |||||
| 81924 | sqlite3BtreeEnter(p); | ||||
| 81925 | assert( p->inTrans>TRANS_NONE )((void) (0)); | ||||
| 81926 | assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) )((void) (0)); | ||||
| 81927 | assert( pBt->pPage1 )((void) (0)); | ||||
| 81928 | assert( idx>=0 && idx<=15 )((void) (0)); | ||||
| 81929 | |||||
| 81930 | if( idx==BTREE_DATA_VERSION15 ){ | ||||
| 81931 | *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion; | ||||
| 81932 | }else{ | ||||
| 81933 | *pMeta = get4bytesqlite3Get4byte(&pBt->pPage1->aData[36 + idx*4]); | ||||
| 81934 | } | ||||
| 81935 | |||||
| 81936 | /* If auto-vacuum is disabled in this build and this is an auto-vacuum | ||||
| 81937 | ** database, mark the database as read-only. */ | ||||
| 81938 | #ifdef SQLITE_OMIT_AUTOVACUUM | ||||
| 81939 | if( idx==BTREE_LARGEST_ROOT_PAGE4 && *pMeta>0 ){ | ||||
| 81940 | pBt->btsFlags |= BTS_READ_ONLY0x0001; | ||||
| 81941 | } | ||||
| 81942 | #endif | ||||
| 81943 | |||||
| 81944 | sqlite3BtreeLeave(p); | ||||
| 81945 | } | ||||
| 81946 | |||||
| 81947 | /* | ||||
| 81948 | ** Write meta-information back into the database. Meta[0] is | ||||
| 81949 | ** read-only and may not be written. | ||||
| 81950 | */ | ||||
| 81951 | SQLITE_PRIVATEstatic int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ | ||||
| 81952 | BtShared *pBt = p->pBt; | ||||
| 81953 | unsigned char *pP1; | ||||
| 81954 | int rc; | ||||
| 81955 | assert( idx>=1 && idx<=15 )((void) (0)); | ||||
| 81956 | sqlite3BtreeEnter(p); | ||||
| 81957 | assert( p->inTrans==TRANS_WRITE )((void) (0)); | ||||
| 81958 | assert( pBt->pPage1!=0 )((void) (0)); | ||||
| 81959 | pP1 = pBt->pPage1->aData; | ||||
| 81960 | rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | ||||
| 81961 | if( rc==SQLITE_OK0 ){ | ||||
| 81962 | put4bytesqlite3Put4byte(&pP1[36 + idx*4], iMeta); | ||||
| 81963 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 81964 | if( idx==BTREE_INCR_VACUUM7 ){ | ||||
| 81965 | assert( pBt->autoVacuum || iMeta==0 )((void) (0)); | ||||
| 81966 | assert( iMeta==0 || iMeta==1 )((void) (0)); | ||||
| 81967 | pBt->incrVacuum = (u8)iMeta; | ||||
| 81968 | } | ||||
| 81969 | #endif | ||||
| 81970 | } | ||||
| 81971 | sqlite3BtreeLeave(p); | ||||
| 81972 | return rc; | ||||
| 81973 | } | ||||
| 81974 | |||||
| 81975 | /* | ||||
| 81976 | ** The first argument, pCur, is a cursor opened on some b-tree. Count the | ||||
| 81977 | ** number of entries in the b-tree and write the result to *pnEntry. | ||||
| 81978 | ** | ||||
| 81979 | ** SQLITE_OK is returned if the operation is successfully executed. | ||||
| 81980 | ** Otherwise, if an error is encountered (i.e. an IO error or database | ||||
| 81981 | ** corruption) an SQLite error code is returned. | ||||
| 81982 | */ | ||||
| 81983 | SQLITE_PRIVATEstatic int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){ | ||||
| 81984 | i64 nEntry = 0; /* Value to return in *pnEntry */ | ||||
| 81985 | int rc; /* Return code */ | ||||
| 81986 | |||||
| 81987 | rc = moveToRoot(pCur); | ||||
| 81988 | if( rc==SQLITE_EMPTY16 ){ | ||||
| 81989 | *pnEntry = 0; | ||||
| 81990 | return SQLITE_OK0; | ||||
| 81991 | } | ||||
| 81992 | |||||
| 81993 | /* Unless an error occurs, the following loop runs one iteration for each | ||||
| 81994 | ** page in the B-Tree structure (not including overflow pages). | ||||
| 81995 | */ | ||||
| 81996 | while( rc==SQLITE_OK0 && !AtomicLoad(&db->u1.isInterrupted)__atomic_load_n((&db->u1.isInterrupted),0) ){ | ||||
| 81997 | int iIdx; /* Index of child node in parent */ | ||||
| 81998 | MemPage *pPage; /* Current page of the b-tree */ | ||||
| 81999 | |||||
| 82000 | /* If this is a leaf page or the tree is not an int-key tree, then | ||||
| 82001 | ** this page contains countable entries. Increment the entry counter | ||||
| 82002 | ** accordingly. | ||||
| 82003 | */ | ||||
| 82004 | pPage = pCur->pPage; | ||||
| 82005 | if( pPage->leaf || !pPage->intKey ){ | ||||
| 82006 | nEntry += pPage->nCell; | ||||
| 82007 | } | ||||
| 82008 | |||||
| 82009 | /* pPage is a leaf node. This loop navigates the cursor so that it | ||||
| 82010 | ** points to the first interior cell that it points to the parent of | ||||
| 82011 | ** the next page in the tree that has not yet been visited. The | ||||
| 82012 | ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell | ||||
| 82013 | ** of the page, or to the number of cells in the page if the next page | ||||
| 82014 | ** to visit is the right-child of its parent. | ||||
| 82015 | ** | ||||
| 82016 | ** If all pages in the tree have been visited, return SQLITE_OK to the | ||||
| 82017 | ** caller. | ||||
| 82018 | */ | ||||
| 82019 | if( pPage->leaf ){ | ||||
| 82020 | do { | ||||
| 82021 | if( pCur->iPage==0 ){ | ||||
| 82022 | /* All pages of the b-tree have been visited. Return successfully. */ | ||||
| 82023 | *pnEntry = nEntry; | ||||
| 82024 | return moveToRoot(pCur); | ||||
| 82025 | } | ||||
| 82026 | moveToParent(pCur); | ||||
| 82027 | }while ( pCur->ix>=pCur->pPage->nCell ); | ||||
| 82028 | |||||
| 82029 | pCur->ix++; | ||||
| 82030 | pPage = pCur->pPage; | ||||
| 82031 | } | ||||
| 82032 | |||||
| 82033 | /* Descend to the child node of the cell that the cursor currently | ||||
| 82034 | ** points at. This is the right-child if (iIdx==pPage->nCell). | ||||
| 82035 | */ | ||||
| 82036 | iIdx = pCur->ix; | ||||
| 82037 | if( iIdx==pPage->nCell ){ | ||||
| 82038 | rc = moveToChild(pCur, get4bytesqlite3Get4byte(&pPage->aData[pPage->hdrOffset+8])); | ||||
| 82039 | }else{ | ||||
| 82040 | rc = moveToChild(pCur, get4bytesqlite3Get4byte(findCell(pPage, iIdx)((pPage)->aData + ((pPage)->maskPage & ((&(pPage )->aCellIdx[2*(iIdx)])[0]<<8 | (&(pPage)->aCellIdx [2*(iIdx)])[1]))))); | ||||
| 82041 | } | ||||
| 82042 | } | ||||
| 82043 | |||||
| 82044 | /* An error has occurred. Return an error code. */ | ||||
| 82045 | return rc; | ||||
| 82046 | } | ||||
| 82047 | |||||
| 82048 | /* | ||||
| 82049 | ** Return the pager associated with a BTree. This routine is used for | ||||
| 82050 | ** testing and debugging only. | ||||
| 82051 | */ | ||||
| 82052 | SQLITE_PRIVATEstatic Pager *sqlite3BtreePager(Btree *p){ | ||||
| 82053 | return p->pBt->pPager; | ||||
| 82054 | } | ||||
| 82055 | |||||
| 82056 | #ifndef SQLITE_OMIT_INTEGRITY_CHECK | ||||
| 82057 | /* | ||||
| 82058 | ** Record an OOM error during integrity_check | ||||
| 82059 | */ | ||||
| 82060 | static void checkOom(IntegrityCk *pCheck){ | ||||
| 82061 | pCheck->rc = SQLITE_NOMEM7; | ||||
| 82062 | pCheck->mxErr = 0; /* Causes integrity_check processing to stop */ | ||||
| 82063 | if( pCheck->nErr==0 ) pCheck->nErr++; | ||||
| 82064 | } | ||||
| 82065 | |||||
| 82066 | /* | ||||
| 82067 | ** Invoke the progress handler, if appropriate. Also check for an | ||||
| 82068 | ** interrupt. | ||||
| 82069 | */ | ||||
| 82070 | static void checkProgress(IntegrityCk *pCheck){ | ||||
| 82071 | sqlite3 *db = pCheck->db; | ||||
| 82072 | if( AtomicLoad(&db->u1.isInterrupted)__atomic_load_n((&db->u1.isInterrupted),0) ){ | ||||
| 82073 | pCheck->rc = SQLITE_INTERRUPT9; | ||||
| 82074 | pCheck->nErr++; | ||||
| 82075 | pCheck->mxErr = 0; | ||||
| 82076 | } | ||||
| 82077 | #ifndef SQLITE_OMIT_PROGRESS_CALLBACK1 | ||||
| 82078 | if( db->xProgress ){ | ||||
| 82079 | assert( db->nProgressOps>0 )((void) (0)); | ||||
| 82080 | pCheck->nStep++; | ||||
| 82081 | if( (pCheck->nStep % db->nProgressOps)==0 | ||||
| 82082 | && db->xProgress(db->pProgressArg) | ||||
| 82083 | ){ | ||||
| 82084 | pCheck->rc = SQLITE_INTERRUPT9; | ||||
| 82085 | pCheck->nErr++; | ||||
| 82086 | pCheck->mxErr = 0; | ||||
| 82087 | } | ||||
| 82088 | } | ||||
| 82089 | #endif | ||||
| 82090 | } | ||||
| 82091 | |||||
| 82092 | /* | ||||
| 82093 | ** Append a message to the error message string. | ||||
| 82094 | */ | ||||
| 82095 | static void checkAppendMsg( | ||||
| 82096 | IntegrityCk *pCheck, | ||||
| 82097 | const char *zFormat, | ||||
| 82098 | ... | ||||
| 82099 | ){ | ||||
| 82100 | va_list ap; | ||||
| 82101 | checkProgress(pCheck); | ||||
| 82102 | if( !pCheck->mxErr ) return; | ||||
| 82103 | pCheck->mxErr--; | ||||
| 82104 | pCheck->nErr++; | ||||
| 82105 | va_start(ap, zFormat)__builtin_va_start(ap, zFormat); | ||||
| 82106 | if( pCheck->errMsg.nChar ){ | ||||
| 82107 | sqlite3_str_append(&pCheck->errMsg, "\n", 1); | ||||
| 82108 | } | ||||
| 82109 | if( pCheck->zPfx ){ | ||||
| 82110 | sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, | ||||
| 82111 | pCheck->v0, pCheck->v1, pCheck->v2); | ||||
| 82112 | } | ||||
| 82113 | sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap); | ||||
| 82114 | va_end(ap)__builtin_va_end(ap); | ||||
| 82115 | if( pCheck->errMsg.accError==SQLITE_NOMEM7 ){ | ||||
| 82116 | checkOom(pCheck); | ||||
| 82117 | } | ||||
| 82118 | } | ||||
| 82119 | #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | ||||
| 82120 | |||||
| 82121 | #ifndef SQLITE_OMIT_INTEGRITY_CHECK | ||||
| 82122 | |||||
| 82123 | /* | ||||
| 82124 | ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that | ||||
| 82125 | ** corresponds to page iPg is already set. | ||||
| 82126 | */ | ||||
| 82127 | static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ | ||||
| 82128 | assert( pCheck->aPgRef!=0 )((void) (0)); | ||||
| 82129 | assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 )((void) (0)); | ||||
| 82130 | return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); | ||||
| 82131 | } | ||||
| 82132 | |||||
| 82133 | /* | ||||
| 82134 | ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. | ||||
| 82135 | */ | ||||
| 82136 | static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ | ||||
| 82137 | assert( pCheck->aPgRef!=0 )((void) (0)); | ||||
| 82138 | assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 )((void) (0)); | ||||
| 82139 | pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); | ||||
| 82140 | } | ||||
| 82141 | |||||
| 82142 | |||||
| 82143 | /* | ||||
| 82144 | ** Add 1 to the reference count for page iPage. If this is the second | ||||
| 82145 | ** reference to the page, add an error message to pCheck->zErrMsg. | ||||
| 82146 | ** Return 1 if there are 2 or more references to the page and 0 if | ||||
| 82147 | ** if this is the first reference to the page. | ||||
| 82148 | ** | ||||
| 82149 | ** Also check that the page number is in bounds. | ||||
| 82150 | */ | ||||
| 82151 | static int checkRef(IntegrityCk *pCheck, Pgno iPage){ | ||||
| 82152 | if( iPage>pCheck->nCkPage || iPage==0 ){ | ||||
| 82153 | checkAppendMsg(pCheck, "invalid page number %u", iPage); | ||||
| 82154 | return 1; | ||||
| 82155 | } | ||||
| 82156 | if( getPageReferenced(pCheck, iPage) ){ | ||||
| 82157 | checkAppendMsg(pCheck, "2nd reference to page %u", iPage); | ||||
| 82158 | return 1; | ||||
| 82159 | } | ||||
| 82160 | setPageReferenced(pCheck, iPage); | ||||
| 82161 | return 0; | ||||
| 82162 | } | ||||
| 82163 | |||||
| 82164 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82165 | /* | ||||
| 82166 | ** Check that the entry in the pointer-map for page iChild maps to | ||||
| 82167 | ** page iParent, pointer type ptrType. If not, append an error message | ||||
| 82168 | ** to pCheck. | ||||
| 82169 | */ | ||||
| 82170 | static void checkPtrmap( | ||||
| 82171 | IntegrityCk *pCheck, /* Integrity check context */ | ||||
| 82172 | Pgno iChild, /* Child page number */ | ||||
| 82173 | u8 eType, /* Expected pointer map type */ | ||||
| 82174 | Pgno iParent /* Expected pointer map parent page number */ | ||||
| 82175 | ){ | ||||
| 82176 | int rc; | ||||
| 82177 | u8 ePtrmapType; | ||||
| 82178 | Pgno iPtrmapParent; | ||||
| 82179 | |||||
| 82180 | rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); | ||||
| 82181 | if( rc!=SQLITE_OK0 ){ | ||||
| 82182 | if( rc==SQLITE_NOMEM7 || rc==SQLITE_IOERR_NOMEM(10 | (12<<8)) ) checkOom(pCheck); | ||||
| 82183 | checkAppendMsg(pCheck, "Failed to read ptrmap key=%u", iChild); | ||||
| 82184 | return; | ||||
| 82185 | } | ||||
| 82186 | |||||
| 82187 | if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ | ||||
| 82188 | checkAppendMsg(pCheck, | ||||
| 82189 | "Bad ptr map entry key=%u expected=(%u,%u) got=(%u,%u)", | ||||
| 82190 | iChild, eType, iParent, ePtrmapType, iPtrmapParent); | ||||
| 82191 | } | ||||
| 82192 | } | ||||
| 82193 | #endif | ||||
| 82194 | |||||
| 82195 | /* | ||||
| 82196 | ** Check the integrity of the freelist or of an overflow page list. | ||||
| 82197 | ** Verify that the number of pages on the list is N. | ||||
| 82198 | */ | ||||
| 82199 | static void checkList( | ||||
| 82200 | IntegrityCk *pCheck, /* Integrity checking context */ | ||||
| 82201 | int isFreeList, /* True for a freelist. False for overflow page list */ | ||||
| 82202 | Pgno iPage, /* Page number for first page in the list */ | ||||
| 82203 | u32 N /* Expected number of pages in the list */ | ||||
| 82204 | ){ | ||||
| 82205 | int i; | ||||
| 82206 | u32 expected = N; | ||||
| 82207 | int nErrAtStart = pCheck->nErr; | ||||
| 82208 | while( iPage!=0 && pCheck->mxErr ){ | ||||
| 82209 | DbPage *pOvflPage; | ||||
| 82210 | unsigned char *pOvflData; | ||||
| 82211 | if( checkRef(pCheck, iPage) ) break; | ||||
| 82212 | N--; | ||||
| 82213 | if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ | ||||
| 82214 | checkAppendMsg(pCheck, "failed to get page %u", iPage); | ||||
| 82215 | break; | ||||
| 82216 | } | ||||
| 82217 | pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); | ||||
| 82218 | if( isFreeList ){ | ||||
| 82219 | u32 n = (u32)get4bytesqlite3Get4byte(&pOvflData[4]); | ||||
| 82220 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82221 | if( pCheck->pBt->autoVacuum ){ | ||||
| 82222 | checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE2, 0); | ||||
| 82223 | } | ||||
| 82224 | #endif | ||||
| 82225 | if( n>pCheck->pBt->usableSize/4-2 ){ | ||||
| 82226 | checkAppendMsg(pCheck, | ||||
| 82227 | "freelist leaf count too big on page %u", iPage); | ||||
| 82228 | N--; | ||||
| 82229 | }else{ | ||||
| 82230 | for(i=0; i<(int)n; i++){ | ||||
| 82231 | Pgno iFreePage = get4bytesqlite3Get4byte(&pOvflData[8+i*4]); | ||||
| 82232 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82233 | if( pCheck->pBt->autoVacuum ){ | ||||
| 82234 | checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE2, 0); | ||||
| 82235 | } | ||||
| 82236 | #endif | ||||
| 82237 | checkRef(pCheck, iFreePage); | ||||
| 82238 | } | ||||
| 82239 | N -= n; | ||||
| 82240 | } | ||||
| 82241 | } | ||||
| 82242 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82243 | else{ | ||||
| 82244 | /* If this database supports auto-vacuum and iPage is not the last | ||||
| 82245 | ** page in this overflow list, check that the pointer-map entry for | ||||
| 82246 | ** the following page matches iPage. | ||||
| 82247 | */ | ||||
| 82248 | if( pCheck->pBt->autoVacuum && N>0 ){ | ||||
| 82249 | i = get4bytesqlite3Get4byte(pOvflData); | ||||
| 82250 | checkPtrmap(pCheck, i, PTRMAP_OVERFLOW24, iPage); | ||||
| 82251 | } | ||||
| 82252 | } | ||||
| 82253 | #endif | ||||
| 82254 | iPage = get4bytesqlite3Get4byte(pOvflData); | ||||
| 82255 | sqlite3PagerUnref(pOvflPage); | ||||
| 82256 | } | ||||
| 82257 | if( N && nErrAtStart==pCheck->nErr ){ | ||||
| 82258 | checkAppendMsg(pCheck, | ||||
| 82259 | "%s is %u but should be %u", | ||||
| 82260 | isFreeList ? "size" : "overflow list length", | ||||
| 82261 | expected-N, expected); | ||||
| 82262 | } | ||||
| 82263 | } | ||||
| 82264 | #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | ||||
| 82265 | |||||
| 82266 | /* | ||||
| 82267 | ** An implementation of a min-heap. | ||||
| 82268 | ** | ||||
| 82269 | ** aHeap[0] is the number of elements on the heap. aHeap[1] is the | ||||
| 82270 | ** root element. The daughter nodes of aHeap[N] are aHeap[N*2] | ||||
| 82271 | ** and aHeap[N*2+1]. | ||||
| 82272 | ** | ||||
| 82273 | ** The heap property is this: Every node is less than or equal to both | ||||
| 82274 | ** of its daughter nodes. A consequence of the heap property is that the | ||||
| 82275 | ** root node aHeap[1] is always the minimum value currently in the heap. | ||||
| 82276 | ** | ||||
| 82277 | ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto | ||||
| 82278 | ** the heap, preserving the heap property. The btreeHeapPull() routine | ||||
| 82279 | ** removes the root element from the heap (the minimum value in the heap) | ||||
| 82280 | ** and then moves other nodes around as necessary to preserve the heap | ||||
| 82281 | ** property. | ||||
| 82282 | ** | ||||
| 82283 | ** This heap is used for cell overlap and coverage testing. Each u32 | ||||
| 82284 | ** entry represents the span of a cell or freeblock on a btree page. | ||||
| 82285 | ** The upper 16 bits are the index of the first byte of a range and the | ||||
| 82286 | ** lower 16 bits are the index of the last byte of that range. | ||||
| 82287 | */ | ||||
| 82288 | static void btreeHeapInsert(u32 *aHeap, u32 x){ | ||||
| 82289 | u32 j, i; | ||||
| 82290 | assert( aHeap!=0 )((void) (0)); | ||||
| 82291 | i = ++aHeap[0]; | ||||
| 82292 | aHeap[i] = x; | ||||
| 82293 | while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){ | ||||
| 82294 | x = aHeap[j]; | ||||
| 82295 | aHeap[j] = aHeap[i]; | ||||
| 82296 | aHeap[i] = x; | ||||
| 82297 | i = j; | ||||
| 82298 | } | ||||
| 82299 | } | ||||
| 82300 | static int btreeHeapPull(u32 *aHeap, u32 *pOut){ | ||||
| 82301 | u32 j, i, x; | ||||
| 82302 | if( (x = aHeap[0])==0 ) return 0; | ||||
| 82303 | *pOut = aHeap[1]; | ||||
| 82304 | aHeap[1] = aHeap[x]; | ||||
| 82305 | aHeap[x] = 0xffffffff; | ||||
| 82306 | aHeap[0]--; | ||||
| 82307 | i = 1; | ||||
| 82308 | while( (j = i*2)<=aHeap[0] ){ | ||||
| 82309 | if( aHeap[j]>aHeap[j+1] ) j++; | ||||
| 82310 | if( aHeap[i]<aHeap[j] ) break; | ||||
| 82311 | x = aHeap[i]; | ||||
| 82312 | aHeap[i] = aHeap[j]; | ||||
| 82313 | aHeap[j] = x; | ||||
| 82314 | i = j; | ||||
| 82315 | } | ||||
| 82316 | return 1; | ||||
| 82317 | } | ||||
| 82318 | |||||
| 82319 | #ifndef SQLITE_OMIT_INTEGRITY_CHECK | ||||
| 82320 | /* | ||||
| 82321 | ** Do various sanity checks on a single page of a tree. Return | ||||
| 82322 | ** the tree depth. Root pages return 0. Parents of root pages | ||||
| 82323 | ** return 1, and so forth. | ||||
| 82324 | ** | ||||
| 82325 | ** These checks are done: | ||||
| 82326 | ** | ||||
| 82327 | ** 1. Make sure that cells and freeblocks do not overlap | ||||
| 82328 | ** but combine to completely cover the page. | ||||
| 82329 | ** 2. Make sure integer cell keys are in order. | ||||
| 82330 | ** 3. Check the integrity of overflow pages. | ||||
| 82331 | ** 4. Recursively call checkTreePage on all children. | ||||
| 82332 | ** 5. Verify that the depth of all children is the same. | ||||
| 82333 | */ | ||||
| 82334 | static int checkTreePage( | ||||
| 82335 | IntegrityCk *pCheck, /* Context for the sanity check */ | ||||
| 82336 | Pgno iPage, /* Page number of the page to check */ | ||||
| 82337 | i64 *piMinKey, /* Write minimum integer primary key here */ | ||||
| 82338 | i64 maxKey /* Error if integer primary key greater than this */ | ||||
| 82339 | ){ | ||||
| 82340 | MemPage *pPage = 0; /* The page being analyzed */ | ||||
| 82341 | int i; /* Loop counter */ | ||||
| 82342 | int rc; /* Result code from subroutine call */ | ||||
| 82343 | int depth = -1, d2; /* Depth of a subtree */ | ||||
| 82344 | int pgno; /* Page number */ | ||||
| 82345 | int nFrag; /* Number of fragmented bytes on the page */ | ||||
| 82346 | int hdr; /* Offset to the page header */ | ||||
| 82347 | int cellStart; /* Offset to the start of the cell pointer array */ | ||||
| 82348 | int nCell; /* Number of cells */ | ||||
| 82349 | int doCoverageCheck = 1; /* True if cell coverage checking should be done */ | ||||
| 82350 | int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey | ||||
| 82351 | ** False if IPK must be strictly less than maxKey */ | ||||
| 82352 | u8 *data; /* Page content */ | ||||
| 82353 | u8 *pCell; /* Cell content */ | ||||
| 82354 | u8 *pCellIdx; /* Next element of the cell pointer array */ | ||||
| 82355 | BtShared *pBt; /* The BtShared object that owns pPage */ | ||||
| 82356 | u32 pc; /* Address of a cell */ | ||||
| 82357 | u32 usableSize; /* Usable size of the page */ | ||||
| 82358 | u32 contentOffset; /* Offset to the start of the cell content area */ | ||||
| 82359 | u32 *heap = 0; /* Min-heap used for checking cell coverage */ | ||||
| 82360 | u32 x, prev = 0; /* Next and previous entry on the min-heap */ | ||||
| 82361 | const char *saved_zPfx = pCheck->zPfx; | ||||
| 82362 | int saved_v1 = pCheck->v1; | ||||
| 82363 | int saved_v2 = pCheck->v2; | ||||
| 82364 | u8 savedIsInit = 0; | ||||
| 82365 | |||||
| 82366 | /* Check that the page exists | ||||
| 82367 | */ | ||||
| 82368 | checkProgress(pCheck); | ||||
| 82369 | if( pCheck->mxErr==0 ) goto end_of_check; | ||||
| 82370 | pBt = pCheck->pBt; | ||||
| 82371 | usableSize = pBt->usableSize; | ||||
| 82372 | if( iPage==0 ) return 0; | ||||
| 82373 | if( checkRef(pCheck, iPage) ) return 0; | ||||
| 82374 | pCheck->zPfx = "Tree %u page %u: "; | ||||
| 82375 | pCheck->v1 = iPage; | ||||
| 82376 | if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){ | ||||
| 82377 | checkAppendMsg(pCheck, | ||||
| 82378 | "unable to get the page. error code=%d", rc); | ||||
| 82379 | if( rc==SQLITE_IOERR_NOMEM(10 | (12<<8)) ) pCheck->rc = SQLITE_NOMEM7; | ||||
| 82380 | goto end_of_check; | ||||
| 82381 | } | ||||
| 82382 | |||||
| 82383 | /* Clear MemPage.isInit to make sure the corruption detection code in | ||||
| 82384 | ** btreeInitPage() is executed. */ | ||||
| 82385 | savedIsInit = pPage->isInit; | ||||
| 82386 | pPage->isInit = 0; | ||||
| 82387 | if( (rc = btreeInitPage(pPage))!=0 ){ | ||||
| 82388 | assert( rc==SQLITE_CORRUPT )((void) (0)); /* The only possible error from InitPage */ | ||||
| 82389 | checkAppendMsg(pCheck, | ||||
| 82390 | "btreeInitPage() returns error code %d", rc); | ||||
| 82391 | goto end_of_check; | ||||
| 82392 | } | ||||
| 82393 | if( (rc = btreeComputeFreeSpace(pPage))!=0 ){ | ||||
| 82394 | assert( rc==SQLITE_CORRUPT )((void) (0)); | ||||
| 82395 | checkAppendMsg(pCheck, "free space corruption", rc); | ||||
| 82396 | goto end_of_check; | ||||
| 82397 | } | ||||
| 82398 | data = pPage->aData; | ||||
| 82399 | hdr = pPage->hdrOffset; | ||||
| 82400 | |||||
| 82401 | /* Set up for cell analysis */ | ||||
| 82402 | pCheck->zPfx = "Tree %u page %u cell %u: "; | ||||
| 82403 | contentOffset = get2byteNotZero(&data[hdr+5])(((((int)((&data[hdr+5])[0]<<8 | (&data[hdr+5]) [1]))-1)&0xffff)+1); | ||||
| 82404 | assert( contentOffset<=usableSize )((void) (0)); /* Enforced by btreeInitPage() */ | ||||
| 82405 | |||||
| 82406 | /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the | ||||
| 82407 | ** number of cells on the page. */ | ||||
| 82408 | nCell = get2byte(&data[hdr+3])((&data[hdr+3])[0]<<8 | (&data[hdr+3])[1]); | ||||
| 82409 | assert( pPage->nCell==nCell )((void) (0)); | ||||
| 82410 | if( pPage->leaf || pPage->intKey==0 ){ | ||||
| 82411 | pCheck->nRow += nCell; | ||||
| 82412 | } | ||||
| 82413 | |||||
| 82414 | /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page | ||||
| 82415 | ** immediately follows the b-tree page header. */ | ||||
| 82416 | cellStart = hdr + 12 - 4*pPage->leaf; | ||||
| 82417 | assert( pPage->aCellIdx==&data[cellStart] )((void) (0)); | ||||
| 82418 | pCellIdx = &data[cellStart + 2*(nCell-1)]; | ||||
| 82419 | |||||
| 82420 | if( !pPage->leaf ){ | ||||
| 82421 | /* Analyze the right-child page of internal pages */ | ||||
| 82422 | pgno = get4bytesqlite3Get4byte(&data[hdr+8]); | ||||
| 82423 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82424 | if( pBt->autoVacuum ){ | ||||
| 82425 | pCheck->zPfx = "Tree %u page %u right child: "; | ||||
| 82426 | checkPtrmap(pCheck, pgno, PTRMAP_BTREE5, iPage); | ||||
| 82427 | } | ||||
| 82428 | #endif | ||||
| 82429 | depth = checkTreePage(pCheck, pgno, &maxKey, maxKey); | ||||
| 82430 | keyCanBeEqual = 0; | ||||
| 82431 | }else{ | ||||
| 82432 | /* For leaf pages, the coverage check will occur in the same loop | ||||
| 82433 | ** as the other cell checks, so initialize the heap. */ | ||||
| 82434 | heap = pCheck->heap; | ||||
| 82435 | heap[0] = 0; | ||||
| 82436 | } | ||||
| 82437 | |||||
| 82438 | /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte | ||||
| 82439 | ** integer offsets to the cell contents. */ | ||||
| 82440 | for(i=nCell-1; i>=0 && pCheck->mxErr; i--){ | ||||
| 82441 | CellInfo info; | ||||
| 82442 | |||||
| 82443 | /* Check cell size */ | ||||
| 82444 | pCheck->v2 = i; | ||||
| 82445 | assert( pCellIdx==&data[cellStart + i*2] )((void) (0)); | ||||
| 82446 | pc = get2byteAligned(pCellIdx)((pCellIdx)[0]<<8 | (pCellIdx)[1]); | ||||
| 82447 | pCellIdx -= 2; | ||||
| 82448 | if( pc<contentOffset || pc>usableSize-4 ){ | ||||
| 82449 | checkAppendMsg(pCheck, "Offset %u out of range %u..%u", | ||||
| 82450 | pc, contentOffset, usableSize-4); | ||||
| 82451 | doCoverageCheck = 0; | ||||
| 82452 | continue; | ||||
| 82453 | } | ||||
| 82454 | pCell = &data[pc]; | ||||
| 82455 | pPage->xParseCell(pPage, pCell, &info); | ||||
| 82456 | if( pc+info.nSize>usableSize ){ | ||||
| 82457 | checkAppendMsg(pCheck, "Extends off end of page"); | ||||
| 82458 | doCoverageCheck = 0; | ||||
| 82459 | continue; | ||||
| 82460 | } | ||||
| 82461 | |||||
| 82462 | /* Check for integer primary key out of range */ | ||||
| 82463 | if( pPage->intKey ){ | ||||
| 82464 | if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){ | ||||
| 82465 | checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); | ||||
| 82466 | } | ||||
| 82467 | maxKey = info.nKey; | ||||
| 82468 | keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */ | ||||
| 82469 | } | ||||
| 82470 | |||||
| 82471 | /* Check the content overflow list */ | ||||
| 82472 | if( info.nPayload>info.nLocal ){ | ||||
| 82473 | u32 nPage; /* Number of pages on the overflow chain */ | ||||
| 82474 | Pgno pgnoOvfl; /* First page of the overflow chain */ | ||||
| 82475 | assert( pc + info.nSize - 4 <= usableSize )((void) (0)); | ||||
| 82476 | nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); | ||||
| 82477 | pgnoOvfl = get4bytesqlite3Get4byte(&pCell[info.nSize - 4]); | ||||
| 82478 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82479 | if( pBt->autoVacuum ){ | ||||
| 82480 | checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW13, iPage); | ||||
| 82481 | } | ||||
| 82482 | #endif | ||||
| 82483 | checkList(pCheck, 0, pgnoOvfl, nPage); | ||||
| 82484 | } | ||||
| 82485 | |||||
| 82486 | if( !pPage->leaf ){ | ||||
| 82487 | /* Check sanity of left child page for internal pages */ | ||||
| 82488 | pgno = get4bytesqlite3Get4byte(pCell); | ||||
| 82489 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82490 | if( pBt->autoVacuum ){ | ||||
| 82491 | checkPtrmap(pCheck, pgno, PTRMAP_BTREE5, iPage); | ||||
| 82492 | } | ||||
| 82493 | #endif | ||||
| 82494 | d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey); | ||||
| 82495 | keyCanBeEqual = 0; | ||||
| 82496 | if( d2!=depth ){ | ||||
| 82497 | checkAppendMsg(pCheck, "Child page depth differs"); | ||||
| 82498 | depth = d2; | ||||
| 82499 | } | ||||
| 82500 | }else{ | ||||
| 82501 | /* Populate the coverage-checking heap for leaf pages */ | ||||
| 82502 | btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); | ||||
| 82503 | } | ||||
| 82504 | } | ||||
| 82505 | *piMinKey = maxKey; | ||||
| 82506 | |||||
| 82507 | /* Check for complete coverage of the page | ||||
| 82508 | */ | ||||
| 82509 | pCheck->zPfx = 0; | ||||
| 82510 | if( doCoverageCheck && pCheck->mxErr>0 ){ | ||||
| 82511 | /* For leaf pages, the min-heap has already been initialized and the | ||||
| 82512 | ** cells have already been inserted. But for internal pages, that has | ||||
| 82513 | ** not yet been done, so do it now */ | ||||
| 82514 | if( !pPage->leaf ){ | ||||
| 82515 | heap = pCheck->heap; | ||||
| 82516 | heap[0] = 0; | ||||
| 82517 | for(i=nCell-1; i>=0; i--){ | ||||
| 82518 | u32 size; | ||||
| 82519 | pc = get2byteAligned(&data[cellStart+i*2])((&data[cellStart+i*2])[0]<<8 | (&data[cellStart +i*2])[1]); | ||||
| 82520 | size = pPage->xCellSize(pPage, &data[pc]); | ||||
| 82521 | btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); | ||||
| 82522 | } | ||||
| 82523 | } | ||||
| 82524 | assert( heap!=0 )((void) (0)); | ||||
| 82525 | /* Add the freeblocks to the min-heap | ||||
| 82526 | ** | ||||
| 82527 | ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header | ||||
| 82528 | ** is the offset of the first freeblock, or zero if there are no | ||||
| 82529 | ** freeblocks on the page. | ||||
| 82530 | */ | ||||
| 82531 | i = get2byte(&data[hdr+1])((&data[hdr+1])[0]<<8 | (&data[hdr+1])[1]); | ||||
| 82532 | while( i>0 ){ | ||||
| 82533 | int size, j; | ||||
| 82534 | assert( (u32)i<=usableSize-4 )((void) (0)); /* Enforced by btreeComputeFreeSpace() */ | ||||
| 82535 | size = get2byte(&data[i+2])((&data[i+2])[0]<<8 | (&data[i+2])[1]); | ||||
| 82536 | assert( (u32)(i+size)<=usableSize )((void) (0)); /* due to btreeComputeFreeSpace() */ | ||||
| 82537 | btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); | ||||
| 82538 | /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a | ||||
| 82539 | ** big-endian integer which is the offset in the b-tree page of the next | ||||
| 82540 | ** freeblock in the chain, or zero if the freeblock is the last on the | ||||
| 82541 | ** chain. */ | ||||
| 82542 | j = get2byte(&data[i])((&data[i])[0]<<8 | (&data[i])[1]); | ||||
| 82543 | /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of | ||||
| 82544 | ** increasing offset. */ | ||||
| 82545 | assert( j==0 || j>i+size )((void) (0)); /* Enforced by btreeComputeFreeSpace() */ | ||||
| 82546 | assert( (u32)j<=usableSize-4 )((void) (0)); /* Enforced by btreeComputeFreeSpace() */ | ||||
| 82547 | i = j; | ||||
| 82548 | } | ||||
| 82549 | /* Analyze the min-heap looking for overlap between cells and/or | ||||
| 82550 | ** freeblocks, and counting the number of untracked bytes in nFrag. | ||||
| 82551 | ** | ||||
| 82552 | ** Each min-heap entry is of the form: (start_address<<16)|end_address. | ||||
| 82553 | ** There is an implied first entry the covers the page header, the cell | ||||
| 82554 | ** pointer index, and the gap between the cell pointer index and the start | ||||
| 82555 | ** of cell content. | ||||
| 82556 | ** | ||||
| 82557 | ** The loop below pulls entries from the min-heap in order and compares | ||||
| 82558 | ** the start_address against the previous end_address. If there is an | ||||
| 82559 | ** overlap, that means bytes are used multiple times. If there is a gap, | ||||
| 82560 | ** that gap is added to the fragmentation count. | ||||
| 82561 | */ | ||||
| 82562 | nFrag = 0; | ||||
| 82563 | prev = contentOffset - 1; /* Implied first min-heap entry */ | ||||
| 82564 | while( btreeHeapPull(heap,&x) ){ | ||||
| 82565 | if( (prev&0xffff)>=(x>>16) ){ | ||||
| 82566 | checkAppendMsg(pCheck, | ||||
| 82567 | "Multiple uses for byte %u of page %u", x>>16, iPage); | ||||
| 82568 | break; | ||||
| 82569 | }else{ | ||||
| 82570 | nFrag += (x>>16) - (prev&0xffff) - 1; | ||||
| 82571 | prev = x; | ||||
| 82572 | } | ||||
| 82573 | } | ||||
| 82574 | nFrag += usableSize - (prev&0xffff) - 1; | ||||
| 82575 | /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments | ||||
| 82576 | ** is stored in the fifth field of the b-tree page header. | ||||
| 82577 | ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the | ||||
| 82578 | ** number of fragmented free bytes within the cell content area. | ||||
| 82579 | */ | ||||
| 82580 | if( heap[0]==0 && nFrag!=data[hdr+7] ){ | ||||
| 82581 | checkAppendMsg(pCheck, | ||||
| 82582 | "Fragmentation of %u bytes reported as %u on page %u", | ||||
| 82583 | nFrag, data[hdr+7], iPage); | ||||
| 82584 | } | ||||
| 82585 | } | ||||
| 82586 | |||||
| 82587 | end_of_check: | ||||
| 82588 | if( !doCoverageCheck ) pPage->isInit = savedIsInit; | ||||
| 82589 | releasePage(pPage); | ||||
| 82590 | pCheck->zPfx = saved_zPfx; | ||||
| 82591 | pCheck->v1 = saved_v1; | ||||
| 82592 | pCheck->v2 = saved_v2; | ||||
| 82593 | return depth+1; | ||||
| 82594 | } | ||||
| 82595 | #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | ||||
| 82596 | |||||
| 82597 | #ifndef SQLITE_OMIT_INTEGRITY_CHECK | ||||
| 82598 | /* | ||||
| 82599 | ** This routine does a complete check of the given BTree file. aRoot[] is | ||||
| 82600 | ** an array of pages numbers were each page number is the root page of | ||||
| 82601 | ** a table. nRoot is the number of entries in aRoot. | ||||
| 82602 | ** | ||||
| 82603 | ** A read-only or read-write transaction must be opened before calling | ||||
| 82604 | ** this function. | ||||
| 82605 | ** | ||||
| 82606 | ** Write the number of error seen in *pnErr. Except for some memory | ||||
| 82607 | ** allocation errors, an error message held in memory obtained from | ||||
| 82608 | ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is | ||||
| 82609 | ** returned. If a memory allocation error occurs, NULL is returned. | ||||
| 82610 | ** | ||||
| 82611 | ** If the first entry in aRoot[] is 0, that indicates that the list of | ||||
| 82612 | ** root pages is incomplete. This is a "partial integrity-check". This | ||||
| 82613 | ** happens when performing an integrity check on a single table. The | ||||
| 82614 | ** zero is skipped, of course. But in addition, the freelist checks | ||||
| 82615 | ** and the checks to make sure every page is referenced are also skipped, | ||||
| 82616 | ** since obviously it is not possible to know which pages are covered by | ||||
| 82617 | ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist | ||||
| 82618 | ** checks are still performed. | ||||
| 82619 | */ | ||||
| 82620 | SQLITE_PRIVATEstatic int sqlite3BtreeIntegrityCheck( | ||||
| 82621 | sqlite3 *db, /* Database connection that is running the check */ | ||||
| 82622 | Btree *p, /* The btree to be checked */ | ||||
| 82623 | Pgno *aRoot, /* An array of root pages numbers for individual trees */ | ||||
| 82624 | Mem *aCnt, /* Memory cells to write counts for each tree to */ | ||||
| 82625 | int nRoot, /* Number of entries in aRoot[] */ | ||||
| 82626 | int mxErr, /* Stop reporting errors after this many */ | ||||
| 82627 | int *pnErr, /* OUT: Write number of errors seen to this variable */ | ||||
| 82628 | char **pzOut /* OUT: Write the error message string here */ | ||||
| 82629 | ){ | ||||
| 82630 | Pgno i; | ||||
| 82631 | IntegrityCk sCheck; | ||||
| 82632 | BtShared *pBt = p->pBt; | ||||
| 82633 | u64 savedDbFlags = pBt->db->flags; | ||||
| 82634 | char zErr[100]; | ||||
| 82635 | int bPartial = 0; /* True if not checking all btrees */ | ||||
| 82636 | int bCkFreelist = 1; /* True to scan the freelist */ | ||||
| 82637 | VVA_ONLY( int nRef ); | ||||
| 82638 | |||||
| 82639 | assert( nRoot>0 )((void) (0)); | ||||
| 82640 | assert( aCnt!=0 )((void) (0)); | ||||
| 82641 | |||||
| 82642 | /* aRoot[0]==0 means this is a partial check */ | ||||
| 82643 | if( aRoot[0]==0 ){ | ||||
| 82644 | assert( nRoot>1 )((void) (0)); | ||||
| 82645 | bPartial = 1; | ||||
| 82646 | if( aRoot[1]!=1 ) bCkFreelist = 0; | ||||
| 82647 | } | ||||
| 82648 | |||||
| 82649 | sqlite3BtreeEnter(p); | ||||
| 82650 | assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE )((void) (0)); | ||||
| 82651 | VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); | ||||
| 82652 | assert( nRef>=0 )((void) (0)); | ||||
| 82653 | memset(&sCheck, 0, sizeof(sCheck)); | ||||
| 82654 | sCheck.db = db; | ||||
| 82655 | sCheck.pBt = pBt; | ||||
| 82656 | sCheck.pPager = pBt->pPager; | ||||
| 82657 | sCheck.nCkPage = btreePagecount(sCheck.pBt); | ||||
| 82658 | sCheck.mxErr = mxErr; | ||||
| 82659 | sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH2147483645); | ||||
| 82660 | sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL0x01; | ||||
| 82661 | if( sCheck.nCkPage==0 ){ | ||||
| 82662 | goto integrity_ck_cleanup; | ||||
| 82663 | } | ||||
| 82664 | |||||
| 82665 | sCheck.aPgRef = sqlite3MallocZero((sCheck.nCkPage / 8)+ 1); | ||||
| 82666 | if( !sCheck.aPgRef ){ | ||||
| 82667 | checkOom(&sCheck); | ||||
| 82668 | goto integrity_ck_cleanup; | ||||
| 82669 | } | ||||
| 82670 | sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); | ||||
| 82671 | if( sCheck.heap==0 ){ | ||||
| 82672 | checkOom(&sCheck); | ||||
| 82673 | goto integrity_ck_cleanup; | ||||
| 82674 | } | ||||
| 82675 | |||||
| 82676 | i = PENDING_BYTE_PAGE(pBt)((Pgno)((sqlite3PendingByte/((pBt)->pageSize))+1)); | ||||
| 82677 | if( i<=sCheck.nCkPage ) setPageReferenced(&sCheck, i); | ||||
| 82678 | |||||
| 82679 | /* Check the integrity of the freelist | ||||
| 82680 | */ | ||||
| 82681 | if( bCkFreelist ){ | ||||
| 82682 | sCheck.zPfx = "Freelist: "; | ||||
| 82683 | checkList(&sCheck, 1, get4bytesqlite3Get4byte(&pBt->pPage1->aData[32]), | ||||
| 82684 | get4bytesqlite3Get4byte(&pBt->pPage1->aData[36])); | ||||
| 82685 | sCheck.zPfx = 0; | ||||
| 82686 | } | ||||
| 82687 | |||||
| 82688 | /* Check all the tables. | ||||
| 82689 | */ | ||||
| 82690 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82691 | if( !bPartial ){ | ||||
| 82692 | if( pBt->autoVacuum ){ | ||||
| 82693 | Pgno mx = 0; | ||||
| 82694 | Pgno mxInHdr; | ||||
| 82695 | for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i]; | ||||
| 82696 | mxInHdr = get4bytesqlite3Get4byte(&pBt->pPage1->aData[52]); | ||||
| 82697 | if( mx!=mxInHdr ){ | ||||
| 82698 | checkAppendMsg(&sCheck, | ||||
| 82699 | "max rootpage (%u) disagrees with header (%u)", | ||||
| 82700 | mx, mxInHdr | ||||
| 82701 | ); | ||||
| 82702 | } | ||||
| 82703 | }else if( get4bytesqlite3Get4byte(&pBt->pPage1->aData[64])!=0 ){ | ||||
| 82704 | checkAppendMsg(&sCheck, | ||||
| 82705 | "incremental_vacuum enabled with a max rootpage of zero" | ||||
| 82706 | ); | ||||
| 82707 | } | ||||
| 82708 | } | ||||
| 82709 | #endif | ||||
| 82710 | testcase( pBt->db->flags & SQLITE_CellSizeCk ); | ||||
| 82711 | pBt->db->flags &= ~(u64)SQLITE_CellSizeCk0x00200000; | ||||
| 82712 | for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ | ||||
| 82713 | sCheck.nRow = 0; | ||||
| 82714 | if( aRoot[i] ){ | ||||
| 82715 | i64 notUsed; | ||||
| 82716 | #ifndef SQLITE_OMIT_AUTOVACUUM | ||||
| 82717 | if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){ | ||||
| 82718 | checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE1, 0); | ||||
| 82719 | } | ||||
| 82720 | #endif | ||||
| 82721 | sCheck.v0 = aRoot[i]; | ||||
| 82722 | checkTreePage(&sCheck, aRoot[i], ¬Used, LARGEST_INT64(0xffffffff|(((i64)0x7fffffff)<<32))); | ||||
| 82723 | } | ||||
| 82724 | sqlite3MemSetArrayInt64(aCnt, i, sCheck.nRow); | ||||
| 82725 | } | ||||
| 82726 | pBt->db->flags = savedDbFlags; | ||||
| 82727 | |||||
| 82728 | /* Make sure every page in the file is referenced | ||||
| 82729 | */ | ||||
| 82730 | if( !bPartial ){ | ||||
| 82731 | for(i=1; i<=sCheck.nCkPage && sCheck.mxErr; i++){ | ||||
| 82732 | #ifdef SQLITE_OMIT_AUTOVACUUM | ||||
| 82733 | if( getPageReferenced(&sCheck, i)==0 ){ | ||||
| 82734 | checkAppendMsg(&sCheck, "Page %u: never used", i); | ||||
| 82735 | } | ||||
| 82736 | #else | ||||
| 82737 | /* If the database supports auto-vacuum, make sure no tables contain | ||||
| 82738 | ** references to pointer-map pages. | ||||
| 82739 | */ | ||||
| 82740 | if( getPageReferenced(&sCheck, i)==0 && | ||||
| 82741 | (PTRMAP_PAGENO(pBt, i)ptrmapPageno(pBt, i)!=i || !pBt->autoVacuum) ){ | ||||
| 82742 | checkAppendMsg(&sCheck, "Page %u: never used", i); | ||||
| 82743 | } | ||||
| 82744 | if( getPageReferenced(&sCheck, i)!=0 && | ||||
| 82745 | (PTRMAP_PAGENO(pBt, i)ptrmapPageno(pBt, i)==i && pBt->autoVacuum) ){ | ||||
| 82746 | checkAppendMsg(&sCheck, "Page %u: pointer map referenced", i); | ||||
| 82747 | } | ||||
| 82748 | #endif | ||||
| 82749 | } | ||||
| 82750 | } | ||||
| 82751 | |||||
| 82752 | /* Clean up and report errors. | ||||
| 82753 | */ | ||||
| 82754 | integrity_ck_cleanup: | ||||
| 82755 | sqlite3PageFree(sCheck.heap); | ||||
| 82756 | sqlite3_free(sCheck.aPgRef); | ||||
| 82757 | *pnErr = sCheck.nErr; | ||||
| 82758 | if( sCheck.nErr==0 ){ | ||||
| 82759 | sqlite3_str_reset(&sCheck.errMsg); | ||||
| 82760 | *pzOut = 0; | ||||
| 82761 | }else{ | ||||
| 82762 | *pzOut = sqlite3StrAccumFinish(&sCheck.errMsg); | ||||
| 82763 | } | ||||
| 82764 | /* Make sure this analysis did not leave any unref() pages. */ | ||||
| 82765 | assert( nRef==sqlite3PagerRefcount(pBt->pPager) )((void) (0)); | ||||
| 82766 | sqlite3BtreeLeave(p); | ||||
| 82767 | return sCheck.rc; | ||||
| 82768 | } | ||||
| 82769 | #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | ||||
| 82770 | |||||
| 82771 | /* | ||||
| 82772 | ** Return the full pathname of the underlying database file. Return | ||||
| 82773 | ** an empty string if the database is in-memory or a TEMP database. | ||||
| 82774 | ** | ||||
| 82775 | ** The pager filename is invariant as long as the pager is | ||||
| 82776 | ** open so it is safe to access without the BtShared mutex. | ||||
| 82777 | */ | ||||
| 82778 | SQLITE_PRIVATEstatic const char *sqlite3BtreeGetFilename(Btree *p){ | ||||
| 82779 | assert( p->pBt->pPager!=0 )((void) (0)); | ||||
| 82780 | return sqlite3PagerFilename(p->pBt->pPager, 1); | ||||
| 82781 | } | ||||
| 82782 | |||||
| 82783 | /* | ||||
| 82784 | ** Return the pathname of the journal file for this database. The return | ||||
| 82785 | ** value of this routine is the same regardless of whether the journal file | ||||
| 82786 | ** has been created or not. | ||||
| 82787 | ** | ||||
| 82788 | ** The pager journal filename is invariant as long as the pager is | ||||
| 82789 | ** open so it is safe to access without the BtShared mutex. | ||||
| 82790 | */ | ||||
| 82791 | SQLITE_PRIVATEstatic const char *sqlite3BtreeGetJournalname(Btree *p){ | ||||
| 82792 | assert( p->pBt->pPager!=0 )((void) (0)); | ||||
| 82793 | return sqlite3PagerJournalname(p->pBt->pPager); | ||||
| 82794 | } | ||||
| 82795 | |||||
| 82796 | /* | ||||
| 82797 | ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE | ||||
| 82798 | ** to describe the current transaction state of Btree p. | ||||
| 82799 | */ | ||||
| 82800 | SQLITE_PRIVATEstatic int sqlite3BtreeTxnState(Btree *p){ | ||||
| 82801 | assert( p==0 || sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 82802 | return p ? p->inTrans : 0; | ||||
| 82803 | } | ||||
| 82804 | |||||
| 82805 | #ifndef SQLITE_OMIT_WAL | ||||
| 82806 | /* | ||||
| 82807 | ** Run a checkpoint on the Btree passed as the first argument. | ||||
| 82808 | ** | ||||
| 82809 | ** Return SQLITE_LOCKED if this or any other connection has an open | ||||
| 82810 | ** transaction on the shared-cache the argument Btree is connected to. | ||||
| 82811 | ** | ||||
| 82812 | ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. | ||||
| 82813 | */ | ||||
| 82814 | SQLITE_PRIVATEstatic int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ | ||||
| 82815 | int rc = SQLITE_OK0; | ||||
| 82816 | if( p ){ | ||||
| 82817 | BtShared *pBt = p->pBt; | ||||
| 82818 | sqlite3BtreeEnter(p); | ||||
| 82819 | if( pBt->inTransaction!=TRANS_NONE0 ){ | ||||
| 82820 | rc = SQLITE_LOCKED6; | ||||
| 82821 | }else{ | ||||
| 82822 | rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt); | ||||
| 82823 | } | ||||
| 82824 | sqlite3BtreeLeave(p); | ||||
| 82825 | } | ||||
| 82826 | return rc; | ||||
| 82827 | } | ||||
| 82828 | #endif | ||||
| 82829 | |||||
| 82830 | /* | ||||
| 82831 | ** Return true if there is currently a backup running on Btree p. | ||||
| 82832 | */ | ||||
| 82833 | SQLITE_PRIVATEstatic int sqlite3BtreeIsInBackup(Btree *p){ | ||||
| 82834 | assert( p )((void) (0)); | ||||
| 82835 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 82836 | return p->nBackup!=0; | ||||
| 82837 | } | ||||
| 82838 | |||||
| 82839 | /* | ||||
| 82840 | ** This function returns a pointer to a blob of memory associated with | ||||
| 82841 | ** a single shared-btree. The memory is used by client code for its own | ||||
| 82842 | ** purposes (for example, to store a high-level schema associated with | ||||
| 82843 | ** the shared-btree). The btree layer manages reference counting issues. | ||||
| 82844 | ** | ||||
| 82845 | ** The first time this is called on a shared-btree, nBytes bytes of memory | ||||
| 82846 | ** are allocated, zeroed, and returned to the caller. For each subsequent | ||||
| 82847 | ** call the nBytes parameter is ignored and a pointer to the same blob | ||||
| 82848 | ** of memory returned. | ||||
| 82849 | ** | ||||
| 82850 | ** If the nBytes parameter is 0 and the blob of memory has not yet been | ||||
| 82851 | ** allocated, a null pointer is returned. If the blob has already been | ||||
| 82852 | ** allocated, it is returned as normal. | ||||
| 82853 | ** | ||||
| 82854 | ** Just before the shared-btree is closed, the function passed as the | ||||
| 82855 | ** xFree argument when the memory allocation was made is invoked on the | ||||
| 82856 | ** blob of allocated memory. The xFree function should not call sqlite3_free() | ||||
| 82857 | ** on the memory, the btree layer does that. | ||||
| 82858 | */ | ||||
| 82859 | SQLITE_PRIVATEstatic void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ | ||||
| 82860 | BtShared *pBt = p->pBt; | ||||
| 82861 | assert( nBytes==0 || nBytes==sizeof(Schema) )((void) (0)); | ||||
| 82862 | sqlite3BtreeEnter(p); | ||||
| 82863 | if( !pBt->pSchema && nBytes ){ | ||||
| 82864 | pBt->pSchema = sqlite3DbMallocZero(0, nBytes); | ||||
| 82865 | pBt->xFreeSchema = xFree; | ||||
| 82866 | } | ||||
| 82867 | sqlite3BtreeLeave(p); | ||||
| 82868 | return pBt->pSchema; | ||||
| 82869 | } | ||||
| 82870 | |||||
| 82871 | /* | ||||
| 82872 | ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared | ||||
| 82873 | ** btree as the argument handle holds an exclusive lock on the | ||||
| 82874 | ** sqlite_schema table. Otherwise SQLITE_OK. | ||||
| 82875 | */ | ||||
| 82876 | SQLITE_PRIVATEstatic int sqlite3BtreeSchemaLocked(Btree *p){ | ||||
| 82877 | int rc; | ||||
| 82878 | assert( sqlite3_mutex_held(p->db->mutex) )((void) (0)); | ||||
| 82879 | sqlite3BtreeEnter(p); | ||||
| 82880 | rc = querySharedCacheTableLock(p, SCHEMA_ROOT1, READ_LOCK1); | ||||
| 82881 | assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE )((void) (0)); | ||||
| 82882 | sqlite3BtreeLeave(p); | ||||
| 82883 | return rc; | ||||
| 82884 | } | ||||
| 82885 | |||||
| 82886 | |||||
| 82887 | #ifndef SQLITE_OMIT_SHARED_CACHE | ||||
| 82888 | /* | ||||
| 82889 | ** Obtain a lock on the table whose root page is iTab. The | ||||
| 82890 | ** lock is a write lock if isWritelock is true or a read lock | ||||
| 82891 | ** if it is false. | ||||
| 82892 | */ | ||||
| 82893 | SQLITE_PRIVATEstatic int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ | ||||
| 82894 | int rc = SQLITE_OK0; | ||||
| 82895 | assert( p->inTrans!=TRANS_NONE )((void) (0)); | ||||
| 82896 | if( p->sharable ){ | ||||
| 82897 | u8 lockType = READ_LOCK1 + isWriteLock; | ||||
| 82898 | assert( READ_LOCK+1==WRITE_LOCK )((void) (0)); | ||||
| 82899 | assert( isWriteLock==0 || isWriteLock==1 )((void) (0)); | ||||
| 82900 | |||||
| 82901 | sqlite3BtreeEnter(p); | ||||
| 82902 | rc = querySharedCacheTableLock(p, iTab, lockType); | ||||
| 82903 | if( rc==SQLITE_OK0 ){ | ||||
| 82904 | rc = setSharedCacheTableLock(p, iTab, lockType); | ||||
| 82905 | } | ||||
| 82906 | sqlite3BtreeLeave(p); | ||||
| 82907 | } | ||||
| 82908 | return rc; | ||||
| 82909 | } | ||||
| 82910 | #endif | ||||
| 82911 | |||||
| 82912 | #ifndef SQLITE_OMIT_INCRBLOB | ||||
| 82913 | /* | ||||
| 82914 | ** Argument pCsr must be a cursor opened for writing on an | ||||
| 82915 | ** INTKEY table currently pointing at a valid table entry. | ||||
| 82916 | ** This function modifies the data stored as part of that entry. | ||||
| 82917 | ** | ||||
| 82918 | ** Only the data content may only be modified, it is not possible to | ||||
| 82919 | ** change the length of the data stored. If this function is called with | ||||
| 82920 | ** parameters that attempt to write past the end of the existing data, | ||||
| 82921 | ** no modifications are made and SQLITE_CORRUPT is returned. | ||||
| 82922 | */ | ||||
| 82923 | SQLITE_PRIVATEstatic int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ | ||||
| 82924 | int rc; | ||||
| 82925 | assert( cursorOwnsBtShared(pCsr) )((void) (0)); | ||||
| 82926 | assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) )((void) (0)); | ||||
| 82927 | assert( pCsr->curFlags & BTCF_Incrblob )((void) (0)); | ||||
| 82928 | |||||
| 82929 | rc = restoreCursorPosition(pCsr)(pCsr->eState>=3 ? btreeRestoreCursorPosition(pCsr) : 0 ); | ||||
| 82930 | if( rc!=SQLITE_OK0 ){ | ||||
| 82931 | return rc; | ||||
| 82932 | } | ||||
| 82933 | assert( pCsr->eState!=CURSOR_REQUIRESEEK )((void) (0)); | ||||
| 82934 | if( pCsr->eState!=CURSOR_VALID0 ){ | ||||
| 82935 | return SQLITE_ABORT4; | ||||
| 82936 | } | ||||
| 82937 | |||||
| 82938 | /* Save the positions of all other cursors open on this table. This is | ||||
| 82939 | ** required in case any of them are holding references to an xFetch | ||||
| 82940 | ** version of the b-tree page modified by the accessPayload call below. | ||||
| 82941 | ** | ||||
| 82942 | ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() | ||||
| 82943 | ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence | ||||
| 82944 | ** saveAllCursors can only return SQLITE_OK. | ||||
| 82945 | */ | ||||
| 82946 | VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); | ||||
| 82947 | assert( rc==SQLITE_OK )((void) (0)); | ||||
| 82948 | |||||
| 82949 | /* Check some assumptions: | ||||
| 82950 | ** (a) the cursor is open for writing, | ||||
| 82951 | ** (b) there is a read/write transaction open, | ||||
| 82952 | ** (c) the connection holds a write-lock on the table (if required), | ||||
| 82953 | ** (d) there are no conflicting read-locks, and | ||||
| 82954 | ** (e) the cursor points at a valid row of an intKey table. | ||||
| 82955 | */ | ||||
| 82956 | if( (pCsr->curFlags & BTCF_WriteFlag0x01)==0 ){ | ||||
| 82957 | return SQLITE_READONLY8; | ||||
| 82958 | } | ||||
| 82959 | assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0((void) (0)) | ||||
| 82960 | && pCsr->pBt->inTransaction==TRANS_WRITE )((void) (0)); | ||||
| 82961 | assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) )((void) (0)); | ||||
| 82962 | assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) )((void) (0)); | ||||
| 82963 | assert( pCsr->pPage->intKey )((void) (0)); | ||||
| 82964 | |||||
| 82965 | return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); | ||||
| 82966 | } | ||||
| 82967 | |||||
| 82968 | /* | ||||
| 82969 | ** Mark this cursor as an incremental blob cursor. | ||||
| 82970 | */ | ||||
| 82971 | SQLITE_PRIVATEstatic void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ | ||||
| 82972 | pCur->curFlags |= BTCF_Incrblob0x10; | ||||
| 82973 | pCur->pBtree->hasIncrblobCur = 1; | ||||
| 82974 | } | ||||
| 82975 | #endif | ||||
| 82976 | |||||
| 82977 | /* | ||||
| 82978 | ** Set both the "read version" (single byte at byte offset 18) and | ||||
| 82979 | ** "write version" (single byte at byte offset 19) fields in the database | ||||
| 82980 | ** header to iVersion. | ||||
| 82981 | */ | ||||
| 82982 | SQLITE_PRIVATEstatic int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ | ||||
| 82983 | BtShared *pBt = pBtree->pBt; | ||||
| 82984 | int rc; /* Return code */ | ||||
| 82985 | |||||
| 82986 | assert( iVersion==1 || iVersion==2 )((void) (0)); | ||||
| 82987 | |||||
| 82988 | /* If setting the version fields to 1, do not automatically open the | ||||
| 82989 | ** WAL connection, even if the version fields are currently set to 2. | ||||
| 82990 | */ | ||||
| 82991 | pBt->btsFlags &= ~BTS_NO_WAL0x0020; | ||||
| 82992 | if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL0x0020; | ||||
| 82993 | |||||
| 82994 | rc = sqlite3BtreeBeginTrans(pBtree, 0, 0); | ||||
| 82995 | if( rc==SQLITE_OK0 ){ | ||||
| 82996 | u8 *aData = pBt->pPage1->aData; | ||||
| 82997 | if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ | ||||
| 82998 | rc = sqlite3BtreeBeginTrans(pBtree, 2, 0); | ||||
| 82999 | if( rc==SQLITE_OK0 ){ | ||||
| 83000 | rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | ||||
| 83001 | if( rc==SQLITE_OK0 ){ | ||||
| 83002 | aData[18] = (u8)iVersion; | ||||
| 83003 | aData[19] = (u8)iVersion; | ||||
| 83004 | } | ||||
| 83005 | } | ||||
| 83006 | } | ||||
| 83007 | } | ||||
| 83008 | |||||
| 83009 | pBt->btsFlags &= ~BTS_NO_WAL0x0020; | ||||
| 83010 | return rc; | ||||
| 83011 | } | ||||
| 83012 | |||||
| 83013 | /* | ||||
| 83014 | ** Return true if the cursor has a hint specified. This routine is | ||||
| 83015 | ** only used from within assert() statements | ||||
| 83016 | */ | ||||
| 83017 | SQLITE_PRIVATEstatic int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ | ||||
| 83018 | return (pCsr->hints & mask)!=0; | ||||
| 83019 | } | ||||
| 83020 | |||||
| 83021 | /* | ||||
| 83022 | ** Return true if the given Btree is read-only. | ||||
| 83023 | */ | ||||
| 83024 | SQLITE_PRIVATEstatic int sqlite3BtreeIsReadonly(Btree *p){ | ||||
| 83025 | return (p->pBt->btsFlags & BTS_READ_ONLY0x0001)!=0; | ||||
| 83026 | } | ||||
| 83027 | |||||
| 83028 | /* | ||||
| 83029 | ** Return the size of the header added to each page by this module. | ||||
| 83030 | */ | ||||
| 83031 | SQLITE_PRIVATEstatic int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage))(((sizeof(MemPage))+7)&~7); } | ||||
| 83032 | |||||
| 83033 | /* | ||||
| 83034 | ** If no transaction is active and the database is not a temp-db, clear | ||||
| 83035 | ** the in-memory pager cache. | ||||
| 83036 | */ | ||||
| 83037 | SQLITE_PRIVATEstatic void sqlite3BtreeClearCache(Btree *p){ | ||||
| 83038 | BtShared *pBt = p->pBt; | ||||
| 83039 | if( pBt->inTransaction==TRANS_NONE0 ){ | ||||
| 83040 | sqlite3PagerClearCache(pBt->pPager); | ||||
| 83041 | } | ||||
| 83042 | } | ||||
| 83043 | |||||
| 83044 | #if !defined(SQLITE_OMIT_SHARED_CACHE) | ||||
| 83045 | /* | ||||
| 83046 | ** Return true if the Btree passed as the only argument is sharable. | ||||
| 83047 | */ | ||||
| 83048 | SQLITE_PRIVATEstatic int sqlite3BtreeSharable(Btree *p){ | ||||
| 83049 | return p->sharable; | ||||
| 83050 | } | ||||
| 83051 | |||||
| 83052 | /* | ||||
| 83053 | ** Return the number of connections to the BtShared object accessed by | ||||
| 83054 | ** the Btree handle passed as the only argument. For private caches | ||||
| 83055 | ** this is always 1. For shared caches it may be 1 or greater. | ||||
| 83056 | */ | ||||
| 83057 | SQLITE_PRIVATEstatic int sqlite3BtreeConnectionCount(Btree *p){ | ||||
| 83058 | testcase( p->sharable ); | ||||
| 83059 | return p->pBt->nRef; | ||||
| 83060 | } | ||||
| 83061 | #endif | ||||
| 83062 | |||||
| 83063 | /************** End of btree.c ***********************************************/ | ||||
| 83064 | /************** Begin file backup.c ******************************************/ | ||||
| 83065 | /* | ||||
| 83066 | ** 2009 January 28 | ||||
| 83067 | ** | ||||
| 83068 | ** The author disclaims copyright to this source code. In place of | ||||
| 83069 | ** a legal notice, here is a blessing: | ||||
| 83070 | ** | ||||
| 83071 | ** May you do good and not evil. | ||||
| 83072 | ** May you find forgiveness for yourself and forgive others. | ||||
| 83073 | ** May you share freely, never taking more than you give. | ||||
| 83074 | ** | ||||
| 83075 | ************************************************************************* | ||||
| 83076 | ** This file contains the implementation of the sqlite3_backup_XXX() | ||||
| 83077 | ** API functions and the related features. | ||||
| 83078 | */ | ||||
| 83079 | /* #include "sqliteInt.h" */ | ||||
| 83080 | /* #include "btreeInt.h" */ | ||||
| 83081 | |||||
| 83082 | /* | ||||
| 83083 | ** Structure allocated for each backup operation. | ||||
| 83084 | */ | ||||
| 83085 | struct sqlite3_backup { | ||||
| 83086 | sqlite3* pDestDb; /* Destination database handle */ | ||||
| 83087 | Btree *pDest; /* Destination b-tree file */ | ||||
| 83088 | u32 iDestSchema; /* Original schema cookie in destination */ | ||||
| 83089 | int bDestLocked; /* True once a write-transaction is open on pDest */ | ||||
| 83090 | |||||
| 83091 | Pgno iNext; /* Page number of the next source page to copy */ | ||||
| 83092 | sqlite3* pSrcDb; /* Source database handle */ | ||||
| 83093 | Btree *pSrc; /* Source b-tree file */ | ||||
| 83094 | |||||
| 83095 | int rc; /* Backup process error code */ | ||||
| 83096 | |||||
| 83097 | /* These two variables are set by every call to backup_step(). They are | ||||
| 83098 | ** read by calls to backup_remaining() and backup_pagecount(). | ||||
| 83099 | */ | ||||
| 83100 | Pgno nRemaining; /* Number of pages left to copy */ | ||||
| 83101 | Pgno nPagecount; /* Total number of pages to copy */ | ||||
| 83102 | |||||
| 83103 | int isAttached; /* True once backup has been registered with pager */ | ||||
| 83104 | sqlite3_backup *pNext; /* Next backup associated with source pager */ | ||||
| 83105 | }; | ||||
| 83106 | |||||
| 83107 | /* | ||||
| 83108 | ** THREAD SAFETY NOTES: | ||||
| 83109 | ** | ||||
| 83110 | ** Once it has been created using backup_init(), a single sqlite3_backup | ||||
| 83111 | ** structure may be accessed via two groups of thread-safe entry points: | ||||
| 83112 | ** | ||||
| 83113 | ** * Via the sqlite3_backup_XXX() API function backup_step() and | ||||
| 83114 | ** backup_finish(). Both these functions obtain the source database | ||||
| 83115 | ** handle mutex and the mutex associated with the source BtShared | ||||
| 83116 | ** structure, in that order. | ||||
| 83117 | ** | ||||
| 83118 | ** * Via the BackupUpdate() and BackupRestart() functions, which are | ||||
| 83119 | ** invoked by the pager layer to report various state changes in | ||||
| 83120 | ** the page cache associated with the source database. The mutex | ||||
| 83121 | ** associated with the source database BtShared structure will always | ||||
| 83122 | ** be held when either of these functions are invoked. | ||||
| 83123 | ** | ||||
| 83124 | ** The other sqlite3_backup_XXX() API functions, backup_remaining() and | ||||
| 83125 | ** backup_pagecount() are not thread-safe functions. If they are called | ||||
| 83126 | ** while some other thread is calling backup_step() or backup_finish(), | ||||
| 83127 | ** the values returned may be invalid. There is no way for a call to | ||||
| 83128 | ** BackupUpdate() or BackupRestart() to interfere with backup_remaining() | ||||
| 83129 | ** or backup_pagecount(). | ||||
| 83130 | ** | ||||
| 83131 | ** Depending on the SQLite configuration, the database handles and/or | ||||
| 83132 | ** the Btree objects may have their own mutexes that require locking. | ||||
| 83133 | ** Non-sharable Btrees (in-memory databases for example), do not have | ||||
| 83134 | ** associated mutexes. | ||||
| 83135 | */ | ||||
| 83136 | |||||
| 83137 | /* | ||||
| 83138 | ** Return a pointer corresponding to database zDb (i.e. "main", "temp") | ||||
| 83139 | ** in connection handle pDb. If such a database cannot be found, return | ||||
| 83140 | ** a NULL pointer and write an error message to pErrorDb. | ||||
| 83141 | ** | ||||
| 83142 | ** If the "temp" database is requested, it may need to be opened by this | ||||
| 83143 | ** function. If an error occurs while doing so, return 0 and write an | ||||
| 83144 | ** error message to pErrorDb. | ||||
| 83145 | */ | ||||
| 83146 | static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ | ||||
| 83147 | int i = sqlite3FindDbName(pDb, zDb); | ||||
| 83148 | |||||
| 83149 | if( i==1 ){ | ||||
| 83150 | Parse sParse; | ||||
| 83151 | int rc = 0; | ||||
| 83152 | sqlite3ParseObjectInit(&sParse,pDb); | ||||
| 83153 | if( sqlite3OpenTempDatabase(&sParse) ){ | ||||
| 83154 | sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg); | ||||
| 83155 | rc = SQLITE_ERROR1; | ||||
| 83156 | } | ||||
| 83157 | sqlite3DbFree(pErrorDb, sParse.zErrMsg); | ||||
| 83158 | sqlite3ParseObjectReset(&sParse); | ||||
| 83159 | if( rc ){ | ||||
| 83160 | return 0; | ||||
| 83161 | } | ||||
| 83162 | } | ||||
| 83163 | |||||
| 83164 | if( i<0 ){ | ||||
| 83165 | sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR1, "unknown database %s", zDb); | ||||
| 83166 | return 0; | ||||
| 83167 | } | ||||
| 83168 | |||||
| 83169 | return pDb->aDb[i].pBt; | ||||
| 83170 | } | ||||
| 83171 | |||||
| 83172 | /* | ||||
| 83173 | ** Attempt to set the page size of the destination to match the page size | ||||
| 83174 | ** of the source. | ||||
| 83175 | */ | ||||
| 83176 | static int setDestPgsz(sqlite3_backup *p){ | ||||
| 83177 | int rc; | ||||
| 83178 | rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0); | ||||
| 83179 | return rc; | ||||
| 83180 | } | ||||
| 83181 | |||||
| 83182 | /* | ||||
| 83183 | ** Check that there is no open read-transaction on the b-tree passed as the | ||||
| 83184 | ** second argument. If there is not, return SQLITE_OK. Otherwise, if there | ||||
| 83185 | ** is an open read-transaction, return SQLITE_ERROR and leave an error | ||||
| 83186 | ** message in database handle db. | ||||
| 83187 | */ | ||||
| 83188 | static int checkReadTransaction(sqlite3 *db, Btree *p){ | ||||
| 83189 | if( sqlite3BtreeTxnState(p)!=SQLITE_TXN_NONE0 ){ | ||||
| 83190 | sqlite3ErrorWithMsg(db, SQLITE_ERROR1, "destination database is in use"); | ||||
| 83191 | return SQLITE_ERROR1; | ||||
| 83192 | } | ||||
| 83193 | return SQLITE_OK0; | ||||
| 83194 | } | ||||
| 83195 | |||||
| 83196 | /* | ||||
| 83197 | ** Create an sqlite3_backup process to copy the contents of zSrcDb from | ||||
| 83198 | ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return | ||||
| 83199 | ** a pointer to the new sqlite3_backup object. | ||||
| 83200 | ** | ||||
| 83201 | ** If an error occurs, NULL is returned and an error code and error message | ||||
| 83202 | ** stored in database handle pDestDb. | ||||
| 83203 | */ | ||||
| 83204 | SQLITE_API sqlite3_backup *sqlite3_backup_init( | ||||
| 83205 | sqlite3* pDestDb, /* Database to write to */ | ||||
| 83206 | const char *zDestDb, /* Name of database within pDestDb */ | ||||
| 83207 | sqlite3* pSrcDb, /* Database connection to read from */ | ||||
| 83208 | const char *zSrcDb /* Name of database within pSrcDb */ | ||||
| 83209 | ){ | ||||
| 83210 | sqlite3_backup *p; /* Value to return */ | ||||
| 83211 | |||||
| 83212 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 83213 | if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){ | ||||
| 83214 | (void)SQLITE_MISUSE_BKPTsqlite3MisuseError(83214); | ||||
| 83215 | return 0; | ||||
| 83216 | } | ||||
| 83217 | #endif | ||||
| 83218 | |||||
| 83219 | /* Lock the source database handle. The destination database | ||||
| 83220 | ** handle is not locked in this routine, but it is locked in | ||||
| 83221 | ** sqlite3_backup_step(). The user is required to ensure that no | ||||
| 83222 | ** other thread accesses the destination handle for the duration | ||||
| 83223 | ** of the backup operation. Any attempt to use the destination | ||||
| 83224 | ** database connection while a backup is in progress may cause | ||||
| 83225 | ** a malfunction or a deadlock. | ||||
| 83226 | */ | ||||
| 83227 | sqlite3_mutex_enter(pSrcDb->mutex); | ||||
| 83228 | sqlite3_mutex_enter(pDestDb->mutex); | ||||
| 83229 | |||||
| 83230 | if( pSrcDb==pDestDb ){ | ||||
| 83231 | sqlite3ErrorWithMsg( | ||||
| 83232 | pDestDb, SQLITE_ERROR1, "source and destination must be distinct" | ||||
| 83233 | ); | ||||
| 83234 | p = 0; | ||||
| 83235 | }else { | ||||
| 83236 | /* Allocate space for a new sqlite3_backup object... | ||||
| 83237 | ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a | ||||
| 83238 | ** call to sqlite3_backup_init() and is destroyed by a call to | ||||
| 83239 | ** sqlite3_backup_finish(). */ | ||||
| 83240 | p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); | ||||
| 83241 | if( !p ){ | ||||
| 83242 | sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT7); | ||||
| 83243 | } | ||||
| 83244 | } | ||||
| 83245 | |||||
| 83246 | /* If the allocation succeeded, populate the new object. */ | ||||
| 83247 | if( p ){ | ||||
| 83248 | p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); | ||||
| 83249 | p->pDest = findBtree(pDestDb, pDestDb, zDestDb); | ||||
| 83250 | p->pDestDb = pDestDb; | ||||
| 83251 | p->pSrcDb = pSrcDb; | ||||
| 83252 | p->iNext = 1; | ||||
| 83253 | p->isAttached = 0; | ||||
| 83254 | |||||
| 83255 | if( 0==p->pSrc || 0==p->pDest | ||||
| 83256 | || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK0 | ||||
| 83257 | ){ | ||||
| 83258 | /* One (or both) of the named databases did not exist or an OOM | ||||
| 83259 | ** error was hit. Or there is a transaction open on the destination | ||||
| 83260 | ** database. The error has already been written into the pDestDb | ||||
| 83261 | ** handle. All that is left to do here is free the sqlite3_backup | ||||
| 83262 | ** structure. */ | ||||
| 83263 | sqlite3_free(p); | ||||
| 83264 | p = 0; | ||||
| 83265 | } | ||||
| 83266 | } | ||||
| 83267 | if( p ){ | ||||
| 83268 | p->pSrc->nBackup++; | ||||
| 83269 | } | ||||
| 83270 | |||||
| 83271 | sqlite3_mutex_leave(pDestDb->mutex); | ||||
| 83272 | sqlite3_mutex_leave(pSrcDb->mutex); | ||||
| 83273 | return p; | ||||
| 83274 | } | ||||
| 83275 | |||||
| 83276 | /* | ||||
| 83277 | ** Argument rc is an SQLite error code. Return true if this error is | ||||
| 83278 | ** considered fatal if encountered during a backup operation. All errors | ||||
| 83279 | ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. | ||||
| 83280 | */ | ||||
| 83281 | static int isFatalError(int rc){ | ||||
| 83282 | return (rc!=SQLITE_OK0 && rc!=SQLITE_BUSY5 && ALWAYS(rc!=SQLITE_LOCKED)(rc!=6)); | ||||
| 83283 | } | ||||
| 83284 | |||||
| 83285 | /* | ||||
| 83286 | ** Parameter zSrcData points to a buffer containing the data for | ||||
| 83287 | ** page iSrcPg from the source database. Copy this data into the | ||||
| 83288 | ** destination database. | ||||
| 83289 | */ | ||||
| 83290 | static int backupOnePage( | ||||
| 83291 | sqlite3_backup *p, /* Backup handle */ | ||||
| 83292 | Pgno iSrcPg, /* Source database page to backup */ | ||||
| 83293 | const u8 *zSrcData, /* Source database page data */ | ||||
| 83294 | int bUpdate /* True for an update, false otherwise */ | ||||
| 83295 | ){ | ||||
| 83296 | Pager * const pDestPager = sqlite3BtreePager(p->pDest); | ||||
| 83297 | const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc); | ||||
| 83298 | int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest); | ||||
| 83299 | const int nCopy = MIN(nSrcPgsz, nDestPgsz)((nSrcPgsz)<(nDestPgsz)?(nSrcPgsz):(nDestPgsz)); | ||||
| 83300 | const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz; | ||||
| 83301 | int rc = SQLITE_OK0; | ||||
| 83302 | i64 iOff; | ||||
| 83303 | |||||
| 83304 | assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 )((void) (0)); | ||||
| 83305 | assert( p->bDestLocked )((void) (0)); | ||||
| 83306 | assert( !isFatalError(p->rc) )((void) (0)); | ||||
| 83307 | assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) )((void) (0)); | ||||
| 83308 | assert( zSrcData )((void) (0)); | ||||
| 83309 | assert( nSrcPgsz==nDestPgsz || sqlite3PagerIsMemdb(pDestPager)==0 )((void) (0)); | ||||
| 83310 | |||||
| 83311 | /* This loop runs once for each destination page spanned by the source | ||||
| 83312 | ** page. For each iteration, variable iOff is set to the byte offset | ||||
| 83313 | ** of the destination page. | ||||
| 83314 | */ | ||||
| 83315 | for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK0 && iOff<iEnd; iOff+=nDestPgsz){ | ||||
| 83316 | DbPage *pDestPg = 0; | ||||
| 83317 | Pgno iDest = (Pgno)(iOff/nDestPgsz)+1; | ||||
| 83318 | if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt)((Pgno)((sqlite3PendingByte/((p->pDest->pBt)->pageSize ))+1)) ) continue; | ||||
| 83319 | if( SQLITE_OK0==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0)) | ||||
| 83320 | && SQLITE_OK0==(rc = sqlite3PagerWrite(pDestPg)) | ||||
| 83321 | ){ | ||||
| 83322 | const u8 *zIn = &zSrcData[iOff%nSrcPgsz]; | ||||
| 83323 | u8 *zDestData = sqlite3PagerGetData(pDestPg); | ||||
| 83324 | u8 *zOut = &zDestData[iOff%nDestPgsz]; | ||||
| 83325 | |||||
| 83326 | /* Copy the data from the source page into the destination page. | ||||
| 83327 | ** Then clear the Btree layer MemPage.isInit flag. Both this module | ||||
| 83328 | ** and the pager code use this trick (clearing the first byte | ||||
| 83329 | ** of the page 'extra' space to invalidate the Btree layers | ||||
| 83330 | ** cached parse of the page). MemPage.isInit is marked | ||||
| 83331 | ** "MUST BE FIRST" for this purpose. | ||||
| 83332 | */ | ||||
| 83333 | memcpy(zOut, zIn, nCopy); | ||||
| 83334 | ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; | ||||
| 83335 | if( iOff==0 && bUpdate==0 ){ | ||||
| 83336 | sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); | ||||
| 83337 | } | ||||
| 83338 | } | ||||
| 83339 | sqlite3PagerUnref(pDestPg); | ||||
| 83340 | } | ||||
| 83341 | |||||
| 83342 | return rc; | ||||
| 83343 | } | ||||
| 83344 | |||||
| 83345 | /* | ||||
| 83346 | ** If pFile is currently larger than iSize bytes, then truncate it to | ||||
| 83347 | ** exactly iSize bytes. If pFile is not larger than iSize bytes, then | ||||
| 83348 | ** this function is a no-op. | ||||
| 83349 | ** | ||||
| 83350 | ** Return SQLITE_OK if everything is successful, or an SQLite error | ||||
| 83351 | ** code if an error occurs. | ||||
| 83352 | */ | ||||
| 83353 | static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ | ||||
| 83354 | i64 iCurrent; | ||||
| 83355 | int rc = sqlite3OsFileSize(pFile, &iCurrent); | ||||
| 83356 | if( rc==SQLITE_OK0 && iCurrent>iSize ){ | ||||
| 83357 | rc = sqlite3OsTruncate(pFile, iSize); | ||||
| 83358 | } | ||||
| 83359 | return rc; | ||||
| 83360 | } | ||||
| 83361 | |||||
| 83362 | /* | ||||
| 83363 | ** Register this backup object with the associated source pager for | ||||
| 83364 | ** callbacks when pages are changed or the cache invalidated. | ||||
| 83365 | */ | ||||
| 83366 | static void attachBackupObject(sqlite3_backup *p){ | ||||
| 83367 | sqlite3_backup **pp; | ||||
| 83368 | assert( sqlite3BtreeHoldsMutex(p->pSrc) )((void) (0)); | ||||
| 83369 | pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); | ||||
| 83370 | p->pNext = *pp; | ||||
| 83371 | *pp = p; | ||||
| 83372 | p->isAttached = 1; | ||||
| 83373 | } | ||||
| 83374 | |||||
| 83375 | /* | ||||
| 83376 | ** Copy nPage pages from the source b-tree to the destination. | ||||
| 83377 | */ | ||||
| 83378 | SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ | ||||
| 83379 | int rc; | ||||
| 83380 | int destMode; /* Destination journal mode */ | ||||
| 83381 | int pgszSrc = 0; /* Source page size */ | ||||
| 83382 | int pgszDest = 0; /* Destination page size */ | ||||
| 83383 | |||||
| 83384 | #ifdef SQLITE_ENABLE_API_ARMOR1 | ||||
| 83385 | if( p
| ||||
| 83386 | #endif | ||||
| 83387 | sqlite3_mutex_enter(p->pSrcDb->mutex); | ||||
| 83388 | sqlite3BtreeEnter(p->pSrc); | ||||
| 83389 | if( p->pDestDb
| ||||
| 83390 | sqlite3_mutex_enter(p->pDestDb->mutex); | ||||
| 83391 | } | ||||
| 83392 | |||||
| 83393 | rc = p->rc; | ||||
| 83394 | if( !isFatalError(rc) ){ | ||||
| 83395 | Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ | ||||
| 83396 | Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ | ||||
| 83397 | int ii; /* Iterator variable */ | ||||
| 83398 | int nSrcPage = -1; /* Size of source db in pages */ | ||||
| 83399 | int bCloseTrans = 0; /* True if src db requires unlocking */ | ||||
| 83400 | |||||
| 83401 | /* If the source pager is currently in a write-transaction, return | ||||
| 83402 | ** SQLITE_BUSY immediately. | ||||
| 83403 | */ | ||||
| 83404 | if( p->pDestDb
| ||||
| 83405 | rc = SQLITE_BUSY5; | ||||
| 83406 | }else{ | ||||
| 83407 | rc = SQLITE_OK0; | ||||
| 83408 | } | ||||
| 83409 | |||||
| 83410 | /* If there is no open read-transaction on the source database, open | ||||
| 83411 | ** one now. If a transaction is opened here, then it will be closed | ||||
| 83412 | ** before this function exits. | ||||
| 83413 | */ | ||||
| 83414 | if( rc
| ||||
| 83415 | rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0); | ||||
| 83416 | bCloseTrans = 1; | ||||
| 83417 | } | ||||
| 83418 | |||||
| 83419 | /* If the destination database has not yet been locked (i.e. if this | ||||
| 83420 | ** is the first call to backup_step() for the current backup operation), | ||||
| 83421 | ** try to set its page size to the same as the source database. This | ||||
| 83422 | ** is especially important on ZipVFS systems, as in that case it is | ||||
| 83423 | ** not possible to create a database file that uses one page size by | ||||
| 83424 | ** writing to it with another. */ | ||||
| 83425 | if( p->bDestLocked
| ||||
| 83426 | rc = SQLITE_NOMEM7; | ||||
| 83427 | } | ||||
| 83428 | |||||
| 83429 | /* Lock the destination database, if it is not locked already. */ | ||||
| 83430 | if( SQLITE_OK0==rc
| ||||
| 83431 | && SQLITE_OK0==(rc = sqlite3BtreeBeginTrans(p->pDest, 2, | ||||
| 83432 | (int*)&p->iDestSchema)) | ||||
| 83433 | ){ | ||||
| 83434 | p->bDestLocked = 1; | ||||
| 83435 | } | ||||
| 83436 | |||||
| 83437 | /* Do not allow backup if the destination database is in WAL mode | ||||
| 83438 | ** and the page sizes are different between source and destination */ | ||||
| 83439 | pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); | ||||
| 83440 | pgszDest = sqlite3BtreeGetPageSize(p->pDest); | ||||
| 83441 | destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); | ||||
| 83442 | if( SQLITE_OK0==rc |
9.1 | 'rc' is equal to SQLITE_OK |
11.1 | 'nPage' is >= 0 |
11.2 | 'ii' is < 'nPage' |
12.1 | 'rc' is equal to SQLITE_OK |
13.1 | 'nSrcPage' is < field 'iNext' |
14.1 | 'rc' is equal to SQLITE_DONE |
15.1 | 'nSrcPage' is equal to 0 |
16.1 | 'rc' is equal to SQLITE_OK |
16.2 | 'rc' is equal to SQLITE_OK |
17.1 | Field 'pDestDb' is null |
18.1 | 'destMode' is not equal to PAGER_JOURNALMODE_WAL |
19.1 | 'rc' is equal to SQLITE_OK |
24.1 | 'pgszSrc' is < 'pgszDest' |
25.1 | 'rc' is equal to SQLITE_OK |
27.1 | 'rc' is equal to SQLITE_OK |
1 | Assuming field 'pMethods' is null |