/db/sqlite3/src/sqlite3.c

http://github.com/zpao/v8monkey · C · 26292 lines · 13021 code · 1482 blank · 11789 comment · 1247 complexity · 5a0bcd447240768779afd76ca74478d0 MD5 · raw file

  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.7.10. 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. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. #ifndef SQLITE_API
  26. # define SQLITE_API
  27. #endif
  28. /************** Begin file sqliteInt.h ***************************************/
  29. /*
  30. ** 2001 September 15
  31. **
  32. ** The author disclaims copyright to this source code. In place of
  33. ** a legal notice, here is a blessing:
  34. **
  35. ** May you do good and not evil.
  36. ** May you find forgiveness for yourself and forgive others.
  37. ** May you share freely, never taking more than you give.
  38. **
  39. *************************************************************************
  40. ** Internal interface definitions for SQLite.
  41. **
  42. */
  43. #ifndef _SQLITEINT_H_
  44. #define _SQLITEINT_H_
  45. /*
  46. ** These #defines should enable >2GB file support on POSIX if the
  47. ** underlying operating system supports it. If the OS lacks
  48. ** large file support, or if the OS is windows, these should be no-ops.
  49. **
  50. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  51. ** system #includes. Hence, this block of code must be the very first
  52. ** code in all source files.
  53. **
  54. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  55. ** on the compiler command line. This is necessary if you are compiling
  56. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  57. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  58. ** without this option, LFS is enable. But LFS does not exist in the kernel
  59. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  60. ** portability you should omit LFS.
  61. **
  62. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  63. */
  64. #ifndef SQLITE_DISABLE_LFS
  65. # define _LARGE_FILE 1
  66. # ifndef _FILE_OFFSET_BITS
  67. # define _FILE_OFFSET_BITS 64
  68. # endif
  69. # define _LARGEFILE_SOURCE 1
  70. #endif
  71. /*
  72. ** Include the configuration header output by 'configure' if we're using the
  73. ** autoconf-based build
  74. */
  75. #ifdef _HAVE_SQLITE_CONFIG_H
  76. #include "config.h"
  77. #endif
  78. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  79. /************** Begin file sqliteLimit.h *************************************/
  80. /*
  81. ** 2007 May 7
  82. **
  83. ** The author disclaims copyright to this source code. In place of
  84. ** a legal notice, here is a blessing:
  85. **
  86. ** May you do good and not evil.
  87. ** May you find forgiveness for yourself and forgive others.
  88. ** May you share freely, never taking more than you give.
  89. **
  90. *************************************************************************
  91. **
  92. ** This file defines various limits of what SQLite can process.
  93. */
  94. /*
  95. ** The maximum length of a TEXT or BLOB in bytes. This also
  96. ** limits the size of a row in a table or index.
  97. **
  98. ** The hard limit is the ability of a 32-bit signed integer
  99. ** to count the size: 2^31-1 or 2147483647.
  100. */
  101. #ifndef SQLITE_MAX_LENGTH
  102. # define SQLITE_MAX_LENGTH 1000000000
  103. #endif
  104. /*
  105. ** This is the maximum number of
  106. **
  107. ** * Columns in a table
  108. ** * Columns in an index
  109. ** * Columns in a view
  110. ** * Terms in the SET clause of an UPDATE statement
  111. ** * Terms in the result set of a SELECT statement
  112. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  113. ** * Terms in the VALUES clause of an INSERT statement
  114. **
  115. ** The hard upper limit here is 32676. Most database people will
  116. ** tell you that in a well-normalized database, you usually should
  117. ** not have more than a dozen or so columns in any table. And if
  118. ** that is the case, there is no point in having more than a few
  119. ** dozen values in any of the other situations described above.
  120. */
  121. #ifndef SQLITE_MAX_COLUMN
  122. # define SQLITE_MAX_COLUMN 2000
  123. #endif
  124. /*
  125. ** The maximum length of a single SQL statement in bytes.
  126. **
  127. ** It used to be the case that setting this value to zero would
  128. ** turn the limit off. That is no longer true. It is not possible
  129. ** to turn this limit off.
  130. */
  131. #ifndef SQLITE_MAX_SQL_LENGTH
  132. # define SQLITE_MAX_SQL_LENGTH 1000000000
  133. #endif
  134. /*
  135. ** The maximum depth of an expression tree. This is limited to
  136. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  137. ** want to place more severe limits on the complexity of an
  138. ** expression.
  139. **
  140. ** A value of 0 used to mean that the limit was not enforced.
  141. ** But that is no longer true. The limit is now strictly enforced
  142. ** at all times.
  143. */
  144. #ifndef SQLITE_MAX_EXPR_DEPTH
  145. # define SQLITE_MAX_EXPR_DEPTH 1000
  146. #endif
  147. /*
  148. ** The maximum number of terms in a compound SELECT statement.
  149. ** The code generator for compound SELECT statements does one
  150. ** level of recursion for each term. A stack overflow can result
  151. ** if the number of terms is too large. In practice, most SQL
  152. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  153. ** any limit on the number of terms in a compount SELECT.
  154. */
  155. #ifndef SQLITE_MAX_COMPOUND_SELECT
  156. # define SQLITE_MAX_COMPOUND_SELECT 500
  157. #endif
  158. /*
  159. ** The maximum number of opcodes in a VDBE program.
  160. ** Not currently enforced.
  161. */
  162. #ifndef SQLITE_MAX_VDBE_OP
  163. # define SQLITE_MAX_VDBE_OP 25000
  164. #endif
  165. /*
  166. ** The maximum number of arguments to an SQL function.
  167. */
  168. #ifndef SQLITE_MAX_FUNCTION_ARG
  169. # define SQLITE_MAX_FUNCTION_ARG 127
  170. #endif
  171. /*
  172. ** The maximum number of in-memory pages to use for the main database
  173. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  174. */
  175. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  176. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  177. #endif
  178. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  179. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  180. #endif
  181. /*
  182. ** The default number of frames to accumulate in the log file before
  183. ** checkpointing the database in WAL mode.
  184. */
  185. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  186. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  187. #endif
  188. /*
  189. ** The maximum number of attached databases. This must be between 0
  190. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  191. ** is used internally to track attached databases.
  192. */
  193. #ifndef SQLITE_MAX_ATTACHED
  194. # define SQLITE_MAX_ATTACHED 10
  195. #endif
  196. /*
  197. ** The maximum value of a ?nnn wildcard that the parser will accept.
  198. */
  199. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  200. # define SQLITE_MAX_VARIABLE_NUMBER 999
  201. #endif
  202. /* Maximum page size. The upper bound on this value is 65536. This a limit
  203. ** imposed by the use of 16-bit offsets within each page.
  204. **
  205. ** Earlier versions of SQLite allowed the user to change this value at
  206. ** compile time. This is no longer permitted, on the grounds that it creates
  207. ** a library that is technically incompatible with an SQLite library
  208. ** compiled with a different limit. If a process operating on a database
  209. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  210. ** compiled with the default page-size limit will not be able to rollback
  211. ** the aborted transaction. This could lead to database corruption.
  212. */
  213. #ifdef SQLITE_MAX_PAGE_SIZE
  214. # undef SQLITE_MAX_PAGE_SIZE
  215. #endif
  216. #define SQLITE_MAX_PAGE_SIZE 65536
  217. /*
  218. ** The default size of a database page.
  219. */
  220. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  221. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  222. #endif
  223. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  224. # undef SQLITE_DEFAULT_PAGE_SIZE
  225. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  226. #endif
  227. /*
  228. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  229. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  230. ** device characteristics (sector-size and atomic write() support),
  231. ** SQLite may choose a larger value. This constant is the maximum value
  232. ** SQLite will choose on its own.
  233. */
  234. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  235. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  236. #endif
  237. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  238. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  239. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  240. #endif
  241. /*
  242. ** Maximum number of pages in one database file.
  243. **
  244. ** This is really just the default value for the max_page_count pragma.
  245. ** This value can be lowered (or raised) at run-time using that the
  246. ** max_page_count macro.
  247. */
  248. #ifndef SQLITE_MAX_PAGE_COUNT
  249. # define SQLITE_MAX_PAGE_COUNT 1073741823
  250. #endif
  251. /*
  252. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  253. ** operator.
  254. */
  255. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  256. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  257. #endif
  258. /*
  259. ** Maximum depth of recursion for triggers.
  260. **
  261. ** A value of 1 means that a trigger program will not be able to itself
  262. ** fire any triggers. A value of 0 means that no trigger programs at all
  263. ** may be executed.
  264. */
  265. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  266. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  267. #endif
  268. /************** End of sqliteLimit.h *****************************************/
  269. /************** Continuing where we left off in sqliteInt.h ******************/
  270. /* Disable nuisance warnings on Borland compilers */
  271. #if defined(__BORLANDC__)
  272. #pragma warn -rch /* unreachable code */
  273. #pragma warn -ccc /* Condition is always true or false */
  274. #pragma warn -aus /* Assigned value is never used */
  275. #pragma warn -csu /* Comparing signed and unsigned */
  276. #pragma warn -spa /* Suspicious pointer arithmetic */
  277. #endif
  278. /* Needed for various definitions... */
  279. #ifndef _GNU_SOURCE
  280. # define _GNU_SOURCE
  281. #endif
  282. /*
  283. ** Include standard header files as necessary
  284. */
  285. #ifdef HAVE_STDINT_H
  286. #include <stdint.h>
  287. #endif
  288. #ifdef HAVE_INTTYPES_H
  289. #include <inttypes.h>
  290. #endif
  291. /*
  292. ** The following macros are used to cast pointers to integers and
  293. ** integers to pointers. The way you do this varies from one compiler
  294. ** to the next, so we have developed the following set of #if statements
  295. ** to generate appropriate macros for a wide range of compilers.
  296. **
  297. ** The correct "ANSI" way to do this is to use the intptr_t type.
  298. ** Unfortunately, that typedef is not available on all compilers, or
  299. ** if it is available, it requires an #include of specific headers
  300. ** that vary from one machine to the next.
  301. **
  302. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  303. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  304. ** So we have to define the macros in different ways depending on the
  305. ** compiler.
  306. */
  307. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  308. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  309. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  310. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  311. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  312. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  313. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  314. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  315. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  316. #else /* Generates a warning - but it always works */
  317. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  318. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  319. #endif
  320. /*
  321. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  322. ** 0 means mutexes are permanently disable and the library is never
  323. ** threadsafe. 1 means the library is serialized which is the highest
  324. ** level of threadsafety. 2 means the libary is multithreaded - multiple
  325. ** threads can use SQLite as long as no two threads try to use the same
  326. ** database connection at the same time.
  327. **
  328. ** Older versions of SQLite used an optional THREADSAFE macro.
  329. ** We support that for legacy.
  330. */
  331. #if !defined(SQLITE_THREADSAFE)
  332. #if defined(THREADSAFE)
  333. # define SQLITE_THREADSAFE THREADSAFE
  334. #else
  335. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  336. #endif
  337. #endif
  338. /*
  339. ** Powersafe overwrite is on by default. But can be turned off using
  340. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  341. */
  342. #ifndef SQLITE_POWERSAFE_OVERWRITE
  343. # define SQLITE_POWERSAFE_OVERWRITE 1
  344. #endif
  345. /*
  346. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  347. ** It determines whether or not the features related to
  348. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  349. ** be overridden at runtime using the sqlite3_config() API.
  350. */
  351. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  352. # define SQLITE_DEFAULT_MEMSTATUS 1
  353. #endif
  354. /*
  355. ** Exactly one of the following macros must be defined in order to
  356. ** specify which memory allocation subsystem to use.
  357. **
  358. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  359. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  360. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  361. **
  362. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  363. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  364. ** will cause HeapValidate to be called. If heap validation should fail, an
  365. ** assertion will be triggered.
  366. **
  367. ** (Historical note: There used to be several other options, but we've
  368. ** pared it down to just these three.)
  369. **
  370. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  371. ** the default.
  372. */
  373. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
  374. # error "At most one of the following compile-time configuration options\
  375. is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
  376. #endif
  377. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
  378. # define SQLITE_SYSTEM_MALLOC 1
  379. #endif
  380. /*
  381. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  382. ** sizes of memory allocations below this value where possible.
  383. */
  384. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  385. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  386. #endif
  387. /*
  388. ** We need to define _XOPEN_SOURCE as follows in order to enable
  389. ** recursive mutexes on most Unix systems. But Mac OS X is different.
  390. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
  391. ** so it is omitted there. See ticket #2673.
  392. **
  393. ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
  394. ** implemented on some systems. So we avoid defining it at all
  395. ** if it is already defined or if it is unneeded because we are
  396. ** not doing a threadsafe build. Ticket #2681.
  397. **
  398. ** See also ticket #2741.
  399. */
  400. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
  401. # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
  402. #endif
  403. /*
  404. ** The TCL headers are only needed when compiling the TCL bindings.
  405. */
  406. #if defined(SQLITE_TCL) || defined(TCLSH)
  407. # include <tcl.h>
  408. #endif
  409. /*
  410. ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
  411. ** Setting NDEBUG makes the code smaller and run faster. So the following
  412. ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
  413. ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  414. ** feature.
  415. */
  416. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  417. # define NDEBUG 1
  418. #endif
  419. /*
  420. ** The testcase() macro is used to aid in coverage testing. When
  421. ** doing coverage testing, the condition inside the argument to
  422. ** testcase() must be evaluated both true and false in order to
  423. ** get full branch coverage. The testcase() macro is inserted
  424. ** to help ensure adequate test coverage in places where simple
  425. ** condition/decision coverage is inadequate. For example, testcase()
  426. ** can be used to make sure boundary values are tested. For
  427. ** bitmask tests, testcase() can be used to make sure each bit
  428. ** is significant and used at least once. On switch statements
  429. ** where multiple cases go to the same block of code, testcase()
  430. ** can insure that all cases are evaluated.
  431. **
  432. */
  433. #ifdef SQLITE_COVERAGE_TEST
  434. SQLITE_PRIVATE void sqlite3Coverage(int);
  435. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  436. #else
  437. # define testcase(X)
  438. #endif
  439. /*
  440. ** The TESTONLY macro is used to enclose variable declarations or
  441. ** other bits of code that are needed to support the arguments
  442. ** within testcase() and assert() macros.
  443. */
  444. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  445. # define TESTONLY(X) X
  446. #else
  447. # define TESTONLY(X)
  448. #endif
  449. /*
  450. ** Sometimes we need a small amount of code such as a variable initialization
  451. ** to setup for a later assert() statement. We do not want this code to
  452. ** appear when assert() is disabled. The following macro is therefore
  453. ** used to contain that setup code. The "VVA" acronym stands for
  454. ** "Verification, Validation, and Accreditation". In other words, the
  455. ** code within VVA_ONLY() will only run during verification processes.
  456. */
  457. #ifndef NDEBUG
  458. # define VVA_ONLY(X) X
  459. #else
  460. # define VVA_ONLY(X)
  461. #endif
  462. /*
  463. ** The ALWAYS and NEVER macros surround boolean expressions which
  464. ** are intended to always be true or false, respectively. Such
  465. ** expressions could be omitted from the code completely. But they
  466. ** are included in a few cases in order to enhance the resilience
  467. ** of SQLite to unexpected behavior - to make the code "self-healing"
  468. ** or "ductile" rather than being "brittle" and crashing at the first
  469. ** hint of unplanned behavior.
  470. **
  471. ** In other words, ALWAYS and NEVER are added for defensive code.
  472. **
  473. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  474. ** be true and false so that the unreachable code then specify will
  475. ** not be counted as untested code.
  476. */
  477. #if defined(SQLITE_COVERAGE_TEST)
  478. # define ALWAYS(X) (1)
  479. # define NEVER(X) (0)
  480. #elif !defined(NDEBUG)
  481. # define ALWAYS(X) ((X)?1:(assert(0),0))
  482. # define NEVER(X) ((X)?(assert(0),1):0)
  483. #else
  484. # define ALWAYS(X) (X)
  485. # define NEVER(X) (X)
  486. #endif
  487. /*
  488. ** Return true (non-zero) if the input is a integer that is too large
  489. ** to fit in 32-bits. This macro is used inside of various testcase()
  490. ** macros to verify that we have tested SQLite for large-file support.
  491. */
  492. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  493. /*
  494. ** The macro unlikely() is a hint that surrounds a boolean
  495. ** expression that is usually false. Macro likely() surrounds
  496. ** a boolean expression that is usually true. GCC is able to
  497. ** use these hints to generate better code, sometimes.
  498. */
  499. #if defined(__GNUC__) && 0
  500. # define likely(X) __builtin_expect((X),1)
  501. # define unlikely(X) __builtin_expect((X),0)
  502. #else
  503. # define likely(X) !!(X)
  504. # define unlikely(X) !!(X)
  505. #endif
  506. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  507. /************** Begin file sqlite3.h *****************************************/
  508. /*
  509. ** 2001 September 15
  510. **
  511. ** The author disclaims copyright to this source code. In place of
  512. ** a legal notice, here is a blessing:
  513. **
  514. ** May you do good and not evil.
  515. ** May you find forgiveness for yourself and forgive others.
  516. ** May you share freely, never taking more than you give.
  517. **
  518. *************************************************************************
  519. ** This header file defines the interface that the SQLite library
  520. ** presents to client programs. If a C-function, structure, datatype,
  521. ** or constant definition does not appear in this file, then it is
  522. ** not a published API of SQLite, is subject to change without
  523. ** notice, and should not be referenced by programs that use SQLite.
  524. **
  525. ** Some of the definitions that are in this file are marked as
  526. ** "experimental". Experimental interfaces are normally new
  527. ** features recently added to SQLite. We do not anticipate changes
  528. ** to experimental interfaces but reserve the right to make minor changes
  529. ** if experience from use "in the wild" suggest such changes are prudent.
  530. **
  531. ** The official C-language API documentation for SQLite is derived
  532. ** from comments in this file. This file is the authoritative source
  533. ** on how SQLite interfaces are suppose to operate.
  534. **
  535. ** The name of this file under configuration management is "sqlite.h.in".
  536. ** The makefile makes some minor changes to this file (such as inserting
  537. ** the version number) and changes its name to "sqlite3.h" as
  538. ** part of the build process.
  539. */
  540. #ifndef _SQLITE3_H_
  541. #define _SQLITE3_H_
  542. #include <stdarg.h> /* Needed for the definition of va_list */
  543. /*
  544. ** Make sure we can call this stuff from C++.
  545. */
  546. #if 0
  547. extern "C" {
  548. #endif
  549. /*
  550. ** Add the ability to override 'extern'
  551. */
  552. #ifndef SQLITE_EXTERN
  553. # define SQLITE_EXTERN extern
  554. #endif
  555. #ifndef SQLITE_API
  556. # define SQLITE_API
  557. #endif
  558. /*
  559. ** These no-op macros are used in front of interfaces to mark those
  560. ** interfaces as either deprecated or experimental. New applications
  561. ** should not use deprecated interfaces - they are support for backwards
  562. ** compatibility only. Application writers should be aware that
  563. ** experimental interfaces are subject to change in point releases.
  564. **
  565. ** These macros used to resolve to various kinds of compiler magic that
  566. ** would generate warning messages when they were used. But that
  567. ** compiler magic ended up generating such a flurry of bug reports
  568. ** that we have taken it all out and gone back to using simple
  569. ** noop macros.
  570. */
  571. #define SQLITE_DEPRECATED
  572. #define SQLITE_EXPERIMENTAL
  573. /*
  574. ** Ensure these symbols were not defined by some previous header file.
  575. */
  576. #ifdef SQLITE_VERSION
  577. # undef SQLITE_VERSION
  578. #endif
  579. #ifdef SQLITE_VERSION_NUMBER
  580. # undef SQLITE_VERSION_NUMBER
  581. #endif
  582. /*
  583. ** CAPI3REF: Compile-Time Library Version Numbers
  584. **
  585. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  586. ** evaluates to a string literal that is the SQLite version in the
  587. ** format "X.Y.Z" where X is the major version number (always 3 for
  588. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  589. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  590. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  591. ** numbers used in [SQLITE_VERSION].)^
  592. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  593. ** be larger than the release from which it is derived. Either Y will
  594. ** be held constant and Z will be incremented or else Y will be incremented
  595. ** and Z will be reset to zero.
  596. **
  597. ** Since version 3.6.18, SQLite source code has been stored in the
  598. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  599. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  600. ** a string which identifies a particular check-in of SQLite
  601. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  602. ** string contains the date and time of the check-in (UTC) and an SHA1
  603. ** hash of the entire source tree.
  604. **
  605. ** See also: [sqlite3_libversion()],
  606. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  607. ** [sqlite_version()] and [sqlite_source_id()].
  608. */
  609. #define SQLITE_VERSION "3.7.10"
  610. #define SQLITE_VERSION_NUMBER 3007010
  611. #define SQLITE_SOURCE_ID "2012-01-16 13:28:40 ebd01a8deffb5024a5d7494eef800d2366d97204"
  612. /*
  613. ** CAPI3REF: Run-Time Library Version Numbers
  614. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  615. **
  616. ** These interfaces provide the same information as the [SQLITE_VERSION],
  617. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  618. ** but are associated with the library instead of the header file. ^(Cautious
  619. ** programmers might include assert() statements in their application to
  620. ** verify that values returned by these interfaces match the macros in
  621. ** the header, and thus insure that the application is
  622. ** compiled with matching library and header files.
  623. **
  624. ** <blockquote><pre>
  625. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  626. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  627. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  628. ** </pre></blockquote>)^
  629. **
  630. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  631. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  632. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  633. ** function is provided for use in DLLs since DLL users usually do not have
  634. ** direct access to string constants within the DLL. ^The
  635. ** sqlite3_libversion_number() function returns an integer equal to
  636. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  637. ** a pointer to a string constant whose value is the same as the
  638. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  639. **
  640. ** See also: [sqlite_version()] and [sqlite_source_id()].
  641. */
  642. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  643. SQLITE_API const char *sqlite3_libversion(void);
  644. SQLITE_API const char *sqlite3_sourceid(void);
  645. SQLITE_API int sqlite3_libversion_number(void);
  646. /*
  647. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  648. **
  649. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  650. ** indicating whether the specified option was defined at
  651. ** compile time. ^The SQLITE_ prefix may be omitted from the
  652. ** option name passed to sqlite3_compileoption_used().
  653. **
  654. ** ^The sqlite3_compileoption_get() function allows iterating
  655. ** over the list of options that were defined at compile time by
  656. ** returning the N-th compile time option string. ^If N is out of range,
  657. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  658. ** prefix is omitted from any strings returned by
  659. ** sqlite3_compileoption_get().
  660. **
  661. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  662. ** and sqlite3_compileoption_get() may be omitted by specifying the
  663. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  664. **
  665. ** See also: SQL functions [sqlite_compileoption_used()] and
  666. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  667. */
  668. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  669. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  670. SQLITE_API const char *sqlite3_compileoption_get(int N);
  671. #endif
  672. /*
  673. ** CAPI3REF: Test To See If The Library Is Threadsafe
  674. **
  675. ** ^The sqlite3_threadsafe() function returns zero if and only if
  676. ** SQLite was compiled with mutexing code omitted due to the
  677. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  678. **
  679. ** SQLite can be compiled with or without mutexes. When
  680. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  681. ** are enabled and SQLite is threadsafe. When the
  682. ** [SQLITE_THREADSAFE] macro is 0,
  683. ** the mutexes are omitted. Without the mutexes, it is not safe
  684. ** to use SQLite concurrently from more than one thread.
  685. **
  686. ** Enabling mutexes incurs a measurable performance penalty.
  687. ** So if speed is of utmost importance, it makes sense to disable
  688. ** the mutexes. But for maximum safety, mutexes should be enabled.
  689. ** ^The default behavior is for mutexes to be enabled.
  690. **
  691. ** This interface can be used by an application to make sure that the
  692. ** version of SQLite that it is linking against was compiled with
  693. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  694. **
  695. ** This interface only reports on the compile-time mutex setting
  696. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  697. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  698. ** can be fully or partially disabled using a call to [sqlite3_config()]
  699. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  700. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  701. ** sqlite3_threadsafe() function shows only the compile-time setting of
  702. ** thread safety, not any run-time changes to that setting made by
  703. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  704. ** is unchanged by calls to sqlite3_config().)^
  705. **
  706. ** See the [threading mode] documentation for additional information.
  707. */
  708. SQLITE_API int sqlite3_threadsafe(void);
  709. /*
  710. ** CAPI3REF: Database Connection Handle
  711. ** KEYWORDS: {database connection} {database connections}
  712. **
  713. ** Each open SQLite database is represented by a pointer to an instance of
  714. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  715. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  716. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  717. ** is its destructor. There are many other interfaces (such as
  718. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  719. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  720. ** sqlite3 object.
  721. */
  722. typedef struct sqlite3 sqlite3;
  723. /*
  724. ** CAPI3REF: 64-Bit Integer Types
  725. ** KEYWORDS: sqlite_int64 sqlite_uint64
  726. **
  727. ** Because there is no cross-platform way to specify 64-bit integer types
  728. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  729. **
  730. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  731. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  732. ** compatibility only.
  733. **
  734. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  735. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  736. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  737. ** between 0 and +18446744073709551615 inclusive.
  738. */
  739. #ifdef SQLITE_INT64_TYPE
  740. typedef SQLITE_INT64_TYPE sqlite_int64;
  741. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  742. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  743. typedef __int64 sqlite_int64;
  744. typedef unsigned __int64 sqlite_uint64;
  745. #else
  746. typedef long long int sqlite_int64;
  747. typedef unsigned long long int sqlite_uint64;
  748. #endif
  749. typedef sqlite_int64 sqlite3_int64;
  750. typedef sqlite_uint64 sqlite3_uint64;
  751. /*
  752. ** If compiling for a processor that lacks floating point support,
  753. ** substitute integer for floating-point.
  754. */
  755. #ifdef SQLITE_OMIT_FLOATING_POINT
  756. # define double sqlite3_int64
  757. #endif
  758. /*
  759. ** CAPI3REF: Closing A Database Connection
  760. **
  761. ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
  762. ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
  763. ** successfully destroyed and all associated resources are deallocated.
  764. **
  765. ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
  766. ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
  767. ** the [sqlite3] object prior to attempting to close the object. ^If
  768. ** sqlite3_close() is called on a [database connection] that still has
  769. ** outstanding [prepared statements] or [BLOB handles], then it returns
  770. ** SQLITE_BUSY.
  771. **
  772. ** ^If [sqlite3_close()] is invoked while a transaction is open,
  773. ** the transaction is automatically rolled back.
  774. **
  775. ** The C parameter to [sqlite3_close(C)] must be either a NULL
  776. ** pointer or an [sqlite3] object pointer obtained
  777. ** from [sqlite3_open()], [sqlite3_open16()], or
  778. ** [sqlite3_open_v2()], and not previously closed.
  779. ** ^Calling sqlite3_close() with a NULL pointer argument is a
  780. ** harmless no-op.
  781. */
  782. SQLITE_API int sqlite3_close(sqlite3 *);
  783. /*
  784. ** The type for a callback function.
  785. ** This is legacy and deprecated. It is included for historical
  786. ** compatibility and is not documented.
  787. */
  788. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  789. /*
  790. ** CAPI3REF: One-Step Query Execution Interface
  791. **
  792. ** The sqlite3_exec() interface is a convenience wrapper around
  793. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  794. ** that allows an application to run multiple statements of SQL
  795. ** without having to use a lot of C code.
  796. **
  797. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  798. ** semicolon-separate SQL statements passed into its 2nd argument,
  799. ** in the context of the [database connection] passed in as its 1st
  800. ** argument. ^If the callback function of the 3rd argument to
  801. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  802. ** coming out of the evaluated SQL statements. ^The 4th argument to
  803. ** sqlite3_exec() is relayed through to the 1st argument of each
  804. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  805. ** is NULL, then no callback is ever invoked and result rows are
  806. ** ignored.
  807. **
  808. ** ^If an error occurs while evaluating the SQL statements passed into
  809. ** sqlite3_exec(), then execution of the current statement stops and
  810. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  811. ** is not NULL then any error message is written into memory obtained
  812. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  813. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  814. ** on error message strings returned through the 5th parameter of
  815. ** of sqlite3_exec() after the error message string is no longer needed.
  816. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  817. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  818. ** NULL before returning.
  819. **
  820. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  821. ** routine returns SQLITE_ABORT without invoking the callback again and
  822. ** without running any subsequent SQL statements.
  823. **
  824. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  825. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  826. ** callback is an array of pointers to strings obtained as if from
  827. ** [sqlite3_column_text()], one for each column. ^If an element of a
  828. ** result row is NULL then the corresponding string pointer for the
  829. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  830. ** sqlite3_exec() callback is an array of pointers to strings where each
  831. ** entry represents the name of corresponding result column as obtained
  832. ** from [sqlite3_column_name()].
  833. **
  834. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  835. ** to an empty string, or a pointer that contains only whitespace and/or
  836. ** SQL comments, then no SQL statements are evaluated and the database
  837. ** is not changed.
  838. **
  839. ** Restrictions:
  840. **
  841. ** <ul>
  842. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  843. ** is a valid and open [database connection].
  844. ** <li> The application must not close [database connection] specified by
  845. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  846. ** <li> The application must not modify the SQL statement text passed into
  847. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  848. ** </ul>
  849. */
  850. SQLITE_API int sqlite3_exec(
  851. sqlite3*, /* An open database */
  852. const char *sql, /* SQL to be evaluated */
  853. int (*callback)(void*,int,char**,char**), /* Callback function */
  854. void *, /* 1st argument to callback */
  855. char **errmsg /* Error msg written here */
  856. );
  857. /*
  858. ** CAPI3REF: Result Codes
  859. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  860. ** KEYWORDS: {result code} {result codes}
  861. **
  862. ** Many SQLite functions return an integer result code from the set shown
  863. ** here in order to indicate success or failure.
  864. **
  865. ** New error codes may be added in future versions of SQLite.
  866. **
  867. ** See also: [SQLITE_IOERR_READ | extended result codes],
  868. ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
  869. */
  870. #define SQLITE_OK 0 /* Successful result */
  871. /* beginning-of-error-codes */
  872. #define SQLITE_ERROR 1 /* SQL error or missing database */
  873. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  874. #define SQLITE_PERM 3 /* Access permission denied */
  875. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  876. #define SQLITE_BUSY 5 /* The database file is locked */
  877. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  878. #define SQLITE_NOMEM 7 /* A malloc() failed */
  879. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  880. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  881. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  882. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  883. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  884. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  885. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  886. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  887. #define SQLITE_EMPTY 16 /* Database is empty */
  888. #define SQLITE_SCHEMA 17 /* The database schema changed */
  889. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  890. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  891. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  892. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  893. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  894. #define SQLITE_AUTH 23 /* Authorization denied */
  895. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  896. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  897. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  898. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  899. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  900. /* end-of-error-codes */
  901. /*
  902. ** CAPI3REF: Extended Result Codes
  903. ** KEYWORDS: {extended error code} {extended error codes}
  904. ** KEYWORDS: {extended result code} {extended result codes}
  905. **
  906. ** In its default configuration, SQLite API routines return one of 26 integer
  907. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  908. ** these result codes are too coarse-grained. They do not provide as
  909. ** much information about problems as programmers might like. In an effort to
  910. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  911. ** support for additional result codes that provide more detailed information
  912. ** about errors. The extended result codes are enabled or disabled
  913. ** on a per database connection basis using the
  914. ** [sqlite3_extended_result_codes()] API.
  915. **
  916. ** Some of the available extended result codes are listed here.
  917. ** One may expect the number of extended result codes will be expand
  918. ** over time. Software that uses extended result codes should expect
  919. ** to see new result codes in future releases of SQLite.
  920. **
  921. ** The SQLITE_OK result code will never be extended. It will always
  922. ** be exactly zero.
  923. */
  924. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  925. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  926. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  927. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  928. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  929. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  930. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  931. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  932. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  933. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  934. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  935. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  936. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  937. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  938. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  939. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  940. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  941. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  942. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  943. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  944. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  945. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  946. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  947. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  948. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  949. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  950. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  951. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  952. /*
  953. ** CAPI3REF: Flags For File Open Operations
  954. **
  955. ** These bit values are intended for use in the
  956. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  957. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  958. */
  959. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  960. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  961. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  962. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  963. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  964. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  965. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  966. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  967. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  968. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  969. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  970. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  971. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  972. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  973. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  974. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  975. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  976. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  977. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  978. /* Reserved: 0x00F00000 */
  979. /*
  980. ** CAPI3REF: Device Characteristics
  981. **
  982. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  983. ** object returns an integer which is a vector of the these
  984. ** bit values expressing I/O characteristics of the mass storage
  985. ** device that holds the file that the [sqlite3_io_methods]
  986. ** refers to.
  987. **
  988. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  989. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  990. ** mean that writes of blocks that are nnn bytes in size and
  991. ** are aligned to an address which is an integer multiple of
  992. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  993. ** that when data is appended to a file, the data is appended
  994. ** first then the size of the file is extended, never the other
  995. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  996. ** information is written to disk in the same order as calls
  997. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  998. ** after reboot following a crash or power loss, the only bytes in a
  999. ** file that were written at the application level might have changed
  1000. ** and that adjacent bytes, even bytes within the same sector are
  1001. ** guaranteed to be unchanged.
  1002. */
  1003. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1004. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1005. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1006. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1007. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1008. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1009. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1010. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1011. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1012. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1013. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1014. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1015. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1016. /*
  1017. ** CAPI3REF: File Locking Levels
  1018. **
  1019. ** SQLite uses one of these integer values as the second
  1020. ** argument to calls it makes to the xLock() and xUnlock() methods
  1021. ** of an [sqlite3_io_methods] object.
  1022. */
  1023. #define SQLITE_LOCK_NONE 0
  1024. #define SQLITE_LOCK_SHARED 1
  1025. #define SQLITE_LOCK_RESERVED 2
  1026. #define SQLITE_LOCK_PENDING 3
  1027. #define SQLITE_LOCK_EXCLUSIVE 4
  1028. /*
  1029. ** CAPI3REF: Synchronization Type Flags
  1030. **
  1031. ** When SQLite invokes the xSync() method of an
  1032. ** [sqlite3_io_methods] object it uses a combination of
  1033. ** these integer values as the second argument.
  1034. **
  1035. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1036. ** sync operation only needs to flush data to mass storage. Inode
  1037. ** information need not be flushed. If the lower four bits of the flag
  1038. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1039. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1040. ** to use Mac OS X style fullsync instead of fsync().
  1041. **
  1042. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1043. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1044. ** settings. The [synchronous pragma] determines when calls to the
  1045. ** xSync VFS method occur and applies uniformly across all platforms.
  1046. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1047. ** energetic or rigorous or forceful the sync operations are and
  1048. ** only make a difference on Mac OSX for the default SQLite code.
  1049. ** (Third-party VFS implementations might also make the distinction
  1050. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1051. ** operating systems natively supported by SQLite, only Mac OSX
  1052. ** cares about the difference.)
  1053. */
  1054. #define SQLITE_SYNC_NORMAL 0x00002
  1055. #define SQLITE_SYNC_FULL 0x00003
  1056. #define SQLITE_SYNC_DATAONLY 0x00010
  1057. /*
  1058. ** CAPI3REF: OS Interface Open File Handle
  1059. **
  1060. ** An [sqlite3_file] object represents an open file in the
  1061. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1062. ** implementations will
  1063. ** want to subclass this object by appending additional fields
  1064. ** for their own use. The pMethods entry is a pointer to an
  1065. ** [sqlite3_io_methods] object that defines methods for performing
  1066. ** I/O operations on the open file.
  1067. */
  1068. typedef struct sqlite3_file sqlite3_file;
  1069. struct sqlite3_file {
  1070. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1071. };
  1072. /*
  1073. ** CAPI3REF: OS Interface File Virtual Methods Object
  1074. **
  1075. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1076. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1077. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1078. ** This object defines the methods used to perform various operations
  1079. ** against the open file represented by the [sqlite3_file] object.
  1080. **
  1081. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1082. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1083. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1084. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1085. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1086. ** to NULL.
  1087. **
  1088. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1089. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1090. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1091. ** flag may be ORed in to indicate that only the data of the file
  1092. ** and not its inode needs to be synced.
  1093. **
  1094. ** The integer values to xLock() and xUnlock() are one of
  1095. ** <ul>
  1096. ** <li> [SQLITE_LOCK_NONE],
  1097. ** <li> [SQLITE_LOCK_SHARED],
  1098. ** <li> [SQLITE_LOCK_RESERVED],
  1099. ** <li> [SQLITE_LOCK_PENDING], or
  1100. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1101. ** </ul>
  1102. ** xLock() increases the lock. xUnlock() decreases the lock.
  1103. ** The xCheckReservedLock() method checks whether any database connection,
  1104. ** either in this process or in some other process, is holding a RESERVED,
  1105. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1106. ** if such a lock exists and false otherwise.
  1107. **
  1108. ** The xFileControl() method is a generic interface that allows custom
  1109. ** VFS implementations to directly control an open file using the
  1110. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1111. ** integer opcode. The third argument is a generic pointer intended to
  1112. ** point to a structure that may contain arguments or space in which to
  1113. ** write return values. Potential uses for xFileControl() might be
  1114. ** functions to enable blocking locks with timeouts, to change the
  1115. ** locking strategy (for example to use dot-file locks), to inquire
  1116. ** about the status of a lock, or to break stale locks. The SQLite
  1117. ** core reserves all opcodes less than 100 for its own use.
  1118. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  1119. ** Applications that define a custom xFileControl method should use opcodes
  1120. ** greater than 100 to avoid conflicts. VFS implementations should
  1121. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1122. ** recognize.
  1123. **
  1124. ** The xSectorSize() method returns the sector size of the
  1125. ** device that underlies the file. The sector size is the
  1126. ** minimum write that can be performed without disturbing
  1127. ** other bytes in the file. The xDeviceCharacteristics()
  1128. ** method returns a bit vector describing behaviors of the
  1129. ** underlying device:
  1130. **
  1131. ** <ul>
  1132. ** <li> [SQLITE_IOCAP_ATOMIC]
  1133. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1134. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1135. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1136. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1137. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1138. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1139. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1140. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1141. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1142. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1143. ** </ul>
  1144. **
  1145. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1146. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1147. ** mean that writes of blocks that are nnn bytes in size and
  1148. ** are aligned to an address which is an integer multiple of
  1149. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1150. ** that when data is appended to a file, the data is appended
  1151. ** first then the size of the file is extended, never the other
  1152. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1153. ** information is written to disk in the same order as calls
  1154. ** to xWrite().
  1155. **
  1156. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1157. ** in the unread portions of the buffer with zeros. A VFS that
  1158. ** fails to zero-fill short reads might seem to work. However,
  1159. ** failure to zero-fill short reads will eventually lead to
  1160. ** database corruption.
  1161. */
  1162. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1163. struct sqlite3_io_methods {
  1164. int iVersion;
  1165. int (*xClose)(sqlite3_file*);
  1166. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1167. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1168. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1169. int (*xSync)(sqlite3_file*, int flags);
  1170. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1171. int (*xLock)(sqlite3_file*, int);
  1172. int (*xUnlock)(sqlite3_file*, int);
  1173. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1174. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1175. int (*xSectorSize)(sqlite3_file*);
  1176. int (*xDeviceCharacteristics)(sqlite3_file*);
  1177. /* Methods above are valid for version 1 */
  1178. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1179. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1180. void (*xShmBarrier)(sqlite3_file*);
  1181. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1182. /* Methods above are valid for version 2 */
  1183. /* Additional methods may be added in future releases */
  1184. };
  1185. /*
  1186. ** CAPI3REF: Standard File Control Opcodes
  1187. **
  1188. ** These integer constants are opcodes for the xFileControl method
  1189. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1190. ** interface.
  1191. **
  1192. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1193. ** opcode causes the xFileControl method to write the current state of
  1194. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1195. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1196. ** into an integer that the pArg argument points to. This capability
  1197. ** is used during testing and only needs to be supported when SQLITE_TEST
  1198. ** is defined.
  1199. **
  1200. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1201. ** layer a hint of how large the database file will grow to be during the
  1202. ** current transaction. This hint is not guaranteed to be accurate but it
  1203. ** is often close. The underlying VFS might choose to preallocate database
  1204. ** file space based on this hint in order to help writes to the database
  1205. ** file run faster.
  1206. **
  1207. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1208. ** extends and truncates the database file in chunks of a size specified
  1209. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1210. ** point to an integer (type int) containing the new chunk-size to use
  1211. ** for the nominated database. Allocating database file space in large
  1212. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1213. ** improve performance on some systems.
  1214. **
  1215. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1216. ** to the [sqlite3_file] object associated with a particular database
  1217. ** connection. See the [sqlite3_file_control()] documentation for
  1218. ** additional information.
  1219. **
  1220. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  1221. ** SQLite and sent to all VFSes in place of a call to the xSync method
  1222. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  1223. ** Some specialized VFSes need this signal in order to operate correctly
  1224. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  1225. ** VFSes do not need this signal and should silently ignore this opcode.
  1226. ** Applications should not call [sqlite3_file_control()] with this
  1227. ** opcode as doing so may disrupt the operation of the specialized VFSes
  1228. ** that do require it.
  1229. **
  1230. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1231. ** retry counts and intervals for certain disk I/O operations for the
  1232. ** windows [VFS] in order to provide robustness in the presence of
  1233. ** anti-virus programs. By default, the windows VFS will retry file read,
  1234. ** file write, and file delete operations up to 10 times, with a delay
  1235. ** of 25 milliseconds before the first retry and with the delay increasing
  1236. ** by an additional 25 milliseconds with each subsequent retry. This
  1237. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1238. ** to be adjusted. The values are changed for all database connections
  1239. ** within the same process. The argument is a pointer to an array of two
  1240. ** integers where the first integer i the new retry count and the second
  1241. ** integer is the delay. If either integer is negative, then the setting
  1242. ** is not changed but instead the prior value of that setting is written
  1243. ** into the array entry, allowing the current retry settings to be
  1244. ** interrogated. The zDbName parameter is ignored.
  1245. **
  1246. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1247. ** persistent [WAL | Write AHead Log] setting. By default, the auxiliary
  1248. ** write ahead log and shared memory files used for transaction control
  1249. ** are automatically deleted when the latest connection to the database
  1250. ** closes. Setting persistent WAL mode causes those files to persist after
  1251. ** close. Persisting the files is useful when other processes that do not
  1252. ** have write permission on the directory containing the database file want
  1253. ** to read the database file, as the WAL and shared memory files must exist
  1254. ** in order for the database to be readable. The fourth parameter to
  1255. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1256. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1257. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1258. ** WAL persistence setting.
  1259. **
  1260. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1261. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1262. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1263. ** xDeviceCharacteristics methods. The fourth parameter to
  1264. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1265. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1266. ** mode. If the integer is -1, then it is overwritten with the current
  1267. ** zero-damage mode setting.
  1268. **
  1269. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1270. ** a write transaction to indicate that, unless it is rolled back for some
  1271. ** reason, the entire database file will be overwritten by the current
  1272. ** transaction. This is used by VACUUM operations.
  1273. **
  1274. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1275. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1276. ** final bottom-level VFS are written into memory obtained from
  1277. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1278. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1279. ** The caller is responsible for freeing the memory when done. As with
  1280. ** all file-control actions, there is no guarantee that this will actually
  1281. ** do anything. Callers should initialize the char* variable to a NULL
  1282. ** pointer in case this file-control is not implemented. This file-control
  1283. ** is intended for diagnostic use only.
  1284. */
  1285. #define SQLITE_FCNTL_LOCKSTATE 1
  1286. #define SQLITE_GET_LOCKPROXYFILE 2
  1287. #define SQLITE_SET_LOCKPROXYFILE 3
  1288. #define SQLITE_LAST_ERRNO 4
  1289. #define SQLITE_FCNTL_SIZE_HINT 5
  1290. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1291. #define SQLITE_FCNTL_FILE_POINTER 7
  1292. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1293. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1294. #define SQLITE_FCNTL_PERSIST_WAL 10
  1295. #define SQLITE_FCNTL_OVERWRITE 11
  1296. #define SQLITE_FCNTL_VFSNAME 12
  1297. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1298. /*
  1299. ** CAPI3REF: Mutex Handle
  1300. **
  1301. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1302. ** abstract type for a mutex object. The SQLite core never looks
  1303. ** at the internal representation of an [sqlite3_mutex]. It only
  1304. ** deals with pointers to the [sqlite3_mutex] object.
  1305. **
  1306. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1307. */
  1308. typedef struct sqlite3_mutex sqlite3_mutex;
  1309. /*
  1310. ** CAPI3REF: OS Interface Object
  1311. **
  1312. ** An instance of the sqlite3_vfs object defines the interface between
  1313. ** the SQLite core and the underlying operating system. The "vfs"
  1314. ** in the name of the object stands for "virtual file system". See
  1315. ** the [VFS | VFS documentation] for further information.
  1316. **
  1317. ** The value of the iVersion field is initially 1 but may be larger in
  1318. ** future versions of SQLite. Additional fields may be appended to this
  1319. ** object when the iVersion value is increased. Note that the structure
  1320. ** of the sqlite3_vfs object changes in the transaction between
  1321. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1322. ** modified.
  1323. **
  1324. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1325. ** structure used by this VFS. mxPathname is the maximum length of
  1326. ** a pathname in this VFS.
  1327. **
  1328. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1329. ** the pNext pointer. The [sqlite3_vfs_register()]
  1330. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1331. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1332. ** searches the list. Neither the application code nor the VFS
  1333. ** implementation should use the pNext pointer.
  1334. **
  1335. ** The pNext field is the only field in the sqlite3_vfs
  1336. ** structure that SQLite will ever modify. SQLite will only access
  1337. ** or modify this field while holding a particular static mutex.
  1338. ** The application should never modify anything within the sqlite3_vfs
  1339. ** object once the object has been registered.
  1340. **
  1341. ** The zName field holds the name of the VFS module. The name must
  1342. ** be unique across all VFS modules.
  1343. **
  1344. ** [[sqlite3_vfs.xOpen]]
  1345. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1346. ** is either a NULL pointer or string obtained
  1347. ** from xFullPathname() with an optional suffix added.
  1348. ** ^If a suffix is added to the zFilename parameter, it will
  1349. ** consist of a single "-" character followed by no more than
  1350. ** 11 alphanumeric and/or "-" characters.
  1351. ** ^SQLite further guarantees that
  1352. ** the string will be valid and unchanged until xClose() is
  1353. ** called. Because of the previous sentence,
  1354. ** the [sqlite3_file] can safely store a pointer to the
  1355. ** filename if it needs to remember the filename for some reason.
  1356. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1357. ** must invent its own temporary name for the file. ^Whenever the
  1358. ** xFilename parameter is NULL it will also be the case that the
  1359. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1360. **
  1361. ** The flags argument to xOpen() includes all bits set in
  1362. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1363. ** or [sqlite3_open16()] is used, then flags includes at least
  1364. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1365. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1366. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1367. **
  1368. ** ^(SQLite will also add one of the following flags to the xOpen()
  1369. ** call, depending on the object being opened:
  1370. **
  1371. ** <ul>
  1372. ** <li> [SQLITE_OPEN_MAIN_DB]
  1373. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1374. ** <li> [SQLITE_OPEN_TEMP_DB]
  1375. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1376. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1377. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1378. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1379. ** <li> [SQLITE_OPEN_WAL]
  1380. ** </ul>)^
  1381. **
  1382. ** The file I/O implementation can use the object type flags to
  1383. ** change the way it deals with files. For example, an application
  1384. ** that does not care about crash recovery or rollback might make
  1385. ** the open of a journal file a no-op. Writes to this journal would
  1386. ** also be no-ops, and any attempt to read the journal would return
  1387. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1388. ** file will be doing page-aligned sector reads and writes in a random
  1389. ** order and set up its I/O subsystem accordingly.
  1390. **
  1391. ** SQLite might also add one of the following flags to the xOpen method:
  1392. **
  1393. ** <ul>
  1394. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1395. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1396. ** </ul>
  1397. **
  1398. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1399. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1400. ** will be set for TEMP databases and their journals, transient
  1401. ** databases, and subjournals.
  1402. **
  1403. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1404. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1405. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1406. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1407. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1408. ** be created, and that it is an error if it already exists.
  1409. ** It is <i>not</i> used to indicate the file should be opened
  1410. ** for exclusive access.
  1411. **
  1412. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1413. ** to hold the [sqlite3_file] structure passed as the third
  1414. ** argument to xOpen. The xOpen method does not have to
  1415. ** allocate the structure; it should just fill it in. Note that
  1416. ** the xOpen method must set the sqlite3_file.pMethods to either
  1417. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1418. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1419. ** element will be valid after xOpen returns regardless of the success
  1420. ** or failure of the xOpen call.
  1421. **
  1422. ** [[sqlite3_vfs.xAccess]]
  1423. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1424. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1425. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1426. ** to test whether a file is at least readable. The file can be a
  1427. ** directory.
  1428. **
  1429. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1430. ** output buffer xFullPathname. The exact size of the output buffer
  1431. ** is also passed as a parameter to both methods. If the output buffer
  1432. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1433. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1434. ** to prevent this by setting mxPathname to a sufficiently large value.
  1435. **
  1436. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1437. ** interfaces are not strictly a part of the filesystem, but they are
  1438. ** included in the VFS structure for completeness.
  1439. ** The xRandomness() function attempts to return nBytes bytes
  1440. ** of good-quality randomness into zOut. The return value is
  1441. ** the actual number of bytes of randomness obtained.
  1442. ** The xSleep() method causes the calling thread to sleep for at
  1443. ** least the number of microseconds given. ^The xCurrentTime()
  1444. ** method returns a Julian Day Number for the current date and time as
  1445. ** a floating point value.
  1446. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1447. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1448. ** a 24-hour day).
  1449. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1450. ** date and time if that method is available (if iVersion is 2 or
  1451. ** greater and the function pointer is not NULL) and will fall back
  1452. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1453. **
  1454. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1455. ** are not used by the SQLite core. These optional interfaces are provided
  1456. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1457. ** system calls with functions under its control, a test program can
  1458. ** simulate faults and error conditions that would otherwise be difficult
  1459. ** or impossible to induce. The set of system calls that can be overridden
  1460. ** varies from one VFS to another, and from one version of the same VFS to the
  1461. ** next. Applications that use these interfaces must be prepared for any
  1462. ** or all of these interfaces to be NULL or for their behavior to change
  1463. ** from one release to the next. Applications must not attempt to access
  1464. ** any of these methods if the iVersion of the VFS is less than 3.
  1465. */
  1466. typedef struct sqlite3_vfs sqlite3_vfs;
  1467. typedef void (*sqlite3_syscall_ptr)(void);
  1468. struct sqlite3_vfs {
  1469. int iVersion; /* Structure version number (currently 3) */
  1470. int szOsFile; /* Size of subclassed sqlite3_file */
  1471. int mxPathname; /* Maximum file pathname length */
  1472. sqlite3_vfs *pNext; /* Next registered VFS */
  1473. const char *zName; /* Name of this virtual file system */
  1474. void *pAppData; /* Pointer to application-specific data */
  1475. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1476. int flags, int *pOutFlags);
  1477. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1478. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1479. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1480. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1481. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1482. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1483. void (*xDlClose)(sqlite3_vfs*, void*);
  1484. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1485. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1486. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1487. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1488. /*
  1489. ** The methods above are in version 1 of the sqlite_vfs object
  1490. ** definition. Those that follow are added in version 2 or later
  1491. */
  1492. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1493. /*
  1494. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1495. ** Those below are for version 3 and greater.
  1496. */
  1497. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1498. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1499. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1500. /*
  1501. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1502. ** New fields may be appended in figure versions. The iVersion
  1503. ** value will increment whenever this happens.
  1504. */
  1505. };
  1506. /*
  1507. ** CAPI3REF: Flags for the xAccess VFS method
  1508. **
  1509. ** These integer constants can be used as the third parameter to
  1510. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1511. ** what kind of permissions the xAccess method is looking for.
  1512. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1513. ** simply checks whether the file exists.
  1514. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1515. ** checks whether the named directory is both readable and writable
  1516. ** (in other words, if files can be added, removed, and renamed within
  1517. ** the directory).
  1518. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1519. ** [temp_store_directory pragma], though this could change in a future
  1520. ** release of SQLite.
  1521. ** With SQLITE_ACCESS_READ, the xAccess method
  1522. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1523. ** currently unused, though it might be used in a future release of
  1524. ** SQLite.
  1525. */
  1526. #define SQLITE_ACCESS_EXISTS 0
  1527. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1528. #define SQLITE_ACCESS_READ 2 /* Unused */
  1529. /*
  1530. ** CAPI3REF: Flags for the xShmLock VFS method
  1531. **
  1532. ** These integer constants define the various locking operations
  1533. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1534. ** following are the only legal combinations of flags to the
  1535. ** xShmLock method:
  1536. **
  1537. ** <ul>
  1538. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1539. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1540. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1541. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1542. ** </ul>
  1543. **
  1544. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1545. ** was given no the corresponding lock.
  1546. **
  1547. ** The xShmLock method can transition between unlocked and SHARED or
  1548. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1549. ** and EXCLUSIVE.
  1550. */
  1551. #define SQLITE_SHM_UNLOCK 1
  1552. #define SQLITE_SHM_LOCK 2
  1553. #define SQLITE_SHM_SHARED 4
  1554. #define SQLITE_SHM_EXCLUSIVE 8
  1555. /*
  1556. ** CAPI3REF: Maximum xShmLock index
  1557. **
  1558. ** The xShmLock method on [sqlite3_io_methods] may use values
  1559. ** between 0 and this upper bound as its "offset" argument.
  1560. ** The SQLite core will never attempt to acquire or release a
  1561. ** lock outside of this range
  1562. */
  1563. #define SQLITE_SHM_NLOCK 8
  1564. /*
  1565. ** CAPI3REF: Initialize The SQLite Library
  1566. **
  1567. ** ^The sqlite3_initialize() routine initializes the
  1568. ** SQLite library. ^The sqlite3_shutdown() routine
  1569. ** deallocates any resources that were allocated by sqlite3_initialize().
  1570. ** These routines are designed to aid in process initialization and
  1571. ** shutdown on embedded systems. Workstation applications using
  1572. ** SQLite normally do not need to invoke either of these routines.
  1573. **
  1574. ** A call to sqlite3_initialize() is an "effective" call if it is
  1575. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1576. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1577. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1578. ** of sqlite3_initialize() does any initialization. All other calls
  1579. ** are harmless no-ops.)^
  1580. **
  1581. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1582. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1583. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1584. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1585. **
  1586. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1587. ** is not. The sqlite3_shutdown() interface must only be called from a
  1588. ** single thread. All open [database connections] must be closed and all
  1589. ** other SQLite resources must be deallocated prior to invoking
  1590. ** sqlite3_shutdown().
  1591. **
  1592. ** Among other things, ^sqlite3_initialize() will invoke
  1593. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1594. ** will invoke sqlite3_os_end().
  1595. **
  1596. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1597. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1598. ** the library (perhaps it is unable to allocate a needed resource such
  1599. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1600. **
  1601. ** ^The sqlite3_initialize() routine is called internally by many other
  1602. ** SQLite interfaces so that an application usually does not need to
  1603. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1604. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1605. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1606. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1607. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1608. ** are omitted and the application must call sqlite3_initialize() directly
  1609. ** prior to using any other SQLite interface. For maximum portability,
  1610. ** it is recommended that applications always invoke sqlite3_initialize()
  1611. ** directly prior to using any other SQLite interface. Future releases
  1612. ** of SQLite may require this. In other words, the behavior exhibited
  1613. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1614. ** default behavior in some future release of SQLite.
  1615. **
  1616. ** The sqlite3_os_init() routine does operating-system specific
  1617. ** initialization of the SQLite library. The sqlite3_os_end()
  1618. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1619. ** performed by these routines include allocation or deallocation
  1620. ** of static resources, initialization of global variables,
  1621. ** setting up a default [sqlite3_vfs] module, or setting up
  1622. ** a default configuration using [sqlite3_config()].
  1623. **
  1624. ** The application should never invoke either sqlite3_os_init()
  1625. ** or sqlite3_os_end() directly. The application should only invoke
  1626. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1627. ** interface is called automatically by sqlite3_initialize() and
  1628. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1629. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1630. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1631. ** When [custom builds | built for other platforms]
  1632. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1633. ** option) the application must supply a suitable implementation for
  1634. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1635. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1636. ** must return [SQLITE_OK] on success and some other [error code] upon
  1637. ** failure.
  1638. */
  1639. SQLITE_API int sqlite3_initialize(void);
  1640. SQLITE_API int sqlite3_shutdown(void);
  1641. SQLITE_API int sqlite3_os_init(void);
  1642. SQLITE_API int sqlite3_os_end(void);
  1643. /*
  1644. ** CAPI3REF: Configuring The SQLite Library
  1645. **
  1646. ** The sqlite3_config() interface is used to make global configuration
  1647. ** changes to SQLite in order to tune SQLite to the specific needs of
  1648. ** the application. The default configuration is recommended for most
  1649. ** applications and so this routine is usually not necessary. It is
  1650. ** provided to support rare applications with unusual needs.
  1651. **
  1652. ** The sqlite3_config() interface is not threadsafe. The application
  1653. ** must insure that no other SQLite interfaces are invoked by other
  1654. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1655. ** may only be invoked prior to library initialization using
  1656. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1657. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1658. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1659. ** Note, however, that ^sqlite3_config() can be called as part of the
  1660. ** implementation of an application-defined [sqlite3_os_init()].
  1661. **
  1662. ** The first argument to sqlite3_config() is an integer
  1663. ** [configuration option] that determines
  1664. ** what property of SQLite is to be configured. Subsequent arguments
  1665. ** vary depending on the [configuration option]
  1666. ** in the first argument.
  1667. **
  1668. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1669. ** ^If the option is unknown or SQLite is unable to set the option
  1670. ** then this routine returns a non-zero [error code].
  1671. */
  1672. SQLITE_API int sqlite3_config(int, ...);
  1673. /*
  1674. ** CAPI3REF: Configure database connections
  1675. **
  1676. ** The sqlite3_db_config() interface is used to make configuration
  1677. ** changes to a [database connection]. The interface is similar to
  1678. ** [sqlite3_config()] except that the changes apply to a single
  1679. ** [database connection] (specified in the first argument).
  1680. **
  1681. ** The second argument to sqlite3_db_config(D,V,...) is the
  1682. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1683. ** that indicates what aspect of the [database connection] is being configured.
  1684. ** Subsequent arguments vary depending on the configuration verb.
  1685. **
  1686. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1687. ** the call is considered successful.
  1688. */
  1689. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1690. /*
  1691. ** CAPI3REF: Memory Allocation Routines
  1692. **
  1693. ** An instance of this object defines the interface between SQLite
  1694. ** and low-level memory allocation routines.
  1695. **
  1696. ** This object is used in only one place in the SQLite interface.
  1697. ** A pointer to an instance of this object is the argument to
  1698. ** [sqlite3_config()] when the configuration option is
  1699. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1700. ** By creating an instance of this object
  1701. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1702. ** during configuration, an application can specify an alternative
  1703. ** memory allocation subsystem for SQLite to use for all of its
  1704. ** dynamic memory needs.
  1705. **
  1706. ** Note that SQLite comes with several [built-in memory allocators]
  1707. ** that are perfectly adequate for the overwhelming majority of applications
  1708. ** and that this object is only useful to a tiny minority of applications
  1709. ** with specialized memory allocation requirements. This object is
  1710. ** also used during testing of SQLite in order to specify an alternative
  1711. ** memory allocator that simulates memory out-of-memory conditions in
  1712. ** order to verify that SQLite recovers gracefully from such
  1713. ** conditions.
  1714. **
  1715. ** The xMalloc, xRealloc, and xFree methods must work like the
  1716. ** malloc(), realloc() and free() functions from the standard C library.
  1717. ** ^SQLite guarantees that the second argument to
  1718. ** xRealloc is always a value returned by a prior call to xRoundup.
  1719. **
  1720. ** xSize should return the allocated size of a memory allocation
  1721. ** previously obtained from xMalloc or xRealloc. The allocated size
  1722. ** is always at least as big as the requested size but may be larger.
  1723. **
  1724. ** The xRoundup method returns what would be the allocated size of
  1725. ** a memory allocation given a particular requested size. Most memory
  1726. ** allocators round up memory allocations at least to the next multiple
  1727. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1728. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1729. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1730. ** that causes the corresponding memory allocation to fail.
  1731. **
  1732. ** The xInit method initializes the memory allocator. (For example,
  1733. ** it might allocate any require mutexes or initialize internal data
  1734. ** structures. The xShutdown method is invoked (indirectly) by
  1735. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1736. ** by xInit. The pAppData pointer is used as the only parameter to
  1737. ** xInit and xShutdown.
  1738. **
  1739. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1740. ** the xInit method, so the xInit method need not be threadsafe. The
  1741. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1742. ** not need to be threadsafe either. For all other methods, SQLite
  1743. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1744. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1745. ** it is by default) and so the methods are automatically serialized.
  1746. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1747. ** methods must be threadsafe or else make their own arrangements for
  1748. ** serialization.
  1749. **
  1750. ** SQLite will never invoke xInit() more than once without an intervening
  1751. ** call to xShutdown().
  1752. */
  1753. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1754. struct sqlite3_mem_methods {
  1755. void *(*xMalloc)(int); /* Memory allocation function */
  1756. void (*xFree)(void*); /* Free a prior allocation */
  1757. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1758. int (*xSize)(void*); /* Return the size of an allocation */
  1759. int (*xRoundup)(int); /* Round up request size to allocation size */
  1760. int (*xInit)(void*); /* Initialize the memory allocator */
  1761. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1762. void *pAppData; /* Argument to xInit() and xShutdown() */
  1763. };
  1764. /*
  1765. ** CAPI3REF: Configuration Options
  1766. ** KEYWORDS: {configuration option}
  1767. **
  1768. ** These constants are the available integer configuration options that
  1769. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1770. **
  1771. ** New configuration options may be added in future releases of SQLite.
  1772. ** Existing configuration options might be discontinued. Applications
  1773. ** should check the return code from [sqlite3_config()] to make sure that
  1774. ** the call worked. The [sqlite3_config()] interface will return a
  1775. ** non-zero [error code] if a discontinued or unsupported configuration option
  1776. ** is invoked.
  1777. **
  1778. ** <dl>
  1779. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1780. ** <dd>There are no arguments to this option. ^This option sets the
  1781. ** [threading mode] to Single-thread. In other words, it disables
  1782. ** all mutexing and puts SQLite into a mode where it can only be used
  1783. ** by a single thread. ^If SQLite is compiled with
  1784. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1785. ** it is not possible to change the [threading mode] from its default
  1786. ** value of Single-thread and so [sqlite3_config()] will return
  1787. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1788. ** configuration option.</dd>
  1789. **
  1790. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1791. ** <dd>There are no arguments to this option. ^This option sets the
  1792. ** [threading mode] to Multi-thread. In other words, it disables
  1793. ** mutexing on [database connection] and [prepared statement] objects.
  1794. ** The application is responsible for serializing access to
  1795. ** [database connections] and [prepared statements]. But other mutexes
  1796. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1797. ** environment as long as no two threads attempt to use the same
  1798. ** [database connection] at the same time. ^If SQLite is compiled with
  1799. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1800. ** it is not possible to set the Multi-thread [threading mode] and
  1801. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1802. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1803. **
  1804. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1805. ** <dd>There are no arguments to this option. ^This option sets the
  1806. ** [threading mode] to Serialized. In other words, this option enables
  1807. ** all mutexes including the recursive
  1808. ** mutexes on [database connection] and [prepared statement] objects.
  1809. ** In this mode (which is the default when SQLite is compiled with
  1810. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1811. ** to [database connections] and [prepared statements] so that the
  1812. ** application is free to use the same [database connection] or the
  1813. ** same [prepared statement] in different threads at the same time.
  1814. ** ^If SQLite is compiled with
  1815. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1816. ** it is not possible to set the Serialized [threading mode] and
  1817. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1818. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1819. **
  1820. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1821. ** <dd> ^(This option takes a single argument which is a pointer to an
  1822. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1823. ** alternative low-level memory allocation routines to be used in place of
  1824. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1825. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1826. ** before the [sqlite3_config()] call returns.</dd>
  1827. **
  1828. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1829. ** <dd> ^(This option takes a single argument which is a pointer to an
  1830. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1831. ** structure is filled with the currently defined memory allocation routines.)^
  1832. ** This option can be used to overload the default memory allocation
  1833. ** routines with a wrapper that simulations memory allocation failure or
  1834. ** tracks memory usage, for example. </dd>
  1835. **
  1836. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1837. ** <dd> ^This option takes single argument of type int, interpreted as a
  1838. ** boolean, which enables or disables the collection of memory allocation
  1839. ** statistics. ^(When memory allocation statistics are disabled, the
  1840. ** following SQLite interfaces become non-operational:
  1841. ** <ul>
  1842. ** <li> [sqlite3_memory_used()]
  1843. ** <li> [sqlite3_memory_highwater()]
  1844. ** <li> [sqlite3_soft_heap_limit64()]
  1845. ** <li> [sqlite3_status()]
  1846. ** </ul>)^
  1847. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1848. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1849. ** allocation statistics are disabled by default.
  1850. ** </dd>
  1851. **
  1852. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1853. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1854. ** scratch memory. There are three arguments: A pointer an 8-byte
  1855. ** aligned memory buffer from which the scratch allocations will be
  1856. ** drawn, the size of each scratch allocation (sz),
  1857. ** and the maximum number of scratch allocations (N). The sz
  1858. ** argument must be a multiple of 16.
  1859. ** The first argument must be a pointer to an 8-byte aligned buffer
  1860. ** of at least sz*N bytes of memory.
  1861. ** ^SQLite will use no more than two scratch buffers per thread. So
  1862. ** N should be set to twice the expected maximum number of threads.
  1863. ** ^SQLite will never require a scratch buffer that is more than 6
  1864. ** times the database page size. ^If SQLite needs needs additional
  1865. ** scratch memory beyond what is provided by this configuration option, then
  1866. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1867. **
  1868. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1869. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1870. ** the database page cache with the default page cache implementation.
  1871. ** This configuration should not be used if an application-define page
  1872. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1873. ** There are three arguments to this option: A pointer to 8-byte aligned
  1874. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1875. ** The sz argument should be the size of the largest database page
  1876. ** (a power of two between 512 and 32768) plus a little extra for each
  1877. ** page header. ^The page header size is 20 to 40 bytes depending on
  1878. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1879. ** to make sz a little too large. The first
  1880. ** argument should point to an allocation of at least sz*N bytes of memory.
  1881. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1882. ** memory needs for the first N pages that it adds to cache. ^If additional
  1883. ** page cache memory is needed beyond what is provided by this option, then
  1884. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1885. ** The pointer in the first argument must
  1886. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1887. ** will be undefined.</dd>
  1888. **
  1889. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1890. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1891. ** for all of its dynamic memory allocation needs beyond those provided
  1892. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1893. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1894. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1895. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1896. ** to using its default memory allocator (the system malloc() implementation),
  1897. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1898. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1899. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1900. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1901. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1902. ** boundary or subsequent behavior of SQLite will be undefined.
  1903. ** The minimum allocation size is capped at 2**12. Reasonable values
  1904. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1905. **
  1906. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1907. ** <dd> ^(This option takes a single argument which is a pointer to an
  1908. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1909. ** alternative low-level mutex routines to be used in place
  1910. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1911. ** content of the [sqlite3_mutex_methods] structure before the call to
  1912. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1913. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1914. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1915. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1916. ** return [SQLITE_ERROR].</dd>
  1917. **
  1918. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1919. ** <dd> ^(This option takes a single argument which is a pointer to an
  1920. ** instance of the [sqlite3_mutex_methods] structure. The
  1921. ** [sqlite3_mutex_methods]
  1922. ** structure is filled with the currently defined mutex routines.)^
  1923. ** This option can be used to overload the default mutex allocation
  1924. ** routines with a wrapper used to track mutex usage for performance
  1925. ** profiling or testing, for example. ^If SQLite is compiled with
  1926. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1927. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1928. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1929. ** return [SQLITE_ERROR].</dd>
  1930. **
  1931. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1932. ** <dd> ^(This option takes two arguments that determine the default
  1933. ** memory allocation for the lookaside memory allocator on each
  1934. ** [database connection]. The first argument is the
  1935. ** size of each lookaside buffer slot and the second is the number of
  1936. ** slots allocated to each database connection.)^ ^(This option sets the
  1937. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1938. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1939. ** configuration on individual connections.)^ </dd>
  1940. **
  1941. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1942. ** <dd> ^(This option takes a single argument which is a pointer to
  1943. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  1944. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1945. ** object and uses it for page cache memory allocations.</dd>
  1946. **
  1947. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1948. ** <dd> ^(This option takes a single argument which is a pointer to an
  1949. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  1950. ** page cache implementation into that object.)^ </dd>
  1951. **
  1952. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1953. ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1954. ** function with a call signature of void(*)(void*,int,const char*),
  1955. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1956. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1957. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1958. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1959. ** passed through as the first parameter to the application-defined logger
  1960. ** function whenever that function is invoked. ^The second parameter to
  1961. ** the logger function is a copy of the first parameter to the corresponding
  1962. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1963. ** [extended result code]. ^The third parameter passed to the logger is
  1964. ** log message after formatting via [sqlite3_snprintf()].
  1965. ** The SQLite logging interface is not reentrant; the logger function
  1966. ** supplied by the application must not invoke any SQLite interface.
  1967. ** In a multi-threaded application, the application-defined logger
  1968. ** function must be threadsafe. </dd>
  1969. **
  1970. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1971. ** <dd> This option takes a single argument of type int. If non-zero, then
  1972. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1973. ** is globally disabled. If URI handling is globally enabled, all filenames
  1974. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1975. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1976. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1977. ** connection is opened. If it is globally disabled, filenames are
  1978. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1979. ** database connection is opened. By default, URI handling is globally
  1980. ** disabled. The default value may be changed by compiling with the
  1981. ** [SQLITE_USE_URI] symbol defined.
  1982. **
  1983. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1984. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFNIG_GETPCACHE
  1985. ** <dd> These options are obsolete and should not be used by new code.
  1986. ** They are retained for backwards compatibility but are now no-ops.
  1987. ** </dl>
  1988. */
  1989. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1990. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1991. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1992. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1993. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1994. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1995. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1996. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1997. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1998. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1999. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2000. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2001. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2002. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2003. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2004. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2005. #define SQLITE_CONFIG_URI 17 /* int */
  2006. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2007. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2008. /*
  2009. ** CAPI3REF: Database Connection Configuration Options
  2010. **
  2011. ** These constants are the available integer configuration options that
  2012. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2013. **
  2014. ** New configuration options may be added in future releases of SQLite.
  2015. ** Existing configuration options might be discontinued. Applications
  2016. ** should check the return code from [sqlite3_db_config()] to make sure that
  2017. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2018. ** non-zero [error code] if a discontinued or unsupported configuration option
  2019. ** is invoked.
  2020. **
  2021. ** <dl>
  2022. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2023. ** <dd> ^This option takes three additional arguments that determine the
  2024. ** [lookaside memory allocator] configuration for the [database connection].
  2025. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2026. ** pointer to a memory buffer to use for lookaside memory.
  2027. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2028. ** may be NULL in which case SQLite will allocate the
  2029. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2030. ** size of each lookaside buffer slot. ^The third argument is the number of
  2031. ** slots. The size of the buffer in the first argument must be greater than
  2032. ** or equal to the product of the second and third arguments. The buffer
  2033. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2034. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2035. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2036. ** configuration for a database connection can only be changed when that
  2037. ** connection is not currently using lookaside memory, or in other words
  2038. ** when the "current value" returned by
  2039. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2040. ** Any attempt to change the lookaside memory configuration when lookaside
  2041. ** memory is in use leaves the configuration unchanged and returns
  2042. ** [SQLITE_BUSY].)^</dd>
  2043. **
  2044. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2045. ** <dd> ^This option is used to enable or disable the enforcement of
  2046. ** [foreign key constraints]. There should be two additional arguments.
  2047. ** The first argument is an integer which is 0 to disable FK enforcement,
  2048. ** positive to enable FK enforcement or negative to leave FK enforcement
  2049. ** unchanged. The second parameter is a pointer to an integer into which
  2050. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2051. ** following this call. The second parameter may be a NULL pointer, in
  2052. ** which case the FK enforcement setting is not reported back. </dd>
  2053. **
  2054. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2055. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2056. ** There should be two additional arguments.
  2057. ** The first argument is an integer which is 0 to disable triggers,
  2058. ** positive to enable triggers or negative to leave the setting unchanged.
  2059. ** The second parameter is a pointer to an integer into which
  2060. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2061. ** following this call. The second parameter may be a NULL pointer, in
  2062. ** which case the trigger setting is not reported back. </dd>
  2063. **
  2064. ** </dl>
  2065. */
  2066. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2067. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2068. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2069. /*
  2070. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2071. **
  2072. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2073. ** [extended result codes] feature of SQLite. ^The extended result
  2074. ** codes are disabled by default for historical compatibility.
  2075. */
  2076. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  2077. /*
  2078. ** CAPI3REF: Last Insert Rowid
  2079. **
  2080. ** ^Each entry in an SQLite table has a unique 64-bit signed
  2081. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2082. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2083. ** names are not also used by explicitly declared columns. ^If
  2084. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2085. ** is another alias for the rowid.
  2086. **
  2087. ** ^This routine returns the [rowid] of the most recent
  2088. ** successful [INSERT] into the database from the [database connection]
  2089. ** in the first argument. ^As of SQLite version 3.7.7, this routines
  2090. ** records the last insert rowid of both ordinary tables and [virtual tables].
  2091. ** ^If no successful [INSERT]s
  2092. ** have ever occurred on that database connection, zero is returned.
  2093. **
  2094. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2095. ** method, then this routine will return the [rowid] of the inserted
  2096. ** row as long as the trigger or virtual table method is running.
  2097. ** But once the trigger or virtual table method ends, the value returned
  2098. ** by this routine reverts to what it was before the trigger or virtual
  2099. ** table method began.)^
  2100. **
  2101. ** ^An [INSERT] that fails due to a constraint violation is not a
  2102. ** successful [INSERT] and does not change the value returned by this
  2103. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2104. ** and INSERT OR ABORT make no changes to the return value of this
  2105. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2106. ** encounters a constraint violation, it does not fail. The
  2107. ** INSERT continues to completion after deleting rows that caused
  2108. ** the constraint problem so INSERT OR REPLACE will always change
  2109. ** the return value of this interface.)^
  2110. **
  2111. ** ^For the purposes of this routine, an [INSERT] is considered to
  2112. ** be successful even if it is subsequently rolled back.
  2113. **
  2114. ** This function is accessible to SQL statements via the
  2115. ** [last_insert_rowid() SQL function].
  2116. **
  2117. ** If a separate thread performs a new [INSERT] on the same
  2118. ** database connection while the [sqlite3_last_insert_rowid()]
  2119. ** function is running and thus changes the last insert [rowid],
  2120. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2121. ** unpredictable and might not equal either the old or the new
  2122. ** last insert [rowid].
  2123. */
  2124. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  2125. /*
  2126. ** CAPI3REF: Count The Number Of Rows Modified
  2127. **
  2128. ** ^This function returns the number of database rows that were changed
  2129. ** or inserted or deleted by the most recently completed SQL statement
  2130. ** on the [database connection] specified by the first parameter.
  2131. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  2132. ** or [DELETE] statement are counted. Auxiliary changes caused by
  2133. ** triggers or [foreign key actions] are not counted.)^ Use the
  2134. ** [sqlite3_total_changes()] function to find the total number of changes
  2135. ** including changes caused by triggers and foreign key actions.
  2136. **
  2137. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  2138. ** are not counted. Only real table changes are counted.
  2139. **
  2140. ** ^(A "row change" is a change to a single row of a single table
  2141. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  2142. ** are changed as side effects of [REPLACE] constraint resolution,
  2143. ** rollback, ABORT processing, [DROP TABLE], or by any other
  2144. ** mechanisms do not count as direct row changes.)^
  2145. **
  2146. ** A "trigger context" is a scope of execution that begins and
  2147. ** ends with the script of a [CREATE TRIGGER | trigger].
  2148. ** Most SQL statements are
  2149. ** evaluated outside of any trigger. This is the "top level"
  2150. ** trigger context. If a trigger fires from the top level, a
  2151. ** new trigger context is entered for the duration of that one
  2152. ** trigger. Subtriggers create subcontexts for their duration.
  2153. **
  2154. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  2155. ** not create a new trigger context.
  2156. **
  2157. ** ^This function returns the number of direct row changes in the
  2158. ** most recent INSERT, UPDATE, or DELETE statement within the same
  2159. ** trigger context.
  2160. **
  2161. ** ^Thus, when called from the top level, this function returns the
  2162. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  2163. ** that also occurred at the top level. ^(Within the body of a trigger,
  2164. ** the sqlite3_changes() interface can be called to find the number of
  2165. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  2166. ** statement within the body of the same trigger.
  2167. ** However, the number returned does not include changes
  2168. ** caused by subtriggers since those have their own context.)^
  2169. **
  2170. ** See also the [sqlite3_total_changes()] interface, the
  2171. ** [count_changes pragma], and the [changes() SQL function].
  2172. **
  2173. ** If a separate thread makes changes on the same database connection
  2174. ** while [sqlite3_changes()] is running then the value returned
  2175. ** is unpredictable and not meaningful.
  2176. */
  2177. SQLITE_API int sqlite3_changes(sqlite3*);
  2178. /*
  2179. ** CAPI3REF: Total Number Of Rows Modified
  2180. **
  2181. ** ^This function returns the number of row changes caused by [INSERT],
  2182. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  2183. ** ^(The count returned by sqlite3_total_changes() includes all changes
  2184. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  2185. ** [foreign key actions]. However,
  2186. ** the count does not include changes used to implement [REPLACE] constraints,
  2187. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  2188. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  2189. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  2190. ** are counted.)^
  2191. ** ^The sqlite3_total_changes() function counts the changes as soon as
  2192. ** the statement that makes them is completed (when the statement handle
  2193. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  2194. **
  2195. ** See also the [sqlite3_changes()] interface, the
  2196. ** [count_changes pragma], and the [total_changes() SQL function].
  2197. **
  2198. ** If a separate thread makes changes on the same database connection
  2199. ** while [sqlite3_total_changes()] is running then the value
  2200. ** returned is unpredictable and not meaningful.
  2201. */
  2202. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2203. /*
  2204. ** CAPI3REF: Interrupt A Long-Running Query
  2205. **
  2206. ** ^This function causes any pending database operation to abort and
  2207. ** return at its earliest opportunity. This routine is typically
  2208. ** called in response to a user action such as pressing "Cancel"
  2209. ** or Ctrl-C where the user wants a long query operation to halt
  2210. ** immediately.
  2211. **
  2212. ** ^It is safe to call this routine from a thread different from the
  2213. ** thread that is currently running the database operation. But it
  2214. ** is not safe to call this routine with a [database connection] that
  2215. ** is closed or might close before sqlite3_interrupt() returns.
  2216. **
  2217. ** ^If an SQL operation is very nearly finished at the time when
  2218. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2219. ** to be interrupted and might continue to completion.
  2220. **
  2221. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2222. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2223. ** that is inside an explicit transaction, then the entire transaction
  2224. ** will be rolled back automatically.
  2225. **
  2226. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2227. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2228. ** that are started after the sqlite3_interrupt() call and before the
  2229. ** running statements reaches zero are interrupted as if they had been
  2230. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2231. ** that are started after the running statement count reaches zero are
  2232. ** not effected by the sqlite3_interrupt().
  2233. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2234. ** SQL statements is a no-op and has no effect on SQL statements
  2235. ** that are started after the sqlite3_interrupt() call returns.
  2236. **
  2237. ** If the database connection closes while [sqlite3_interrupt()]
  2238. ** is running then bad things will likely happen.
  2239. */
  2240. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2241. /*
  2242. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2243. **
  2244. ** These routines are useful during command-line input to determine if the
  2245. ** currently entered text seems to form a complete SQL statement or
  2246. ** if additional input is needed before sending the text into
  2247. ** SQLite for parsing. ^These routines return 1 if the input string
  2248. ** appears to be a complete SQL statement. ^A statement is judged to be
  2249. ** complete if it ends with a semicolon token and is not a prefix of a
  2250. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2251. ** string literals or quoted identifier names or comments are not
  2252. ** independent tokens (they are part of the token in which they are
  2253. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2254. ** and comments that follow the final semicolon are ignored.
  2255. **
  2256. ** ^These routines return 0 if the statement is incomplete. ^If a
  2257. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2258. **
  2259. ** ^These routines do not parse the SQL statements thus
  2260. ** will not detect syntactically incorrect SQL.
  2261. **
  2262. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2263. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2264. ** automatically by sqlite3_complete16(). If that initialization fails,
  2265. ** then the return value from sqlite3_complete16() will be non-zero
  2266. ** regardless of whether or not the input SQL is complete.)^
  2267. **
  2268. ** The input to [sqlite3_complete()] must be a zero-terminated
  2269. ** UTF-8 string.
  2270. **
  2271. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2272. ** UTF-16 string in native byte order.
  2273. */
  2274. SQLITE_API int sqlite3_complete(const char *sql);
  2275. SQLITE_API int sqlite3_complete16(const void *sql);
  2276. /*
  2277. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2278. **
  2279. ** ^This routine sets a callback function that might be invoked whenever
  2280. ** an attempt is made to open a database table that another thread
  2281. ** or process has locked.
  2282. **
  2283. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  2284. ** is returned immediately upon encountering the lock. ^If the busy callback
  2285. ** is not NULL, then the callback might be invoked with two arguments.
  2286. **
  2287. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2288. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2289. ** the busy handler callback is the number of times that the busy handler has
  2290. ** been invoked for this locking event. ^If the
  2291. ** busy callback returns 0, then no additional attempts are made to
  2292. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  2293. ** ^If the callback returns non-zero, then another attempt
  2294. ** is made to open the database for reading and the cycle repeats.
  2295. **
  2296. ** The presence of a busy handler does not guarantee that it will be invoked
  2297. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2298. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2299. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  2300. ** Consider a scenario where one process is holding a read lock that
  2301. ** it is trying to promote to a reserved lock and
  2302. ** a second process is holding a reserved lock that it is trying
  2303. ** to promote to an exclusive lock. The first process cannot proceed
  2304. ** because it is blocked by the second and the second process cannot
  2305. ** proceed because it is blocked by the first. If both processes
  2306. ** invoke the busy handlers, neither will make any progress. Therefore,
  2307. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2308. ** will induce the first process to release its read lock and allow
  2309. ** the second process to proceed.
  2310. **
  2311. ** ^The default busy callback is NULL.
  2312. **
  2313. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2314. ** when SQLite is in the middle of a large transaction where all the
  2315. ** changes will not fit into the in-memory cache. SQLite will
  2316. ** already hold a RESERVED lock on the database file, but it needs
  2317. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2318. ** pages into the database file without harm to concurrent
  2319. ** readers. ^If it is unable to promote the lock, then the in-memory
  2320. ** cache will be left in an inconsistent state and so the error
  2321. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2322. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2323. ** forces an automatic rollback of the changes. See the
  2324. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2325. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2326. ** this is important.
  2327. **
  2328. ** ^(There can only be a single busy handler defined for each
  2329. ** [database connection]. Setting a new busy handler clears any
  2330. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2331. ** will also set or clear the busy handler.
  2332. **
  2333. ** The busy callback should not take any actions which modify the
  2334. ** database connection that invoked the busy handler. Any such actions
  2335. ** result in undefined behavior.
  2336. **
  2337. ** A busy handler must not close the database connection
  2338. ** or [prepared statement] that invoked the busy handler.
  2339. */
  2340. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2341. /*
  2342. ** CAPI3REF: Set A Busy Timeout
  2343. **
  2344. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2345. ** for a specified amount of time when a table is locked. ^The handler
  2346. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2347. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2348. ** the handler returns 0 which causes [sqlite3_step()] to return
  2349. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2350. **
  2351. ** ^Calling this routine with an argument less than or equal to zero
  2352. ** turns off all busy handlers.
  2353. **
  2354. ** ^(There can only be a single busy handler for a particular
  2355. ** [database connection] any any given moment. If another busy handler
  2356. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2357. ** this routine, that other busy handler is cleared.)^
  2358. */
  2359. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2360. /*
  2361. ** CAPI3REF: Convenience Routines For Running Queries
  2362. **
  2363. ** This is a legacy interface that is preserved for backwards compatibility.
  2364. ** Use of this interface is not recommended.
  2365. **
  2366. ** Definition: A <b>result table</b> is memory data structure created by the
  2367. ** [sqlite3_get_table()] interface. A result table records the
  2368. ** complete query results from one or more queries.
  2369. **
  2370. ** The table conceptually has a number of rows and columns. But
  2371. ** these numbers are not part of the result table itself. These
  2372. ** numbers are obtained separately. Let N be the number of rows
  2373. ** and M be the number of columns.
  2374. **
  2375. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2376. ** There are (N+1)*M elements in the array. The first M pointers point
  2377. ** to zero-terminated strings that contain the names of the columns.
  2378. ** The remaining entries all point to query results. NULL values result
  2379. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2380. ** string representation as returned by [sqlite3_column_text()].
  2381. **
  2382. ** A result table might consist of one or more memory allocations.
  2383. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2384. ** A result table should be deallocated using [sqlite3_free_table()].
  2385. **
  2386. ** ^(As an example of the result table format, suppose a query result
  2387. ** is as follows:
  2388. **
  2389. ** <blockquote><pre>
  2390. ** Name | Age
  2391. ** -----------------------
  2392. ** Alice | 43
  2393. ** Bob | 28
  2394. ** Cindy | 21
  2395. ** </pre></blockquote>
  2396. **
  2397. ** There are two column (M==2) and three rows (N==3). Thus the
  2398. ** result table has 8 entries. Suppose the result table is stored
  2399. ** in an array names azResult. Then azResult holds this content:
  2400. **
  2401. ** <blockquote><pre>
  2402. ** azResult&#91;0] = "Name";
  2403. ** azResult&#91;1] = "Age";
  2404. ** azResult&#91;2] = "Alice";
  2405. ** azResult&#91;3] = "43";
  2406. ** azResult&#91;4] = "Bob";
  2407. ** azResult&#91;5] = "28";
  2408. ** azResult&#91;6] = "Cindy";
  2409. ** azResult&#91;7] = "21";
  2410. ** </pre></blockquote>)^
  2411. **
  2412. ** ^The sqlite3_get_table() function evaluates one or more
  2413. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2414. ** string of its 2nd parameter and returns a result table to the
  2415. ** pointer given in its 3rd parameter.
  2416. **
  2417. ** After the application has finished with the result from sqlite3_get_table(),
  2418. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2419. ** release the memory that was malloced. Because of the way the
  2420. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2421. ** function must not try to call [sqlite3_free()] directly. Only
  2422. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2423. **
  2424. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2425. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2426. ** to any internal data structures of SQLite. It uses only the public
  2427. ** interface defined here. As a consequence, errors that occur in the
  2428. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2429. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2430. ** [sqlite3_errmsg()].
  2431. */
  2432. SQLITE_API int sqlite3_get_table(
  2433. sqlite3 *db, /* An open database */
  2434. const char *zSql, /* SQL to be evaluated */
  2435. char ***pazResult, /* Results of the query */
  2436. int *pnRow, /* Number of result rows written here */
  2437. int *pnColumn, /* Number of result columns written here */
  2438. char **pzErrmsg /* Error msg written here */
  2439. );
  2440. SQLITE_API void sqlite3_free_table(char **result);
  2441. /*
  2442. ** CAPI3REF: Formatted String Printing Functions
  2443. **
  2444. ** These routines are work-alikes of the "printf()" family of functions
  2445. ** from the standard C library.
  2446. **
  2447. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2448. ** results into memory obtained from [sqlite3_malloc()].
  2449. ** The strings returned by these two routines should be
  2450. ** released by [sqlite3_free()]. ^Both routines return a
  2451. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2452. ** memory to hold the resulting string.
  2453. **
  2454. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2455. ** the standard C library. The result is written into the
  2456. ** buffer supplied as the second parameter whose size is given by
  2457. ** the first parameter. Note that the order of the
  2458. ** first two parameters is reversed from snprintf().)^ This is an
  2459. ** historical accident that cannot be fixed without breaking
  2460. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2461. ** returns a pointer to its buffer instead of the number of
  2462. ** characters actually written into the buffer.)^ We admit that
  2463. ** the number of characters written would be a more useful return
  2464. ** value but we cannot change the implementation of sqlite3_snprintf()
  2465. ** now without breaking compatibility.
  2466. **
  2467. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2468. ** guarantees that the buffer is always zero-terminated. ^The first
  2469. ** parameter "n" is the total size of the buffer, including space for
  2470. ** the zero terminator. So the longest string that can be completely
  2471. ** written will be n-1 characters.
  2472. **
  2473. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2474. **
  2475. ** These routines all implement some additional formatting
  2476. ** options that are useful for constructing SQL statements.
  2477. ** All of the usual printf() formatting options apply. In addition, there
  2478. ** is are "%q", "%Q", and "%z" options.
  2479. **
  2480. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2481. ** string from the argument list. But %q also doubles every '\'' character.
  2482. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2483. ** character it escapes that character and allows it to be inserted into
  2484. ** the string.
  2485. **
  2486. ** For example, assume the string variable zText contains text as follows:
  2487. **
  2488. ** <blockquote><pre>
  2489. ** char *zText = "It's a happy day!";
  2490. ** </pre></blockquote>
  2491. **
  2492. ** One can use this text in an SQL statement as follows:
  2493. **
  2494. ** <blockquote><pre>
  2495. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2496. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2497. ** sqlite3_free(zSQL);
  2498. ** </pre></blockquote>
  2499. **
  2500. ** Because the %q format string is used, the '\'' character in zText
  2501. ** is escaped and the SQL generated is as follows:
  2502. **
  2503. ** <blockquote><pre>
  2504. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2505. ** </pre></blockquote>
  2506. **
  2507. ** This is correct. Had we used %s instead of %q, the generated SQL
  2508. ** would have looked like this:
  2509. **
  2510. ** <blockquote><pre>
  2511. ** INSERT INTO table1 VALUES('It's a happy day!');
  2512. ** </pre></blockquote>
  2513. **
  2514. ** This second example is an SQL syntax error. As a general rule you should
  2515. ** always use %q instead of %s when inserting text into a string literal.
  2516. **
  2517. ** ^(The %Q option works like %q except it also adds single quotes around
  2518. ** the outside of the total string. Additionally, if the parameter in the
  2519. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2520. ** single quotes).)^ So, for example, one could say:
  2521. **
  2522. ** <blockquote><pre>
  2523. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2524. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2525. ** sqlite3_free(zSQL);
  2526. ** </pre></blockquote>
  2527. **
  2528. ** The code above will render a correct SQL statement in the zSQL
  2529. ** variable even if the zText variable is a NULL pointer.
  2530. **
  2531. ** ^(The "%z" formatting option works like "%s" but with the
  2532. ** addition that after the string has been read and copied into
  2533. ** the result, [sqlite3_free()] is called on the input string.)^
  2534. */
  2535. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2536. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2537. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2538. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2539. /*
  2540. ** CAPI3REF: Memory Allocation Subsystem
  2541. **
  2542. ** The SQLite core uses these three routines for all of its own
  2543. ** internal memory allocation needs. "Core" in the previous sentence
  2544. ** does not include operating-system specific VFS implementation. The
  2545. ** Windows VFS uses native malloc() and free() for some operations.
  2546. **
  2547. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2548. ** of memory at least N bytes in length, where N is the parameter.
  2549. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2550. ** memory, it returns a NULL pointer. ^If the parameter N to
  2551. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2552. ** a NULL pointer.
  2553. **
  2554. ** ^Calling sqlite3_free() with a pointer previously returned
  2555. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2556. ** that it might be reused. ^The sqlite3_free() routine is
  2557. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2558. ** to sqlite3_free() is harmless. After being freed, memory
  2559. ** should neither be read nor written. Even reading previously freed
  2560. ** memory might result in a segmentation fault or other severe error.
  2561. ** Memory corruption, a segmentation fault, or other severe error
  2562. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2563. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2564. **
  2565. ** ^(The sqlite3_realloc() interface attempts to resize a
  2566. ** prior memory allocation to be at least N bytes, where N is the
  2567. ** second parameter. The memory allocation to be resized is the first
  2568. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2569. ** is a NULL pointer then its behavior is identical to calling
  2570. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2571. ** ^If the second parameter to sqlite3_realloc() is zero or
  2572. ** negative then the behavior is exactly the same as calling
  2573. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2574. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2575. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2576. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2577. ** of the prior allocation are copied into the beginning of buffer returned
  2578. ** by sqlite3_realloc() and the prior allocation is freed.
  2579. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2580. ** is not freed.
  2581. **
  2582. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2583. ** is always aligned to at least an 8 byte boundary, or to a
  2584. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2585. ** option is used.
  2586. **
  2587. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2588. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2589. ** implementation of these routines to be omitted. That capability
  2590. ** is no longer provided. Only built-in memory allocators can be used.
  2591. **
  2592. ** The Windows OS interface layer calls
  2593. ** the system malloc() and free() directly when converting
  2594. ** filenames between the UTF-8 encoding used by SQLite
  2595. ** and whatever filename encoding is used by the particular Windows
  2596. ** installation. Memory allocation errors are detected, but
  2597. ** they are reported back as [SQLITE_CANTOPEN] or
  2598. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2599. **
  2600. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2601. ** must be either NULL or else pointers obtained from a prior
  2602. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2603. ** not yet been released.
  2604. **
  2605. ** The application must not read or write any part of
  2606. ** a block of memory after it has been released using
  2607. ** [sqlite3_free()] or [sqlite3_realloc()].
  2608. */
  2609. SQLITE_API void *sqlite3_malloc(int);
  2610. SQLITE_API void *sqlite3_realloc(void*, int);
  2611. SQLITE_API void sqlite3_free(void*);
  2612. /*
  2613. ** CAPI3REF: Memory Allocator Statistics
  2614. **
  2615. ** SQLite provides these two interfaces for reporting on the status
  2616. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2617. ** routines, which form the built-in memory allocation subsystem.
  2618. **
  2619. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2620. ** of memory currently outstanding (malloced but not freed).
  2621. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2622. ** value of [sqlite3_memory_used()] since the high-water mark
  2623. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2624. ** [sqlite3_memory_highwater()] include any overhead
  2625. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2626. ** but not overhead added by the any underlying system library
  2627. ** routines that [sqlite3_malloc()] may call.
  2628. **
  2629. ** ^The memory high-water mark is reset to the current value of
  2630. ** [sqlite3_memory_used()] if and only if the parameter to
  2631. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2632. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2633. ** prior to the reset.
  2634. */
  2635. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2636. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2637. /*
  2638. ** CAPI3REF: Pseudo-Random Number Generator
  2639. **
  2640. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2641. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2642. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2643. ** the build-in random() and randomblob() SQL functions. This interface allows
  2644. ** applications to access the same PRNG for other purposes.
  2645. **
  2646. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2647. **
  2648. ** ^The first time this routine is invoked (either internally or by
  2649. ** the application) the PRNG is seeded using randomness obtained
  2650. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2651. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2652. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2653. ** method.
  2654. */
  2655. SQLITE_API void sqlite3_randomness(int N, void *P);
  2656. /*
  2657. ** CAPI3REF: Compile-Time Authorization Callbacks
  2658. **
  2659. ** ^This routine registers an authorizer callback with a particular
  2660. ** [database connection], supplied in the first argument.
  2661. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2662. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2663. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2664. ** points during the compilation process, as logic is being created
  2665. ** to perform various actions, the authorizer callback is invoked to
  2666. ** see if those actions are allowed. ^The authorizer callback should
  2667. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2668. ** specific action but allow the SQL statement to continue to be
  2669. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2670. ** rejected with an error. ^If the authorizer callback returns
  2671. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2672. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2673. ** the authorizer will fail with an error message.
  2674. **
  2675. ** When the callback returns [SQLITE_OK], that means the operation
  2676. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2677. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2678. ** authorizer will fail with an error message explaining that
  2679. ** access is denied.
  2680. **
  2681. ** ^The first parameter to the authorizer callback is a copy of the third
  2682. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2683. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2684. ** the particular action to be authorized. ^The third through sixth parameters
  2685. ** to the callback are zero-terminated strings that contain additional
  2686. ** details about the action to be authorized.
  2687. **
  2688. ** ^If the action code is [SQLITE_READ]
  2689. ** and the callback returns [SQLITE_IGNORE] then the
  2690. ** [prepared statement] statement is constructed to substitute
  2691. ** a NULL value in place of the table column that would have
  2692. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2693. ** return can be used to deny an untrusted user access to individual
  2694. ** columns of a table.
  2695. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2696. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2697. ** [truncate optimization] is disabled and all rows are deleted individually.
  2698. **
  2699. ** An authorizer is used when [sqlite3_prepare | preparing]
  2700. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2701. ** do not try to access data they are not allowed to see, or that they do not
  2702. ** try to execute malicious statements that damage the database. For
  2703. ** example, an application may allow a user to enter arbitrary
  2704. ** SQL queries for evaluation by a database. But the application does
  2705. ** not want the user to be able to make arbitrary changes to the
  2706. ** database. An authorizer could then be put in place while the
  2707. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2708. ** disallows everything except [SELECT] statements.
  2709. **
  2710. ** Applications that need to process SQL from untrusted sources
  2711. ** might also consider lowering resource limits using [sqlite3_limit()]
  2712. ** and limiting database size using the [max_page_count] [PRAGMA]
  2713. ** in addition to using an authorizer.
  2714. **
  2715. ** ^(Only a single authorizer can be in place on a database connection
  2716. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2717. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2718. ** The authorizer is disabled by default.
  2719. **
  2720. ** The authorizer callback must not do anything that will modify
  2721. ** the database connection that invoked the authorizer callback.
  2722. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2723. ** database connections for the meaning of "modify" in this paragraph.
  2724. **
  2725. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2726. ** statement might be re-prepared during [sqlite3_step()] due to a
  2727. ** schema change. Hence, the application should ensure that the
  2728. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2729. **
  2730. ** ^Note that the authorizer callback is invoked only during
  2731. ** [sqlite3_prepare()] or its variants. Authorization is not
  2732. ** performed during statement evaluation in [sqlite3_step()], unless
  2733. ** as stated in the previous paragraph, sqlite3_step() invokes
  2734. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2735. */
  2736. SQLITE_API int sqlite3_set_authorizer(
  2737. sqlite3*,
  2738. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2739. void *pUserData
  2740. );
  2741. /*
  2742. ** CAPI3REF: Authorizer Return Codes
  2743. **
  2744. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2745. ** return either [SQLITE_OK] or one of these two constants in order
  2746. ** to signal SQLite whether or not the action is permitted. See the
  2747. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2748. ** information.
  2749. **
  2750. ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2751. ** from the [sqlite3_vtab_on_conflict()] interface.
  2752. */
  2753. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2754. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2755. /*
  2756. ** CAPI3REF: Authorizer Action Codes
  2757. **
  2758. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2759. ** that is invoked to authorize certain SQL statement actions. The
  2760. ** second parameter to the callback is an integer code that specifies
  2761. ** what action is being authorized. These are the integer action codes that
  2762. ** the authorizer callback may be passed.
  2763. **
  2764. ** These action code values signify what kind of operation is to be
  2765. ** authorized. The 3rd and 4th parameters to the authorization
  2766. ** callback function will be parameters or NULL depending on which of these
  2767. ** codes is used as the second parameter. ^(The 5th parameter to the
  2768. ** authorizer callback is the name of the database ("main", "temp",
  2769. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2770. ** is the name of the inner-most trigger or view that is responsible for
  2771. ** the access attempt or NULL if this access attempt is directly from
  2772. ** top-level SQL code.
  2773. */
  2774. /******************************************* 3rd ************ 4th ***********/
  2775. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2776. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2777. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2778. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2779. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2780. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2781. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2782. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2783. #define SQLITE_DELETE 9 /* Table Name NULL */
  2784. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2785. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2786. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2787. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2788. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2789. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2790. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2791. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2792. #define SQLITE_INSERT 18 /* Table Name NULL */
  2793. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2794. #define SQLITE_READ 20 /* Table Name Column Name */
  2795. #define SQLITE_SELECT 21 /* NULL NULL */
  2796. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2797. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2798. #define SQLITE_ATTACH 24 /* Filename NULL */
  2799. #define SQLITE_DETACH 25 /* Database Name NULL */
  2800. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2801. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2802. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2803. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2804. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2805. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2806. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2807. #define SQLITE_COPY 0 /* No longer used */
  2808. /*
  2809. ** CAPI3REF: Tracing And Profiling Functions
  2810. **
  2811. ** These routines register callback functions that can be used for
  2812. ** tracing and profiling the execution of SQL statements.
  2813. **
  2814. ** ^The callback function registered by sqlite3_trace() is invoked at
  2815. ** various times when an SQL statement is being run by [sqlite3_step()].
  2816. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2817. ** SQL statement text as the statement first begins executing.
  2818. ** ^(Additional sqlite3_trace() callbacks might occur
  2819. ** as each triggered subprogram is entered. The callbacks for triggers
  2820. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2821. **
  2822. ** ^The callback function registered by sqlite3_profile() is invoked
  2823. ** as each SQL statement finishes. ^The profile callback contains
  2824. ** the original statement text and an estimate of wall-clock time
  2825. ** of how long that statement took to run. ^The profile callback
  2826. ** time is in units of nanoseconds, however the current implementation
  2827. ** is only capable of millisecond resolution so the six least significant
  2828. ** digits in the time are meaningless. Future versions of SQLite
  2829. ** might provide greater resolution on the profiler callback. The
  2830. ** sqlite3_profile() function is considered experimental and is
  2831. ** subject to change in future versions of SQLite.
  2832. */
  2833. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2834. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2835. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2836. /*
  2837. ** CAPI3REF: Query Progress Callbacks
  2838. **
  2839. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2840. ** function X to be invoked periodically during long running calls to
  2841. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2842. ** database connection D. An example use for this
  2843. ** interface is to keep a GUI updated during a large query.
  2844. **
  2845. ** ^The parameter P is passed through as the only parameter to the
  2846. ** callback function X. ^The parameter N is the number of
  2847. ** [virtual machine instructions] that are evaluated between successive
  2848. ** invocations of the callback X.
  2849. **
  2850. ** ^Only a single progress handler may be defined at one time per
  2851. ** [database connection]; setting a new progress handler cancels the
  2852. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2853. ** ^The progress handler is also disabled by setting N to a value less
  2854. ** than 1.
  2855. **
  2856. ** ^If the progress callback returns non-zero, the operation is
  2857. ** interrupted. This feature can be used to implement a
  2858. ** "Cancel" button on a GUI progress dialog box.
  2859. **
  2860. ** The progress handler callback must not do anything that will modify
  2861. ** the database connection that invoked the progress handler.
  2862. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2863. ** database connections for the meaning of "modify" in this paragraph.
  2864. **
  2865. */
  2866. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2867. /*
  2868. ** CAPI3REF: Opening A New Database Connection
  2869. **
  2870. ** ^These routines open an SQLite database file as specified by the
  2871. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2872. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2873. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2874. ** returned in *ppDb, even if an error occurs. The only exception is that
  2875. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2876. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2877. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2878. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2879. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2880. ** an English language description of the error following a failure of any
  2881. ** of the sqlite3_open() routines.
  2882. **
  2883. ** ^The default encoding for the database will be UTF-8 if
  2884. ** sqlite3_open() or sqlite3_open_v2() is called and
  2885. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2886. **
  2887. ** Whether or not an error occurs when it is opened, resources
  2888. ** associated with the [database connection] handle should be released by
  2889. ** passing it to [sqlite3_close()] when it is no longer required.
  2890. **
  2891. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2892. ** except that it accepts two additional parameters for additional control
  2893. ** over the new database connection. ^(The flags parameter to
  2894. ** sqlite3_open_v2() can take one of
  2895. ** the following three values, optionally combined with the
  2896. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2897. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2898. **
  2899. ** <dl>
  2900. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2901. ** <dd>The database is opened in read-only mode. If the database does not
  2902. ** already exist, an error is returned.</dd>)^
  2903. **
  2904. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2905. ** <dd>The database is opened for reading and writing if possible, or reading
  2906. ** only if the file is write protected by the operating system. In either
  2907. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2908. **
  2909. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2910. ** <dd>The database is opened for reading and writing, and is created if
  2911. ** it does not already exist. This is the behavior that is always used for
  2912. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2913. ** </dl>
  2914. **
  2915. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2916. ** combinations shown above optionally combined with other
  2917. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2918. ** then the behavior is undefined.
  2919. **
  2920. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2921. ** opens in the multi-thread [threading mode] as long as the single-thread
  2922. ** mode has not been set at compile-time or start-time. ^If the
  2923. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2924. ** in the serialized [threading mode] unless single-thread was
  2925. ** previously selected at compile-time or start-time.
  2926. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2927. ** eligible to use [shared cache mode], regardless of whether or not shared
  2928. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2929. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2930. ** participate in [shared cache mode] even if it is enabled.
  2931. **
  2932. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2933. ** [sqlite3_vfs] object that defines the operating system interface that
  2934. ** the new database connection should use. ^If the fourth parameter is
  2935. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2936. **
  2937. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2938. ** is created for the connection. ^This in-memory database will vanish when
  2939. ** the database connection is closed. Future versions of SQLite might
  2940. ** make use of additional special filenames that begin with the ":" character.
  2941. ** It is recommended that when a database filename actually does begin with
  2942. ** a ":" character you should prefix the filename with a pathname such as
  2943. ** "./" to avoid ambiguity.
  2944. **
  2945. ** ^If the filename is an empty string, then a private, temporary
  2946. ** on-disk database will be created. ^This private database will be
  2947. ** automatically deleted as soon as the database connection is closed.
  2948. **
  2949. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2950. **
  2951. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2952. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2953. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2954. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2955. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2956. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2957. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2958. ** by default, but future releases of SQLite might enable URI filename
  2959. ** interpretation by default. See "[URI filenames]" for additional
  2960. ** information.
  2961. **
  2962. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2963. ** authority, then it must be either an empty string or the string
  2964. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2965. ** error is returned to the caller. ^The fragment component of a URI, if
  2966. ** present, is ignored.
  2967. **
  2968. ** ^SQLite uses the path component of the URI as the name of the disk file
  2969. ** which contains the database. ^If the path begins with a '/' character,
  2970. ** then it is interpreted as an absolute path. ^If the path does not begin
  2971. ** with a '/' (meaning that the authority section is omitted from the URI)
  2972. ** then the path is interpreted as a relative path.
  2973. ** ^On windows, the first component of an absolute path
  2974. ** is a drive specification (e.g. "C:").
  2975. **
  2976. ** [[core URI query parameters]]
  2977. ** The query component of a URI may contain parameters that are interpreted
  2978. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2979. ** SQLite interprets the following three query parameters:
  2980. **
  2981. ** <ul>
  2982. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2983. ** a VFS object that provides the operating system interface that should
  2984. ** be used to access the database file on disk. ^If this option is set to
  2985. ** an empty string the default VFS object is used. ^Specifying an unknown
  2986. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2987. ** present, then the VFS specified by the option takes precedence over
  2988. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2989. **
  2990. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
  2991. ** "rwc". Attempting to set it to any other value is an error)^.
  2992. ** ^If "ro" is specified, then the database is opened for read-only
  2993. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  2994. ** third argument to sqlite3_prepare_v2(). ^If the mode option is set to
  2995. ** "rw", then the database is opened for read-write (but not create)
  2996. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  2997. ** been set. ^Value "rwc" is equivalent to setting both
  2998. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is
  2999. ** used, it is an error to specify a value for the mode parameter that is
  3000. ** less restrictive than that specified by the flags passed as the third
  3001. ** parameter.
  3002. **
  3003. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3004. ** "private". ^Setting it to "shared" is equivalent to setting the
  3005. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3006. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3007. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3008. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3009. ** a URI filename, its value overrides any behaviour requested by setting
  3010. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3011. ** </ul>
  3012. **
  3013. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3014. ** error. Future versions of SQLite might understand additional query
  3015. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3016. ** additional information.
  3017. **
  3018. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3019. **
  3020. ** <table border="1" align=center cellpadding=5>
  3021. ** <tr><th> URI filenames <th> Results
  3022. ** <tr><td> file:data.db <td>
  3023. ** Open the file "data.db" in the current directory.
  3024. ** <tr><td> file:/home/fred/data.db<br>
  3025. ** file:///home/fred/data.db <br>
  3026. ** file://localhost/home/fred/data.db <br> <td>
  3027. ** Open the database file "/home/fred/data.db".
  3028. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3029. ** An error. "darkstar" is not a recognized authority.
  3030. ** <tr><td style="white-space:nowrap">
  3031. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3032. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3033. ** C:. Note that the %20 escaping in this example is not strictly
  3034. ** necessary - space characters can be used literally
  3035. ** in URI filenames.
  3036. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3037. ** Open file "data.db" in the current directory for read-only access.
  3038. ** Regardless of whether or not shared-cache mode is enabled by
  3039. ** default, use a private cache.
  3040. ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  3041. ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  3042. ** <tr><td> file:data.db?mode=readonly <td>
  3043. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3044. ** </table>
  3045. **
  3046. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3047. ** query components of a URI. A hexadecimal escape sequence consists of a
  3048. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3049. ** specifying an octet value. ^Before the path or query components of a
  3050. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3051. ** hexadecimal escape sequences replaced by a single byte containing the
  3052. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3053. ** the results are undefined.
  3054. **
  3055. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3056. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3057. ** codepage is currently defined. Filenames containing international
  3058. ** characters must be converted to UTF-8 prior to passing them into
  3059. ** sqlite3_open() or sqlite3_open_v2().
  3060. */
  3061. SQLITE_API int sqlite3_open(
  3062. const char *filename, /* Database filename (UTF-8) */
  3063. sqlite3 **ppDb /* OUT: SQLite db handle */
  3064. );
  3065. SQLITE_API int sqlite3_open16(
  3066. const void *filename, /* Database filename (UTF-16) */
  3067. sqlite3 **ppDb /* OUT: SQLite db handle */
  3068. );
  3069. SQLITE_API int sqlite3_open_v2(
  3070. const char *filename, /* Database filename (UTF-8) */
  3071. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3072. int flags, /* Flags */
  3073. const char *zVfs /* Name of VFS module to use */
  3074. );
  3075. /*
  3076. ** CAPI3REF: Obtain Values For URI Parameters
  3077. **
  3078. ** These are utility routines, useful to VFS implementations, that check
  3079. ** to see if a database file was a URI that contained a specific query
  3080. ** parameter, and if so obtains the value of that query parameter.
  3081. **
  3082. ** If F is the database filename pointer passed into the xOpen() method of
  3083. ** a VFS implementation when the flags parameter to xOpen() has one or
  3084. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3085. ** P is the name of the query parameter, then
  3086. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3087. ** parameter if it exists or a NULL pointer if P does not appear as a
  3088. ** query parameter on F. If P is a query parameter of F
  3089. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3090. ** a pointer to an empty string.
  3091. **
  3092. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3093. ** parameter and returns true (1) or false (0) according to the value
  3094. ** of P. The value of P is true if it is "yes" or "true" or "on" or
  3095. ** a non-zero number and is false otherwise. If P is not a query parameter
  3096. ** on F then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3097. **
  3098. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3099. ** 64-bit signed integer and returns that integer, or D if P does not
  3100. ** exist. If the value of P is something other than an integer, then
  3101. ** zero is returned.
  3102. **
  3103. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3104. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3105. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3106. ** VFS method, then the behavior of this routine is undefined and probably
  3107. ** undesirable.
  3108. */
  3109. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3110. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3111. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3112. /*
  3113. ** CAPI3REF: Error Codes And Messages
  3114. **
  3115. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  3116. ** [extended result code] for the most recent failed sqlite3_* API call
  3117. ** associated with a [database connection]. If a prior API call failed
  3118. ** but the most recent API call succeeded, the return value from
  3119. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  3120. ** interface is the same except that it always returns the
  3121. ** [extended result code] even when extended result codes are
  3122. ** disabled.
  3123. **
  3124. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3125. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3126. ** ^(Memory to hold the error message string is managed internally.
  3127. ** The application does not need to worry about freeing the result.
  3128. ** However, the error string might be overwritten or deallocated by
  3129. ** subsequent calls to other SQLite interface functions.)^
  3130. **
  3131. ** When the serialized [threading mode] is in use, it might be the
  3132. ** case that a second error occurs on a separate thread in between
  3133. ** the time of the first error and the call to these interfaces.
  3134. ** When that happens, the second error will be reported since these
  3135. ** interfaces always report the most recent result. To avoid
  3136. ** this, each thread can obtain exclusive use of the [database connection] D
  3137. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3138. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3139. ** all calls to the interfaces listed here are completed.
  3140. **
  3141. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3142. ** was invoked incorrectly by the application. In that case, the
  3143. ** error code and message may or may not be set.
  3144. */
  3145. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3146. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3147. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3148. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3149. /*
  3150. ** CAPI3REF: SQL Statement Object
  3151. ** KEYWORDS: {prepared statement} {prepared statements}
  3152. **
  3153. ** An instance of this object represents a single SQL statement.
  3154. ** This object is variously known as a "prepared statement" or a
  3155. ** "compiled SQL statement" or simply as a "statement".
  3156. **
  3157. ** The life of a statement object goes something like this:
  3158. **
  3159. ** <ol>
  3160. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  3161. ** function.
  3162. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  3163. ** interfaces.
  3164. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3165. ** <li> Reset the statement using [sqlite3_reset()] then go back
  3166. ** to step 2. Do this zero or more times.
  3167. ** <li> Destroy the object using [sqlite3_finalize()].
  3168. ** </ol>
  3169. **
  3170. ** Refer to documentation on individual methods above for additional
  3171. ** information.
  3172. */
  3173. typedef struct sqlite3_stmt sqlite3_stmt;
  3174. /*
  3175. ** CAPI3REF: Run-time Limits
  3176. **
  3177. ** ^(This interface allows the size of various constructs to be limited
  3178. ** on a connection by connection basis. The first parameter is the
  3179. ** [database connection] whose limit is to be set or queried. The
  3180. ** second parameter is one of the [limit categories] that define a
  3181. ** class of constructs to be size limited. The third parameter is the
  3182. ** new limit for that construct.)^
  3183. **
  3184. ** ^If the new limit is a negative number, the limit is unchanged.
  3185. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3186. ** [limits | hard upper bound]
  3187. ** set at compile-time by a C preprocessor macro called
  3188. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3189. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3190. ** ^Attempts to increase a limit above its hard upper bound are
  3191. ** silently truncated to the hard upper bound.
  3192. **
  3193. ** ^Regardless of whether or not the limit was changed, the
  3194. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3195. ** ^Hence, to find the current value of a limit without changing it,
  3196. ** simply invoke this interface with the third parameter set to -1.
  3197. **
  3198. ** Run-time limits are intended for use in applications that manage
  3199. ** both their own internal database and also databases that are controlled
  3200. ** by untrusted external sources. An example application might be a
  3201. ** web browser that has its own databases for storing history and
  3202. ** separate databases controlled by JavaScript applications downloaded
  3203. ** off the Internet. The internal databases can be given the
  3204. ** large, default limits. Databases managed by external sources can
  3205. ** be given much smaller limits designed to prevent a denial of service
  3206. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3207. ** interface to further control untrusted SQL. The size of the database
  3208. ** created by an untrusted script can be contained using the
  3209. ** [max_page_count] [PRAGMA].
  3210. **
  3211. ** New run-time limit categories may be added in future releases.
  3212. */
  3213. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3214. /*
  3215. ** CAPI3REF: Run-Time Limit Categories
  3216. ** KEYWORDS: {limit category} {*limit categories}
  3217. **
  3218. ** These constants define various performance limits
  3219. ** that can be lowered at run-time using [sqlite3_limit()].
  3220. ** The synopsis of the meanings of the various limits is shown below.
  3221. ** Additional information is available at [limits | Limits in SQLite].
  3222. **
  3223. ** <dl>
  3224. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3225. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3226. **
  3227. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3228. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3229. **
  3230. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3231. ** <dd>The maximum number of columns in a table definition or in the
  3232. ** result set of a [SELECT] or the maximum number of columns in an index
  3233. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3234. **
  3235. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3236. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3237. **
  3238. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3239. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3240. **
  3241. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3242. ** <dd>The maximum number of instructions in a virtual machine program
  3243. ** used to implement an SQL statement. This limit is not currently
  3244. ** enforced, though that might be added in some future release of
  3245. ** SQLite.</dd>)^
  3246. **
  3247. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3248. ** <dd>The maximum number of arguments on a function.</dd>)^
  3249. **
  3250. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3251. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3252. **
  3253. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3254. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3255. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3256. ** [GLOB] operators.</dd>)^
  3257. **
  3258. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3259. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3260. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3261. **
  3262. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3263. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3264. ** </dl>
  3265. */
  3266. #define SQLITE_LIMIT_LENGTH 0
  3267. #define SQLITE_LIMIT_SQL_LENGTH 1
  3268. #define SQLITE_LIMIT_COLUMN 2
  3269. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3270. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3271. #define SQLITE_LIMIT_VDBE_OP 5
  3272. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3273. #define SQLITE_LIMIT_ATTACHED 7
  3274. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3275. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3276. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3277. /*
  3278. ** CAPI3REF: Compiling An SQL Statement
  3279. ** KEYWORDS: {SQL statement compiler}
  3280. **
  3281. ** To execute an SQL query, it must first be compiled into a byte-code
  3282. ** program using one of these routines.
  3283. **
  3284. ** The first argument, "db", is a [database connection] obtained from a
  3285. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3286. ** [sqlite3_open16()]. The database connection must not have been closed.
  3287. **
  3288. ** The second argument, "zSql", is the statement to be compiled, encoded
  3289. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3290. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3291. ** use UTF-16.
  3292. **
  3293. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3294. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3295. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3296. ** zSql string ends at either the first '\000' or '\u0000' character or
  3297. ** the nByte-th byte, whichever comes first. If the caller knows
  3298. ** that the supplied string is nul-terminated, then there is a small
  3299. ** performance advantage to be gained by passing an nByte parameter that
  3300. ** is equal to the number of bytes in the input string <i>including</i>
  3301. ** the nul-terminator bytes as this saves SQLite from having to
  3302. ** make a copy of the input string.
  3303. **
  3304. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3305. ** past the end of the first SQL statement in zSql. These routines only
  3306. ** compile the first statement in zSql, so *pzTail is left pointing to
  3307. ** what remains uncompiled.
  3308. **
  3309. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3310. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3311. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3312. ** string or a comment) then *ppStmt is set to NULL.
  3313. ** The calling procedure is responsible for deleting the compiled
  3314. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3315. ** ppStmt may not be NULL.
  3316. **
  3317. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3318. ** otherwise an [error code] is returned.
  3319. **
  3320. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3321. ** recommended for all new programs. The two older interfaces are retained
  3322. ** for backwards compatibility, but their use is discouraged.
  3323. ** ^In the "v2" interfaces, the prepared statement
  3324. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3325. ** original SQL text. This causes the [sqlite3_step()] interface to
  3326. ** behave differently in three ways:
  3327. **
  3328. ** <ol>
  3329. ** <li>
  3330. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3331. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3332. ** statement and try to run it again.
  3333. ** </li>
  3334. **
  3335. ** <li>
  3336. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3337. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3338. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3339. ** and the application would have to make a second call to [sqlite3_reset()]
  3340. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3341. ** interfaces, the underlying reason for the error is returned immediately.
  3342. ** </li>
  3343. **
  3344. ** <li>
  3345. ** ^If the specific value bound to [parameter | host parameter] in the
  3346. ** WHERE clause might influence the choice of query plan for a statement,
  3347. ** then the statement will be automatically recompiled, as if there had been
  3348. ** a schema change, on the first [sqlite3_step()] call following any change
  3349. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3350. ** ^The specific value of WHERE-clause [parameter] might influence the
  3351. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3352. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3353. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3354. ** the
  3355. ** </li>
  3356. ** </ol>
  3357. */
  3358. SQLITE_API int sqlite3_prepare(
  3359. sqlite3 *db, /* Database handle */
  3360. const char *zSql, /* SQL statement, UTF-8 encoded */
  3361. int nByte, /* Maximum length of zSql in bytes. */
  3362. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3363. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3364. );
  3365. SQLITE_API int sqlite3_prepare_v2(
  3366. sqlite3 *db, /* Database handle */
  3367. const char *zSql, /* SQL statement, UTF-8 encoded */
  3368. int nByte, /* Maximum length of zSql in bytes. */
  3369. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3370. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3371. );
  3372. SQLITE_API int sqlite3_prepare16(
  3373. sqlite3 *db, /* Database handle */
  3374. const void *zSql, /* SQL statement, UTF-16 encoded */
  3375. int nByte, /* Maximum length of zSql in bytes. */
  3376. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3377. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3378. );
  3379. SQLITE_API int sqlite3_prepare16_v2(
  3380. sqlite3 *db, /* Database handle */
  3381. const void *zSql, /* SQL statement, UTF-16 encoded */
  3382. int nByte, /* Maximum length of zSql in bytes. */
  3383. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3384. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3385. );
  3386. /*
  3387. ** CAPI3REF: Retrieving Statement SQL
  3388. **
  3389. ** ^This interface can be used to retrieve a saved copy of the original
  3390. ** SQL text used to create a [prepared statement] if that statement was
  3391. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3392. */
  3393. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3394. /*
  3395. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3396. **
  3397. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3398. ** and only if the [prepared statement] X makes no direct changes to
  3399. ** the content of the database file.
  3400. **
  3401. ** Note that [application-defined SQL functions] or
  3402. ** [virtual tables] might change the database indirectly as a side effect.
  3403. ** ^(For example, if an application defines a function "eval()" that
  3404. ** calls [sqlite3_exec()], then the following SQL statement would
  3405. ** change the database file through side-effects:
  3406. **
  3407. ** <blockquote><pre>
  3408. ** SELECT eval('DELETE FROM t1') FROM t2;
  3409. ** </pre></blockquote>
  3410. **
  3411. ** But because the [SELECT] statement does not change the database file
  3412. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3413. **
  3414. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3415. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3416. ** since the statements themselves do not actually modify the database but
  3417. ** rather they control the timing of when other statements modify the
  3418. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3419. ** sqlite3_stmt_readonly() to return true since, while those statements
  3420. ** change the configuration of a database connection, they do not make
  3421. ** changes to the content of the database files on disk.
  3422. */
  3423. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3424. /*
  3425. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3426. **
  3427. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3428. ** [prepared statement] S has been stepped at least once using
  3429. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3430. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3431. ** interface returns false if S is a NULL pointer. If S is not a
  3432. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3433. ** object, then the behavior is undefined and probably undesirable.
  3434. **
  3435. ** This interface can be used in combination [sqlite3_next_stmt()]
  3436. ** to locate all prepared statements associated with a database
  3437. ** connection that are in need of being reset. This can be used,
  3438. ** for example, in diagnostic routines to search for prepared
  3439. ** statements that are holding a transaction open.
  3440. */
  3441. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3442. /*
  3443. ** CAPI3REF: Dynamically Typed Value Object
  3444. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3445. **
  3446. ** SQLite uses the sqlite3_value object to represent all values
  3447. ** that can be stored in a database table. SQLite uses dynamic typing
  3448. ** for the values it stores. ^Values stored in sqlite3_value objects
  3449. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3450. **
  3451. ** An sqlite3_value object may be either "protected" or "unprotected".
  3452. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3453. ** will accept either a protected or an unprotected sqlite3_value.
  3454. ** Every interface that accepts sqlite3_value arguments specifies
  3455. ** whether or not it requires a protected sqlite3_value.
  3456. **
  3457. ** The terms "protected" and "unprotected" refer to whether or not
  3458. ** a mutex is held. An internal mutex is held for a protected
  3459. ** sqlite3_value object but no mutex is held for an unprotected
  3460. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3461. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3462. ** or if SQLite is run in one of reduced mutex modes
  3463. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3464. ** then there is no distinction between protected and unprotected
  3465. ** sqlite3_value objects and they can be used interchangeably. However,
  3466. ** for maximum code portability it is recommended that applications
  3467. ** still make the distinction between protected and unprotected
  3468. ** sqlite3_value objects even when not strictly required.
  3469. **
  3470. ** ^The sqlite3_value objects that are passed as parameters into the
  3471. ** implementation of [application-defined SQL functions] are protected.
  3472. ** ^The sqlite3_value object returned by
  3473. ** [sqlite3_column_value()] is unprotected.
  3474. ** Unprotected sqlite3_value objects may only be used with
  3475. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3476. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3477. ** interfaces require protected sqlite3_value objects.
  3478. */
  3479. typedef struct Mem sqlite3_value;
  3480. /*
  3481. ** CAPI3REF: SQL Function Context Object
  3482. **
  3483. ** The context in which an SQL function executes is stored in an
  3484. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3485. ** is always first parameter to [application-defined SQL functions].
  3486. ** The application-defined SQL function implementation will pass this
  3487. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3488. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3489. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3490. ** and/or [sqlite3_set_auxdata()].
  3491. */
  3492. typedef struct sqlite3_context sqlite3_context;
  3493. /*
  3494. ** CAPI3REF: Binding Values To Prepared Statements
  3495. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3496. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3497. **
  3498. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3499. ** literals may be replaced by a [parameter] that matches one of following
  3500. ** templates:
  3501. **
  3502. ** <ul>
  3503. ** <li> ?
  3504. ** <li> ?NNN
  3505. ** <li> :VVV
  3506. ** <li> @VVV
  3507. ** <li> $VVV
  3508. ** </ul>
  3509. **
  3510. ** In the templates above, NNN represents an integer literal,
  3511. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3512. ** parameters (also called "host parameter names" or "SQL parameters")
  3513. ** can be set using the sqlite3_bind_*() routines defined here.
  3514. **
  3515. ** ^The first argument to the sqlite3_bind_*() routines is always
  3516. ** a pointer to the [sqlite3_stmt] object returned from
  3517. ** [sqlite3_prepare_v2()] or its variants.
  3518. **
  3519. ** ^The second argument is the index of the SQL parameter to be set.
  3520. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3521. ** SQL parameter is used more than once, second and subsequent
  3522. ** occurrences have the same index as the first occurrence.
  3523. ** ^The index for named parameters can be looked up using the
  3524. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3525. ** for "?NNN" parameters is the value of NNN.
  3526. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3527. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3528. **
  3529. ** ^The third argument is the value to bind to the parameter.
  3530. **
  3531. ** ^(In those routines that have a fourth argument, its value is the
  3532. ** number of bytes in the parameter. To be clear: the value is the
  3533. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3534. ** ^If the fourth parameter is negative, the length of the string is
  3535. ** the number of bytes up to the first zero terminator.
  3536. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3537. ** or sqlite3_bind_text16() then that parameter must be the byte offset
  3538. ** where the NUL terminator would occur assuming the string were NUL
  3539. ** terminated. If any NUL characters occur at byte offsets less than
  3540. ** the value of the fourth parameter then the resulting string value will
  3541. ** contain embedded NULs. The result of expressions involving strings
  3542. ** with embedded NULs is undefined.
  3543. **
  3544. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3545. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3546. ** string after SQLite has finished with it. ^The destructor is called
  3547. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3548. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3549. ** ^If the fifth argument is
  3550. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3551. ** information is in static, unmanaged space and does not need to be freed.
  3552. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3553. ** SQLite makes its own private copy of the data immediately, before
  3554. ** the sqlite3_bind_*() routine returns.
  3555. **
  3556. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3557. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3558. ** (just an integer to hold its size) while it is being processed.
  3559. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3560. ** content is later written using
  3561. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3562. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3563. **
  3564. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3565. ** for the [prepared statement] or with a prepared statement for which
  3566. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3567. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3568. ** routine is passed a [prepared statement] that has been finalized, the
  3569. ** result is undefined and probably harmful.
  3570. **
  3571. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3572. ** ^Unbound parameters are interpreted as NULL.
  3573. **
  3574. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3575. ** [error code] if anything goes wrong.
  3576. ** ^[SQLITE_RANGE] is returned if the parameter
  3577. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3578. **
  3579. ** See also: [sqlite3_bind_parameter_count()],
  3580. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3581. */
  3582. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3583. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3584. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3585. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3586. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3587. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3588. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3589. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3590. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3591. /*
  3592. ** CAPI3REF: Number Of SQL Parameters
  3593. **
  3594. ** ^This routine can be used to find the number of [SQL parameters]
  3595. ** in a [prepared statement]. SQL parameters are tokens of the
  3596. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3597. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3598. ** to the parameters at a later time.
  3599. **
  3600. ** ^(This routine actually returns the index of the largest (rightmost)
  3601. ** parameter. For all forms except ?NNN, this will correspond to the
  3602. ** number of unique parameters. If parameters of the ?NNN form are used,
  3603. ** there may be gaps in the list.)^
  3604. **
  3605. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3606. ** [sqlite3_bind_parameter_name()], and
  3607. ** [sqlite3_bind_parameter_index()].
  3608. */
  3609. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3610. /*
  3611. ** CAPI3REF: Name Of A Host Parameter
  3612. **
  3613. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3614. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3615. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3616. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3617. ** respectively.
  3618. ** In other words, the initial ":" or "$" or "@" or "?"
  3619. ** is included as part of the name.)^
  3620. ** ^Parameters of the form "?" without a following integer have no name
  3621. ** and are referred to as "nameless" or "anonymous parameters".
  3622. **
  3623. ** ^The first host parameter has an index of 1, not 0.
  3624. **
  3625. ** ^If the value N is out of range or if the N-th parameter is
  3626. ** nameless, then NULL is returned. ^The returned string is
  3627. ** always in UTF-8 encoding even if the named parameter was
  3628. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3629. ** [sqlite3_prepare16_v2()].
  3630. **
  3631. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3632. ** [sqlite3_bind_parameter_count()], and
  3633. ** [sqlite3_bind_parameter_index()].
  3634. */
  3635. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3636. /*
  3637. ** CAPI3REF: Index Of A Parameter With A Given Name
  3638. **
  3639. ** ^Return the index of an SQL parameter given its name. ^The
  3640. ** index value returned is suitable for use as the second
  3641. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3642. ** is returned if no matching parameter is found. ^The parameter
  3643. ** name must be given in UTF-8 even if the original statement
  3644. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3645. **
  3646. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3647. ** [sqlite3_bind_parameter_count()], and
  3648. ** [sqlite3_bind_parameter_index()].
  3649. */
  3650. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3651. /*
  3652. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3653. **
  3654. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3655. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3656. ** ^Use this routine to reset all host parameters to NULL.
  3657. */
  3658. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3659. /*
  3660. ** CAPI3REF: Number Of Columns In A Result Set
  3661. **
  3662. ** ^Return the number of columns in the result set returned by the
  3663. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3664. ** statement that does not return data (for example an [UPDATE]).
  3665. **
  3666. ** See also: [sqlite3_data_count()]
  3667. */
  3668. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3669. /*
  3670. ** CAPI3REF: Column Names In A Result Set
  3671. **
  3672. ** ^These routines return the name assigned to a particular column
  3673. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3674. ** interface returns a pointer to a zero-terminated UTF-8 string
  3675. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3676. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3677. ** that implements the [SELECT] statement. ^The second parameter is the
  3678. ** column number. ^The leftmost column is number 0.
  3679. **
  3680. ** ^The returned string pointer is valid until either the [prepared statement]
  3681. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3682. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3683. ** or until the next call to
  3684. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3685. **
  3686. ** ^If sqlite3_malloc() fails during the processing of either routine
  3687. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3688. ** NULL pointer is returned.
  3689. **
  3690. ** ^The name of a result column is the value of the "AS" clause for
  3691. ** that column, if there is an AS clause. If there is no AS clause
  3692. ** then the name of the column is unspecified and may change from
  3693. ** one release of SQLite to the next.
  3694. */
  3695. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3696. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3697. /*
  3698. ** CAPI3REF: Source Of Data In A Query Result
  3699. **
  3700. ** ^These routines provide a means to determine the database, table, and
  3701. ** table column that is the origin of a particular result column in
  3702. ** [SELECT] statement.
  3703. ** ^The name of the database or table or column can be returned as
  3704. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3705. ** the database name, the _table_ routines return the table name, and
  3706. ** the origin_ routines return the column name.
  3707. ** ^The returned string is valid until the [prepared statement] is destroyed
  3708. ** using [sqlite3_finalize()] or until the statement is automatically
  3709. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3710. ** or until the same information is requested
  3711. ** again in a different encoding.
  3712. **
  3713. ** ^The names returned are the original un-aliased names of the
  3714. ** database, table, and column.
  3715. **
  3716. ** ^The first argument to these interfaces is a [prepared statement].
  3717. ** ^These functions return information about the Nth result column returned by
  3718. ** the statement, where N is the second function argument.
  3719. ** ^The left-most column is column 0 for these routines.
  3720. **
  3721. ** ^If the Nth column returned by the statement is an expression or
  3722. ** subquery and is not a column value, then all of these functions return
  3723. ** NULL. ^These routine might also return NULL if a memory allocation error
  3724. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3725. ** or column that query result column was extracted from.
  3726. **
  3727. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3728. ** UTF-16 encoded strings and the other functions return UTF-8.
  3729. **
  3730. ** ^These APIs are only available if the library was compiled with the
  3731. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3732. **
  3733. ** If two or more threads call one or more of these routines against the same
  3734. ** prepared statement and column at the same time then the results are
  3735. ** undefined.
  3736. **
  3737. ** If two or more threads call one or more
  3738. ** [sqlite3_column_database_name | column metadata interfaces]
  3739. ** for the same [prepared statement] and result column
  3740. ** at the same time then the results are undefined.
  3741. */
  3742. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3743. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3744. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3745. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3746. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3747. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3748. /*
  3749. ** CAPI3REF: Declared Datatype Of A Query Result
  3750. **
  3751. ** ^(The first parameter is a [prepared statement].
  3752. ** If this statement is a [SELECT] statement and the Nth column of the
  3753. ** returned result set of that [SELECT] is a table column (not an
  3754. ** expression or subquery) then the declared type of the table
  3755. ** column is returned.)^ ^If the Nth column of the result set is an
  3756. ** expression or subquery, then a NULL pointer is returned.
  3757. ** ^The returned string is always UTF-8 encoded.
  3758. **
  3759. ** ^(For example, given the database schema:
  3760. **
  3761. ** CREATE TABLE t1(c1 VARIANT);
  3762. **
  3763. ** and the following statement to be compiled:
  3764. **
  3765. ** SELECT c1 + 1, c1 FROM t1;
  3766. **
  3767. ** this routine would return the string "VARIANT" for the second result
  3768. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3769. **
  3770. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3771. ** is declared to contain a particular type does not mean that the
  3772. ** data stored in that column is of the declared type. SQLite is
  3773. ** strongly typed, but the typing is dynamic not static. ^Type
  3774. ** is associated with individual values, not with the containers
  3775. ** used to hold those values.
  3776. */
  3777. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3778. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3779. /*
  3780. ** CAPI3REF: Evaluate An SQL Statement
  3781. **
  3782. ** After a [prepared statement] has been prepared using either
  3783. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3784. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3785. ** must be called one or more times to evaluate the statement.
  3786. **
  3787. ** The details of the behavior of the sqlite3_step() interface depend
  3788. ** on whether the statement was prepared using the newer "v2" interface
  3789. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3790. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3791. ** new "v2" interface is recommended for new applications but the legacy
  3792. ** interface will continue to be supported.
  3793. **
  3794. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3795. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3796. ** ^With the "v2" interface, any of the other [result codes] or
  3797. ** [extended result codes] might be returned as well.
  3798. **
  3799. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3800. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3801. ** or occurs outside of an explicit transaction, then you can retry the
  3802. ** statement. If the statement is not a [COMMIT] and occurs within an
  3803. ** explicit transaction then you should rollback the transaction before
  3804. ** continuing.
  3805. **
  3806. ** ^[SQLITE_DONE] means that the statement has finished executing
  3807. ** successfully. sqlite3_step() should not be called again on this virtual
  3808. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3809. ** machine back to its initial state.
  3810. **
  3811. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3812. ** is returned each time a new row of data is ready for processing by the
  3813. ** caller. The values may be accessed using the [column access functions].
  3814. ** sqlite3_step() is called again to retrieve the next row of data.
  3815. **
  3816. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3817. ** violation) has occurred. sqlite3_step() should not be called again on
  3818. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3819. ** ^With the legacy interface, a more specific error code (for example,
  3820. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3821. ** can be obtained by calling [sqlite3_reset()] on the
  3822. ** [prepared statement]. ^In the "v2" interface,
  3823. ** the more specific error code is returned directly by sqlite3_step().
  3824. **
  3825. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3826. ** Perhaps it was called on a [prepared statement] that has
  3827. ** already been [sqlite3_finalize | finalized] or on one that had
  3828. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3829. ** be the case that the same database connection is being used by two or
  3830. ** more threads at the same moment in time.
  3831. **
  3832. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3833. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3834. ** other than [SQLITE_ROW] before any subsequent invocation of
  3835. ** sqlite3_step(). Failure to reset the prepared statement using
  3836. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3837. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3838. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3839. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3840. ** break because any application that ever receives an SQLITE_MISUSE error
  3841. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3842. ** can be used to restore the legacy behavior.
  3843. **
  3844. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3845. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3846. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3847. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3848. ** specific [error codes] that better describes the error.
  3849. ** We admit that this is a goofy design. The problem has been fixed
  3850. ** with the "v2" interface. If you prepare all of your SQL statements
  3851. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3852. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3853. ** then the more specific [error codes] are returned directly
  3854. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3855. */
  3856. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3857. /*
  3858. ** CAPI3REF: Number of columns in a result set
  3859. **
  3860. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3861. ** current row of the result set of [prepared statement] P.
  3862. ** ^If prepared statement P does not have results ready to return
  3863. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3864. ** interfaces) then sqlite3_data_count(P) returns 0.
  3865. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3866. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3867. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3868. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3869. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3870. ** where it always returns zero since each step of that multi-step
  3871. ** pragma returns 0 columns of data.
  3872. **
  3873. ** See also: [sqlite3_column_count()]
  3874. */
  3875. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3876. /*
  3877. ** CAPI3REF: Fundamental Datatypes
  3878. ** KEYWORDS: SQLITE_TEXT
  3879. **
  3880. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3881. **
  3882. ** <ul>
  3883. ** <li> 64-bit signed integer
  3884. ** <li> 64-bit IEEE floating point number
  3885. ** <li> string
  3886. ** <li> BLOB
  3887. ** <li> NULL
  3888. ** </ul>)^
  3889. **
  3890. ** These constants are codes for each of those types.
  3891. **
  3892. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3893. ** for a completely different meaning. Software that links against both
  3894. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3895. ** SQLITE_TEXT.
  3896. */
  3897. #define SQLITE_INTEGER 1
  3898. #define SQLITE_FLOAT 2
  3899. #define SQLITE_BLOB 4
  3900. #define SQLITE_NULL 5
  3901. #ifdef SQLITE_TEXT
  3902. # undef SQLITE_TEXT
  3903. #else
  3904. # define SQLITE_TEXT 3
  3905. #endif
  3906. #define SQLITE3_TEXT 3
  3907. /*
  3908. ** CAPI3REF: Result Values From A Query
  3909. ** KEYWORDS: {column access functions}
  3910. **
  3911. ** These routines form the "result set" interface.
  3912. **
  3913. ** ^These routines return information about a single column of the current
  3914. ** result row of a query. ^In every case the first argument is a pointer
  3915. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3916. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3917. ** and the second argument is the index of the column for which information
  3918. ** should be returned. ^The leftmost column of the result set has the index 0.
  3919. ** ^The number of columns in the result can be determined using
  3920. ** [sqlite3_column_count()].
  3921. **
  3922. ** If the SQL statement does not currently point to a valid row, or if the
  3923. ** column index is out of range, the result is undefined.
  3924. ** These routines may only be called when the most recent call to
  3925. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3926. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3927. ** If any of these routines are called after [sqlite3_reset()] or
  3928. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3929. ** something other than [SQLITE_ROW], the results are undefined.
  3930. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3931. ** are called from a different thread while any of these routines
  3932. ** are pending, then the results are undefined.
  3933. **
  3934. ** ^The sqlite3_column_type() routine returns the
  3935. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3936. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3937. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3938. ** returned by sqlite3_column_type() is only meaningful if no type
  3939. ** conversions have occurred as described below. After a type conversion,
  3940. ** the value returned by sqlite3_column_type() is undefined. Future
  3941. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3942. ** following a type conversion.
  3943. **
  3944. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3945. ** routine returns the number of bytes in that BLOB or string.
  3946. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3947. ** the string to UTF-8 and then returns the number of bytes.
  3948. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3949. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3950. ** the number of bytes in that string.
  3951. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3952. **
  3953. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3954. ** routine returns the number of bytes in that BLOB or string.
  3955. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3956. ** the string to UTF-16 and then returns the number of bytes.
  3957. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3958. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3959. ** the number of bytes in that string.
  3960. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3961. **
  3962. ** ^The values returned by [sqlite3_column_bytes()] and
  3963. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3964. ** of the string. ^For clarity: the values returned by
  3965. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3966. ** bytes in the string, not the number of characters.
  3967. **
  3968. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3969. ** even empty strings, are always zero-terminated. ^The return
  3970. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3971. **
  3972. ** ^The object returned by [sqlite3_column_value()] is an
  3973. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3974. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3975. ** If the [unprotected sqlite3_value] object returned by
  3976. ** [sqlite3_column_value()] is used in any other way, including calls
  3977. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3978. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3979. **
  3980. ** These routines attempt to convert the value where appropriate. ^For
  3981. ** example, if the internal representation is FLOAT and a text result
  3982. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3983. ** conversion automatically. ^(The following table details the conversions
  3984. ** that are applied:
  3985. **
  3986. ** <blockquote>
  3987. ** <table border="1">
  3988. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3989. **
  3990. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3991. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3992. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  3993. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  3994. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3995. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3996. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3997. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  3998. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3999. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  4000. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  4001. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  4002. ** <tr><td> TEXT <td> BLOB <td> No change
  4003. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  4004. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  4005. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4006. ** </table>
  4007. ** </blockquote>)^
  4008. **
  4009. ** The table above makes reference to standard C library functions atoi()
  4010. ** and atof(). SQLite does not really use these functions. It has its
  4011. ** own equivalent internal routines. The atoi() and atof() names are
  4012. ** used in the table for brevity and because they are familiar to most
  4013. ** C programmers.
  4014. **
  4015. ** Note that when type conversions occur, pointers returned by prior
  4016. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4017. ** sqlite3_column_text16() may be invalidated.
  4018. ** Type conversions and pointer invalidations might occur
  4019. ** in the following cases:
  4020. **
  4021. ** <ul>
  4022. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4023. ** sqlite3_column_text16() is called. A zero-terminator might
  4024. ** need to be added to the string.</li>
  4025. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4026. ** sqlite3_column_text16() is called. The content must be converted
  4027. ** to UTF-16.</li>
  4028. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4029. ** sqlite3_column_text() is called. The content must be converted
  4030. ** to UTF-8.</li>
  4031. ** </ul>
  4032. **
  4033. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4034. ** not invalidate a prior pointer, though of course the content of the buffer
  4035. ** that the prior pointer references will have been modified. Other kinds
  4036. ** of conversion are done in place when it is possible, but sometimes they
  4037. ** are not possible and in those cases prior pointers are invalidated.
  4038. **
  4039. ** The safest and easiest to remember policy is to invoke these routines
  4040. ** in one of the following ways:
  4041. **
  4042. ** <ul>
  4043. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4044. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4045. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4046. ** </ul>
  4047. **
  4048. ** In other words, you should call sqlite3_column_text(),
  4049. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4050. ** into the desired format, then invoke sqlite3_column_bytes() or
  4051. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4052. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4053. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4054. ** with calls to sqlite3_column_bytes().
  4055. **
  4056. ** ^The pointers returned are valid until a type conversion occurs as
  4057. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4058. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4059. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  4060. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4061. ** [sqlite3_free()].
  4062. **
  4063. ** ^(If a memory allocation error occurs during the evaluation of any
  4064. ** of these routines, a default value is returned. The default value
  4065. ** is either the integer 0, the floating point number 0.0, or a NULL
  4066. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4067. ** [SQLITE_NOMEM].)^
  4068. */
  4069. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4070. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4071. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4072. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  4073. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  4074. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4075. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  4076. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4077. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  4078. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  4079. /*
  4080. ** CAPI3REF: Destroy A Prepared Statement Object
  4081. **
  4082. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4083. ** ^If the most recent evaluation of the statement encountered no errors
  4084. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4085. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4086. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4087. ** [extended error code].
  4088. **
  4089. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4090. ** the life cycle of [prepared statement] S:
  4091. ** before statement S is ever evaluated, after
  4092. ** one or more calls to [sqlite3_reset()], or after any call
  4093. ** to [sqlite3_step()] regardless of whether or not the statement has
  4094. ** completed execution.
  4095. **
  4096. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4097. **
  4098. ** The application must finalize every [prepared statement] in order to avoid
  4099. ** resource leaks. It is a grievous error for the application to try to use
  4100. ** a prepared statement after it has been finalized. Any use of a prepared
  4101. ** statement after it has been finalized can result in undefined and
  4102. ** undesirable behavior such as segfaults and heap corruption.
  4103. */
  4104. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4105. /*
  4106. ** CAPI3REF: Reset A Prepared Statement Object
  4107. **
  4108. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4109. ** object back to its initial state, ready to be re-executed.
  4110. ** ^Any SQL statement variables that had values bound to them using
  4111. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4112. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4113. **
  4114. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4115. ** back to the beginning of its program.
  4116. **
  4117. ** ^If the most recent call to [sqlite3_step(S)] for the
  4118. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4119. ** or if [sqlite3_step(S)] has never before been called on S,
  4120. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4121. **
  4122. ** ^If the most recent call to [sqlite3_step(S)] for the
  4123. ** [prepared statement] S indicated an error, then
  4124. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4125. **
  4126. ** ^The [sqlite3_reset(S)] interface does not change the values
  4127. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4128. */
  4129. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4130. /*
  4131. ** CAPI3REF: Create Or Redefine SQL Functions
  4132. ** KEYWORDS: {function creation routines}
  4133. ** KEYWORDS: {application-defined SQL function}
  4134. ** KEYWORDS: {application-defined SQL functions}
  4135. **
  4136. ** ^These functions (collectively known as "function creation routines")
  4137. ** are used to add SQL functions or aggregates or to redefine the behavior
  4138. ** of existing SQL functions or aggregates. The only differences between
  4139. ** these routines are the text encoding expected for
  4140. ** the second parameter (the name of the function being created)
  4141. ** and the presence or absence of a destructor callback for
  4142. ** the application data pointer.
  4143. **
  4144. ** ^The first parameter is the [database connection] to which the SQL
  4145. ** function is to be added. ^If an application uses more than one database
  4146. ** connection then application-defined SQL functions must be added
  4147. ** to each database connection separately.
  4148. **
  4149. ** ^The second parameter is the name of the SQL function to be created or
  4150. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4151. ** representation, exclusive of the zero-terminator. ^Note that the name
  4152. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4153. ** ^Any attempt to create a function with a longer name
  4154. ** will result in [SQLITE_MISUSE] being returned.
  4155. **
  4156. ** ^The third parameter (nArg)
  4157. ** is the number of arguments that the SQL function or
  4158. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4159. ** aggregate may take any number of arguments between 0 and the limit
  4160. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4161. ** parameter is less than -1 or greater than 127 then the behavior is
  4162. ** undefined.
  4163. **
  4164. ** ^The fourth parameter, eTextRep, specifies what
  4165. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4166. ** its parameters. Every SQL function implementation must be able to work
  4167. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  4168. ** more efficient with one encoding than another. ^An application may
  4169. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  4170. ** times with the same function but with different values of eTextRep.
  4171. ** ^When multiple implementations of the same function are available, SQLite
  4172. ** will pick the one that involves the least amount of data conversion.
  4173. ** If there is only a single implementation which does not care what text
  4174. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  4175. **
  4176. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4177. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4178. **
  4179. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4180. ** pointers to C-language functions that implement the SQL function or
  4181. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4182. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4183. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4184. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4185. ** SQL function or aggregate, pass NULL pointers for all three function
  4186. ** callbacks.
  4187. **
  4188. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4189. ** then it is destructor for the application data pointer.
  4190. ** The destructor is invoked when the function is deleted, either by being
  4191. ** overloaded or when the database connection closes.)^
  4192. ** ^The destructor is also invoked if the call to
  4193. ** sqlite3_create_function_v2() fails.
  4194. ** ^When the destructor callback of the tenth parameter is invoked, it
  4195. ** is passed a single argument which is a copy of the application data
  4196. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4197. **
  4198. ** ^It is permitted to register multiple implementations of the same
  4199. ** functions with the same name but with either differing numbers of
  4200. ** arguments or differing preferred text encodings. ^SQLite will use
  4201. ** the implementation that most closely matches the way in which the
  4202. ** SQL function is used. ^A function implementation with a non-negative
  4203. ** nArg parameter is a better match than a function implementation with
  4204. ** a negative nArg. ^A function where the preferred text encoding
  4205. ** matches the database encoding is a better
  4206. ** match than a function where the encoding is different.
  4207. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4208. ** is a closer match than a function where the encoding difference is
  4209. ** between UTF8 and UTF16.
  4210. **
  4211. ** ^Built-in functions may be overloaded by new application-defined functions.
  4212. **
  4213. ** ^An application-defined function is permitted to call other
  4214. ** SQLite interfaces. However, such calls must not
  4215. ** close the database connection nor finalize or reset the prepared
  4216. ** statement in which the function is running.
  4217. */
  4218. SQLITE_API int sqlite3_create_function(
  4219. sqlite3 *db,
  4220. const char *zFunctionName,
  4221. int nArg,
  4222. int eTextRep,
  4223. void *pApp,
  4224. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4225. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4226. void (*xFinal)(sqlite3_context*)
  4227. );
  4228. SQLITE_API int sqlite3_create_function16(
  4229. sqlite3 *db,
  4230. const void *zFunctionName,
  4231. int nArg,
  4232. int eTextRep,
  4233. void *pApp,
  4234. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4235. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4236. void (*xFinal)(sqlite3_context*)
  4237. );
  4238. SQLITE_API int sqlite3_create_function_v2(
  4239. sqlite3 *db,
  4240. const char *zFunctionName,
  4241. int nArg,
  4242. int eTextRep,
  4243. void *pApp,
  4244. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4245. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4246. void (*xFinal)(sqlite3_context*),
  4247. void(*xDestroy)(void*)
  4248. );
  4249. /*
  4250. ** CAPI3REF: Text Encodings
  4251. **
  4252. ** These constant define integer codes that represent the various
  4253. ** text encodings supported by SQLite.
  4254. */
  4255. #define SQLITE_UTF8 1
  4256. #define SQLITE_UTF16LE 2
  4257. #define SQLITE_UTF16BE 3
  4258. #define SQLITE_UTF16 4 /* Use native byte order */
  4259. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  4260. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4261. /*
  4262. ** CAPI3REF: Deprecated Functions
  4263. ** DEPRECATED
  4264. **
  4265. ** These functions are [deprecated]. In order to maintain
  4266. ** backwards compatibility with older code, these functions continue
  4267. ** to be supported. However, new applications should avoid
  4268. ** the use of these functions. To help encourage people to avoid
  4269. ** using these functions, we are not going to tell you what they do.
  4270. */
  4271. #ifndef SQLITE_OMIT_DEPRECATED
  4272. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4273. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4274. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4275. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4276. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4277. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
  4278. #endif
  4279. /*
  4280. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4281. **
  4282. ** The C-language implementation of SQL functions and aggregates uses
  4283. ** this set of interface routines to access the parameter values on
  4284. ** the function or aggregate.
  4285. **
  4286. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4287. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4288. ** define callbacks that implement the SQL functions and aggregates.
  4289. ** The 3rd parameter to these callbacks is an array of pointers to
  4290. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4291. ** each parameter to the SQL function. These routines are used to
  4292. ** extract values from the [sqlite3_value] objects.
  4293. **
  4294. ** These routines work only with [protected sqlite3_value] objects.
  4295. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4296. ** object results in undefined behavior.
  4297. **
  4298. ** ^These routines work just like the corresponding [column access functions]
  4299. ** except that these routines take a single [protected sqlite3_value] object
  4300. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4301. **
  4302. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4303. ** in the native byte-order of the host machine. ^The
  4304. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4305. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4306. **
  4307. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4308. ** numeric affinity to the value. This means that an attempt is
  4309. ** made to convert the value to an integer or floating point. If
  4310. ** such a conversion is possible without loss of information (in other
  4311. ** words, if the value is a string that looks like a number)
  4312. ** then the conversion is performed. Otherwise no conversion occurs.
  4313. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4314. **
  4315. ** Please pay particular attention to the fact that the pointer returned
  4316. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4317. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4318. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4319. ** or [sqlite3_value_text16()].
  4320. **
  4321. ** These routines must be called from the same thread as
  4322. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4323. */
  4324. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4325. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4326. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4327. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4328. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4329. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4330. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4331. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4332. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4333. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4334. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4335. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4336. /*
  4337. ** CAPI3REF: Obtain Aggregate Function Context
  4338. **
  4339. ** Implementations of aggregate SQL functions use this
  4340. ** routine to allocate memory for storing their state.
  4341. **
  4342. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4343. ** for a particular aggregate function, SQLite
  4344. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4345. ** to the new memory. ^On second and subsequent calls to
  4346. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4347. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4348. ** called once for each invocation of the xStep callback and then one
  4349. ** last time when the xFinal callback is invoked. ^(When no rows match
  4350. ** an aggregate query, the xStep() callback of the aggregate function
  4351. ** implementation is never called and xFinal() is called exactly once.
  4352. ** In those cases, sqlite3_aggregate_context() might be called for the
  4353. ** first time from within xFinal().)^
  4354. **
  4355. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
  4356. ** less than or equal to zero or if a memory allocate error occurs.
  4357. **
  4358. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4359. ** determined by the N parameter on first successful call. Changing the
  4360. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4361. ** the same aggregate function instance will not resize the memory
  4362. ** allocation.)^
  4363. **
  4364. ** ^SQLite automatically frees the memory allocated by
  4365. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4366. **
  4367. ** The first parameter must be a copy of the
  4368. ** [sqlite3_context | SQL function context] that is the first parameter
  4369. ** to the xStep or xFinal callback routine that implements the aggregate
  4370. ** function.
  4371. **
  4372. ** This routine must be called from the same thread in which
  4373. ** the aggregate SQL function is running.
  4374. */
  4375. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4376. /*
  4377. ** CAPI3REF: User Data For Functions
  4378. **
  4379. ** ^The sqlite3_user_data() interface returns a copy of
  4380. ** the pointer that was the pUserData parameter (the 5th parameter)
  4381. ** of the [sqlite3_create_function()]
  4382. ** and [sqlite3_create_function16()] routines that originally
  4383. ** registered the application defined function.
  4384. **
  4385. ** This routine must be called from the same thread in which
  4386. ** the application-defined function is running.
  4387. */
  4388. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4389. /*
  4390. ** CAPI3REF: Database Connection For Functions
  4391. **
  4392. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4393. ** the pointer to the [database connection] (the 1st parameter)
  4394. ** of the [sqlite3_create_function()]
  4395. ** and [sqlite3_create_function16()] routines that originally
  4396. ** registered the application defined function.
  4397. */
  4398. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4399. /*
  4400. ** CAPI3REF: Function Auxiliary Data
  4401. **
  4402. ** The following two functions may be used by scalar SQL functions to
  4403. ** associate metadata with argument values. If the same value is passed to
  4404. ** multiple invocations of the same SQL function during query execution, under
  4405. ** some circumstances the associated metadata may be preserved. This may
  4406. ** be used, for example, to add a regular-expression matching scalar
  4407. ** function. The compiled version of the regular expression is stored as
  4408. ** metadata associated with the SQL value passed as the regular expression
  4409. ** pattern. The compiled regular expression can be reused on multiple
  4410. ** invocations of the same function so that the original pattern string
  4411. ** does not need to be recompiled on each invocation.
  4412. **
  4413. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4414. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4415. ** value to the application-defined function. ^If no metadata has been ever
  4416. ** been set for the Nth argument of the function, or if the corresponding
  4417. ** function parameter has changed since the meta-data was set,
  4418. ** then sqlite3_get_auxdata() returns a NULL pointer.
  4419. **
  4420. ** ^The sqlite3_set_auxdata() interface saves the metadata
  4421. ** pointed to by its 3rd parameter as the metadata for the N-th
  4422. ** argument of the application-defined function. Subsequent
  4423. ** calls to sqlite3_get_auxdata() might return this data, if it has
  4424. ** not been destroyed.
  4425. ** ^If it is not NULL, SQLite will invoke the destructor
  4426. ** function given by the 4th parameter to sqlite3_set_auxdata() on
  4427. ** the metadata when the corresponding function parameter changes
  4428. ** or when the SQL statement completes, whichever comes first.
  4429. **
  4430. ** SQLite is free to call the destructor and drop metadata on any
  4431. ** parameter of any function at any time. ^The only guarantee is that
  4432. ** the destructor will be called before the metadata is dropped.
  4433. **
  4434. ** ^(In practice, metadata is preserved between function calls for
  4435. ** expressions that are constant at compile time. This includes literal
  4436. ** values and [parameters].)^
  4437. **
  4438. ** These routines must be called from the same thread in which
  4439. ** the SQL function is running.
  4440. */
  4441. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4442. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4443. /*
  4444. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4445. **
  4446. ** These are special values for the destructor that is passed in as the
  4447. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4448. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4449. ** and will never change. It does not need to be destroyed. ^The
  4450. ** SQLITE_TRANSIENT value means that the content will likely change in
  4451. ** the near future and that SQLite should make its own private copy of
  4452. ** the content before returning.
  4453. **
  4454. ** The typedef is necessary to work around problems in certain
  4455. ** C++ compilers. See ticket #2191.
  4456. */
  4457. typedef void (*sqlite3_destructor_type)(void*);
  4458. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4459. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4460. /*
  4461. ** CAPI3REF: Setting The Result Of An SQL Function
  4462. **
  4463. ** These routines are used by the xFunc or xFinal callbacks that
  4464. ** implement SQL functions and aggregates. See
  4465. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4466. ** for additional information.
  4467. **
  4468. ** These functions work very much like the [parameter binding] family of
  4469. ** functions used to bind values to host parameters in prepared statements.
  4470. ** Refer to the [SQL parameter] documentation for additional information.
  4471. **
  4472. ** ^The sqlite3_result_blob() interface sets the result from
  4473. ** an application-defined function to be the BLOB whose content is pointed
  4474. ** to by the second parameter and which is N bytes long where N is the
  4475. ** third parameter.
  4476. **
  4477. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4478. ** the application-defined function to be a BLOB containing all zero
  4479. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4480. **
  4481. ** ^The sqlite3_result_double() interface sets the result from
  4482. ** an application-defined function to be a floating point value specified
  4483. ** by its 2nd argument.
  4484. **
  4485. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4486. ** cause the implemented SQL function to throw an exception.
  4487. ** ^SQLite uses the string pointed to by the
  4488. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4489. ** as the text of an error message. ^SQLite interprets the error
  4490. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4491. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4492. ** byte order. ^If the third parameter to sqlite3_result_error()
  4493. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4494. ** message all text up through the first zero character.
  4495. ** ^If the third parameter to sqlite3_result_error() or
  4496. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4497. ** bytes (not characters) from the 2nd parameter as the error message.
  4498. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4499. ** routines make a private copy of the error message text before
  4500. ** they return. Hence, the calling function can deallocate or
  4501. ** modify the text after they return without harm.
  4502. ** ^The sqlite3_result_error_code() function changes the error code
  4503. ** returned by SQLite as a result of an error in a function. ^By default,
  4504. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4505. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4506. **
  4507. ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
  4508. ** indicating that a string or BLOB is too long to represent.
  4509. **
  4510. ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
  4511. ** indicating that a memory allocation failed.
  4512. **
  4513. ** ^The sqlite3_result_int() interface sets the return value
  4514. ** of the application-defined function to be the 32-bit signed integer
  4515. ** value given in the 2nd argument.
  4516. ** ^The sqlite3_result_int64() interface sets the return value
  4517. ** of the application-defined function to be the 64-bit signed integer
  4518. ** value given in the 2nd argument.
  4519. **
  4520. ** ^The sqlite3_result_null() interface sets the return value
  4521. ** of the application-defined function to be NULL.
  4522. **
  4523. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4524. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4525. ** set the return value of the application-defined function to be
  4526. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4527. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4528. ** ^SQLite takes the text result from the application from
  4529. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4530. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4531. ** is negative, then SQLite takes result text from the 2nd parameter
  4532. ** through the first zero character.
  4533. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4534. ** is non-negative, then as many bytes (not characters) of the text
  4535. ** pointed to by the 2nd parameter are taken as the application-defined
  4536. ** function result. If the 3rd parameter is non-negative, then it
  4537. ** must be the byte offset into the string where the NUL terminator would
  4538. ** appear if the string where NUL terminated. If any NUL characters occur
  4539. ** in the string at a byte offset that is less than the value of the 3rd
  4540. ** parameter, then the resulting string will contain embedded NULs and the
  4541. ** result of expressions operating on strings with embedded NULs is undefined.
  4542. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4543. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4544. ** function as the destructor on the text or BLOB result when it has
  4545. ** finished using that result.
  4546. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4547. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4548. ** assumes that the text or BLOB result is in constant space and does not
  4549. ** copy the content of the parameter nor call a destructor on the content
  4550. ** when it has finished using that result.
  4551. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4552. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4553. ** then SQLite makes a copy of the result into space obtained from
  4554. ** from [sqlite3_malloc()] before it returns.
  4555. **
  4556. ** ^The sqlite3_result_value() interface sets the result of
  4557. ** the application-defined function to be a copy the
  4558. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4559. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4560. ** so that the [sqlite3_value] specified in the parameter may change or
  4561. ** be deallocated after sqlite3_result_value() returns without harm.
  4562. ** ^A [protected sqlite3_value] object may always be used where an
  4563. ** [unprotected sqlite3_value] object is required, so either
  4564. ** kind of [sqlite3_value] object can be used with this interface.
  4565. **
  4566. ** If these routines are called from within the different thread
  4567. ** than the one containing the application-defined function that received
  4568. ** the [sqlite3_context] pointer, the results are undefined.
  4569. */
  4570. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4571. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4572. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4573. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4574. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4575. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4576. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4577. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4578. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4579. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4580. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4581. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4582. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4583. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4584. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4585. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4586. /*
  4587. ** CAPI3REF: Define New Collating Sequences
  4588. **
  4589. ** ^These functions add, remove, or modify a [collation] associated
  4590. ** with the [database connection] specified as the first argument.
  4591. **
  4592. ** ^The name of the collation is a UTF-8 string
  4593. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4594. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4595. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4596. ** considered to be the same name.
  4597. **
  4598. ** ^(The third argument (eTextRep) must be one of the constants:
  4599. ** <ul>
  4600. ** <li> [SQLITE_UTF8],
  4601. ** <li> [SQLITE_UTF16LE],
  4602. ** <li> [SQLITE_UTF16BE],
  4603. ** <li> [SQLITE_UTF16], or
  4604. ** <li> [SQLITE_UTF16_ALIGNED].
  4605. ** </ul>)^
  4606. ** ^The eTextRep argument determines the encoding of strings passed
  4607. ** to the collating function callback, xCallback.
  4608. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4609. ** force strings to be UTF16 with native byte order.
  4610. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4611. ** on an even byte address.
  4612. **
  4613. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4614. ** through as the first argument to the collating function callback.
  4615. **
  4616. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4617. ** ^Multiple collating functions can be registered using the same name but
  4618. ** with different eTextRep parameters and SQLite will use whichever
  4619. ** function requires the least amount of data transformation.
  4620. ** ^If the xCallback argument is NULL then the collating function is
  4621. ** deleted. ^When all collating functions having the same name are deleted,
  4622. ** that collation is no longer usable.
  4623. **
  4624. ** ^The collating function callback is invoked with a copy of the pArg
  4625. ** application data pointer and with two strings in the encoding specified
  4626. ** by the eTextRep argument. The collating function must return an
  4627. ** integer that is negative, zero, or positive
  4628. ** if the first string is less than, equal to, or greater than the second,
  4629. ** respectively. A collating function must always return the same answer
  4630. ** given the same inputs. If two or more collating functions are registered
  4631. ** to the same collation name (using different eTextRep values) then all
  4632. ** must give an equivalent answer when invoked with equivalent strings.
  4633. ** The collating function must obey the following properties for all
  4634. ** strings A, B, and C:
  4635. **
  4636. ** <ol>
  4637. ** <li> If A==B then B==A.
  4638. ** <li> If A==B and B==C then A==C.
  4639. ** <li> If A&lt;B THEN B&gt;A.
  4640. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4641. ** </ol>
  4642. **
  4643. ** If a collating function fails any of the above constraints and that
  4644. ** collating function is registered and used, then the behavior of SQLite
  4645. ** is undefined.
  4646. **
  4647. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4648. ** with the addition that the xDestroy callback is invoked on pArg when
  4649. ** the collating function is deleted.
  4650. ** ^Collating functions are deleted when they are overridden by later
  4651. ** calls to the collation creation functions or when the
  4652. ** [database connection] is closed using [sqlite3_close()].
  4653. **
  4654. ** ^The xDestroy callback is <u>not</u> called if the
  4655. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4656. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4657. ** check the return code and dispose of the application data pointer
  4658. ** themselves rather than expecting SQLite to deal with it for them.
  4659. ** This is different from every other SQLite interface. The inconsistency
  4660. ** is unfortunate but cannot be changed without breaking backwards
  4661. ** compatibility.
  4662. **
  4663. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4664. */
  4665. SQLITE_API int sqlite3_create_collation(
  4666. sqlite3*,
  4667. const char *zName,
  4668. int eTextRep,
  4669. void *pArg,
  4670. int(*xCompare)(void*,int,const void*,int,const void*)
  4671. );
  4672. SQLITE_API int sqlite3_create_collation_v2(
  4673. sqlite3*,
  4674. const char *zName,
  4675. int eTextRep,
  4676. void *pArg,
  4677. int(*xCompare)(void*,int,const void*,int,const void*),
  4678. void(*xDestroy)(void*)
  4679. );
  4680. SQLITE_API int sqlite3_create_collation16(
  4681. sqlite3*,
  4682. const void *zName,
  4683. int eTextRep,
  4684. void *pArg,
  4685. int(*xCompare)(void*,int,const void*,int,const void*)
  4686. );
  4687. /*
  4688. ** CAPI3REF: Collation Needed Callbacks
  4689. **
  4690. ** ^To avoid having to register all collation sequences before a database
  4691. ** can be used, a single callback function may be registered with the
  4692. ** [database connection] to be invoked whenever an undefined collation
  4693. ** sequence is required.
  4694. **
  4695. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4696. ** then it is passed the names of undefined collation sequences as strings
  4697. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4698. ** the names are passed as UTF-16 in machine native byte order.
  4699. ** ^A call to either function replaces the existing collation-needed callback.
  4700. **
  4701. ** ^(When the callback is invoked, the first argument passed is a copy
  4702. ** of the second argument to sqlite3_collation_needed() or
  4703. ** sqlite3_collation_needed16(). The second argument is the database
  4704. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4705. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4706. ** sequence function required. The fourth parameter is the name of the
  4707. ** required collation sequence.)^
  4708. **
  4709. ** The callback function should register the desired collation using
  4710. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4711. ** [sqlite3_create_collation_v2()].
  4712. */
  4713. SQLITE_API int sqlite3_collation_needed(
  4714. sqlite3*,
  4715. void*,
  4716. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4717. );
  4718. SQLITE_API int sqlite3_collation_needed16(
  4719. sqlite3*,
  4720. void*,
  4721. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4722. );
  4723. #ifdef SQLITE_HAS_CODEC
  4724. /*
  4725. ** Specify the key for an encrypted database. This routine should be
  4726. ** called right after sqlite3_open().
  4727. **
  4728. ** The code to implement this API is not available in the public release
  4729. ** of SQLite.
  4730. */
  4731. SQLITE_API int sqlite3_key(
  4732. sqlite3 *db, /* Database to be rekeyed */
  4733. const void *pKey, int nKey /* The key */
  4734. );
  4735. /*
  4736. ** Change the key on an open database. If the current database is not
  4737. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4738. ** database is decrypted.
  4739. **
  4740. ** The code to implement this API is not available in the public release
  4741. ** of SQLite.
  4742. */
  4743. SQLITE_API int sqlite3_rekey(
  4744. sqlite3 *db, /* Database to be rekeyed */
  4745. const void *pKey, int nKey /* The new key */
  4746. );
  4747. /*
  4748. ** Specify the activation key for a SEE database. Unless
  4749. ** activated, none of the SEE routines will work.
  4750. */
  4751. SQLITE_API void sqlite3_activate_see(
  4752. const char *zPassPhrase /* Activation phrase */
  4753. );
  4754. #endif
  4755. #ifdef SQLITE_ENABLE_CEROD
  4756. /*
  4757. ** Specify the activation key for a CEROD database. Unless
  4758. ** activated, none of the CEROD routines will work.
  4759. */
  4760. SQLITE_API void sqlite3_activate_cerod(
  4761. const char *zPassPhrase /* Activation phrase */
  4762. );
  4763. #endif
  4764. /*
  4765. ** CAPI3REF: Suspend Execution For A Short Time
  4766. **
  4767. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4768. ** for at least a number of milliseconds specified in its parameter.
  4769. **
  4770. ** If the operating system does not support sleep requests with
  4771. ** millisecond time resolution, then the time will be rounded up to
  4772. ** the nearest second. The number of milliseconds of sleep actually
  4773. ** requested from the operating system is returned.
  4774. **
  4775. ** ^SQLite implements this interface by calling the xSleep()
  4776. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4777. ** of the default VFS is not implemented correctly, or not implemented at
  4778. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4779. ** in the previous paragraphs.
  4780. */
  4781. SQLITE_API int sqlite3_sleep(int);
  4782. /*
  4783. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4784. **
  4785. ** ^(If this global variable is made to point to a string which is
  4786. ** the name of a folder (a.k.a. directory), then all temporary files
  4787. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4788. ** will be placed in that directory.)^ ^If this variable
  4789. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4790. ** temporary file directory.
  4791. **
  4792. ** It is not safe to read or modify this variable in more than one
  4793. ** thread at a time. It is not safe to read or modify this variable
  4794. ** if a [database connection] is being used at the same time in a separate
  4795. ** thread.
  4796. ** It is intended that this variable be set once
  4797. ** as part of process initialization and before any SQLite interface
  4798. ** routines have been called and that this variable remain unchanged
  4799. ** thereafter.
  4800. **
  4801. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4802. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4803. ** the [temp_store_directory pragma] always assumes that any string
  4804. ** that this variable points to is held in memory obtained from
  4805. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4806. ** using [sqlite3_free].
  4807. ** Hence, if this variable is modified directly, either it should be
  4808. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4809. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4810. */
  4811. SQLITE_API char *sqlite3_temp_directory;
  4812. /*
  4813. ** CAPI3REF: Test For Auto-Commit Mode
  4814. ** KEYWORDS: {autocommit mode}
  4815. **
  4816. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4817. ** zero if the given database connection is or is not in autocommit mode,
  4818. ** respectively. ^Autocommit mode is on by default.
  4819. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4820. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4821. **
  4822. ** If certain kinds of errors occur on a statement within a multi-statement
  4823. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4824. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4825. ** transaction might be rolled back automatically. The only way to
  4826. ** find out whether SQLite automatically rolled back the transaction after
  4827. ** an error is to use this function.
  4828. **
  4829. ** If another thread changes the autocommit status of the database
  4830. ** connection while this routine is running, then the return value
  4831. ** is undefined.
  4832. */
  4833. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4834. /*
  4835. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4836. **
  4837. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4838. ** to which a [prepared statement] belongs. ^The [database connection]
  4839. ** returned by sqlite3_db_handle is the same [database connection]
  4840. ** that was the first argument
  4841. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4842. ** create the statement in the first place.
  4843. */
  4844. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4845. /*
  4846. ** CAPI3REF: Return The Filename For A Database Connection
  4847. **
  4848. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  4849. ** associated with database N of connection D. ^The main database file
  4850. ** has the name "main". If there is no attached database N on the database
  4851. ** connection D, or if database N is a temporary or in-memory database, then
  4852. ** a NULL pointer is returned.
  4853. **
  4854. ** ^The filename returned by this function is the output of the
  4855. ** xFullPathname method of the [VFS]. ^In other words, the filename
  4856. ** will be an absolute pathname, even if the filename used
  4857. ** to open the database originally was a URI or relative pathname.
  4858. */
  4859. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  4860. /*
  4861. ** CAPI3REF: Find the next prepared statement
  4862. **
  4863. ** ^This interface returns a pointer to the next [prepared statement] after
  4864. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4865. ** then this interface returns a pointer to the first prepared statement
  4866. ** associated with the database connection pDb. ^If no prepared statement
  4867. ** satisfies the conditions of this routine, it returns NULL.
  4868. **
  4869. ** The [database connection] pointer D in a call to
  4870. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4871. ** connection and in particular must not be a NULL pointer.
  4872. */
  4873. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4874. /*
  4875. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4876. **
  4877. ** ^The sqlite3_commit_hook() interface registers a callback
  4878. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4879. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4880. ** for the same database connection is overridden.
  4881. ** ^The sqlite3_rollback_hook() interface registers a callback
  4882. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4883. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4884. ** for the same database connection is overridden.
  4885. ** ^The pArg argument is passed through to the callback.
  4886. ** ^If the callback on a commit hook function returns non-zero,
  4887. ** then the commit is converted into a rollback.
  4888. **
  4889. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4890. ** return the P argument from the previous call of the same function
  4891. ** on the same [database connection] D, or NULL for
  4892. ** the first call for each function on D.
  4893. **
  4894. ** The commit and rollback hook callbacks are not reentrant.
  4895. ** The callback implementation must not do anything that will modify
  4896. ** the database connection that invoked the callback. Any actions
  4897. ** to modify the database connection must be deferred until after the
  4898. ** completion of the [sqlite3_step()] call that triggered the commit
  4899. ** or rollback hook in the first place.
  4900. ** Note that running any other SQL statements, including SELECT statements,
  4901. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  4902. ** the database connections for the meaning of "modify" in this paragraph.
  4903. **
  4904. ** ^Registering a NULL function disables the callback.
  4905. **
  4906. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4907. ** operation is allowed to continue normally. ^If the commit hook
  4908. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4909. ** ^The rollback hook is invoked on a rollback that results from a commit
  4910. ** hook returning non-zero, just as it would be with any other rollback.
  4911. **
  4912. ** ^For the purposes of this API, a transaction is said to have been
  4913. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4914. ** an error or constraint causes an implicit rollback to occur.
  4915. ** ^The rollback callback is not invoked if a transaction is
  4916. ** automatically rolled back because the database connection is closed.
  4917. **
  4918. ** See also the [sqlite3_update_hook()] interface.
  4919. */
  4920. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4921. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4922. /*
  4923. ** CAPI3REF: Data Change Notification Callbacks
  4924. **
  4925. ** ^The sqlite3_update_hook() interface registers a callback function
  4926. ** with the [database connection] identified by the first argument
  4927. ** to be invoked whenever a row is updated, inserted or deleted.
  4928. ** ^Any callback set by a previous call to this function
  4929. ** for the same database connection is overridden.
  4930. **
  4931. ** ^The second argument is a pointer to the function to invoke when a
  4932. ** row is updated, inserted or deleted.
  4933. ** ^The first argument to the callback is a copy of the third argument
  4934. ** to sqlite3_update_hook().
  4935. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4936. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4937. ** to be invoked.
  4938. ** ^The third and fourth arguments to the callback contain pointers to the
  4939. ** database and table name containing the affected row.
  4940. ** ^The final callback parameter is the [rowid] of the row.
  4941. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4942. **
  4943. ** ^(The update hook is not invoked when internal system tables are
  4944. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4945. **
  4946. ** ^In the current implementation, the update hook
  4947. ** is not invoked when duplication rows are deleted because of an
  4948. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4949. ** invoked when rows are deleted using the [truncate optimization].
  4950. ** The exceptions defined in this paragraph might change in a future
  4951. ** release of SQLite.
  4952. **
  4953. ** The update hook implementation must not do anything that will modify
  4954. ** the database connection that invoked the update hook. Any actions
  4955. ** to modify the database connection must be deferred until after the
  4956. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4957. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4958. ** database connections for the meaning of "modify" in this paragraph.
  4959. **
  4960. ** ^The sqlite3_update_hook(D,C,P) function
  4961. ** returns the P argument from the previous call
  4962. ** on the same [database connection] D, or NULL for
  4963. ** the first call on D.
  4964. **
  4965. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  4966. ** interfaces.
  4967. */
  4968. SQLITE_API void *sqlite3_update_hook(
  4969. sqlite3*,
  4970. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  4971. void*
  4972. );
  4973. /*
  4974. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  4975. ** KEYWORDS: {shared cache}
  4976. **
  4977. ** ^(This routine enables or disables the sharing of the database cache
  4978. ** and schema data structures between [database connection | connections]
  4979. ** to the same database. Sharing is enabled if the argument is true
  4980. ** and disabled if the argument is false.)^
  4981. **
  4982. ** ^Cache sharing is enabled and disabled for an entire process.
  4983. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  4984. ** sharing was enabled or disabled for each thread separately.
  4985. **
  4986. ** ^(The cache sharing mode set by this interface effects all subsequent
  4987. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  4988. ** Existing database connections continue use the sharing mode
  4989. ** that was in effect at the time they were opened.)^
  4990. **
  4991. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  4992. ** successfully. An [error code] is returned otherwise.)^
  4993. **
  4994. ** ^Shared cache is disabled by default. But this might change in
  4995. ** future releases of SQLite. Applications that care about shared
  4996. ** cache setting should set it explicitly.
  4997. **
  4998. ** See Also: [SQLite Shared-Cache Mode]
  4999. */
  5000. SQLITE_API int sqlite3_enable_shared_cache(int);
  5001. /*
  5002. ** CAPI3REF: Attempt To Free Heap Memory
  5003. **
  5004. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5005. ** of heap memory by deallocating non-essential memory allocations
  5006. ** held by the database library. Memory used to cache database
  5007. ** pages to improve performance is an example of non-essential memory.
  5008. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5009. ** which might be more or less than the amount requested.
  5010. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5011. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5012. **
  5013. ** See also: [sqlite3_db_release_memory()]
  5014. */
  5015. SQLITE_API int sqlite3_release_memory(int);
  5016. /*
  5017. ** CAPI3REF: Free Memory Used By A Database Connection
  5018. **
  5019. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5020. ** memory as possible from database connection D. Unlike the
  5021. ** [sqlite3_release_memory()] interface, this interface is effect even
  5022. ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5023. ** omitted.
  5024. **
  5025. ** See also: [sqlite3_release_memory()]
  5026. */
  5027. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  5028. /*
  5029. ** CAPI3REF: Impose A Limit On Heap Size
  5030. **
  5031. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5032. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5033. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5034. ** limit by reducing the number of pages held in the page cache
  5035. ** as heap memory usages approaches the limit.
  5036. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5037. ** below the limit, it will exceed the limit rather than generate
  5038. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5039. ** is advisory only.
  5040. **
  5041. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5042. ** the soft heap limit prior to the call, or negative in the case of an
  5043. ** error. ^If the argument N is negative
  5044. ** then no change is made to the soft heap limit. Hence, the current
  5045. ** size of the soft heap limit can be determined by invoking
  5046. ** sqlite3_soft_heap_limit64() with a negative argument.
  5047. **
  5048. ** ^If the argument N is zero then the soft heap limit is disabled.
  5049. **
  5050. ** ^(The soft heap limit is not enforced in the current implementation
  5051. ** if one or more of following conditions are true:
  5052. **
  5053. ** <ul>
  5054. ** <li> The soft heap limit is set to zero.
  5055. ** <li> Memory accounting is disabled using a combination of the
  5056. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5057. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5058. ** <li> An alternative page cache implementation is specified using
  5059. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5060. ** <li> The page cache allocates from its own memory pool supplied
  5061. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5062. ** from the heap.
  5063. ** </ul>)^
  5064. **
  5065. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5066. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5067. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5068. ** the soft heap limit is enforced on every memory allocation. Without
  5069. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5070. ** when memory is allocated by the page cache. Testing suggests that because
  5071. ** the page cache is the predominate memory user in SQLite, most
  5072. ** applications will achieve adequate soft heap limit enforcement without
  5073. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5074. **
  5075. ** The circumstances under which SQLite will enforce the soft heap limit may
  5076. ** changes in future releases of SQLite.
  5077. */
  5078. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5079. /*
  5080. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5081. ** DEPRECATED
  5082. **
  5083. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5084. ** interface. This routine is provided for historical compatibility
  5085. ** only. All new applications should use the
  5086. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5087. */
  5088. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  5089. /*
  5090. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5091. **
  5092. ** ^This routine returns metadata about a specific column of a specific
  5093. ** database table accessible using the [database connection] handle
  5094. ** passed as the first function argument.
  5095. **
  5096. ** ^The column is identified by the second, third and fourth parameters to
  5097. ** this function. ^The second parameter is either the name of the database
  5098. ** (i.e. "main", "temp", or an attached database) containing the specified
  5099. ** table or NULL. ^If it is NULL, then all attached databases are searched
  5100. ** for the table using the same algorithm used by the database engine to
  5101. ** resolve unqualified table references.
  5102. **
  5103. ** ^The third and fourth parameters to this function are the table and column
  5104. ** name of the desired column, respectively. Neither of these parameters
  5105. ** may be NULL.
  5106. **
  5107. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5108. ** and subsequent parameters to this function. ^Any of these arguments may be
  5109. ** NULL, in which case the corresponding element of metadata is omitted.
  5110. **
  5111. ** ^(<blockquote>
  5112. ** <table border="1">
  5113. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5114. **
  5115. ** <tr><td> 5th <td> const char* <td> Data type
  5116. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5117. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5118. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5119. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5120. ** </table>
  5121. ** </blockquote>)^
  5122. **
  5123. ** ^The memory pointed to by the character pointers returned for the
  5124. ** declaration type and collation sequence is valid only until the next
  5125. ** call to any SQLite API function.
  5126. **
  5127. ** ^If the specified table is actually a view, an [error code] is returned.
  5128. **
  5129. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  5130. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5131. ** parameters are set for the explicitly declared column. ^(If there is no
  5132. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  5133. ** parameters are set as follows:
  5134. **
  5135. ** <pre>
  5136. ** data type: "INTEGER"
  5137. ** collation sequence: "BINARY"
  5138. ** not null: 0
  5139. ** primary key: 1
  5140. ** auto increment: 0
  5141. ** </pre>)^
  5142. **
  5143. ** ^(This function may load one or more schemas from database files. If an
  5144. ** error occurs during this process, or if the requested table or column
  5145. ** cannot be found, an [error code] is returned and an error message left
  5146. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  5147. **
  5148. ** ^This API is only available if the library was compiled with the
  5149. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  5150. */
  5151. SQLITE_API int sqlite3_table_column_metadata(
  5152. sqlite3 *db, /* Connection handle */
  5153. const char *zDbName, /* Database name or NULL */
  5154. const char *zTableName, /* Table name */
  5155. const char *zColumnName, /* Column name */
  5156. char const **pzDataType, /* OUTPUT: Declared data type */
  5157. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5158. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5159. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5160. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5161. );
  5162. /*
  5163. ** CAPI3REF: Load An Extension
  5164. **
  5165. ** ^This interface loads an SQLite extension library from the named file.
  5166. **
  5167. ** ^The sqlite3_load_extension() interface attempts to load an
  5168. ** SQLite extension library contained in the file zFile.
  5169. **
  5170. ** ^The entry point is zProc.
  5171. ** ^zProc may be 0, in which case the name of the entry point
  5172. ** defaults to "sqlite3_extension_init".
  5173. ** ^The sqlite3_load_extension() interface returns
  5174. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5175. ** ^If an error occurs and pzErrMsg is not 0, then the
  5176. ** [sqlite3_load_extension()] interface shall attempt to
  5177. ** fill *pzErrMsg with error message text stored in memory
  5178. ** obtained from [sqlite3_malloc()]. The calling function
  5179. ** should free this memory by calling [sqlite3_free()].
  5180. **
  5181. ** ^Extension loading must be enabled using
  5182. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5183. ** otherwise an error will be returned.
  5184. **
  5185. ** See also the [load_extension() SQL function].
  5186. */
  5187. SQLITE_API int sqlite3_load_extension(
  5188. sqlite3 *db, /* Load the extension into this database connection */
  5189. const char *zFile, /* Name of the shared library containing extension */
  5190. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5191. char **pzErrMsg /* Put error message here if not 0 */
  5192. );
  5193. /*
  5194. ** CAPI3REF: Enable Or Disable Extension Loading
  5195. **
  5196. ** ^So as not to open security holes in older applications that are
  5197. ** unprepared to deal with extension loading, and as a means of disabling
  5198. ** extension loading while evaluating user-entered SQL, the following API
  5199. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5200. **
  5201. ** ^Extension loading is off by default. See ticket #1863.
  5202. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5203. ** to turn extension loading on and call it with onoff==0 to turn
  5204. ** it back off again.
  5205. */
  5206. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5207. /*
  5208. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5209. **
  5210. ** ^This interface causes the xEntryPoint() function to be invoked for
  5211. ** each new [database connection] that is created. The idea here is that
  5212. ** xEntryPoint() is the entry point for a statically linked SQLite extension
  5213. ** that is to be automatically loaded into all new database connections.
  5214. **
  5215. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5216. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5217. ** arguments and expects and integer result as if the signature of the
  5218. ** entry point where as follows:
  5219. **
  5220. ** <blockquote><pre>
  5221. ** &nbsp; int xEntryPoint(
  5222. ** &nbsp; sqlite3 *db,
  5223. ** &nbsp; const char **pzErrMsg,
  5224. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5225. ** &nbsp; );
  5226. ** </pre></blockquote>)^
  5227. **
  5228. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5229. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5230. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5231. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5232. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5233. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5234. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5235. **
  5236. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5237. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5238. ** will be called more than once for each database connection that is opened.
  5239. **
  5240. ** See also: [sqlite3_reset_auto_extension()].
  5241. */
  5242. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5243. /*
  5244. ** CAPI3REF: Reset Automatic Extension Loading
  5245. **
  5246. ** ^This interface disables all automatic extensions previously
  5247. ** registered using [sqlite3_auto_extension()].
  5248. */
  5249. SQLITE_API void sqlite3_reset_auto_extension(void);
  5250. /*
  5251. ** The interface to the virtual-table mechanism is currently considered
  5252. ** to be experimental. The interface might change in incompatible ways.
  5253. ** If this is a problem for you, do not use the interface at this time.
  5254. **
  5255. ** When the virtual-table mechanism stabilizes, we will declare the
  5256. ** interface fixed, support it indefinitely, and remove this comment.
  5257. */
  5258. /*
  5259. ** Structures used by the virtual table interface
  5260. */
  5261. typedef struct sqlite3_vtab sqlite3_vtab;
  5262. typedef struct sqlite3_index_info sqlite3_index_info;
  5263. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5264. typedef struct sqlite3_module sqlite3_module;
  5265. /*
  5266. ** CAPI3REF: Virtual Table Object
  5267. ** KEYWORDS: sqlite3_module {virtual table module}
  5268. **
  5269. ** This structure, sometimes called a "virtual table module",
  5270. ** defines the implementation of a [virtual tables].
  5271. ** This structure consists mostly of methods for the module.
  5272. **
  5273. ** ^A virtual table module is created by filling in a persistent
  5274. ** instance of this structure and passing a pointer to that instance
  5275. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5276. ** ^The registration remains valid until it is replaced by a different
  5277. ** module or until the [database connection] closes. The content
  5278. ** of this structure must not change while it is registered with
  5279. ** any database connection.
  5280. */
  5281. struct sqlite3_module {
  5282. int iVersion;
  5283. int (*xCreate)(sqlite3*, void *pAux,
  5284. int argc, const char *const*argv,
  5285. sqlite3_vtab **ppVTab, char**);
  5286. int (*xConnect)(sqlite3*, void *pAux,
  5287. int argc, const char *const*argv,
  5288. sqlite3_vtab **ppVTab, char**);
  5289. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5290. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5291. int (*xDestroy)(sqlite3_vtab *pVTab);
  5292. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5293. int (*xClose)(sqlite3_vtab_cursor*);
  5294. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5295. int argc, sqlite3_value **argv);
  5296. int (*xNext)(sqlite3_vtab_cursor*);
  5297. int (*xEof)(sqlite3_vtab_cursor*);
  5298. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5299. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5300. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5301. int (*xBegin)(sqlite3_vtab *pVTab);
  5302. int (*xSync)(sqlite3_vtab *pVTab);
  5303. int (*xCommit)(sqlite3_vtab *pVTab);
  5304. int (*xRollback)(sqlite3_vtab *pVTab);
  5305. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5306. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5307. void **ppArg);
  5308. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5309. /* The methods above are in version 1 of the sqlite_module object. Those
  5310. ** below are for version 2 and greater. */
  5311. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5312. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5313. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5314. };
  5315. /*
  5316. ** CAPI3REF: Virtual Table Indexing Information
  5317. ** KEYWORDS: sqlite3_index_info
  5318. **
  5319. ** The sqlite3_index_info structure and its substructures is used as part
  5320. ** of the [virtual table] interface to
  5321. ** pass information into and receive the reply from the [xBestIndex]
  5322. ** method of a [virtual table module]. The fields under **Inputs** are the
  5323. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5324. ** results into the **Outputs** fields.
  5325. **
  5326. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5327. **
  5328. ** <blockquote>column OP expr</blockquote>
  5329. **
  5330. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5331. ** stored in aConstraint[].op using one of the
  5332. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5333. ** ^(The index of the column is stored in
  5334. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5335. ** expr on the right-hand side can be evaluated (and thus the constraint
  5336. ** is usable) and false if it cannot.)^
  5337. **
  5338. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5339. ** and makes other simplifications to the WHERE clause in an attempt to
  5340. ** get as many WHERE clause terms into the form shown above as possible.
  5341. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5342. ** relevant to the particular virtual table being queried.
  5343. **
  5344. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5345. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5346. **
  5347. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5348. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5349. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5350. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5351. ** is true, then the constraint is assumed to be fully handled by the
  5352. ** virtual table and is not checked again by SQLite.)^
  5353. **
  5354. ** ^The idxNum and idxPtr values are recorded and passed into the
  5355. ** [xFilter] method.
  5356. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5357. ** needToFreeIdxPtr is true.
  5358. **
  5359. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5360. ** the correct order to satisfy the ORDER BY clause so that no separate
  5361. ** sorting step is required.
  5362. **
  5363. ** ^The estimatedCost value is an estimate of the cost of doing the
  5364. ** particular lookup. A full scan of a table with N entries should have
  5365. ** a cost of N. A binary search of a table of N entries should have a
  5366. ** cost of approximately log(N).
  5367. */
  5368. struct sqlite3_index_info {
  5369. /* Inputs */
  5370. int nConstraint; /* Number of entries in aConstraint */
  5371. struct sqlite3_index_constraint {
  5372. int iColumn; /* Column on left-hand side of constraint */
  5373. unsigned char op; /* Constraint operator */
  5374. unsigned char usable; /* True if this constraint is usable */
  5375. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5376. } *aConstraint; /* Table of WHERE clause constraints */
  5377. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5378. struct sqlite3_index_orderby {
  5379. int iColumn; /* Column number */
  5380. unsigned char desc; /* True for DESC. False for ASC. */
  5381. } *aOrderBy; /* The ORDER BY clause */
  5382. /* Outputs */
  5383. struct sqlite3_index_constraint_usage {
  5384. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5385. unsigned char omit; /* Do not code a test for this constraint */
  5386. } *aConstraintUsage;
  5387. int idxNum; /* Number used to identify the index */
  5388. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5389. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5390. int orderByConsumed; /* True if output is already ordered */
  5391. double estimatedCost; /* Estimated cost of using this index */
  5392. };
  5393. /*
  5394. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5395. **
  5396. ** These macros defined the allowed values for the
  5397. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5398. ** an operator that is part of a constraint term in the wHERE clause of
  5399. ** a query that uses a [virtual table].
  5400. */
  5401. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5402. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5403. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5404. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5405. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5406. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5407. /*
  5408. ** CAPI3REF: Register A Virtual Table Implementation
  5409. **
  5410. ** ^These routines are used to register a new [virtual table module] name.
  5411. ** ^Module names must be registered before
  5412. ** creating a new [virtual table] using the module and before using a
  5413. ** preexisting [virtual table] for the module.
  5414. **
  5415. ** ^The module name is registered on the [database connection] specified
  5416. ** by the first parameter. ^The name of the module is given by the
  5417. ** second parameter. ^The third parameter is a pointer to
  5418. ** the implementation of the [virtual table module]. ^The fourth
  5419. ** parameter is an arbitrary client data pointer that is passed through
  5420. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5421. ** when a new virtual table is be being created or reinitialized.
  5422. **
  5423. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5424. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5425. ** invoke the destructor function (if it is not NULL) when SQLite
  5426. ** no longer needs the pClientData pointer. ^The destructor will also
  5427. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5428. ** ^The sqlite3_create_module()
  5429. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5430. ** destructor.
  5431. */
  5432. SQLITE_API int sqlite3_create_module(
  5433. sqlite3 *db, /* SQLite connection to register module with */
  5434. const char *zName, /* Name of the module */
  5435. const sqlite3_module *p, /* Methods for the module */
  5436. void *pClientData /* Client data for xCreate/xConnect */
  5437. );
  5438. SQLITE_API int sqlite3_create_module_v2(
  5439. sqlite3 *db, /* SQLite connection to register module with */
  5440. const char *zName, /* Name of the module */
  5441. const sqlite3_module *p, /* Methods for the module */
  5442. void *pClientData, /* Client data for xCreate/xConnect */
  5443. void(*xDestroy)(void*) /* Module destructor function */
  5444. );
  5445. /*
  5446. ** CAPI3REF: Virtual Table Instance Object
  5447. ** KEYWORDS: sqlite3_vtab
  5448. **
  5449. ** Every [virtual table module] implementation uses a subclass
  5450. ** of this object to describe a particular instance
  5451. ** of the [virtual table]. Each subclass will
  5452. ** be tailored to the specific needs of the module implementation.
  5453. ** The purpose of this superclass is to define certain fields that are
  5454. ** common to all module implementations.
  5455. **
  5456. ** ^Virtual tables methods can set an error message by assigning a
  5457. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5458. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5459. ** prior to assigning a new string to zErrMsg. ^After the error message
  5460. ** is delivered up to the client application, the string will be automatically
  5461. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5462. */
  5463. struct sqlite3_vtab {
  5464. const sqlite3_module *pModule; /* The module for this virtual table */
  5465. int nRef; /* NO LONGER USED */
  5466. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5467. /* Virtual table implementations will typically add additional fields */
  5468. };
  5469. /*
  5470. ** CAPI3REF: Virtual Table Cursor Object
  5471. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5472. **
  5473. ** Every [virtual table module] implementation uses a subclass of the
  5474. ** following structure to describe cursors that point into the
  5475. ** [virtual table] and are used
  5476. ** to loop through the virtual table. Cursors are created using the
  5477. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5478. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5479. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5480. ** of the module. Each module implementation will define
  5481. ** the content of a cursor structure to suit its own needs.
  5482. **
  5483. ** This superclass exists in order to define fields of the cursor that
  5484. ** are common to all implementations.
  5485. */
  5486. struct sqlite3_vtab_cursor {
  5487. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5488. /* Virtual table implementations will typically add additional fields */
  5489. };
  5490. /*
  5491. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5492. **
  5493. ** ^The [xCreate] and [xConnect] methods of a
  5494. ** [virtual table module] call this interface
  5495. ** to declare the format (the names and datatypes of the columns) of
  5496. ** the virtual tables they implement.
  5497. */
  5498. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5499. /*
  5500. ** CAPI3REF: Overload A Function For A Virtual Table
  5501. **
  5502. ** ^(Virtual tables can provide alternative implementations of functions
  5503. ** using the [xFindFunction] method of the [virtual table module].
  5504. ** But global versions of those functions
  5505. ** must exist in order to be overloaded.)^
  5506. **
  5507. ** ^(This API makes sure a global version of a function with a particular
  5508. ** name and number of parameters exists. If no such function exists
  5509. ** before this API is called, a new function is created.)^ ^The implementation
  5510. ** of the new function always causes an exception to be thrown. So
  5511. ** the new function is not good for anything by itself. Its only
  5512. ** purpose is to be a placeholder function that can be overloaded
  5513. ** by a [virtual table].
  5514. */
  5515. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5516. /*
  5517. ** The interface to the virtual-table mechanism defined above (back up
  5518. ** to a comment remarkably similar to this one) is currently considered
  5519. ** to be experimental. The interface might change in incompatible ways.
  5520. ** If this is a problem for you, do not use the interface at this time.
  5521. **
  5522. ** When the virtual-table mechanism stabilizes, we will declare the
  5523. ** interface fixed, support it indefinitely, and remove this comment.
  5524. */
  5525. /*
  5526. ** CAPI3REF: A Handle To An Open BLOB
  5527. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5528. **
  5529. ** An instance of this object represents an open BLOB on which
  5530. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5531. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5532. ** and destroyed by [sqlite3_blob_close()].
  5533. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5534. ** can be used to read or write small subsections of the BLOB.
  5535. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5536. */
  5537. typedef struct sqlite3_blob sqlite3_blob;
  5538. /*
  5539. ** CAPI3REF: Open A BLOB For Incremental I/O
  5540. **
  5541. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5542. ** in row iRow, column zColumn, table zTable in database zDb;
  5543. ** in other words, the same BLOB that would be selected by:
  5544. **
  5545. ** <pre>
  5546. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5547. ** </pre>)^
  5548. **
  5549. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5550. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5551. ** ^It is not possible to open a column that is part of an index or primary
  5552. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5553. ** not possible to open a column that is part of a [child key] for writing.
  5554. **
  5555. ** ^Note that the database name is not the filename that contains
  5556. ** the database but rather the symbolic name of the database that
  5557. ** appears after the AS keyword when the database is connected using [ATTACH].
  5558. ** ^For the main database file, the database name is "main".
  5559. ** ^For TEMP tables, the database name is "temp".
  5560. **
  5561. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5562. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5563. ** to be a null pointer.)^
  5564. ** ^This function sets the [database connection] error code and message
  5565. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5566. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5567. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5568. ** regardless of the success or failure of this routine.
  5569. **
  5570. ** ^(If the row that a BLOB handle points to is modified by an
  5571. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5572. ** then the BLOB handle is marked as "expired".
  5573. ** This is true if any column of the row is changed, even a column
  5574. ** other than the one the BLOB handle is open on.)^
  5575. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5576. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5577. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5578. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5579. ** commit if the transaction continues to completion.)^
  5580. **
  5581. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5582. ** the opened blob. ^The size of a blob may not be changed by this
  5583. ** interface. Use the [UPDATE] SQL command to change the size of a
  5584. ** blob.
  5585. **
  5586. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5587. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5588. ** to create an empty, zero-filled blob in which to read or write using
  5589. ** this interface.
  5590. **
  5591. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5592. ** be released by a call to [sqlite3_blob_close()].
  5593. */
  5594. SQLITE_API int sqlite3_blob_open(
  5595. sqlite3*,
  5596. const char *zDb,
  5597. const char *zTable,
  5598. const char *zColumn,
  5599. sqlite3_int64 iRow,
  5600. int flags,
  5601. sqlite3_blob **ppBlob
  5602. );
  5603. /*
  5604. ** CAPI3REF: Move a BLOB Handle to a New Row
  5605. **
  5606. ** ^This function is used to move an existing blob handle so that it points
  5607. ** to a different row of the same database table. ^The new row is identified
  5608. ** by the rowid value passed as the second argument. Only the row can be
  5609. ** changed. ^The database, table and column on which the blob handle is open
  5610. ** remain the same. Moving an existing blob handle to a new row can be
  5611. ** faster than closing the existing handle and opening a new one.
  5612. **
  5613. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5614. ** it must exist and there must be either a blob or text value stored in
  5615. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5616. ** it does not contain a blob or text value, or if another error occurs, an
  5617. ** SQLite error code is returned and the blob handle is considered aborted.
  5618. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5619. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5620. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5621. ** always returns zero.
  5622. **
  5623. ** ^This function sets the database handle error code and message.
  5624. */
  5625. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5626. /*
  5627. ** CAPI3REF: Close A BLOB Handle
  5628. **
  5629. ** ^Closes an open [BLOB handle].
  5630. **
  5631. ** ^Closing a BLOB shall cause the current transaction to commit
  5632. ** if there are no other BLOBs, no pending prepared statements, and the
  5633. ** database connection is in [autocommit mode].
  5634. ** ^If any writes were made to the BLOB, they might be held in cache
  5635. ** until the close operation if they will fit.
  5636. **
  5637. ** ^(Closing the BLOB often forces the changes
  5638. ** out to disk and so if any I/O errors occur, they will likely occur
  5639. ** at the time when the BLOB is closed. Any errors that occur during
  5640. ** closing are reported as a non-zero return value.)^
  5641. **
  5642. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5643. ** an error code, the BLOB is still closed.)^
  5644. **
  5645. ** ^Calling this routine with a null pointer (such as would be returned
  5646. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5647. */
  5648. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5649. /*
  5650. ** CAPI3REF: Return The Size Of An Open BLOB
  5651. **
  5652. ** ^Returns the size in bytes of the BLOB accessible via the
  5653. ** successfully opened [BLOB handle] in its only argument. ^The
  5654. ** incremental blob I/O routines can only read or overwriting existing
  5655. ** blob content; they cannot change the size of a blob.
  5656. **
  5657. ** This routine only works on a [BLOB handle] which has been created
  5658. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5659. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5660. ** to this routine results in undefined and probably undesirable behavior.
  5661. */
  5662. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5663. /*
  5664. ** CAPI3REF: Read Data From A BLOB Incrementally
  5665. **
  5666. ** ^(This function is used to read data from an open [BLOB handle] into a
  5667. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5668. ** from the open BLOB, starting at offset iOffset.)^
  5669. **
  5670. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5671. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5672. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5673. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5674. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5675. **
  5676. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5677. ** error code of [SQLITE_ABORT].
  5678. **
  5679. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5680. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5681. **
  5682. ** This routine only works on a [BLOB handle] which has been created
  5683. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5684. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5685. ** to this routine results in undefined and probably undesirable behavior.
  5686. **
  5687. ** See also: [sqlite3_blob_write()].
  5688. */
  5689. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5690. /*
  5691. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5692. **
  5693. ** ^This function is used to write data into an open [BLOB handle] from a
  5694. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5695. ** into the open BLOB, starting at offset iOffset.
  5696. **
  5697. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5698. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5699. ** this function returns [SQLITE_READONLY].
  5700. **
  5701. ** ^This function may only modify the contents of the BLOB; it is
  5702. ** not possible to increase the size of a BLOB using this API.
  5703. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5704. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5705. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5706. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5707. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5708. **
  5709. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5710. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5711. ** before the [BLOB handle] expired are not rolled back by the
  5712. ** expiration of the handle, though of course those changes might
  5713. ** have been overwritten by the statement that expired the BLOB handle
  5714. ** or by other independent statements.
  5715. **
  5716. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5717. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5718. **
  5719. ** This routine only works on a [BLOB handle] which has been created
  5720. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5721. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5722. ** to this routine results in undefined and probably undesirable behavior.
  5723. **
  5724. ** See also: [sqlite3_blob_read()].
  5725. */
  5726. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5727. /*
  5728. ** CAPI3REF: Virtual File System Objects
  5729. **
  5730. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5731. ** that SQLite uses to interact
  5732. ** with the underlying operating system. Most SQLite builds come with a
  5733. ** single default VFS that is appropriate for the host computer.
  5734. ** New VFSes can be registered and existing VFSes can be unregistered.
  5735. ** The following interfaces are provided.
  5736. **
  5737. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5738. ** ^Names are case sensitive.
  5739. ** ^Names are zero-terminated UTF-8 strings.
  5740. ** ^If there is no match, a NULL pointer is returned.
  5741. ** ^If zVfsName is NULL then the default VFS is returned.
  5742. **
  5743. ** ^New VFSes are registered with sqlite3_vfs_register().
  5744. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5745. ** ^The same VFS can be registered multiple times without injury.
  5746. ** ^To make an existing VFS into the default VFS, register it again
  5747. ** with the makeDflt flag set. If two different VFSes with the
  5748. ** same name are registered, the behavior is undefined. If a
  5749. ** VFS is registered with a name that is NULL or an empty string,
  5750. ** then the behavior is undefined.
  5751. **
  5752. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5753. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5754. ** the default. The choice for the new VFS is arbitrary.)^
  5755. */
  5756. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5757. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5758. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5759. /*
  5760. ** CAPI3REF: Mutexes
  5761. **
  5762. ** The SQLite core uses these routines for thread
  5763. ** synchronization. Though they are intended for internal
  5764. ** use by SQLite, code that links against SQLite is
  5765. ** permitted to use any of these routines.
  5766. **
  5767. ** The SQLite source code contains multiple implementations
  5768. ** of these mutex routines. An appropriate implementation
  5769. ** is selected automatically at compile-time. ^(The following
  5770. ** implementations are available in the SQLite core:
  5771. **
  5772. ** <ul>
  5773. ** <li> SQLITE_MUTEX_OS2
  5774. ** <li> SQLITE_MUTEX_PTHREADS
  5775. ** <li> SQLITE_MUTEX_W32
  5776. ** <li> SQLITE_MUTEX_NOOP
  5777. ** </ul>)^
  5778. **
  5779. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5780. ** that does no real locking and is appropriate for use in
  5781. ** a single-threaded application. ^The SQLITE_MUTEX_OS2,
  5782. ** SQLITE_MUTEX_PTHREADS, and SQLITE_MUTEX_W32 implementations
  5783. ** are appropriate for use on OS/2, Unix, and Windows.
  5784. **
  5785. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5786. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5787. ** implementation is included with the library. In this case the
  5788. ** application must supply a custom mutex implementation using the
  5789. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5790. ** before calling sqlite3_initialize() or any other public sqlite3_
  5791. ** function that calls sqlite3_initialize().)^
  5792. **
  5793. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5794. ** mutex and returns a pointer to it. ^If it returns NULL
  5795. ** that means that a mutex could not be allocated. ^SQLite
  5796. ** will unwind its stack and return an error. ^(The argument
  5797. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5798. **
  5799. ** <ul>
  5800. ** <li> SQLITE_MUTEX_FAST
  5801. ** <li> SQLITE_MUTEX_RECURSIVE
  5802. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5803. ** <li> SQLITE_MUTEX_STATIC_MEM
  5804. ** <li> SQLITE_MUTEX_STATIC_MEM2
  5805. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5806. ** <li> SQLITE_MUTEX_STATIC_LRU
  5807. ** <li> SQLITE_MUTEX_STATIC_LRU2
  5808. ** </ul>)^
  5809. **
  5810. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5811. ** cause sqlite3_mutex_alloc() to create
  5812. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5813. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5814. ** The mutex implementation does not need to make a distinction
  5815. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5816. ** not want to. ^SQLite will only request a recursive mutex in
  5817. ** cases where it really needs one. ^If a faster non-recursive mutex
  5818. ** implementation is available on the host platform, the mutex subsystem
  5819. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5820. **
  5821. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5822. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5823. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5824. ** used by the current version of SQLite. Future versions of SQLite
  5825. ** may add additional static mutexes. Static mutexes are for internal
  5826. ** use by SQLite only. Applications that use SQLite mutexes should
  5827. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5828. ** SQLITE_MUTEX_RECURSIVE.
  5829. **
  5830. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5831. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5832. ** returns a different mutex on every call. ^But for the static
  5833. ** mutex types, the same mutex is returned on every call that has
  5834. ** the same type number.
  5835. **
  5836. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5837. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5838. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5839. ** use when they are deallocated. Attempting to deallocate a static
  5840. ** mutex results in undefined behavior. ^SQLite never deallocates
  5841. ** a static mutex.
  5842. **
  5843. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5844. ** to enter a mutex. ^If another thread is already within the mutex,
  5845. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5846. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5847. ** upon successful entry. ^(Mutexes created using
  5848. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5849. ** In such cases the,
  5850. ** mutex must be exited an equal number of times before another thread
  5851. ** can enter.)^ ^(If the same thread tries to enter any other
  5852. ** kind of mutex more than once, the behavior is undefined.
  5853. ** SQLite will never exhibit
  5854. ** such behavior in its own use of mutexes.)^
  5855. **
  5856. ** ^(Some systems (for example, Windows 95) do not support the operation
  5857. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5858. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5859. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5860. **
  5861. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5862. ** previously entered by the same thread. ^(The behavior
  5863. ** is undefined if the mutex is not currently entered by the
  5864. ** calling thread or is not currently allocated. SQLite will
  5865. ** never do either.)^
  5866. **
  5867. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5868. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5869. ** behave as no-ops.
  5870. **
  5871. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5872. */
  5873. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5874. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5875. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5876. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5877. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5878. /*
  5879. ** CAPI3REF: Mutex Methods Object
  5880. **
  5881. ** An instance of this structure defines the low-level routines
  5882. ** used to allocate and use mutexes.
  5883. **
  5884. ** Usually, the default mutex implementations provided by SQLite are
  5885. ** sufficient, however the user has the option of substituting a custom
  5886. ** implementation for specialized deployments or systems for which SQLite
  5887. ** does not provide a suitable implementation. In this case, the user
  5888. ** creates and populates an instance of this structure to pass
  5889. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5890. ** Additionally, an instance of this structure can be used as an
  5891. ** output variable when querying the system for the current mutex
  5892. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5893. **
  5894. ** ^The xMutexInit method defined by this structure is invoked as
  5895. ** part of system initialization by the sqlite3_initialize() function.
  5896. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5897. ** effective call to [sqlite3_initialize()].
  5898. **
  5899. ** ^The xMutexEnd method defined by this structure is invoked as
  5900. ** part of system shutdown by the sqlite3_shutdown() function. The
  5901. ** implementation of this method is expected to release all outstanding
  5902. ** resources obtained by the mutex methods implementation, especially
  5903. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5904. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5905. **
  5906. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5907. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5908. ** xMutexNotheld) implement the following interfaces (respectively):
  5909. **
  5910. ** <ul>
  5911. ** <li> [sqlite3_mutex_alloc()] </li>
  5912. ** <li> [sqlite3_mutex_free()] </li>
  5913. ** <li> [sqlite3_mutex_enter()] </li>
  5914. ** <li> [sqlite3_mutex_try()] </li>
  5915. ** <li> [sqlite3_mutex_leave()] </li>
  5916. ** <li> [sqlite3_mutex_held()] </li>
  5917. ** <li> [sqlite3_mutex_notheld()] </li>
  5918. ** </ul>)^
  5919. **
  5920. ** The only difference is that the public sqlite3_XXX functions enumerated
  5921. ** above silently ignore any invocations that pass a NULL pointer instead
  5922. ** of a valid mutex handle. The implementations of the methods defined
  5923. ** by this structure are not required to handle this case, the results
  5924. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  5925. ** (i.e. it is acceptable to provide an implementation that segfaults if
  5926. ** it is passed a NULL pointer).
  5927. **
  5928. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  5929. ** invoke xMutexInit() multiple times within the same process and without
  5930. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  5931. ** xMutexInit() must be no-ops.
  5932. **
  5933. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  5934. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  5935. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  5936. ** memory allocation for a fast or recursive mutex.
  5937. **
  5938. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  5939. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  5940. ** If xMutexInit fails in any way, it is expected to clean up after itself
  5941. ** prior to returning.
  5942. */
  5943. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  5944. struct sqlite3_mutex_methods {
  5945. int (*xMutexInit)(void);
  5946. int (*xMutexEnd)(void);
  5947. sqlite3_mutex *(*xMutexAlloc)(int);
  5948. void (*xMutexFree)(sqlite3_mutex *);
  5949. void (*xMutexEnter)(sqlite3_mutex *);
  5950. int (*xMutexTry)(sqlite3_mutex *);
  5951. void (*xMutexLeave)(sqlite3_mutex *);
  5952. int (*xMutexHeld)(sqlite3_mutex *);
  5953. int (*xMutexNotheld)(sqlite3_mutex *);
  5954. };
  5955. /*
  5956. ** CAPI3REF: Mutex Verification Routines
  5957. **
  5958. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  5959. ** are intended for use inside assert() statements. ^The SQLite core
  5960. ** never uses these routines except inside an assert() and applications
  5961. ** are advised to follow the lead of the core. ^The SQLite core only
  5962. ** provides implementations for these routines when it is compiled
  5963. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  5964. ** are only required to provide these routines if SQLITE_DEBUG is
  5965. ** defined and if NDEBUG is not defined.
  5966. **
  5967. ** ^These routines should return true if the mutex in their argument
  5968. ** is held or not held, respectively, by the calling thread.
  5969. **
  5970. ** ^The implementation is not required to provide versions of these
  5971. ** routines that actually work. If the implementation does not provide working
  5972. ** versions of these routines, it should at least provide stubs that always
  5973. ** return true so that one does not get spurious assertion failures.
  5974. **
  5975. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  5976. ** the routine should return 1. This seems counter-intuitive since
  5977. ** clearly the mutex cannot be held if it does not exist. But
  5978. ** the reason the mutex does not exist is because the build is not
  5979. ** using mutexes. And we do not want the assert() containing the
  5980. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  5981. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  5982. ** interface should also return 1 when given a NULL pointer.
  5983. */
  5984. #ifndef NDEBUG
  5985. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  5986. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  5987. #endif
  5988. /*
  5989. ** CAPI3REF: Mutex Types
  5990. **
  5991. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  5992. ** which is one of these integer constants.
  5993. **
  5994. ** The set of static mutexes may change from one SQLite release to the
  5995. ** next. Applications that override the built-in mutex logic must be
  5996. ** prepared to accommodate additional static mutexes.
  5997. */
  5998. #define SQLITE_MUTEX_FAST 0
  5999. #define SQLITE_MUTEX_RECURSIVE 1
  6000. #define SQLITE_MUTEX_STATIC_MASTER 2
  6001. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6002. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6003. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6004. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6005. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6006. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6007. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6008. /*
  6009. ** CAPI3REF: Retrieve the mutex for a database connection
  6010. **
  6011. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6012. ** serializes access to the [database connection] given in the argument
  6013. ** when the [threading mode] is Serialized.
  6014. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6015. ** routine returns a NULL pointer.
  6016. */
  6017. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6018. /*
  6019. ** CAPI3REF: Low-Level Control Of Database Files
  6020. **
  6021. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6022. ** xFileControl method for the [sqlite3_io_methods] object associated
  6023. ** with a particular database identified by the second argument. ^The
  6024. ** name of the database is "main" for the main database or "temp" for the
  6025. ** TEMP database, or the name that appears after the AS keyword for
  6026. ** databases that are added using the [ATTACH] SQL command.
  6027. ** ^A NULL pointer can be used in place of "main" to refer to the
  6028. ** main database file.
  6029. ** ^The third and fourth parameters to this routine
  6030. ** are passed directly through to the second and third parameters of
  6031. ** the xFileControl method. ^The return value of the xFileControl
  6032. ** method becomes the return value of this routine.
  6033. **
  6034. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6035. ** a pointer to the underlying [sqlite3_file] object to be written into
  6036. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6037. ** case is a short-circuit path which does not actually invoke the
  6038. ** underlying sqlite3_io_methods.xFileControl method.
  6039. **
  6040. ** ^If the second parameter (zDbName) does not match the name of any
  6041. ** open database file, then SQLITE_ERROR is returned. ^This error
  6042. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6043. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6044. ** also return SQLITE_ERROR. There is no way to distinguish between
  6045. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6046. ** xFileControl method.
  6047. **
  6048. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6049. */
  6050. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6051. /*
  6052. ** CAPI3REF: Testing Interface
  6053. **
  6054. ** ^The sqlite3_test_control() interface is used to read out internal
  6055. ** state of SQLite and to inject faults into SQLite for testing
  6056. ** purposes. ^The first parameter is an operation code that determines
  6057. ** the number, meaning, and operation of all subsequent parameters.
  6058. **
  6059. ** This interface is not for use by applications. It exists solely
  6060. ** for verifying the correct operation of the SQLite library. Depending
  6061. ** on how the SQLite library is compiled, this interface might not exist.
  6062. **
  6063. ** The details of the operation codes, their meanings, the parameters
  6064. ** they take, and what they do are all subject to change without notice.
  6065. ** Unlike most of the SQLite API, this function is not guaranteed to
  6066. ** operate consistently from one release to the next.
  6067. */
  6068. SQLITE_API int sqlite3_test_control(int op, ...);
  6069. /*
  6070. ** CAPI3REF: Testing Interface Operation Codes
  6071. **
  6072. ** These constants are the valid operation code parameters used
  6073. ** as the first argument to [sqlite3_test_control()].
  6074. **
  6075. ** These parameters and their meanings are subject to change
  6076. ** without notice. These values are for testing purposes only.
  6077. ** Applications should not use any of these parameters or the
  6078. ** [sqlite3_test_control()] interface.
  6079. */
  6080. #define SQLITE_TESTCTRL_FIRST 5
  6081. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6082. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6083. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6084. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6085. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6086. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6087. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6088. #define SQLITE_TESTCTRL_ASSERT 12
  6089. #define SQLITE_TESTCTRL_ALWAYS 13
  6090. #define SQLITE_TESTCTRL_RESERVE 14
  6091. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6092. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6093. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6094. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6095. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
  6096. #define SQLITE_TESTCTRL_LAST 19
  6097. /*
  6098. ** CAPI3REF: SQLite Runtime Status
  6099. **
  6100. ** ^This interface is used to retrieve runtime status information
  6101. ** about the performance of SQLite, and optionally to reset various
  6102. ** highwater marks. ^The first argument is an integer code for
  6103. ** the specific parameter to measure. ^(Recognized integer codes
  6104. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6105. ** ^The current value of the parameter is returned into *pCurrent.
  6106. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6107. ** resetFlag is true, then the highest record value is reset after
  6108. ** *pHighwater is written. ^(Some parameters do not record the highest
  6109. ** value. For those parameters
  6110. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6111. ** ^(Other parameters record only the highwater mark and not the current
  6112. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6113. **
  6114. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  6115. ** non-zero [error code] on failure.
  6116. **
  6117. ** This routine is threadsafe but is not atomic. This routine can be
  6118. ** called while other threads are running the same or different SQLite
  6119. ** interfaces. However the values returned in *pCurrent and
  6120. ** *pHighwater reflect the status of SQLite at different points in time
  6121. ** and it is possible that another thread might change the parameter
  6122. ** in between the times when *pCurrent and *pHighwater are written.
  6123. **
  6124. ** See also: [sqlite3_db_status()]
  6125. */
  6126. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6127. /*
  6128. ** CAPI3REF: Status Parameters
  6129. ** KEYWORDS: {status parameters}
  6130. **
  6131. ** These integer constants designate various run-time status parameters
  6132. ** that can be returned by [sqlite3_status()].
  6133. **
  6134. ** <dl>
  6135. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6136. ** <dd>This parameter is the current amount of memory checked out
  6137. ** using [sqlite3_malloc()], either directly or indirectly. The
  6138. ** figure includes calls made to [sqlite3_malloc()] by the application
  6139. ** and internal memory usage by the SQLite library. Scratch memory
  6140. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6141. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6142. ** this parameter. The amount returned is the sum of the allocation
  6143. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6144. **
  6145. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6146. ** <dd>This parameter records the largest memory allocation request
  6147. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6148. ** internal equivalents). Only the value returned in the
  6149. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6150. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6151. **
  6152. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6153. ** <dd>This parameter records the number of separate memory allocations
  6154. ** currently checked out.</dd>)^
  6155. **
  6156. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6157. ** <dd>This parameter returns the number of pages used out of the
  6158. ** [pagecache memory allocator] that was configured using
  6159. ** [SQLITE_CONFIG_PAGECACHE]. The
  6160. ** value returned is in pages, not in bytes.</dd>)^
  6161. **
  6162. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6163. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6164. ** <dd>This parameter returns the number of bytes of page cache
  6165. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6166. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6167. ** returned value includes allocations that overflowed because they
  6168. ** where too large (they were larger than the "sz" parameter to
  6169. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6170. ** no space was left in the page cache.</dd>)^
  6171. **
  6172. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6173. ** <dd>This parameter records the largest memory allocation request
  6174. ** handed to [pagecache memory allocator]. Only the value returned in the
  6175. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6176. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6177. **
  6178. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6179. ** <dd>This parameter returns the number of allocations used out of the
  6180. ** [scratch memory allocator] configured using
  6181. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6182. ** in bytes. Since a single thread may only have one scratch allocation
  6183. ** outstanding at time, this parameter also reports the number of threads
  6184. ** using scratch memory at the same time.</dd>)^
  6185. **
  6186. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6187. ** <dd>This parameter returns the number of bytes of scratch memory
  6188. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6189. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6190. ** returned include overflows because the requested allocation was too
  6191. ** larger (that is, because the requested allocation was larger than the
  6192. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6193. ** slots were available.
  6194. ** </dd>)^
  6195. **
  6196. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6197. ** <dd>This parameter records the largest memory allocation request
  6198. ** handed to [scratch memory allocator]. Only the value returned in the
  6199. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6200. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6201. **
  6202. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6203. ** <dd>This parameter records the deepest parser stack. It is only
  6204. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6205. ** </dl>
  6206. **
  6207. ** New status parameters may be added from time to time.
  6208. */
  6209. #define SQLITE_STATUS_MEMORY_USED 0
  6210. #define SQLITE_STATUS_PAGECACHE_USED 1
  6211. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6212. #define SQLITE_STATUS_SCRATCH_USED 3
  6213. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6214. #define SQLITE_STATUS_MALLOC_SIZE 5
  6215. #define SQLITE_STATUS_PARSER_STACK 6
  6216. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6217. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6218. #define SQLITE_STATUS_MALLOC_COUNT 9
  6219. /*
  6220. ** CAPI3REF: Database Connection Status
  6221. **
  6222. ** ^This interface is used to retrieve runtime status information
  6223. ** about a single [database connection]. ^The first argument is the
  6224. ** database connection object to be interrogated. ^The second argument
  6225. ** is an integer constant, taken from the set of
  6226. ** [SQLITE_DBSTATUS options], that
  6227. ** determines the parameter to interrogate. The set of
  6228. ** [SQLITE_DBSTATUS options] is likely
  6229. ** to grow in future releases of SQLite.
  6230. **
  6231. ** ^The current value of the requested parameter is written into *pCur
  6232. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6233. ** the resetFlg is true, then the highest instantaneous value is
  6234. ** reset back down to the current value.
  6235. **
  6236. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6237. ** non-zero [error code] on failure.
  6238. **
  6239. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6240. */
  6241. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6242. /*
  6243. ** CAPI3REF: Status Parameters for database connections
  6244. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6245. **
  6246. ** These constants are the available integer "verbs" that can be passed as
  6247. ** the second argument to the [sqlite3_db_status()] interface.
  6248. **
  6249. ** New verbs may be added in future releases of SQLite. Existing verbs
  6250. ** might be discontinued. Applications should check the return code from
  6251. ** [sqlite3_db_status()] to make sure that the call worked.
  6252. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6253. ** if a discontinued or unsupported verb is invoked.
  6254. **
  6255. ** <dl>
  6256. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6257. ** <dd>This parameter returns the number of lookaside memory slots currently
  6258. ** checked out.</dd>)^
  6259. **
  6260. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6261. ** <dd>This parameter returns the number malloc attempts that were
  6262. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6263. ** the current value is always zero.)^
  6264. **
  6265. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6266. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6267. ** <dd>This parameter returns the number malloc attempts that might have
  6268. ** been satisfied using lookaside memory but failed due to the amount of
  6269. ** memory requested being larger than the lookaside slot size.
  6270. ** Only the high-water value is meaningful;
  6271. ** the current value is always zero.)^
  6272. **
  6273. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6274. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6275. ** <dd>This parameter returns the number malloc attempts that might have
  6276. ** been satisfied using lookaside memory but failed due to all lookaside
  6277. ** memory already being in use.
  6278. ** Only the high-water value is meaningful;
  6279. ** the current value is always zero.)^
  6280. **
  6281. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6282. ** <dd>This parameter returns the approximate number of of bytes of heap
  6283. ** memory used by all pager caches associated with the database connection.)^
  6284. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6285. **
  6286. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6287. ** <dd>This parameter returns the approximate number of of bytes of heap
  6288. ** memory used to store the schema for all databases associated
  6289. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6290. ** ^The full amount of memory used by the schemas is reported, even if the
  6291. ** schema memory is shared with other database connections due to
  6292. ** [shared cache mode] being enabled.
  6293. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6294. **
  6295. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6296. ** <dd>This parameter returns the approximate number of of bytes of heap
  6297. ** and lookaside memory used by all prepared statements associated with
  6298. ** the database connection.)^
  6299. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6300. ** </dd>
  6301. **
  6302. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6303. ** <dd>This parameter returns the number of pager cache hits that have
  6304. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6305. ** is always 0.
  6306. ** </dd>
  6307. **
  6308. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6309. ** <dd>This parameter returns the number of pager cache misses that have
  6310. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6311. ** is always 0.
  6312. ** </dd>
  6313. ** </dl>
  6314. */
  6315. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6316. #define SQLITE_DBSTATUS_CACHE_USED 1
  6317. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6318. #define SQLITE_DBSTATUS_STMT_USED 3
  6319. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6320. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6321. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6322. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6323. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6324. #define SQLITE_DBSTATUS_MAX 8 /* Largest defined DBSTATUS */
  6325. /*
  6326. ** CAPI3REF: Prepared Statement Status
  6327. **
  6328. ** ^(Each prepared statement maintains various
  6329. ** [SQLITE_STMTSTATUS counters] that measure the number
  6330. ** of times it has performed specific operations.)^ These counters can
  6331. ** be used to monitor the performance characteristics of the prepared
  6332. ** statements. For example, if the number of table steps greatly exceeds
  6333. ** the number of table searches or result rows, that would tend to indicate
  6334. ** that the prepared statement is using a full table scan rather than
  6335. ** an index.
  6336. **
  6337. ** ^(This interface is used to retrieve and reset counter values from
  6338. ** a [prepared statement]. The first argument is the prepared statement
  6339. ** object to be interrogated. The second argument
  6340. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6341. ** to be interrogated.)^
  6342. ** ^The current value of the requested counter is returned.
  6343. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6344. ** interface call returns.
  6345. **
  6346. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6347. */
  6348. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6349. /*
  6350. ** CAPI3REF: Status Parameters for prepared statements
  6351. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6352. **
  6353. ** These preprocessor macros define integer codes that name counter
  6354. ** values associated with the [sqlite3_stmt_status()] interface.
  6355. ** The meanings of the various counters are as follows:
  6356. **
  6357. ** <dl>
  6358. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6359. ** <dd>^This is the number of times that SQLite has stepped forward in
  6360. ** a table as part of a full table scan. Large numbers for this counter
  6361. ** may indicate opportunities for performance improvement through
  6362. ** careful use of indices.</dd>
  6363. **
  6364. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6365. ** <dd>^This is the number of sort operations that have occurred.
  6366. ** A non-zero value in this counter may indicate an opportunity to
  6367. ** improvement performance through careful use of indices.</dd>
  6368. **
  6369. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6370. ** <dd>^This is the number of rows inserted into transient indices that
  6371. ** were created automatically in order to help joins run faster.
  6372. ** A non-zero value in this counter may indicate an opportunity to
  6373. ** improvement performance by adding permanent indices that do not
  6374. ** need to be reinitialized each time the statement is run.</dd>
  6375. ** </dl>
  6376. */
  6377. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6378. #define SQLITE_STMTSTATUS_SORT 2
  6379. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6380. /*
  6381. ** CAPI3REF: Custom Page Cache Object
  6382. **
  6383. ** The sqlite3_pcache type is opaque. It is implemented by
  6384. ** the pluggable module. The SQLite core has no knowledge of
  6385. ** its size or internal structure and never deals with the
  6386. ** sqlite3_pcache object except by holding and passing pointers
  6387. ** to the object.
  6388. **
  6389. ** See [sqlite3_pcache_methods2] for additional information.
  6390. */
  6391. typedef struct sqlite3_pcache sqlite3_pcache;
  6392. /*
  6393. ** CAPI3REF: Custom Page Cache Object
  6394. **
  6395. ** The sqlite3_pcache_page object represents a single page in the
  6396. ** page cache. The page cache will allocate instances of this
  6397. ** object. Various methods of the page cache use pointers to instances
  6398. ** of this object as parameters or as their return value.
  6399. **
  6400. ** See [sqlite3_pcache_methods2] for additional information.
  6401. */
  6402. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6403. struct sqlite3_pcache_page {
  6404. void *pBuf; /* The content of the page */
  6405. void *pExtra; /* Extra information associated with the page */
  6406. };
  6407. /*
  6408. ** CAPI3REF: Application Defined Page Cache.
  6409. ** KEYWORDS: {page cache}
  6410. **
  6411. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6412. ** register an alternative page cache implementation by passing in an
  6413. ** instance of the sqlite3_pcache_methods2 structure.)^
  6414. ** In many applications, most of the heap memory allocated by
  6415. ** SQLite is used for the page cache.
  6416. ** By implementing a
  6417. ** custom page cache using this API, an application can better control
  6418. ** the amount of memory consumed by SQLite, the way in which
  6419. ** that memory is allocated and released, and the policies used to
  6420. ** determine exactly which parts of a database file are cached and for
  6421. ** how long.
  6422. **
  6423. ** The alternative page cache mechanism is an
  6424. ** extreme measure that is only needed by the most demanding applications.
  6425. ** The built-in page cache is recommended for most uses.
  6426. **
  6427. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6428. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6429. ** the application may discard the parameter after the call to
  6430. ** [sqlite3_config()] returns.)^
  6431. **
  6432. ** [[the xInit() page cache method]]
  6433. ** ^(The xInit() method is called once for each effective
  6434. ** call to [sqlite3_initialize()])^
  6435. ** (usually only once during the lifetime of the process). ^(The xInit()
  6436. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6437. ** The intent of the xInit() method is to set up global data structures
  6438. ** required by the custom page cache implementation.
  6439. ** ^(If the xInit() method is NULL, then the
  6440. ** built-in default page cache is used instead of the application defined
  6441. ** page cache.)^
  6442. **
  6443. ** [[the xShutdown() page cache method]]
  6444. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6445. ** It can be used to clean up
  6446. ** any outstanding resources before process shutdown, if required.
  6447. ** ^The xShutdown() method may be NULL.
  6448. **
  6449. ** ^SQLite automatically serializes calls to the xInit method,
  6450. ** so the xInit method need not be threadsafe. ^The
  6451. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6452. ** not need to be threadsafe either. All other methods must be threadsafe
  6453. ** in multithreaded applications.
  6454. **
  6455. ** ^SQLite will never invoke xInit() more than once without an intervening
  6456. ** call to xShutdown().
  6457. **
  6458. ** [[the xCreate() page cache methods]]
  6459. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6460. ** SQLite will typically create one cache instance for each open database file,
  6461. ** though this is not guaranteed. ^The
  6462. ** first parameter, szPage, is the size in bytes of the pages that must
  6463. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6464. ** second parameter szExtra is a number of bytes of extra storage
  6465. ** associated with each page cache entry. ^The szExtra parameter will
  6466. ** a number less than 250. SQLite will use the
  6467. ** extra szExtra bytes on each page to store metadata about the underlying
  6468. ** database page on disk. The value passed into szExtra depends
  6469. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6470. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6471. ** created will be used to cache database pages of a file stored on disk, or
  6472. ** false if it is used for an in-memory database. The cache implementation
  6473. ** does not have to do anything special based with the value of bPurgeable;
  6474. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6475. ** never invoke xUnpin() except to deliberately delete a page.
  6476. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6477. ** false will always have the "discard" flag set to true.
  6478. ** ^Hence, a cache created with bPurgeable false will
  6479. ** never contain any unpinned pages.
  6480. **
  6481. ** [[the xCachesize() page cache method]]
  6482. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6483. ** suggested maximum cache-size (number of pages stored by) the cache
  6484. ** instance passed as the first argument. This is the value configured using
  6485. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6486. ** parameter, the implementation is not required to do anything with this
  6487. ** value; it is advisory only.
  6488. **
  6489. ** [[the xPagecount() page cache methods]]
  6490. ** The xPagecount() method must return the number of pages currently
  6491. ** stored in the cache, both pinned and unpinned.
  6492. **
  6493. ** [[the xFetch() page cache methods]]
  6494. ** The xFetch() method locates a page in the cache and returns a pointer to
  6495. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6496. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6497. ** pointer to a buffer of szPage bytes used to store the content of a
  6498. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6499. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6500. ** for each entry in the page cache.
  6501. **
  6502. ** The page to be fetched is determined by the key. ^The minimum key value
  6503. ** is 1. After it has been retrieved using xFetch, the page is considered
  6504. ** to be "pinned".
  6505. **
  6506. ** If the requested page is already in the page cache, then the page cache
  6507. ** implementation must return a pointer to the page buffer with its content
  6508. ** intact. If the requested page is not already in the cache, then the
  6509. ** cache implementation should use the value of the createFlag
  6510. ** parameter to help it determined what action to take:
  6511. **
  6512. ** <table border=1 width=85% align=center>
  6513. ** <tr><th> createFlag <th> Behaviour when page is not already in cache
  6514. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6515. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6516. ** Otherwise return NULL.
  6517. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6518. ** NULL if allocating a new page is effectively impossible.
  6519. ** </table>
  6520. **
  6521. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6522. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6523. ** failed.)^ In between the to xFetch() calls, SQLite may
  6524. ** attempt to unpin one or more cache pages by spilling the content of
  6525. ** pinned pages to disk and synching the operating system disk cache.
  6526. **
  6527. ** [[the xUnpin() page cache method]]
  6528. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6529. ** as its second argument. If the third parameter, discard, is non-zero,
  6530. ** then the page must be evicted from the cache.
  6531. ** ^If the discard parameter is
  6532. ** zero, then the page may be discarded or retained at the discretion of
  6533. ** page cache implementation. ^The page cache implementation
  6534. ** may choose to evict unpinned pages at any time.
  6535. **
  6536. ** The cache must not perform any reference counting. A single
  6537. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6538. ** to xFetch().
  6539. **
  6540. ** [[the xRekey() page cache methods]]
  6541. ** The xRekey() method is used to change the key value associated with the
  6542. ** page passed as the second argument. If the cache
  6543. ** previously contains an entry associated with newKey, it must be
  6544. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6545. ** to be pinned.
  6546. **
  6547. ** When SQLite calls the xTruncate() method, the cache must discard all
  6548. ** existing cache entries with page numbers (keys) greater than or equal
  6549. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6550. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6551. ** they can be safely discarded.
  6552. **
  6553. ** [[the xDestroy() page cache method]]
  6554. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6555. ** All resources associated with the specified cache should be freed. ^After
  6556. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6557. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6558. ** functions.
  6559. **
  6560. ** [[the xShrink() page cache method]]
  6561. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6562. ** free up as much of heap memory as possible. The page cache implementation
  6563. ** is not obligated to free any memory, but well-behaved implementations should
  6564. ** do their best.
  6565. */
  6566. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6567. struct sqlite3_pcache_methods2 {
  6568. int iVersion;
  6569. void *pArg;
  6570. int (*xInit)(void*);
  6571. void (*xShutdown)(void*);
  6572. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6573. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6574. int (*xPagecount)(sqlite3_pcache*);
  6575. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6576. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6577. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6578. unsigned oldKey, unsigned newKey);
  6579. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6580. void (*xDestroy)(sqlite3_pcache*);
  6581. void (*xShrink)(sqlite3_pcache*);
  6582. };
  6583. /*
  6584. ** This is the obsolete pcache_methods object that has now been replaced
  6585. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6586. ** retained in the header file for backwards compatibility only.
  6587. */
  6588. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6589. struct sqlite3_pcache_methods {
  6590. void *pArg;
  6591. int (*xInit)(void*);
  6592. void (*xShutdown)(void*);
  6593. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6594. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6595. int (*xPagecount)(sqlite3_pcache*);
  6596. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6597. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6598. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6599. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6600. void (*xDestroy)(sqlite3_pcache*);
  6601. };
  6602. /*
  6603. ** CAPI3REF: Online Backup Object
  6604. **
  6605. ** The sqlite3_backup object records state information about an ongoing
  6606. ** online backup operation. ^The sqlite3_backup object is created by
  6607. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6608. ** [sqlite3_backup_finish()].
  6609. **
  6610. ** See Also: [Using the SQLite Online Backup API]
  6611. */
  6612. typedef struct sqlite3_backup sqlite3_backup;
  6613. /*
  6614. ** CAPI3REF: Online Backup API.
  6615. **
  6616. ** The backup API copies the content of one database into another.
  6617. ** It is useful either for creating backups of databases or
  6618. ** for copying in-memory databases to or from persistent files.
  6619. **
  6620. ** See Also: [Using the SQLite Online Backup API]
  6621. **
  6622. ** ^SQLite holds a write transaction open on the destination database file
  6623. ** for the duration of the backup operation.
  6624. ** ^The source database is read-locked only while it is being read;
  6625. ** it is not locked continuously for the entire backup operation.
  6626. ** ^Thus, the backup may be performed on a live source database without
  6627. ** preventing other database connections from
  6628. ** reading or writing to the source database while the backup is underway.
  6629. **
  6630. ** ^(To perform a backup operation:
  6631. ** <ol>
  6632. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6633. ** backup,
  6634. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6635. ** the data between the two databases, and finally
  6636. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6637. ** associated with the backup operation.
  6638. ** </ol>)^
  6639. ** There should be exactly one call to sqlite3_backup_finish() for each
  6640. ** successful call to sqlite3_backup_init().
  6641. **
  6642. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6643. **
  6644. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6645. ** [database connection] associated with the destination database
  6646. ** and the database name, respectively.
  6647. ** ^The database name is "main" for the main database, "temp" for the
  6648. ** temporary database, or the name specified after the AS keyword in
  6649. ** an [ATTACH] statement for an attached database.
  6650. ** ^The S and M arguments passed to
  6651. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6652. ** and database name of the source database, respectively.
  6653. ** ^The source and destination [database connections] (parameters S and D)
  6654. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6655. ** an error.
  6656. **
  6657. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6658. ** returned and an error code and error message are stored in the
  6659. ** destination [database connection] D.
  6660. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6661. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6662. ** [sqlite3_errmsg16()] functions.
  6663. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6664. ** [sqlite3_backup] object.
  6665. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6666. ** sqlite3_backup_finish() functions to perform the specified backup
  6667. ** operation.
  6668. **
  6669. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6670. **
  6671. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6672. ** the source and destination databases specified by [sqlite3_backup] object B.
  6673. ** ^If N is negative, all remaining source pages are copied.
  6674. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6675. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6676. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6677. ** from source to destination, then it returns [SQLITE_DONE].
  6678. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6679. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6680. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6681. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6682. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6683. **
  6684. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6685. ** <ol>
  6686. ** <li> the destination database was opened read-only, or
  6687. ** <li> the destination database is using write-ahead-log journaling
  6688. ** and the destination and source page sizes differ, or
  6689. ** <li> the destination database is an in-memory database and the
  6690. ** destination and source page sizes differ.
  6691. ** </ol>)^
  6692. **
  6693. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6694. ** the [sqlite3_busy_handler | busy-handler function]
  6695. ** is invoked (if one is specified). ^If the
  6696. ** busy-handler returns non-zero before the lock is available, then
  6697. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6698. ** sqlite3_backup_step() can be retried later. ^If the source
  6699. ** [database connection]
  6700. ** is being used to write to the source database when sqlite3_backup_step()
  6701. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6702. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6703. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6704. ** [SQLITE_READONLY] is returned, then
  6705. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6706. ** errors are considered fatal.)^ The application must accept
  6707. ** that the backup operation has failed and pass the backup operation handle
  6708. ** to the sqlite3_backup_finish() to release associated resources.
  6709. **
  6710. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6711. ** on the destination file. ^The exclusive lock is not released until either
  6712. ** sqlite3_backup_finish() is called or the backup operation is complete
  6713. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6714. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6715. ** lasts for the duration of the sqlite3_backup_step() call.
  6716. ** ^Because the source database is not locked between calls to
  6717. ** sqlite3_backup_step(), the source database may be modified mid-way
  6718. ** through the backup process. ^If the source database is modified by an
  6719. ** external process or via a database connection other than the one being
  6720. ** used by the backup operation, then the backup will be automatically
  6721. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6722. ** database is modified by the using the same database connection as is used
  6723. ** by the backup operation, then the backup database is automatically
  6724. ** updated at the same time.
  6725. **
  6726. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6727. **
  6728. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6729. ** application wishes to abandon the backup operation, the application
  6730. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6731. ** ^The sqlite3_backup_finish() interfaces releases all
  6732. ** resources associated with the [sqlite3_backup] object.
  6733. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6734. ** active write-transaction on the destination database is rolled back.
  6735. ** The [sqlite3_backup] object is invalid
  6736. ** and may not be used following a call to sqlite3_backup_finish().
  6737. **
  6738. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6739. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6740. ** sqlite3_backup_step() completed.
  6741. ** ^If an out-of-memory condition or IO error occurred during any prior
  6742. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6743. ** sqlite3_backup_finish() returns the corresponding [error code].
  6744. **
  6745. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6746. ** is not a permanent error and does not affect the return value of
  6747. ** sqlite3_backup_finish().
  6748. **
  6749. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6750. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6751. **
  6752. ** ^Each call to sqlite3_backup_step() sets two values inside
  6753. ** the [sqlite3_backup] object: the number of pages still to be backed
  6754. ** up and the total number of pages in the source database file.
  6755. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6756. ** retrieve these two values, respectively.
  6757. **
  6758. ** ^The values returned by these functions are only updated by
  6759. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6760. ** operation, then the values are not updated to account for any extra
  6761. ** pages that need to be updated or the size of the source database file
  6762. ** changing.
  6763. **
  6764. ** <b>Concurrent Usage of Database Handles</b>
  6765. **
  6766. ** ^The source [database connection] may be used by the application for other
  6767. ** purposes while a backup operation is underway or being initialized.
  6768. ** ^If SQLite is compiled and configured to support threadsafe database
  6769. ** connections, then the source database connection may be used concurrently
  6770. ** from within other threads.
  6771. **
  6772. ** However, the application must guarantee that the destination
  6773. ** [database connection] is not passed to any other API (by any thread) after
  6774. ** sqlite3_backup_init() is called and before the corresponding call to
  6775. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6776. ** if the application incorrectly accesses the destination [database connection]
  6777. ** and so no error code is reported, but the operations may malfunction
  6778. ** nevertheless. Use of the destination database connection while a
  6779. ** backup is in progress might also also cause a mutex deadlock.
  6780. **
  6781. ** If running in [shared cache mode], the application must
  6782. ** guarantee that the shared cache used by the destination database
  6783. ** is not accessed while the backup is running. In practice this means
  6784. ** that the application must guarantee that the disk file being
  6785. ** backed up to is not accessed by any connection within the process,
  6786. ** not just the specific connection that was passed to sqlite3_backup_init().
  6787. **
  6788. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6789. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6790. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6791. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6792. ** same time as another thread is invoking sqlite3_backup_step() it is
  6793. ** possible that they return invalid values.
  6794. */
  6795. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6796. sqlite3 *pDest, /* Destination database handle */
  6797. const char *zDestName, /* Destination database name */
  6798. sqlite3 *pSource, /* Source database handle */
  6799. const char *zSourceName /* Source database name */
  6800. );
  6801. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6802. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6803. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6804. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6805. /*
  6806. ** CAPI3REF: Unlock Notification
  6807. **
  6808. ** ^When running in shared-cache mode, a database operation may fail with
  6809. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6810. ** individual tables within the shared-cache cannot be obtained. See
  6811. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6812. ** ^This API may be used to register a callback that SQLite will invoke
  6813. ** when the connection currently holding the required lock relinquishes it.
  6814. ** ^This API is only available if the library was compiled with the
  6815. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6816. **
  6817. ** See Also: [Using the SQLite Unlock Notification Feature].
  6818. **
  6819. ** ^Shared-cache locks are released when a database connection concludes
  6820. ** its current transaction, either by committing it or rolling it back.
  6821. **
  6822. ** ^When a connection (known as the blocked connection) fails to obtain a
  6823. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6824. ** identity of the database connection (the blocking connection) that
  6825. ** has locked the required resource is stored internally. ^After an
  6826. ** application receives an SQLITE_LOCKED error, it may call the
  6827. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6828. ** the first argument to register for a callback that will be invoked
  6829. ** when the blocking connections current transaction is concluded. ^The
  6830. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6831. ** call that concludes the blocking connections transaction.
  6832. **
  6833. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6834. ** there is a chance that the blocking connection will have already
  6835. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6836. ** If this happens, then the specified callback is invoked immediately,
  6837. ** from within the call to sqlite3_unlock_notify().)^
  6838. **
  6839. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6840. ** shared-cache table, and more than one other connection currently holds
  6841. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6842. ** the other connections to use as the blocking connection.
  6843. **
  6844. ** ^(There may be at most one unlock-notify callback registered by a
  6845. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6846. ** blocked connection already has a registered unlock-notify callback,
  6847. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6848. ** called with a NULL pointer as its second argument, then any existing
  6849. ** unlock-notify callback is canceled. ^The blocked connections
  6850. ** unlock-notify callback may also be canceled by closing the blocked
  6851. ** connection using [sqlite3_close()].
  6852. **
  6853. ** The unlock-notify callback is not reentrant. If an application invokes
  6854. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6855. ** crash or deadlock may be the result.
  6856. **
  6857. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6858. ** returns SQLITE_OK.
  6859. **
  6860. ** <b>Callback Invocation Details</b>
  6861. **
  6862. ** When an unlock-notify callback is registered, the application provides a
  6863. ** single void* pointer that is passed to the callback when it is invoked.
  6864. ** However, the signature of the callback function allows SQLite to pass
  6865. ** it an array of void* context pointers. The first argument passed to
  6866. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6867. ** and the second is the number of entries in the array.
  6868. **
  6869. ** When a blocking connections transaction is concluded, there may be
  6870. ** more than one blocked connection that has registered for an unlock-notify
  6871. ** callback. ^If two or more such blocked connections have specified the
  6872. ** same callback function, then instead of invoking the callback function
  6873. ** multiple times, it is invoked once with the set of void* context pointers
  6874. ** specified by the blocked connections bundled together into an array.
  6875. ** This gives the application an opportunity to prioritize any actions
  6876. ** related to the set of unblocked database connections.
  6877. **
  6878. ** <b>Deadlock Detection</b>
  6879. **
  6880. ** Assuming that after registering for an unlock-notify callback a
  6881. ** database waits for the callback to be issued before taking any further
  6882. ** action (a reasonable assumption), then using this API may cause the
  6883. ** application to deadlock. For example, if connection X is waiting for
  6884. ** connection Y's transaction to be concluded, and similarly connection
  6885. ** Y is waiting on connection X's transaction, then neither connection
  6886. ** will proceed and the system may remain deadlocked indefinitely.
  6887. **
  6888. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  6889. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  6890. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  6891. ** unlock-notify callback is registered. The system is said to be in
  6892. ** a deadlocked state if connection A has registered for an unlock-notify
  6893. ** callback on the conclusion of connection B's transaction, and connection
  6894. ** B has itself registered for an unlock-notify callback when connection
  6895. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  6896. ** the system is also considered to be deadlocked if connection B has
  6897. ** registered for an unlock-notify callback on the conclusion of connection
  6898. ** C's transaction, where connection C is waiting on connection A. ^Any
  6899. ** number of levels of indirection are allowed.
  6900. **
  6901. ** <b>The "DROP TABLE" Exception</b>
  6902. **
  6903. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  6904. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  6905. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  6906. ** SQLite checks if there are any currently executing SELECT statements
  6907. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  6908. ** returned. In this case there is no "blocking connection", so invoking
  6909. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  6910. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  6911. ** or "DROP INDEX" query, an infinite loop might be the result.
  6912. **
  6913. ** One way around this problem is to check the extended error code returned
  6914. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  6915. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  6916. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  6917. ** SQLITE_LOCKED.)^
  6918. */
  6919. SQLITE_API int sqlite3_unlock_notify(
  6920. sqlite3 *pBlocked, /* Waiting connection */
  6921. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  6922. void *pNotifyArg /* Argument to pass to xNotify */
  6923. );
  6924. /*
  6925. ** CAPI3REF: String Comparison
  6926. **
  6927. ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
  6928. ** compare the contents of two buffers containing UTF-8 strings in a
  6929. ** case-independent fashion, using the same definition of case independence
  6930. ** that SQLite uses internally when comparing identifiers.
  6931. */
  6932. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  6933. /*
  6934. ** CAPI3REF: Error Logging Interface
  6935. **
  6936. ** ^The [sqlite3_log()] interface writes a message into the error log
  6937. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  6938. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  6939. ** used with [sqlite3_snprintf()] to generate the final output string.
  6940. **
  6941. ** The sqlite3_log() interface is intended for use by extensions such as
  6942. ** virtual tables, collating functions, and SQL functions. While there is
  6943. ** nothing to prevent an application from calling sqlite3_log(), doing so
  6944. ** is considered bad form.
  6945. **
  6946. ** The zFormat string must not be NULL.
  6947. **
  6948. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  6949. ** will not use dynamically allocated memory. The log message is stored in
  6950. ** a fixed-length buffer on the stack. If the log message is longer than
  6951. ** a few hundred characters, it will be truncated to the length of the
  6952. ** buffer.
  6953. */
  6954. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  6955. /*
  6956. ** CAPI3REF: Write-Ahead Log Commit Hook
  6957. **
  6958. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  6959. ** will be invoked each time a database connection commits data to a
  6960. ** [write-ahead log] (i.e. whenever a transaction is committed in
  6961. ** [journal_mode | journal_mode=WAL mode]).
  6962. **
  6963. ** ^The callback is invoked by SQLite after the commit has taken place and
  6964. ** the associated write-lock on the database released, so the implementation
  6965. ** may read, write or [checkpoint] the database as required.
  6966. **
  6967. ** ^The first parameter passed to the callback function when it is invoked
  6968. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  6969. ** registering the callback. ^The second is a copy of the database handle.
  6970. ** ^The third parameter is the name of the database that was written to -
  6971. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  6972. ** is the number of pages currently in the write-ahead log file,
  6973. ** including those that were just committed.
  6974. **
  6975. ** The callback function should normally return [SQLITE_OK]. ^If an error
  6976. ** code is returned, that error will propagate back up through the
  6977. ** SQLite code base to cause the statement that provoked the callback
  6978. ** to report an error, though the commit will have still occurred. If the
  6979. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  6980. ** that does not correspond to any valid SQLite error code, the results
  6981. ** are undefined.
  6982. **
  6983. ** A single database handle may have at most a single write-ahead log callback
  6984. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  6985. ** previously registered write-ahead log callback. ^Note that the
  6986. ** [sqlite3_wal_autocheckpoint()] interface and the
  6987. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  6988. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  6989. */
  6990. SQLITE_API void *sqlite3_wal_hook(
  6991. sqlite3*,
  6992. int(*)(void *,sqlite3*,const char*,int),
  6993. void*
  6994. );
  6995. /*
  6996. ** CAPI3REF: Configure an auto-checkpoint
  6997. **
  6998. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  6999. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7000. ** to automatically [checkpoint]
  7001. ** after committing a transaction if there are N or
  7002. ** more frames in the [write-ahead log] file. ^Passing zero or
  7003. ** a negative value as the nFrame parameter disables automatic
  7004. ** checkpoints entirely.
  7005. **
  7006. ** ^The callback registered by this function replaces any existing callback
  7007. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7008. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7009. ** configured by this function.
  7010. **
  7011. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7012. ** from SQL.
  7013. **
  7014. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7015. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7016. ** pages. The use of this interface
  7017. ** is only necessary if the default setting is found to be suboptimal
  7018. ** for a particular application.
  7019. */
  7020. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7021. /*
  7022. ** CAPI3REF: Checkpoint a database
  7023. **
  7024. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  7025. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  7026. ** empty string, then a checkpoint is run on all databases of
  7027. ** connection D. ^If the database connection D is not in
  7028. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  7029. **
  7030. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  7031. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  7032. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  7033. ** run whenever the WAL reaches a certain size threshold.
  7034. **
  7035. ** See also: [sqlite3_wal_checkpoint_v2()]
  7036. */
  7037. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7038. /*
  7039. ** CAPI3REF: Checkpoint a database
  7040. **
  7041. ** Run a checkpoint operation on WAL database zDb attached to database
  7042. ** handle db. The specific operation is determined by the value of the
  7043. ** eMode parameter:
  7044. **
  7045. ** <dl>
  7046. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7047. ** Checkpoint as many frames as possible without waiting for any database
  7048. ** readers or writers to finish. Sync the db file if all frames in the log
  7049. ** are checkpointed. This mode is the same as calling
  7050. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  7051. **
  7052. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7053. ** This mode blocks (calls the busy-handler callback) until there is no
  7054. ** database writer and all readers are reading from the most recent database
  7055. ** snapshot. It then checkpoints all frames in the log file and syncs the
  7056. ** database file. This call blocks database writers while it is running,
  7057. ** but not database readers.
  7058. **
  7059. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7060. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  7061. ** checkpointing the log file it blocks (calls the busy-handler callback)
  7062. ** until all readers are reading from the database file only. This ensures
  7063. ** that the next client to write to the database file restarts the log file
  7064. ** from the beginning. This call blocks database writers while it is running,
  7065. ** but not database readers.
  7066. ** </dl>
  7067. **
  7068. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7069. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  7070. ** the total number of checkpointed frames (including any that were already
  7071. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  7072. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  7073. ** If no values are available because of an error, they are both set to -1
  7074. ** before returning to communicate this to the caller.
  7075. **
  7076. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  7077. ** any other process is running a checkpoint operation at the same time, the
  7078. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  7079. ** busy-handler configured, it will not be invoked in this case.
  7080. **
  7081. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  7082. ** "writer" lock on the database file. If the writer lock cannot be obtained
  7083. ** immediately, and a busy-handler is configured, it is invoked and the writer
  7084. ** lock retried until either the busy-handler returns 0 or the lock is
  7085. ** successfully obtained. The busy-handler is also invoked while waiting for
  7086. ** database readers as described above. If the busy-handler returns 0 before
  7087. ** the writer lock is obtained or while waiting for database readers, the
  7088. ** checkpoint operation proceeds from that point in the same way as
  7089. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7090. ** without blocking any further. SQLITE_BUSY is returned in this case.
  7091. **
  7092. ** If parameter zDb is NULL or points to a zero length string, then the
  7093. ** specified operation is attempted on all WAL databases. In this case the
  7094. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  7095. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7096. ** attached WAL databases, the operation is still attempted on any remaining
  7097. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  7098. ** error occurs while processing an attached database, processing is abandoned
  7099. ** and the error code returned to the caller immediately. If no error
  7100. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7101. ** databases, SQLITE_OK is returned.
  7102. **
  7103. ** If database zDb is the name of an attached database that is not in WAL
  7104. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  7105. ** zDb is not NULL (or a zero length string) and is not the name of any
  7106. ** attached database, SQLITE_ERROR is returned to the caller.
  7107. */
  7108. SQLITE_API int sqlite3_wal_checkpoint_v2(
  7109. sqlite3 *db, /* Database handle */
  7110. const char *zDb, /* Name of attached database (or NULL) */
  7111. int eMode, /* SQLITE_CHECKPOINT_* value */
  7112. int *pnLog, /* OUT: Size of WAL log in frames */
  7113. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7114. );
  7115. /*
  7116. ** CAPI3REF: Checkpoint operation parameters
  7117. **
  7118. ** These constants can be used as the 3rd parameter to
  7119. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  7120. ** documentation for additional information about the meaning and use of
  7121. ** each of these values.
  7122. */
  7123. #define SQLITE_CHECKPOINT_PASSIVE 0
  7124. #define SQLITE_CHECKPOINT_FULL 1
  7125. #define SQLITE_CHECKPOINT_RESTART 2
  7126. /*
  7127. ** CAPI3REF: Virtual Table Interface Configuration
  7128. **
  7129. ** This function may be called by either the [xConnect] or [xCreate] method
  7130. ** of a [virtual table] implementation to configure
  7131. ** various facets of the virtual table interface.
  7132. **
  7133. ** If this interface is invoked outside the context of an xConnect or
  7134. ** xCreate virtual table method then the behavior is undefined.
  7135. **
  7136. ** At present, there is only one option that may be configured using
  7137. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7138. ** may be added in the future.
  7139. */
  7140. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7141. /*
  7142. ** CAPI3REF: Virtual Table Configuration Options
  7143. **
  7144. ** These macros define the various options to the
  7145. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7146. ** can use to customize and optimize their behavior.
  7147. **
  7148. ** <dl>
  7149. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7150. ** <dd>Calls of the form
  7151. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7152. ** where X is an integer. If X is zero, then the [virtual table] whose
  7153. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7154. ** support constraints. In this configuration (which is the default) if
  7155. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7156. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7157. ** specified as part of the users SQL statement, regardless of the actual
  7158. ** ON CONFLICT mode specified.
  7159. **
  7160. ** If X is non-zero, then the virtual table implementation guarantees
  7161. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7162. ** any modifications to internal or persistent data structures have been made.
  7163. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7164. ** is able to roll back a statement or database transaction, and abandon
  7165. ** or continue processing the current SQL statement as appropriate.
  7166. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7167. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7168. ** had been ABORT.
  7169. **
  7170. ** Virtual table implementations that are required to handle OR REPLACE
  7171. ** must do so within the [xUpdate] method. If a call to the
  7172. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7173. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7174. ** silently replace the appropriate rows within the xUpdate callback and
  7175. ** return SQLITE_OK. Or, if this is not possible, it may return
  7176. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7177. ** constraint handling.
  7178. ** </dl>
  7179. */
  7180. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7181. /*
  7182. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7183. **
  7184. ** This function may only be called from within a call to the [xUpdate] method
  7185. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7186. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7187. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7188. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7189. ** [virtual table].
  7190. */
  7191. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7192. /*
  7193. ** CAPI3REF: Conflict resolution modes
  7194. **
  7195. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7196. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7197. ** is for the SQL statement being evaluated.
  7198. **
  7199. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7200. ** return value from the [sqlite3_set_authorizer()] callback and that
  7201. ** [SQLITE_ABORT] is also a [result code].
  7202. */
  7203. #define SQLITE_ROLLBACK 1
  7204. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7205. #define SQLITE_FAIL 3
  7206. /* #define SQLITE_ABORT 4 // Also an error code */
  7207. #define SQLITE_REPLACE 5
  7208. /*
  7209. ** Undo the hack that converts floating point types to integer for
  7210. ** builds on processors without floating point support.
  7211. */
  7212. #ifdef SQLITE_OMIT_FLOATING_POINT
  7213. # undef double
  7214. #endif
  7215. #if 0
  7216. } /* End of the 'extern "C"' block */
  7217. #endif
  7218. #endif
  7219. /*
  7220. ** 2010 August 30
  7221. **
  7222. ** The author disclaims copyright to this source code. In place of
  7223. ** a legal notice, here is a blessing:
  7224. **
  7225. ** May you do good and not evil.
  7226. ** May you find forgiveness for yourself and forgive others.
  7227. ** May you share freely, never taking more than you give.
  7228. **
  7229. *************************************************************************
  7230. */
  7231. #ifndef _SQLITE3RTREE_H_
  7232. #define _SQLITE3RTREE_H_
  7233. #if 0
  7234. extern "C" {
  7235. #endif
  7236. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7237. /*
  7238. ** Register a geometry callback named zGeom that can be used as part of an
  7239. ** R-Tree geometry query as follows:
  7240. **
  7241. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7242. */
  7243. SQLITE_API int sqlite3_rtree_geometry_callback(
  7244. sqlite3 *db,
  7245. const char *zGeom,
  7246. int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
  7247. void *pContext
  7248. );
  7249. /*
  7250. ** A pointer to a structure of the following type is passed as the first
  7251. ** argument to callbacks registered using rtree_geometry_callback().
  7252. */
  7253. struct sqlite3_rtree_geometry {
  7254. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7255. int nParam; /* Size of array aParam[] */
  7256. double *aParam; /* Parameters passed to SQL geom function */
  7257. void *pUser; /* Callback implementation user data */
  7258. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7259. };
  7260. #if 0
  7261. } /* end of the 'extern "C"' block */
  7262. #endif
  7263. #endif /* ifndef _SQLITE3RTREE_H_ */
  7264. /************** End of sqlite3.h *********************************************/
  7265. /************** Continuing where we left off in sqliteInt.h ******************/
  7266. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7267. /************** Begin file hash.h ********************************************/
  7268. /*
  7269. ** 2001 September 22
  7270. **
  7271. ** The author disclaims copyright to this source code. In place of
  7272. ** a legal notice, here is a blessing:
  7273. **
  7274. ** May you do good and not evil.
  7275. ** May you find forgiveness for yourself and forgive others.
  7276. ** May you share freely, never taking more than you give.
  7277. **
  7278. *************************************************************************
  7279. ** This is the header file for the generic hash-table implemenation
  7280. ** used in SQLite.
  7281. */
  7282. #ifndef _SQLITE_HASH_H_
  7283. #define _SQLITE_HASH_H_
  7284. /* Forward declarations of structures. */
  7285. typedef struct Hash Hash;
  7286. typedef struct HashElem HashElem;
  7287. /* A complete hash table is an instance of the following structure.
  7288. ** The internals of this structure are intended to be opaque -- client
  7289. ** code should not attempt to access or modify the fields of this structure
  7290. ** directly. Change this structure only by using the routines below.
  7291. ** However, some of the "procedures" and "functions" for modifying and
  7292. ** accessing this structure are really macros, so we can't really make
  7293. ** this structure opaque.
  7294. **
  7295. ** All elements of the hash table are on a single doubly-linked list.
  7296. ** Hash.first points to the head of this list.
  7297. **
  7298. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7299. ** the global doubly-linked list. The contents of the bucket are the
  7300. ** element pointed to plus the next _ht.count-1 elements in the list.
  7301. **
  7302. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7303. ** by a linear search of the global list. For small tables, the
  7304. ** Hash.ht table is never allocated because if there are few elements
  7305. ** in the table, it is faster to do a linear search than to manage
  7306. ** the hash table.
  7307. */
  7308. struct Hash {
  7309. unsigned int htsize; /* Number of buckets in the hash table */
  7310. unsigned int count; /* Number of entries in this table */
  7311. HashElem *first; /* The first element of the array */
  7312. struct _ht { /* the hash table */
  7313. int count; /* Number of entries with this hash */
  7314. HashElem *chain; /* Pointer to first entry with this hash */
  7315. } *ht;
  7316. };
  7317. /* Each element in the hash table is an instance of the following
  7318. ** structure. All elements are stored on a single doubly-linked list.
  7319. **
  7320. ** Again, this structure is intended to be opaque, but it can't really
  7321. ** be opaque because it is used by macros.
  7322. */
  7323. struct HashElem {
  7324. HashElem *next, *prev; /* Next and previous elements in the table */
  7325. void *data; /* Data associated with this element */
  7326. const char *pKey; int nKey; /* Key associated with this element */
  7327. };
  7328. /*
  7329. ** Access routines. To delete, insert a NULL pointer.
  7330. */
  7331. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7332. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  7333. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  7334. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7335. /*
  7336. ** Macros for looping over all elements of a hash table. The idiom is
  7337. ** like this:
  7338. **
  7339. ** Hash h;
  7340. ** HashElem *p;
  7341. ** ...
  7342. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7343. ** SomeStructure *pData = sqliteHashData(p);
  7344. ** // do something with pData
  7345. ** }
  7346. */
  7347. #define sqliteHashFirst(H) ((H)->first)
  7348. #define sqliteHashNext(E) ((E)->next)
  7349. #define sqliteHashData(E) ((E)->data)
  7350. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7351. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7352. /*
  7353. ** Number of entries in a hash table
  7354. */
  7355. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7356. #endif /* _SQLITE_HASH_H_ */
  7357. /************** End of hash.h ************************************************/
  7358. /************** Continuing where we left off in sqliteInt.h ******************/
  7359. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7360. /************** Begin file parse.h *******************************************/
  7361. #define TK_SEMI 1
  7362. #define TK_EXPLAIN 2
  7363. #define TK_QUERY 3
  7364. #define TK_PLAN 4
  7365. #define TK_BEGIN 5
  7366. #define TK_TRANSACTION 6
  7367. #define TK_DEFERRED 7
  7368. #define TK_IMMEDIATE 8
  7369. #define TK_EXCLUSIVE 9
  7370. #define TK_COMMIT 10
  7371. #define TK_END 11
  7372. #define TK_ROLLBACK 12
  7373. #define TK_SAVEPOINT 13
  7374. #define TK_RELEASE 14
  7375. #define TK_TO 15
  7376. #define TK_TABLE 16
  7377. #define TK_CREATE 17
  7378. #define TK_IF 18
  7379. #define TK_NOT 19
  7380. #define TK_EXISTS 20
  7381. #define TK_TEMP 21
  7382. #define TK_LP 22
  7383. #define TK_RP 23
  7384. #define TK_AS 24
  7385. #define TK_COMMA 25
  7386. #define TK_ID 26
  7387. #define TK_INDEXED 27
  7388. #define TK_ABORT 28
  7389. #define TK_ACTION 29
  7390. #define TK_AFTER 30
  7391. #define TK_ANALYZE 31
  7392. #define TK_ASC 32
  7393. #define TK_ATTACH 33
  7394. #define TK_BEFORE 34
  7395. #define TK_BY 35
  7396. #define TK_CASCADE 36
  7397. #define TK_CAST 37
  7398. #define TK_COLUMNKW 38
  7399. #define TK_CONFLICT 39
  7400. #define TK_DATABASE 40
  7401. #define TK_DESC 41
  7402. #define TK_DETACH 42
  7403. #define TK_EACH 43
  7404. #define TK_FAIL 44
  7405. #define TK_FOR 45
  7406. #define TK_IGNORE 46
  7407. #define TK_INITIALLY 47
  7408. #define TK_INSTEAD 48
  7409. #define TK_LIKE_KW 49
  7410. #define TK_MATCH 50
  7411. #define TK_NO 51
  7412. #define TK_KEY 52
  7413. #define TK_OF 53
  7414. #define TK_OFFSET 54
  7415. #define TK_PRAGMA 55
  7416. #define TK_RAISE 56
  7417. #define TK_REPLACE 57
  7418. #define TK_RESTRICT 58
  7419. #define TK_ROW 59
  7420. #define TK_TRIGGER 60
  7421. #define TK_VACUUM 61
  7422. #define TK_VIEW 62
  7423. #define TK_VIRTUAL 63
  7424. #define TK_REINDEX 64
  7425. #define TK_RENAME 65
  7426. #define TK_CTIME_KW 66
  7427. #define TK_ANY 67
  7428. #define TK_OR 68
  7429. #define TK_AND 69
  7430. #define TK_IS 70
  7431. #define TK_BETWEEN 71
  7432. #define TK_IN 72
  7433. #define TK_ISNULL 73
  7434. #define TK_NOTNULL 74
  7435. #define TK_NE 75
  7436. #define TK_EQ 76
  7437. #define TK_GT 77
  7438. #define TK_LE 78
  7439. #define TK_LT 79
  7440. #define TK_GE 80
  7441. #define TK_ESCAPE 81
  7442. #define TK_BITAND 82
  7443. #define TK_BITOR 83
  7444. #define TK_LSHIFT 84
  7445. #define TK_RSHIFT 85
  7446. #define TK_PLUS 86
  7447. #define TK_MINUS 87
  7448. #define TK_STAR 88
  7449. #define TK_SLASH 89
  7450. #define TK_REM 90
  7451. #define TK_CONCAT 91
  7452. #define TK_COLLATE 92
  7453. #define TK_BITNOT 93
  7454. #define TK_STRING 94
  7455. #define TK_JOIN_KW 95
  7456. #define TK_CONSTRAINT 96
  7457. #define TK_DEFAULT 97
  7458. #define TK_NULL 98
  7459. #define TK_PRIMARY 99
  7460. #define TK_UNIQUE 100
  7461. #define TK_CHECK 101
  7462. #define TK_REFERENCES 102
  7463. #define TK_AUTOINCR 103
  7464. #define TK_ON 104
  7465. #define TK_INSERT 105
  7466. #define TK_DELETE 106
  7467. #define TK_UPDATE 107
  7468. #define TK_SET 108
  7469. #define TK_DEFERRABLE 109
  7470. #define TK_FOREIGN 110
  7471. #define TK_DROP 111
  7472. #define TK_UNION 112
  7473. #define TK_ALL 113
  7474. #define TK_EXCEPT 114
  7475. #define TK_INTERSECT 115
  7476. #define TK_SELECT 116
  7477. #define TK_DISTINCT 117
  7478. #define TK_DOT 118
  7479. #define TK_FROM 119
  7480. #define TK_JOIN 120
  7481. #define TK_USING 121
  7482. #define TK_ORDER 122
  7483. #define TK_GROUP 123
  7484. #define TK_HAVING 124
  7485. #define TK_LIMIT 125
  7486. #define TK_WHERE 126
  7487. #define TK_INTO 127
  7488. #define TK_VALUES 128
  7489. #define TK_INTEGER 129
  7490. #define TK_FLOAT 130
  7491. #define TK_BLOB 131
  7492. #define TK_REGISTER 132
  7493. #define TK_VARIABLE 133
  7494. #define TK_CASE 134
  7495. #define TK_WHEN 135
  7496. #define TK_THEN 136
  7497. #define TK_ELSE 137
  7498. #define TK_INDEX 138
  7499. #define TK_ALTER 139
  7500. #define TK_ADD 140
  7501. #define TK_TO_TEXT 141
  7502. #define TK_TO_BLOB 142
  7503. #define TK_TO_NUMERIC 143
  7504. #define TK_TO_INT 144
  7505. #define TK_TO_REAL 145
  7506. #define TK_ISNOT 146
  7507. #define TK_END_OF_FILE 147
  7508. #define TK_ILLEGAL 148
  7509. #define TK_SPACE 149
  7510. #define TK_UNCLOSED_STRING 150
  7511. #define TK_FUNCTION 151
  7512. #define TK_COLUMN 152
  7513. #define TK_AGG_FUNCTION 153
  7514. #define TK_AGG_COLUMN 154
  7515. #define TK_CONST_FUNC 155
  7516. #define TK_UMINUS 156
  7517. #define TK_UPLUS 157
  7518. /************** End of parse.h ***********************************************/
  7519. /************** Continuing where we left off in sqliteInt.h ******************/
  7520. #include <stdio.h>
  7521. #include <stdlib.h>
  7522. #include <string.h>
  7523. #include <assert.h>
  7524. #include <stddef.h>
  7525. /*
  7526. ** If compiling for a processor that lacks floating point support,
  7527. ** substitute integer for floating-point
  7528. */
  7529. #ifdef SQLITE_OMIT_FLOATING_POINT
  7530. # define double sqlite_int64
  7531. # define float sqlite_int64
  7532. # define LONGDOUBLE_TYPE sqlite_int64
  7533. # ifndef SQLITE_BIG_DBL
  7534. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7535. # endif
  7536. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7537. # define SQLITE_OMIT_TRACE 1
  7538. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7539. # undef SQLITE_HAVE_ISNAN
  7540. #endif
  7541. #ifndef SQLITE_BIG_DBL
  7542. # define SQLITE_BIG_DBL (1e99)
  7543. #endif
  7544. /*
  7545. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7546. ** afterward. Having this macro allows us to cause the C compiler
  7547. ** to omit code used by TEMP tables without messy #ifndef statements.
  7548. */
  7549. #ifdef SQLITE_OMIT_TEMPDB
  7550. #define OMIT_TEMPDB 1
  7551. #else
  7552. #define OMIT_TEMPDB 0
  7553. #endif
  7554. /*
  7555. ** The "file format" number is an integer that is incremented whenever
  7556. ** the VDBE-level file format changes. The following macros define the
  7557. ** the default file format for new databases and the maximum file format
  7558. ** that the library can read.
  7559. */
  7560. #define SQLITE_MAX_FILE_FORMAT 4
  7561. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7562. # define SQLITE_DEFAULT_FILE_FORMAT 4
  7563. #endif
  7564. /*
  7565. ** Determine whether triggers are recursive by default. This can be
  7566. ** changed at run-time using a pragma.
  7567. */
  7568. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7569. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7570. #endif
  7571. /*
  7572. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7573. ** on the command-line
  7574. */
  7575. #ifndef SQLITE_TEMP_STORE
  7576. # define SQLITE_TEMP_STORE 1
  7577. #endif
  7578. /*
  7579. ** GCC does not define the offsetof() macro so we'll have to do it
  7580. ** ourselves.
  7581. */
  7582. #ifndef offsetof
  7583. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7584. #endif
  7585. /*
  7586. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7587. ** not, there are still machines out there that use EBCDIC.)
  7588. */
  7589. #if 'A' == '\301'
  7590. # define SQLITE_EBCDIC 1
  7591. #else
  7592. # define SQLITE_ASCII 1
  7593. #endif
  7594. /*
  7595. ** Integers of known sizes. These typedefs might change for architectures
  7596. ** where the sizes very. Preprocessor macros are available so that the
  7597. ** types can be conveniently redefined at compile-type. Like this:
  7598. **
  7599. ** cc '-DUINTPTR_TYPE=long long int' ...
  7600. */
  7601. #ifndef UINT32_TYPE
  7602. # ifdef HAVE_UINT32_T
  7603. # define UINT32_TYPE uint32_t
  7604. # else
  7605. # define UINT32_TYPE unsigned int
  7606. # endif
  7607. #endif
  7608. #ifndef UINT16_TYPE
  7609. # ifdef HAVE_UINT16_T
  7610. # define UINT16_TYPE uint16_t
  7611. # else
  7612. # define UINT16_TYPE unsigned short int
  7613. # endif
  7614. #endif
  7615. #ifndef INT16_TYPE
  7616. # ifdef HAVE_INT16_T
  7617. # define INT16_TYPE int16_t
  7618. # else
  7619. # define INT16_TYPE short int
  7620. # endif
  7621. #endif
  7622. #ifndef UINT8_TYPE
  7623. # ifdef HAVE_UINT8_T
  7624. # define UINT8_TYPE uint8_t
  7625. # else
  7626. # define UINT8_TYPE unsigned char
  7627. # endif
  7628. #endif
  7629. #ifndef INT8_TYPE
  7630. # ifdef HAVE_INT8_T
  7631. # define INT8_TYPE int8_t
  7632. # else
  7633. # define INT8_TYPE signed char
  7634. # endif
  7635. #endif
  7636. #ifndef LONGDOUBLE_TYPE
  7637. # define LONGDOUBLE_TYPE long double
  7638. #endif
  7639. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7640. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7641. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7642. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7643. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7644. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7645. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7646. /*
  7647. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  7648. ** that can be stored in a u32 without loss of data. The value
  7649. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  7650. ** have to specify the value in the less intuitive manner shown:
  7651. */
  7652. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  7653. /*
  7654. ** The datatype used to store estimates of the number of rows in a
  7655. ** table or index. This is an unsigned integer type. For 99.9% of
  7656. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  7657. ** can be used at compile-time if desired.
  7658. */
  7659. #ifdef SQLITE_64BIT_STATS
  7660. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  7661. #else
  7662. typedef u32 tRowcnt; /* 32-bit is the default */
  7663. #endif
  7664. /*
  7665. ** Macros to determine whether the machine is big or little endian,
  7666. ** evaluated at runtime.
  7667. */
  7668. #ifdef SQLITE_AMALGAMATION
  7669. SQLITE_PRIVATE const int sqlite3one = 1;
  7670. #else
  7671. SQLITE_PRIVATE const int sqlite3one;
  7672. #endif
  7673. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  7674. || defined(__x86_64) || defined(__x86_64__)
  7675. # define SQLITE_BIGENDIAN 0
  7676. # define SQLITE_LITTLEENDIAN 1
  7677. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  7678. #else
  7679. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  7680. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  7681. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  7682. #endif
  7683. /*
  7684. ** Constants for the largest and smallest possible 64-bit signed integers.
  7685. ** These macros are designed to work correctly on both 32-bit and 64-bit
  7686. ** compilers.
  7687. */
  7688. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  7689. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  7690. /*
  7691. ** Round up a number to the next larger multiple of 8. This is used
  7692. ** to force 8-byte alignment on 64-bit architectures.
  7693. */
  7694. #define ROUND8(x) (((x)+7)&~7)
  7695. /*
  7696. ** Round down to the nearest multiple of 8
  7697. */
  7698. #define ROUNDDOWN8(x) ((x)&~7)
  7699. /*
  7700. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  7701. ** macro is used only within assert() to verify that the code gets
  7702. ** all alignment restrictions correct.
  7703. **
  7704. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  7705. ** underlying malloc() implemention might return us 4-byte aligned
  7706. ** pointers. In that case, only verify 4-byte alignment.
  7707. */
  7708. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  7709. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  7710. #else
  7711. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  7712. #endif
  7713. /*
  7714. ** An instance of the following structure is used to store the busy-handler
  7715. ** callback for a given sqlite handle.
  7716. **
  7717. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  7718. ** callback for the database handle. Each pager opened via the sqlite
  7719. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  7720. ** callback is currently invoked only from within pager.c.
  7721. */
  7722. typedef struct BusyHandler BusyHandler;
  7723. struct BusyHandler {
  7724. int (*xFunc)(void *,int); /* The busy callback */
  7725. void *pArg; /* First arg to busy callback */
  7726. int nBusy; /* Incremented with each busy call */
  7727. };
  7728. /*
  7729. ** Name of the master database table. The master database table
  7730. ** is a special table that holds the names and attributes of all
  7731. ** user tables and indices.
  7732. */
  7733. #define MASTER_NAME "sqlite_master"
  7734. #define TEMP_MASTER_NAME "sqlite_temp_master"
  7735. /*
  7736. ** The root-page of the master database table.
  7737. */
  7738. #define MASTER_ROOT 1
  7739. /*
  7740. ** The name of the schema table.
  7741. */
  7742. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  7743. /*
  7744. ** A convenience macro that returns the number of elements in
  7745. ** an array.
  7746. */
  7747. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  7748. /*
  7749. ** The following value as a destructor means to use sqlite3DbFree().
  7750. ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
  7751. */
  7752. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
  7753. /*
  7754. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  7755. ** not support Writable Static Data (WSD) such as global and static variables.
  7756. ** All variables must either be on the stack or dynamically allocated from
  7757. ** the heap. When WSD is unsupported, the variable declarations scattered
  7758. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  7759. ** macro is used for this purpose. And instead of referencing the variable
  7760. ** directly, we use its constant as a key to lookup the run-time allocated
  7761. ** buffer that holds real variable. The constant is also the initializer
  7762. ** for the run-time allocated buffer.
  7763. **
  7764. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  7765. ** macros become no-ops and have zero performance impact.
  7766. */
  7767. #ifdef SQLITE_OMIT_WSD
  7768. #define SQLITE_WSD const
  7769. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  7770. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  7771. SQLITE_API int sqlite3_wsd_init(int N, int J);
  7772. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  7773. #else
  7774. #define SQLITE_WSD
  7775. #define GLOBAL(t,v) v
  7776. #define sqlite3GlobalConfig sqlite3Config
  7777. #endif
  7778. /*
  7779. ** The following macros are used to suppress compiler warnings and to
  7780. ** make it clear to human readers when a function parameter is deliberately
  7781. ** left unused within the body of a function. This usually happens when
  7782. ** a function is called via a function pointer. For example the
  7783. ** implementation of an SQL aggregate step callback may not use the
  7784. ** parameter indicating the number of arguments passed to the aggregate,
  7785. ** if it knows that this is enforced elsewhere.
  7786. **
  7787. ** When a function parameter is not used at all within the body of a function,
  7788. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  7789. ** However, these macros may also be used to suppress warnings related to
  7790. ** parameters that may or may not be used depending on compilation options.
  7791. ** For example those parameters only used in assert() statements. In these
  7792. ** cases the parameters are named as per the usual conventions.
  7793. */
  7794. #define UNUSED_PARAMETER(x) (void)(x)
  7795. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  7796. /*
  7797. ** Forward references to structures
  7798. */
  7799. typedef struct AggInfo AggInfo;
  7800. typedef struct AuthContext AuthContext;
  7801. typedef struct AutoincInfo AutoincInfo;
  7802. typedef struct Bitvec Bitvec;
  7803. typedef struct CollSeq CollSeq;
  7804. typedef struct Column Column;
  7805. typedef struct Db Db;
  7806. typedef struct Schema Schema;
  7807. typedef struct Expr Expr;
  7808. typedef struct ExprList ExprList;
  7809. typedef struct ExprSpan ExprSpan;
  7810. typedef struct FKey FKey;
  7811. typedef struct FuncDestructor FuncDestructor;
  7812. typedef struct FuncDef FuncDef;
  7813. typedef struct FuncDefHash FuncDefHash;
  7814. typedef struct IdList IdList;
  7815. typedef struct Index Index;
  7816. typedef struct IndexSample IndexSample;
  7817. typedef struct KeyClass KeyClass;
  7818. typedef struct KeyInfo KeyInfo;
  7819. typedef struct Lookaside Lookaside;
  7820. typedef struct LookasideSlot LookasideSlot;
  7821. typedef struct Module Module;
  7822. typedef struct NameContext NameContext;
  7823. typedef struct Parse Parse;
  7824. typedef struct RowSet RowSet;
  7825. typedef struct Savepoint Savepoint;
  7826. typedef struct Select Select;
  7827. typedef struct SrcList SrcList;
  7828. typedef struct StrAccum StrAccum;
  7829. typedef struct Table Table;
  7830. typedef struct TableLock TableLock;
  7831. typedef struct Token Token;
  7832. typedef struct Trigger Trigger;
  7833. typedef struct TriggerPrg TriggerPrg;
  7834. typedef struct TriggerStep TriggerStep;
  7835. typedef struct UnpackedRecord UnpackedRecord;
  7836. typedef struct VTable VTable;
  7837. typedef struct VtabCtx VtabCtx;
  7838. typedef struct Walker Walker;
  7839. typedef struct WherePlan WherePlan;
  7840. typedef struct WhereInfo WhereInfo;
  7841. typedef struct WhereLevel WhereLevel;
  7842. /*
  7843. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  7844. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  7845. ** pointer types (i.e. FuncDef) defined above.
  7846. */
  7847. /************** Include btree.h in the middle of sqliteInt.h *****************/
  7848. /************** Begin file btree.h *******************************************/
  7849. /*
  7850. ** 2001 September 15
  7851. **
  7852. ** The author disclaims copyright to this source code. In place of
  7853. ** a legal notice, here is a blessing:
  7854. **
  7855. ** May you do good and not evil.
  7856. ** May you find forgiveness for yourself and forgive others.
  7857. ** May you share freely, never taking more than you give.
  7858. **
  7859. *************************************************************************
  7860. ** This header file defines the interface that the sqlite B-Tree file
  7861. ** subsystem. See comments in the source code for a detailed description
  7862. ** of what each interface routine does.
  7863. */
  7864. #ifndef _BTREE_H_
  7865. #define _BTREE_H_
  7866. /* TODO: This definition is just included so other modules compile. It
  7867. ** needs to be revisited.
  7868. */
  7869. #define SQLITE_N_BTREE_META 10
  7870. /*
  7871. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  7872. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  7873. */
  7874. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  7875. #define SQLITE_DEFAULT_AUTOVACUUM 0
  7876. #endif
  7877. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  7878. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  7879. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  7880. /*
  7881. ** Forward declarations of structure
  7882. */
  7883. typedef struct Btree Btree;
  7884. typedef struct BtCursor BtCursor;
  7885. typedef struct BtShared BtShared;
  7886. SQLITE_PRIVATE int sqlite3BtreeOpen(
  7887. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  7888. const char *zFilename, /* Name of database file to open */
  7889. sqlite3 *db, /* Associated database connection */
  7890. Btree **ppBtree, /* Return open Btree* here */
  7891. int flags, /* Flags */
  7892. int vfsFlags /* Flags passed through to VFS open */
  7893. );
  7894. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  7895. ** following values.
  7896. **
  7897. ** NOTE: These values must match the corresponding PAGER_ values in
  7898. ** pager.h.
  7899. */
  7900. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  7901. #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
  7902. #define BTREE_MEMORY 4 /* This is an in-memory DB */
  7903. #define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
  7904. #define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
  7905. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  7906. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  7907. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
  7908. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  7909. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  7910. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  7911. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  7912. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  7913. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  7914. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  7915. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  7916. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  7917. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  7918. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  7919. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  7920. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  7921. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
  7922. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  7923. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  7924. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  7925. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  7926. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  7927. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  7928. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  7929. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  7930. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  7931. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  7932. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  7933. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  7934. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  7935. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  7936. ** of the flags shown below.
  7937. **
  7938. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  7939. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  7940. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  7941. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  7942. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  7943. ** indices.)
  7944. */
  7945. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  7946. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  7947. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  7948. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  7949. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  7950. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  7951. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  7952. /*
  7953. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  7954. ** should be one of the following values. The integer values are assigned
  7955. ** to constants so that the offset of the corresponding field in an
  7956. ** SQLite database header may be found using the following formula:
  7957. **
  7958. ** offset = 36 + (idx * 4)
  7959. **
  7960. ** For example, the free-page-count field is located at byte offset 36 of
  7961. ** the database file header. The incr-vacuum-flag field is located at
  7962. ** byte offset 64 (== 36+4*7).
  7963. */
  7964. #define BTREE_FREE_PAGE_COUNT 0
  7965. #define BTREE_SCHEMA_VERSION 1
  7966. #define BTREE_FILE_FORMAT 2
  7967. #define BTREE_DEFAULT_CACHE_SIZE 3
  7968. #define BTREE_LARGEST_ROOT_PAGE 4
  7969. #define BTREE_TEXT_ENCODING 5
  7970. #define BTREE_USER_VERSION 6
  7971. #define BTREE_INCR_VACUUM 7
  7972. SQLITE_PRIVATE int sqlite3BtreeCursor(
  7973. Btree*, /* BTree containing table to open */
  7974. int iTable, /* Index of root page */
  7975. int wrFlag, /* 1 for writing. 0 for read-only */
  7976. struct KeyInfo*, /* First argument to compare function */
  7977. BtCursor *pCursor /* Space to write cursor structure */
  7978. );
  7979. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  7980. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  7981. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  7982. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  7983. BtCursor*,
  7984. UnpackedRecord *pUnKey,
  7985. i64 intKey,
  7986. int bias,
  7987. int *pRes
  7988. );
  7989. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  7990. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  7991. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  7992. const void *pData, int nData,
  7993. int nZero, int bias, int seekResult);
  7994. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  7995. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  7996. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  7997. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  7998. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  7999. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8000. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8001. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  8002. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  8003. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8004. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8005. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  8006. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  8007. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8008. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8009. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8010. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  8011. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8012. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8013. #ifndef NDEBUG
  8014. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8015. #endif
  8016. #ifndef SQLITE_OMIT_BTREECOUNT
  8017. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8018. #endif
  8019. #ifdef SQLITE_TEST
  8020. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8021. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8022. #endif
  8023. #ifndef SQLITE_OMIT_WAL
  8024. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8025. #endif
  8026. /*
  8027. ** If we are not using shared cache, then there is no need to
  8028. ** use mutexes to access the BtShared structures. So make the
  8029. ** Enter and Leave procedures no-ops.
  8030. */
  8031. #ifndef SQLITE_OMIT_SHARED_CACHE
  8032. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8033. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8034. #else
  8035. # define sqlite3BtreeEnter(X)
  8036. # define sqlite3BtreeEnterAll(X)
  8037. #endif
  8038. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8039. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8040. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8041. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8042. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8043. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8044. #ifndef NDEBUG
  8045. /* These routines are used inside assert() statements only. */
  8046. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8047. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8048. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8049. #endif
  8050. #else
  8051. # define sqlite3BtreeSharable(X) 0
  8052. # define sqlite3BtreeLeave(X)
  8053. # define sqlite3BtreeEnterCursor(X)
  8054. # define sqlite3BtreeLeaveCursor(X)
  8055. # define sqlite3BtreeLeaveAll(X)
  8056. # define sqlite3BtreeHoldsMutex(X) 1
  8057. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8058. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8059. #endif
  8060. #endif /* _BTREE_H_ */
  8061. /************** End of btree.h ***********************************************/
  8062. /************** Continuing where we left off in sqliteInt.h ******************/
  8063. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8064. /************** Begin file vdbe.h ********************************************/
  8065. /*
  8066. ** 2001 September 15
  8067. **
  8068. ** The author disclaims copyright to this source code. In place of
  8069. ** a legal notice, here is a blessing:
  8070. **
  8071. ** May you do good and not evil.
  8072. ** May you find forgiveness for yourself and forgive others.
  8073. ** May you share freely, never taking more than you give.
  8074. **
  8075. *************************************************************************
  8076. ** Header file for the Virtual DataBase Engine (VDBE)
  8077. **
  8078. ** This header defines the interface to the virtual database engine
  8079. ** or VDBE. The VDBE implements an abstract machine that runs a
  8080. ** simple program to access and modify the underlying database.
  8081. */
  8082. #ifndef _SQLITE_VDBE_H_
  8083. #define _SQLITE_VDBE_H_
  8084. /* #include <stdio.h> */
  8085. /*
  8086. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8087. ** in the source file sqliteVdbe.c are allowed to see the insides
  8088. ** of this structure.
  8089. */
  8090. typedef struct Vdbe Vdbe;
  8091. /*
  8092. ** The names of the following types declared in vdbeInt.h are required
  8093. ** for the VdbeOp definition.
  8094. */
  8095. typedef struct VdbeFunc VdbeFunc;
  8096. typedef struct Mem Mem;
  8097. typedef struct SubProgram SubProgram;
  8098. /*
  8099. ** A single instruction of the virtual machine has an opcode
  8100. ** and as many as three operands. The instruction is recorded
  8101. ** as an instance of the following structure:
  8102. */
  8103. struct VdbeOp {
  8104. u8 opcode; /* What operation to perform */
  8105. signed char p4type; /* One of the P4_xxx constants for p4 */
  8106. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8107. u8 p5; /* Fifth parameter is an unsigned character */
  8108. int p1; /* First operand */
  8109. int p2; /* Second parameter (often the jump destination) */
  8110. int p3; /* The third parameter */
  8111. union { /* fourth parameter */
  8112. int i; /* Integer value if p4type==P4_INT32 */
  8113. void *p; /* Generic pointer */
  8114. char *z; /* Pointer to data for string (char array) types */
  8115. i64 *pI64; /* Used when p4type is P4_INT64 */
  8116. double *pReal; /* Used when p4type is P4_REAL */
  8117. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8118. VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
  8119. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8120. Mem *pMem; /* Used when p4type is P4_MEM */
  8121. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8122. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8123. int *ai; /* Used when p4type is P4_INTARRAY */
  8124. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8125. int (*xAdvance)(BtCursor *, int *);
  8126. } p4;
  8127. #ifdef SQLITE_DEBUG
  8128. char *zComment; /* Comment to improve readability */
  8129. #endif
  8130. #ifdef VDBE_PROFILE
  8131. int cnt; /* Number of times this instruction was executed */
  8132. u64 cycles; /* Total time spent executing this instruction */
  8133. #endif
  8134. };
  8135. typedef struct VdbeOp VdbeOp;
  8136. /*
  8137. ** A sub-routine used to implement a trigger program.
  8138. */
  8139. struct SubProgram {
  8140. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8141. int nOp; /* Elements in aOp[] */
  8142. int nMem; /* Number of memory cells required */
  8143. int nCsr; /* Number of cursors required */
  8144. int nOnce; /* Number of OP_Once instructions */
  8145. void *token; /* id that may be used to recursive triggers */
  8146. SubProgram *pNext; /* Next sub-program already visited */
  8147. };
  8148. /*
  8149. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8150. ** it takes up less space.
  8151. */
  8152. struct VdbeOpList {
  8153. u8 opcode; /* What operation to perform */
  8154. signed char p1; /* First operand */
  8155. signed char p2; /* Second parameter (often the jump destination) */
  8156. signed char p3; /* Third parameter */
  8157. };
  8158. typedef struct VdbeOpList VdbeOpList;
  8159. /*
  8160. ** Allowed values of VdbeOp.p4type
  8161. */
  8162. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8163. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8164. #define P4_STATIC (-2) /* Pointer to a static string */
  8165. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8166. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8167. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8168. #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
  8169. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8170. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8171. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8172. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8173. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8174. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8175. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8176. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8177. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8178. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8179. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  8180. ** is made. That copy is freed when the Vdbe is finalized. But if the
  8181. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  8182. ** gets freed when the Vdbe is finalized so it still should be obtained
  8183. ** from a single sqliteMalloc(). But no copy is made and the calling
  8184. ** function should *not* try to free the KeyInfo.
  8185. */
  8186. #define P4_KEYINFO_HANDOFF (-16)
  8187. #define P4_KEYINFO_STATIC (-17)
  8188. /*
  8189. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8190. ** number of columns of data returned by the statement.
  8191. */
  8192. #define COLNAME_NAME 0
  8193. #define COLNAME_DECLTYPE 1
  8194. #define COLNAME_DATABASE 2
  8195. #define COLNAME_TABLE 3
  8196. #define COLNAME_COLUMN 4
  8197. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8198. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8199. #else
  8200. # ifdef SQLITE_OMIT_DECLTYPE
  8201. # define COLNAME_N 1 /* Store only the name */
  8202. # else
  8203. # define COLNAME_N 2 /* Store the name and decltype */
  8204. # endif
  8205. #endif
  8206. /*
  8207. ** The following macro converts a relative address in the p2 field
  8208. ** of a VdbeOp structure into a negative number so that
  8209. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  8210. ** the macro again restores the address.
  8211. */
  8212. #define ADDR(X) (-1-(X))
  8213. /*
  8214. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  8215. ** header file that defines a number for each opcode used by the VDBE.
  8216. */
  8217. /************** Include opcodes.h in the middle of vdbe.h ********************/
  8218. /************** Begin file opcodes.h *****************************************/
  8219. /* Automatically generated. Do not edit */
  8220. /* See the mkopcodeh.awk script for details */
  8221. #define OP_Goto 1
  8222. #define OP_Gosub 2
  8223. #define OP_Return 3
  8224. #define OP_Yield 4
  8225. #define OP_HaltIfNull 5
  8226. #define OP_Halt 6
  8227. #define OP_Integer 7
  8228. #define OP_Int64 8
  8229. #define OP_Real 130 /* same as TK_FLOAT */
  8230. #define OP_String8 94 /* same as TK_STRING */
  8231. #define OP_String 9
  8232. #define OP_Null 10
  8233. #define OP_Blob 11
  8234. #define OP_Variable 12
  8235. #define OP_Move 13
  8236. #define OP_Copy 14
  8237. #define OP_SCopy 15
  8238. #define OP_ResultRow 16
  8239. #define OP_Concat 91 /* same as TK_CONCAT */
  8240. #define OP_Add 86 /* same as TK_PLUS */
  8241. #define OP_Subtract 87 /* same as TK_MINUS */
  8242. #define OP_Multiply 88 /* same as TK_STAR */
  8243. #define OP_Divide 89 /* same as TK_SLASH */
  8244. #define OP_Remainder 90 /* same as TK_REM */
  8245. #define OP_CollSeq 17
  8246. #define OP_Function 18
  8247. #define OP_BitAnd 82 /* same as TK_BITAND */
  8248. #define OP_BitOr 83 /* same as TK_BITOR */
  8249. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  8250. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  8251. #define OP_AddImm 20
  8252. #define OP_MustBeInt 21
  8253. #define OP_RealAffinity 22
  8254. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8255. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8256. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  8257. #define OP_ToInt 144 /* same as TK_TO_INT */
  8258. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8259. #define OP_Eq 76 /* same as TK_EQ */
  8260. #define OP_Ne 75 /* same as TK_NE */
  8261. #define OP_Lt 79 /* same as TK_LT */
  8262. #define OP_Le 78 /* same as TK_LE */
  8263. #define OP_Gt 77 /* same as TK_GT */
  8264. #define OP_Ge 80 /* same as TK_GE */
  8265. #define OP_Permutation 23
  8266. #define OP_Compare 24
  8267. #define OP_Jump 25
  8268. #define OP_And 69 /* same as TK_AND */
  8269. #define OP_Or 68 /* same as TK_OR */
  8270. #define OP_Not 19 /* same as TK_NOT */
  8271. #define OP_BitNot 93 /* same as TK_BITNOT */
  8272. #define OP_Once 26
  8273. #define OP_If 27
  8274. #define OP_IfNot 28
  8275. #define OP_IsNull 73 /* same as TK_ISNULL */
  8276. #define OP_NotNull 74 /* same as TK_NOTNULL */
  8277. #define OP_Column 29
  8278. #define OP_Affinity 30
  8279. #define OP_MakeRecord 31
  8280. #define OP_Count 32
  8281. #define OP_Savepoint 33
  8282. #define OP_AutoCommit 34
  8283. #define OP_Transaction 35
  8284. #define OP_ReadCookie 36
  8285. #define OP_SetCookie 37
  8286. #define OP_VerifyCookie 38
  8287. #define OP_OpenRead 39
  8288. #define OP_OpenWrite 40
  8289. #define OP_OpenAutoindex 41
  8290. #define OP_OpenEphemeral 42
  8291. #define OP_SorterOpen 43
  8292. #define OP_OpenPseudo 44
  8293. #define OP_Close 45
  8294. #define OP_SeekLt 46
  8295. #define OP_SeekLe 47
  8296. #define OP_SeekGe 48
  8297. #define OP_SeekGt 49
  8298. #define OP_Seek 50
  8299. #define OP_NotFound 51
  8300. #define OP_Found 52
  8301. #define OP_IsUnique 53
  8302. #define OP_NotExists 54
  8303. #define OP_Sequence 55
  8304. #define OP_NewRowid 56
  8305. #define OP_Insert 57
  8306. #define OP_InsertInt 58
  8307. #define OP_Delete 59
  8308. #define OP_ResetCount 60
  8309. #define OP_SorterCompare 61
  8310. #define OP_SorterData 62
  8311. #define OP_RowKey 63
  8312. #define OP_RowData 64
  8313. #define OP_Rowid 65
  8314. #define OP_NullRow 66
  8315. #define OP_Last 67
  8316. #define OP_SorterSort 70
  8317. #define OP_Sort 71
  8318. #define OP_Rewind 72
  8319. #define OP_SorterNext 81
  8320. #define OP_Prev 92
  8321. #define OP_Next 95
  8322. #define OP_SorterInsert 96
  8323. #define OP_IdxInsert 97
  8324. #define OP_IdxDelete 98
  8325. #define OP_IdxRowid 99
  8326. #define OP_IdxLT 100
  8327. #define OP_IdxGE 101
  8328. #define OP_Destroy 102
  8329. #define OP_Clear 103
  8330. #define OP_CreateIndex 104
  8331. #define OP_CreateTable 105
  8332. #define OP_ParseSchema 106
  8333. #define OP_LoadAnalysis 107
  8334. #define OP_DropTable 108
  8335. #define OP_DropIndex 109
  8336. #define OP_DropTrigger 110
  8337. #define OP_IntegrityCk 111
  8338. #define OP_RowSetAdd 112
  8339. #define OP_RowSetRead 113
  8340. #define OP_RowSetTest 114
  8341. #define OP_Program 115
  8342. #define OP_Param 116
  8343. #define OP_FkCounter 117
  8344. #define OP_FkIfZero 118
  8345. #define OP_MemMax 119
  8346. #define OP_IfPos 120
  8347. #define OP_IfNeg 121
  8348. #define OP_IfZero 122
  8349. #define OP_AggStep 123
  8350. #define OP_AggFinal 124
  8351. #define OP_Checkpoint 125
  8352. #define OP_JournalMode 126
  8353. #define OP_Vacuum 127
  8354. #define OP_IncrVacuum 128
  8355. #define OP_Expire 129
  8356. #define OP_TableLock 131
  8357. #define OP_VBegin 132
  8358. #define OP_VCreate 133
  8359. #define OP_VDestroy 134
  8360. #define OP_VOpen 135
  8361. #define OP_VFilter 136
  8362. #define OP_VColumn 137
  8363. #define OP_VNext 138
  8364. #define OP_VRename 139
  8365. #define OP_VUpdate 140
  8366. #define OP_Pagecount 146
  8367. #define OP_MaxPgcnt 147
  8368. #define OP_Trace 148
  8369. #define OP_Noop 149
  8370. #define OP_Explain 150
  8371. /* Properties such as "out2" or "jump" that are specified in
  8372. ** comments following the "case" for each opcode in the vdbe.c
  8373. ** are encoded into bitvectors as follows:
  8374. */
  8375. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8376. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8377. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8378. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8379. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8380. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  8381. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  8382. #define OPFLG_INITIALIZER {\
  8383. /* 0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
  8384. /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
  8385. /* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
  8386. /* 24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
  8387. /* 32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
  8388. /* 40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
  8389. /* 48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
  8390. /* 56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8391. /* 64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
  8392. /* 72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  8393. /* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  8394. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
  8395. /* 96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
  8396. /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8397. /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
  8398. /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
  8399. /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
  8400. /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
  8401. /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
  8402. /************** End of opcodes.h *********************************************/
  8403. /************** Continuing where we left off in vdbe.h ***********************/
  8404. /*
  8405. ** Prototypes for the VDBE interface. See comments on the implementation
  8406. ** for a description of what each of these routines does.
  8407. */
  8408. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8409. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8410. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8411. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8412. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8413. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8414. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  8415. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8416. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  8417. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  8418. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  8419. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  8420. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8421. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8422. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  8423. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8424. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8425. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8426. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8427. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  8428. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8429. SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
  8430. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  8431. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8432. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8433. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8434. #ifdef SQLITE_DEBUG
  8435. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  8436. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8437. #endif
  8438. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8439. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  8440. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8441. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8442. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8443. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8444. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8445. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  8446. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8447. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  8448. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
  8449. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  8450. #ifndef SQLITE_OMIT_TRACE
  8451. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  8452. #endif
  8453. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  8454. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8455. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  8456. #ifndef SQLITE_OMIT_TRIGGER
  8457. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  8458. #endif
  8459. #ifndef NDEBUG
  8460. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8461. # define VdbeComment(X) sqlite3VdbeComment X
  8462. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8463. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8464. #else
  8465. # define VdbeComment(X)
  8466. # define VdbeNoopComment(X)
  8467. #endif
  8468. #endif
  8469. /************** End of vdbe.h ************************************************/
  8470. /************** Continuing where we left off in sqliteInt.h ******************/
  8471. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8472. /************** Begin file pager.h *******************************************/
  8473. /*
  8474. ** 2001 September 15
  8475. **
  8476. ** The author disclaims copyright to this source code. In place of
  8477. ** a legal notice, here is a blessing:
  8478. **
  8479. ** May you do good and not evil.
  8480. ** May you find forgiveness for yourself and forgive others.
  8481. ** May you share freely, never taking more than you give.
  8482. **
  8483. *************************************************************************
  8484. ** This header file defines the interface that the sqlite page cache
  8485. ** subsystem. The page cache subsystem reads and writes a file a page
  8486. ** at a time and provides a journal for rollback.
  8487. */
  8488. #ifndef _PAGER_H_
  8489. #define _PAGER_H_
  8490. /*
  8491. ** Default maximum size for persistent journal files. A negative
  8492. ** value means no limit. This value may be overridden using the
  8493. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  8494. */
  8495. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8496. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8497. #endif
  8498. /*
  8499. ** The type used to represent a page number. The first page in a file
  8500. ** is called page 1. 0 is used to represent "not a page".
  8501. */
  8502. typedef u32 Pgno;
  8503. /*
  8504. ** Each open file is managed by a separate instance of the "Pager" structure.
  8505. */
  8506. typedef struct Pager Pager;
  8507. /*
  8508. ** Handle type for pages.
  8509. */
  8510. typedef struct PgHdr DbPage;
  8511. /*
  8512. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  8513. ** reserved for working around a windows/posix incompatibility). It is
  8514. ** used in the journal to signify that the remainder of the journal file
  8515. ** is devoted to storing a master journal name - there are no more pages to
  8516. ** roll back. See comments for function writeMasterJournal() in pager.c
  8517. ** for details.
  8518. */
  8519. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  8520. /*
  8521. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8522. **
  8523. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  8524. */
  8525. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8526. #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
  8527. #define PAGER_MEMORY 0x0004 /* In-memory database */
  8528. /*
  8529. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8530. */
  8531. #define PAGER_LOCKINGMODE_QUERY -1
  8532. #define PAGER_LOCKINGMODE_NORMAL 0
  8533. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8534. /*
  8535. ** Numeric constants that encode the journalmode.
  8536. */
  8537. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  8538. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8539. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8540. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8541. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8542. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8543. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  8544. /*
  8545. ** The remainder of this file contains the declarations of the functions
  8546. ** that make up the Pager sub-system API. See source code comments for
  8547. ** a detailed description of each routine.
  8548. */
  8549. /* Open and close a Pager connection. */
  8550. SQLITE_PRIVATE int sqlite3PagerOpen(
  8551. sqlite3_vfs*,
  8552. Pager **ppPager,
  8553. const char*,
  8554. int,
  8555. int,
  8556. int,
  8557. void(*)(DbPage*)
  8558. );
  8559. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  8560. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  8561. /* Functions used to configure a Pager object. */
  8562. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  8563. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  8564. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  8565. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  8566. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  8567. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
  8568. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  8569. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  8570. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  8571. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  8572. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  8573. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  8574. /* Functions used to obtain and release page references. */
  8575. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  8576. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  8577. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  8578. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  8579. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  8580. /* Operations on page references. */
  8581. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  8582. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  8583. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  8584. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  8585. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  8586. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  8587. /* Functions used to manage pager transactions and savepoints. */
  8588. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  8589. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  8590. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  8591. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  8592. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  8593. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  8594. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  8595. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  8596. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  8597. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  8598. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  8599. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  8600. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  8601. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  8602. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  8603. /* Functions used to query pager state and configuration. */
  8604. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  8605. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  8606. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  8607. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
  8608. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  8609. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  8610. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  8611. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  8612. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  8613. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  8614. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  8615. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  8616. /* Functions used to truncate the database file. */
  8617. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  8618. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  8619. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  8620. #endif
  8621. /* Functions to support testing and debugging. */
  8622. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  8623. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  8624. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  8625. #endif
  8626. #ifdef SQLITE_TEST
  8627. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  8628. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  8629. void disable_simulated_io_errors(void);
  8630. void enable_simulated_io_errors(void);
  8631. #else
  8632. # define disable_simulated_io_errors()
  8633. # define enable_simulated_io_errors()
  8634. #endif
  8635. #endif /* _PAGER_H_ */
  8636. /************** End of pager.h ***********************************************/
  8637. /************** Continuing where we left off in sqliteInt.h ******************/
  8638. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  8639. /************** Begin file pcache.h ******************************************/
  8640. /*
  8641. ** 2008 August 05
  8642. **
  8643. ** The author disclaims copyright to this source code. In place of
  8644. ** a legal notice, here is a blessing:
  8645. **
  8646. ** May you do good and not evil.
  8647. ** May you find forgiveness for yourself and forgive others.
  8648. ** May you share freely, never taking more than you give.
  8649. **
  8650. *************************************************************************
  8651. ** This header file defines the interface that the sqlite page cache
  8652. ** subsystem.
  8653. */
  8654. #ifndef _PCACHE_H_
  8655. typedef struct PgHdr PgHdr;
  8656. typedef struct PCache PCache;
  8657. /*
  8658. ** Every page in the cache is controlled by an instance of the following
  8659. ** structure.
  8660. */
  8661. struct PgHdr {
  8662. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  8663. void *pData; /* Page data */
  8664. void *pExtra; /* Extra content */
  8665. PgHdr *pDirty; /* Transient list of dirty pages */
  8666. Pgno pgno; /* Page number for this page */
  8667. Pager *pPager; /* The pager this page is part of */
  8668. #ifdef SQLITE_CHECK_PAGES
  8669. u32 pageHash; /* Hash of page content */
  8670. #endif
  8671. u16 flags; /* PGHDR flags defined below */
  8672. /**********************************************************************
  8673. ** Elements above are public. All that follows is private to pcache.c
  8674. ** and should not be accessed by other modules.
  8675. */
  8676. i16 nRef; /* Number of users of this page */
  8677. PCache *pCache; /* Cache that owns this page */
  8678. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  8679. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  8680. };
  8681. /* Bit values for PgHdr.flags */
  8682. #define PGHDR_DIRTY 0x002 /* Page has changed */
  8683. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  8684. ** writing this page to the database */
  8685. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  8686. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  8687. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  8688. /* Initialize and shutdown the page cache subsystem */
  8689. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  8690. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  8691. /* Page cache buffer management:
  8692. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  8693. */
  8694. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  8695. /* Create a new pager cache.
  8696. ** Under memory stress, invoke xStress to try to make pages clean.
  8697. ** Only clean and unpinned pages can be reclaimed.
  8698. */
  8699. SQLITE_PRIVATE void sqlite3PcacheOpen(
  8700. int szPage, /* Size of every page */
  8701. int szExtra, /* Extra space associated with each page */
  8702. int bPurgeable, /* True if pages are on backing store */
  8703. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  8704. void *pStress, /* Argument to xStress */
  8705. PCache *pToInit /* Preallocated space for the PCache */
  8706. );
  8707. /* Modify the page-size after the cache has been created. */
  8708. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  8709. /* Return the size in bytes of a PCache object. Used to preallocate
  8710. ** storage space.
  8711. */
  8712. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  8713. /* One release per successful fetch. Page is pinned until released.
  8714. ** Reference counted.
  8715. */
  8716. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  8717. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  8718. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  8719. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  8720. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  8721. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  8722. /* Change a page number. Used by incr-vacuum. */
  8723. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  8724. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  8725. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  8726. /* Get a list of all dirty pages in the cache, sorted by page number */
  8727. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  8728. /* Reset and close the cache object */
  8729. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  8730. /* Clear flags from pages of the page cache */
  8731. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  8732. /* Discard the contents of the cache */
  8733. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  8734. /* Return the total number of outstanding page references */
  8735. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  8736. /* Increment the reference count of an existing page */
  8737. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  8738. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  8739. /* Return the total number of pages stored in the cache */
  8740. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  8741. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  8742. /* Iterate through all dirty pages currently stored in the cache. This
  8743. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  8744. ** library is built.
  8745. */
  8746. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  8747. #endif
  8748. /* Set and get the suggested cache-size for the specified pager-cache.
  8749. **
  8750. ** If no global maximum is configured, then the system attempts to limit
  8751. ** the total number of pages cached by purgeable pager-caches to the sum
  8752. ** of the suggested cache-sizes.
  8753. */
  8754. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  8755. #ifdef SQLITE_TEST
  8756. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  8757. #endif
  8758. /* Free up as much memory as possible from the page cache */
  8759. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  8760. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  8761. /* Try to return memory used by the pcache module to the main memory heap */
  8762. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  8763. #endif
  8764. #ifdef SQLITE_TEST
  8765. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  8766. #endif
  8767. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  8768. #endif /* _PCACHE_H_ */
  8769. /************** End of pcache.h **********************************************/
  8770. /************** Continuing where we left off in sqliteInt.h ******************/
  8771. /************** Include os.h in the middle of sqliteInt.h ********************/
  8772. /************** Begin file os.h **********************************************/
  8773. /*
  8774. ** 2001 September 16
  8775. **
  8776. ** The author disclaims copyright to this source code. In place of
  8777. ** a legal notice, here is a blessing:
  8778. **
  8779. ** May you do good and not evil.
  8780. ** May you find forgiveness for yourself and forgive others.
  8781. ** May you share freely, never taking more than you give.
  8782. **
  8783. ******************************************************************************
  8784. **
  8785. ** This header file (together with is companion C source-code file
  8786. ** "os.c") attempt to abstract the underlying operating system so that
  8787. ** the SQLite library will work on both POSIX and windows systems.
  8788. **
  8789. ** This header file is #include-ed by sqliteInt.h and thus ends up
  8790. ** being included by every source file.
  8791. */
  8792. #ifndef _SQLITE_OS_H_
  8793. #define _SQLITE_OS_H_
  8794. /*
  8795. ** Figure out if we are dealing with Unix, Windows, or some other
  8796. ** operating system. After the following block of preprocess macros,
  8797. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
  8798. ** will defined to either 1 or 0. One of the four will be 1. The other
  8799. ** three will be 0.
  8800. */
  8801. #if defined(SQLITE_OS_OTHER)
  8802. # if SQLITE_OS_OTHER==1
  8803. # undef SQLITE_OS_UNIX
  8804. # define SQLITE_OS_UNIX 0
  8805. # undef SQLITE_OS_WIN
  8806. # define SQLITE_OS_WIN 0
  8807. # undef SQLITE_OS_OS2
  8808. # define SQLITE_OS_OS2 0
  8809. # else
  8810. # undef SQLITE_OS_OTHER
  8811. # endif
  8812. #endif
  8813. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  8814. # define SQLITE_OS_OTHER 0
  8815. # ifndef SQLITE_OS_WIN
  8816. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  8817. # define SQLITE_OS_WIN 1
  8818. # define SQLITE_OS_UNIX 0
  8819. # define SQLITE_OS_OS2 0
  8820. # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
  8821. # define SQLITE_OS_WIN 0
  8822. # define SQLITE_OS_UNIX 0
  8823. # define SQLITE_OS_OS2 1
  8824. # else
  8825. # define SQLITE_OS_WIN 0
  8826. # define SQLITE_OS_UNIX 1
  8827. # define SQLITE_OS_OS2 0
  8828. # endif
  8829. # else
  8830. # define SQLITE_OS_UNIX 0
  8831. # define SQLITE_OS_OS2 0
  8832. # endif
  8833. #else
  8834. # ifndef SQLITE_OS_WIN
  8835. # define SQLITE_OS_WIN 0
  8836. # endif
  8837. #endif
  8838. /*
  8839. ** Define the maximum size of a temporary filename
  8840. */
  8841. #if SQLITE_OS_WIN
  8842. # include <windows.h>
  8843. # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
  8844. #elif SQLITE_OS_OS2
  8845. # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
  8846. # include <os2safe.h> /* has to be included before os2.h for linking to work */
  8847. # endif
  8848. # define INCL_DOSDATETIME
  8849. # define INCL_DOSFILEMGR
  8850. # define INCL_DOSERRORS
  8851. # define INCL_DOSMISC
  8852. # define INCL_DOSPROCESS
  8853. # define INCL_DOSMODULEMGR
  8854. # define INCL_DOSSEMAPHORES
  8855. # include <os2.h>
  8856. # include <uconv.h>
  8857. # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
  8858. #else
  8859. # define SQLITE_TEMPNAME_SIZE 200
  8860. #endif
  8861. /*
  8862. ** Determine if we are dealing with Windows NT.
  8863. */
  8864. #if defined(_WIN32_WINNT)
  8865. # define SQLITE_OS_WINNT 1
  8866. #else
  8867. # define SQLITE_OS_WINNT 0
  8868. #endif
  8869. /*
  8870. ** Determine if we are dealing with WindowsCE - which has a much
  8871. ** reduced API.
  8872. */
  8873. #if defined(_WIN32_WCE)
  8874. # define SQLITE_OS_WINCE 1
  8875. #else
  8876. # define SQLITE_OS_WINCE 0
  8877. #endif
  8878. /* If the SET_FULLSYNC macro is not defined above, then make it
  8879. ** a no-op
  8880. */
  8881. #ifndef SET_FULLSYNC
  8882. # define SET_FULLSYNC(x,y)
  8883. #endif
  8884. /*
  8885. ** The default size of a disk sector
  8886. */
  8887. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  8888. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  8889. #endif
  8890. /*
  8891. ** Temporary files are named starting with this prefix followed by 16 random
  8892. ** alphanumeric characters, and no file extension. They are stored in the
  8893. ** OS's standard temporary file directory, and are deleted prior to exit.
  8894. ** If sqlite is being embedded in another program, you may wish to change the
  8895. ** prefix to reflect your program's name, so that if your program exits
  8896. ** prematurely, old temporary files can be easily identified. This can be done
  8897. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  8898. **
  8899. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  8900. ** Mcafee started using SQLite in their anti-virus product and it
  8901. ** started putting files with the "sqlite" name in the c:/temp folder.
  8902. ** This annoyed many windows users. Those users would then do a
  8903. ** Google search for "sqlite", find the telephone numbers of the
  8904. ** developers and call to wake them up at night and complain.
  8905. ** For this reason, the default name prefix is changed to be "sqlite"
  8906. ** spelled backwards. So the temp files are still identified, but
  8907. ** anybody smart enough to figure out the code is also likely smart
  8908. ** enough to know that calling the developer will not help get rid
  8909. ** of the file.
  8910. */
  8911. #ifndef SQLITE_TEMP_FILE_PREFIX
  8912. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  8913. #endif
  8914. /*
  8915. ** The following values may be passed as the second argument to
  8916. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  8917. **
  8918. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  8919. ** RESERVED: A single process may hold a RESERVED lock on a file at
  8920. ** any time. Other processes may hold and obtain new SHARED locks.
  8921. ** PENDING: A single process may hold a PENDING lock on a file at
  8922. ** any one time. Existing SHARED locks may persist, but no new
  8923. ** SHARED locks may be obtained by other processes.
  8924. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  8925. **
  8926. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  8927. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  8928. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  8929. ** sqlite3OsLock().
  8930. */
  8931. #define NO_LOCK 0
  8932. #define SHARED_LOCK 1
  8933. #define RESERVED_LOCK 2
  8934. #define PENDING_LOCK 3
  8935. #define EXCLUSIVE_LOCK 4
  8936. /*
  8937. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  8938. **
  8939. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  8940. ** those functions are not available. So we use only LockFile() and
  8941. ** UnlockFile().
  8942. **
  8943. ** LockFile() prevents not just writing but also reading by other processes.
  8944. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  8945. ** byte out of a specific range of bytes. The lock byte is obtained at
  8946. ** random so two separate readers can probably access the file at the
  8947. ** same time, unless they are unlucky and choose the same lock byte.
  8948. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  8949. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  8950. ** a single byte of the file that is designated as the reserved lock byte.
  8951. ** A PENDING_LOCK is obtained by locking a designated byte different from
  8952. ** the RESERVED_LOCK byte.
  8953. **
  8954. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  8955. ** which means we can use reader/writer locks. When reader/writer locks
  8956. ** are used, the lock is placed on the same range of bytes that is used
  8957. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  8958. ** will support two or more Win95 readers or two or more WinNT readers.
  8959. ** But a single Win95 reader will lock out all WinNT readers and a single
  8960. ** WinNT reader will lock out all other Win95 readers.
  8961. **
  8962. ** The following #defines specify the range of bytes used for locking.
  8963. ** SHARED_SIZE is the number of bytes available in the pool from which
  8964. ** a random byte is selected for a shared lock. The pool of bytes for
  8965. ** shared locks begins at SHARED_FIRST.
  8966. **
  8967. ** The same locking strategy and
  8968. ** byte ranges are used for Unix. This leaves open the possiblity of having
  8969. ** clients on win95, winNT, and unix all talking to the same shared file
  8970. ** and all locking correctly. To do so would require that samba (or whatever
  8971. ** tool is being used for file sharing) implements locks correctly between
  8972. ** windows and unix. I'm guessing that isn't likely to happen, but by
  8973. ** using the same locking range we are at least open to the possibility.
  8974. **
  8975. ** Locking in windows is manditory. For this reason, we cannot store
  8976. ** actual data in the bytes used for locking. The pager never allocates
  8977. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  8978. ** that all locks will fit on a single page even at the minimum page size.
  8979. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  8980. ** is set high so that we don't have to allocate an unused page except
  8981. ** for very large databases. But one should test the page skipping logic
  8982. ** by setting PENDING_BYTE low and running the entire regression suite.
  8983. **
  8984. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  8985. ** file format. Depending on how it is changed, you might not notice
  8986. ** the incompatibility right away, even running a full regression test.
  8987. ** The default location of PENDING_BYTE is the first byte past the
  8988. ** 1GB boundary.
  8989. **
  8990. */
  8991. #ifdef SQLITE_OMIT_WSD
  8992. # define PENDING_BYTE (0x40000000)
  8993. #else
  8994. # define PENDING_BYTE sqlite3PendingByte
  8995. #endif
  8996. #define RESERVED_BYTE (PENDING_BYTE+1)
  8997. #define SHARED_FIRST (PENDING_BYTE+2)
  8998. #define SHARED_SIZE 510
  8999. /*
  9000. ** Wrapper around OS specific sqlite3_os_init() function.
  9001. */
  9002. SQLITE_PRIVATE int sqlite3OsInit(void);
  9003. /*
  9004. ** Functions for accessing sqlite3_file methods
  9005. */
  9006. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9007. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9008. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9009. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9010. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9011. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9012. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9013. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9014. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9015. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9016. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9017. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9018. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9019. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9020. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9021. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9022. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9023. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9024. /*
  9025. ** Functions for accessing sqlite3_vfs methods
  9026. */
  9027. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9028. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9029. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9030. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9031. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9032. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9033. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9034. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9035. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9036. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9037. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9038. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9039. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9040. /*
  9041. ** Convenience functions for opening and closing files using
  9042. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9043. */
  9044. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9045. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9046. #endif /* _SQLITE_OS_H_ */
  9047. /************** End of os.h **************************************************/
  9048. /************** Continuing where we left off in sqliteInt.h ******************/
  9049. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9050. /************** Begin file mutex.h *******************************************/
  9051. /*
  9052. ** 2007 August 28
  9053. **
  9054. ** The author disclaims copyright to this source code. In place of
  9055. ** a legal notice, here is a blessing:
  9056. **
  9057. ** May you do good and not evil.
  9058. ** May you find forgiveness for yourself and forgive others.
  9059. ** May you share freely, never taking more than you give.
  9060. **
  9061. *************************************************************************
  9062. **
  9063. ** This file contains the common header for all mutex implementations.
  9064. ** The sqliteInt.h header #includes this file so that it is available
  9065. ** to all source files. We break it out in an effort to keep the code
  9066. ** better organized.
  9067. **
  9068. ** NOTE: source files should *not* #include this header file directly.
  9069. ** Source files should #include the sqliteInt.h file and let that file
  9070. ** include this one indirectly.
  9071. */
  9072. /*
  9073. ** Figure out what version of the code to use. The choices are
  9074. **
  9075. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9076. ** mutexes implemention cannot be overridden
  9077. ** at start-time.
  9078. **
  9079. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9080. ** mutual exclusion is provided. But this
  9081. ** implementation can be overridden at
  9082. ** start-time.
  9083. **
  9084. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9085. **
  9086. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9087. **
  9088. ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
  9089. */
  9090. #if !SQLITE_THREADSAFE
  9091. # define SQLITE_MUTEX_OMIT
  9092. #endif
  9093. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9094. # if SQLITE_OS_UNIX
  9095. # define SQLITE_MUTEX_PTHREADS
  9096. # elif SQLITE_OS_WIN
  9097. # define SQLITE_MUTEX_W32
  9098. # elif SQLITE_OS_OS2
  9099. # define SQLITE_MUTEX_OS2
  9100. # else
  9101. # define SQLITE_MUTEX_NOOP
  9102. # endif
  9103. #endif
  9104. #ifdef SQLITE_MUTEX_OMIT
  9105. /*
  9106. ** If this is a no-op implementation, implement everything as macros.
  9107. */
  9108. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9109. #define sqlite3_mutex_free(X)
  9110. #define sqlite3_mutex_enter(X)
  9111. #define sqlite3_mutex_try(X) SQLITE_OK
  9112. #define sqlite3_mutex_leave(X)
  9113. #define sqlite3_mutex_held(X) ((void)(X),1)
  9114. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9115. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9116. #define sqlite3MutexInit() SQLITE_OK
  9117. #define sqlite3MutexEnd()
  9118. #define MUTEX_LOGIC(X)
  9119. #else
  9120. #define MUTEX_LOGIC(X) X
  9121. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9122. /************** End of mutex.h ***********************************************/
  9123. /************** Continuing where we left off in sqliteInt.h ******************/
  9124. /*
  9125. ** Each database file to be accessed by the system is an instance
  9126. ** of the following structure. There are normally two of these structures
  9127. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9128. ** aDb[1] is the database file used to hold temporary tables. Additional
  9129. ** databases may be attached.
  9130. */
  9131. struct Db {
  9132. char *zName; /* Name of this database */
  9133. Btree *pBt; /* The B*Tree structure for this database file */
  9134. u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  9135. u8 safety_level; /* How aggressive at syncing data to disk */
  9136. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9137. };
  9138. /*
  9139. ** An instance of the following structure stores a database schema.
  9140. **
  9141. ** Most Schema objects are associated with a Btree. The exception is
  9142. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9143. ** In shared cache mode, a single Schema object can be shared by multiple
  9144. ** Btrees that refer to the same underlying BtShared object.
  9145. **
  9146. ** Schema objects are automatically deallocated when the last Btree that
  9147. ** references them is destroyed. The TEMP Schema is manually freed by
  9148. ** sqlite3_close().
  9149. *
  9150. ** A thread must be holding a mutex on the corresponding Btree in order
  9151. ** to access Schema content. This implies that the thread must also be
  9152. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  9153. ** For a TEMP Schema, only the connection mutex is required.
  9154. */
  9155. struct Schema {
  9156. int schema_cookie; /* Database schema version number for this file */
  9157. int iGeneration; /* Generation counter. Incremented with each change */
  9158. Hash tblHash; /* All tables indexed by name */
  9159. Hash idxHash; /* All (named) indices indexed by name */
  9160. Hash trigHash; /* All triggers indexed by name */
  9161. Hash fkeyHash; /* All foreign keys by referenced table name */
  9162. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  9163. u8 file_format; /* Schema format version for this file */
  9164. u8 enc; /* Text encoding used by this database */
  9165. u16 flags; /* Flags associated with this schema */
  9166. int cache_size; /* Number of pages to use in the cache */
  9167. };
  9168. /*
  9169. ** These macros can be used to test, set, or clear bits in the
  9170. ** Db.pSchema->flags field.
  9171. */
  9172. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  9173. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  9174. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  9175. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  9176. /*
  9177. ** Allowed values for the DB.pSchema->flags field.
  9178. **
  9179. ** The DB_SchemaLoaded flag is set after the database schema has been
  9180. ** read into internal hash tables.
  9181. **
  9182. ** DB_UnresetViews means that one or more views have column names that
  9183. ** have been filled out. If the schema changes, these column names might
  9184. ** changes and so the view will need to be reset.
  9185. */
  9186. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  9187. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  9188. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  9189. /*
  9190. ** The number of different kinds of things that can be limited
  9191. ** using the sqlite3_limit() interface.
  9192. */
  9193. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  9194. /*
  9195. ** Lookaside malloc is a set of fixed-size buffers that can be used
  9196. ** to satisfy small transient memory allocation requests for objects
  9197. ** associated with a particular database connection. The use of
  9198. ** lookaside malloc provides a significant performance enhancement
  9199. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  9200. ** SQL statements.
  9201. **
  9202. ** The Lookaside structure holds configuration information about the
  9203. ** lookaside malloc subsystem. Each available memory allocation in
  9204. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  9205. ** objects.
  9206. **
  9207. ** Lookaside allocations are only allowed for objects that are associated
  9208. ** with a particular database connection. Hence, schema information cannot
  9209. ** be stored in lookaside because in shared cache mode the schema information
  9210. ** is shared by multiple database connections. Therefore, while parsing
  9211. ** schema information, the Lookaside.bEnabled flag is cleared so that
  9212. ** lookaside allocations are not used to construct the schema objects.
  9213. */
  9214. struct Lookaside {
  9215. u16 sz; /* Size of each buffer in bytes */
  9216. u8 bEnabled; /* False to disable new lookaside allocations */
  9217. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  9218. int nOut; /* Number of buffers currently checked out */
  9219. int mxOut; /* Highwater mark for nOut */
  9220. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  9221. LookasideSlot *pFree; /* List of available buffers */
  9222. void *pStart; /* First byte of available memory space */
  9223. void *pEnd; /* First byte past end of available space */
  9224. };
  9225. struct LookasideSlot {
  9226. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  9227. };
  9228. /*
  9229. ** A hash table for function definitions.
  9230. **
  9231. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  9232. ** Collisions are on the FuncDef.pHash chain.
  9233. */
  9234. struct FuncDefHash {
  9235. FuncDef *a[23]; /* Hash table for functions */
  9236. };
  9237. /*
  9238. ** Each database connection is an instance of the following structure.
  9239. **
  9240. ** The sqlite.lastRowid records the last insert rowid generated by an
  9241. ** insert statement. Inserts on views do not affect its value. Each
  9242. ** trigger has its own context, so that lastRowid can be updated inside
  9243. ** triggers as usual. The previous value will be restored once the trigger
  9244. ** exits. Upon entering a before or instead of trigger, lastRowid is no
  9245. ** longer (since after version 2.8.12) reset to -1.
  9246. **
  9247. ** The sqlite.nChange does not count changes within triggers and keeps no
  9248. ** context. It is reset at start of sqlite3_exec.
  9249. ** The sqlite.lsChange represents the number of changes made by the last
  9250. ** insert, update, or delete statement. It remains constant throughout the
  9251. ** length of a statement and is then updated by OP_SetCounts. It keeps a
  9252. ** context stack just like lastRowid so that the count of changes
  9253. ** within a trigger is not seen outside the trigger. Changes to views do not
  9254. ** affect the value of lsChange.
  9255. ** The sqlite.csChange keeps track of the number of current changes (since
  9256. ** the last statement) and is used to update sqlite_lsChange.
  9257. **
  9258. ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
  9259. ** store the most recent error code and, if applicable, string. The
  9260. ** internal function sqlite3Error() is used to set these variables
  9261. ** consistently.
  9262. */
  9263. struct sqlite3 {
  9264. sqlite3_vfs *pVfs; /* OS Interface */
  9265. int nDb; /* Number of backends currently in use */
  9266. Db *aDb; /* All backends */
  9267. int flags; /* Miscellaneous flags. See below */
  9268. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  9269. int errCode; /* Most recent error code (SQLITE_*) */
  9270. int errMask; /* & result codes with this before returning */
  9271. u8 autoCommit; /* The auto-commit flag. */
  9272. u8 temp_store; /* 1: file 2: memory 0: default */
  9273. u8 mallocFailed; /* True if we have seen a malloc failure */
  9274. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  9275. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  9276. u8 suppressErr; /* Do not issue error messages if true */
  9277. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  9278. int nextPagesize; /* Pagesize after VACUUM if >0 */
  9279. int nTable; /* Number of tables in the database */
  9280. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  9281. i64 lastRowid; /* ROWID of most recent insert (see above) */
  9282. u32 magic; /* Magic number for detect library misuse */
  9283. int nChange; /* Value returned by sqlite3_changes() */
  9284. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  9285. sqlite3_mutex *mutex; /* Connection mutex */
  9286. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  9287. struct sqlite3InitInfo { /* Information used during initialization */
  9288. int iDb; /* When back is being initialized */
  9289. int newTnum; /* Rootpage of table being initialized */
  9290. u8 busy; /* TRUE if currently initializing */
  9291. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  9292. } init;
  9293. int nExtension; /* Number of loaded extensions */
  9294. void **aExtension; /* Array of shared library handles */
  9295. struct Vdbe *pVdbe; /* List of active virtual machines */
  9296. int activeVdbeCnt; /* Number of VDBEs currently executing */
  9297. int writeVdbeCnt; /* Number of active VDBEs that are writing */
  9298. int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
  9299. void (*xTrace)(void*,const char*); /* Trace function */
  9300. void *pTraceArg; /* Argument to the trace function */
  9301. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  9302. void *pProfileArg; /* Argument to profile function */
  9303. void *pCommitArg; /* Argument to xCommitCallback() */
  9304. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  9305. void *pRollbackArg; /* Argument to xRollbackCallback() */
  9306. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  9307. void *pUpdateArg;
  9308. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  9309. #ifndef SQLITE_OMIT_WAL
  9310. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  9311. void *pWalArg;
  9312. #endif
  9313. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  9314. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  9315. void *pCollNeededArg;
  9316. sqlite3_value *pErr; /* Most recent error message */
  9317. char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
  9318. char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
  9319. union {
  9320. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  9321. double notUsed1; /* Spacer */
  9322. } u1;
  9323. Lookaside lookaside; /* Lookaside malloc configuration */
  9324. #ifndef SQLITE_OMIT_AUTHORIZATION
  9325. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  9326. /* Access authorization function */
  9327. void *pAuthArg; /* 1st argument to the access auth function */
  9328. #endif
  9329. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  9330. int (*xProgress)(void *); /* The progress callback */
  9331. void *pProgressArg; /* Argument to the progress callback */
  9332. int nProgressOps; /* Number of opcodes for progress callback */
  9333. #endif
  9334. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9335. Hash aModule; /* populated by sqlite3_create_module() */
  9336. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  9337. VTable **aVTrans; /* Virtual tables with open transactions */
  9338. int nVTrans; /* Allocated size of aVTrans */
  9339. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  9340. #endif
  9341. FuncDefHash aFunc; /* Hash table of connection functions */
  9342. Hash aCollSeq; /* All collating sequences */
  9343. BusyHandler busyHandler; /* Busy callback */
  9344. int busyTimeout; /* Busy handler timeout, in msec */
  9345. Db aDbStatic[2]; /* Static space for the 2 default backends */
  9346. Savepoint *pSavepoint; /* List of active savepoints */
  9347. int nSavepoint; /* Number of non-transaction savepoints */
  9348. int nStatement; /* Number of nested statement-transactions */
  9349. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  9350. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  9351. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  9352. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9353. /* The following variables are all protected by the STATIC_MASTER
  9354. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  9355. **
  9356. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  9357. ** unlock so that it can proceed.
  9358. **
  9359. ** When X.pBlockingConnection==Y, that means that something that X tried
  9360. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  9361. ** held by Y.
  9362. */
  9363. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  9364. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  9365. void *pUnlockArg; /* Argument to xUnlockNotify */
  9366. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  9367. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  9368. #endif
  9369. };
  9370. /*
  9371. ** A macro to discover the encoding of a database.
  9372. */
  9373. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  9374. /*
  9375. ** Possible values for the sqlite3.flags.
  9376. */
  9377. #define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */
  9378. #define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */
  9379. #define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */
  9380. #define SQLITE_ShortColNames 0x00000800 /* Show short columns names */
  9381. #define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */
  9382. /* DELETE, or UPDATE and return */
  9383. /* the count using a callback. */
  9384. #define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */
  9385. /* result set is empty */
  9386. #define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */
  9387. #define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */
  9388. #define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */
  9389. #define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when
  9390. ** accessing read-only databases */
  9391. #define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */
  9392. #define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */
  9393. #define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */
  9394. #define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */
  9395. #define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */
  9396. #define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */
  9397. #define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */
  9398. #define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */
  9399. #define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */
  9400. #define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */
  9401. #define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */
  9402. #define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */
  9403. #define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */
  9404. /*
  9405. ** Bits of the sqlite3.flags field that are used by the
  9406. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
  9407. ** These must be the low-order bits of the flags field.
  9408. */
  9409. #define SQLITE_QueryFlattener 0x01 /* Disable query flattening */
  9410. #define SQLITE_ColumnCache 0x02 /* Disable the column cache */
  9411. #define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */
  9412. #define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */
  9413. #define SQLITE_IndexCover 0x10 /* Disable index covering table */
  9414. #define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */
  9415. #define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */
  9416. #define SQLITE_IdxRealAsInt 0x80 /* Store REAL as INT in indices */
  9417. #define SQLITE_DistinctOpt 0x80 /* DISTINCT using indexes */
  9418. #define SQLITE_OptMask 0xff /* Mask of all disablable opts */
  9419. /*
  9420. ** Possible values for the sqlite.magic field.
  9421. ** The numbers are obtained at random and have no special meaning, other
  9422. ** than being distinct from one another.
  9423. */
  9424. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9425. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9426. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9427. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9428. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9429. /*
  9430. ** Each SQL function is defined by an instance of the following
  9431. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9432. ** hash table. When multiple functions have the same name, the hash table
  9433. ** points to a linked list of these structures.
  9434. */
  9435. struct FuncDef {
  9436. i16 nArg; /* Number of arguments. -1 means unlimited */
  9437. u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  9438. u8 flags; /* Some combination of SQLITE_FUNC_* */
  9439. void *pUserData; /* User data parameter */
  9440. FuncDef *pNext; /* Next function with same name */
  9441. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9442. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9443. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9444. char *zName; /* SQL name of the function. */
  9445. FuncDef *pHash; /* Next with a different name but the same hash */
  9446. FuncDestructor *pDestructor; /* Reference counted destructor function */
  9447. };
  9448. /*
  9449. ** This structure encapsulates a user-function destructor callback (as
  9450. ** configured using create_function_v2()) and a reference counter. When
  9451. ** create_function_v2() is called to create a function with a destructor,
  9452. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  9453. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  9454. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  9455. ** member of each of the new FuncDef objects is set to point to the allocated
  9456. ** FuncDestructor.
  9457. **
  9458. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  9459. ** count on this object is decremented. When it reaches 0, the destructor
  9460. ** is invoked and the FuncDestructor structure freed.
  9461. */
  9462. struct FuncDestructor {
  9463. int nRef;
  9464. void (*xDestroy)(void *);
  9465. void *pUserData;
  9466. };
  9467. /*
  9468. ** Possible values for FuncDef.flags
  9469. */
  9470. #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
  9471. #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
  9472. #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
  9473. #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
  9474. #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
  9475. #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
  9476. #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
  9477. /*
  9478. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9479. ** used to create the initializers for the FuncDef structures.
  9480. **
  9481. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9482. ** Used to create a scalar function definition of a function zName
  9483. ** implemented by C function xFunc that accepts nArg arguments. The
  9484. ** value passed as iArg is cast to a (void*) and made available
  9485. ** as the user-data (sqlite3_user_data()) for the function. If
  9486. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  9487. **
  9488. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9489. ** Used to create an aggregate function definition implemented by
  9490. ** the C functions xStep and xFinal. The first four parameters
  9491. ** are interpreted in the same way as the first 4 parameters to
  9492. ** FUNCTION().
  9493. **
  9494. ** LIKEFUNC(zName, nArg, pArg, flags)
  9495. ** Used to create a scalar function definition of a function zName
  9496. ** that accepts nArg arguments and is implemented by a call to C
  9497. ** function likeFunc. Argument pArg is cast to a (void *) and made
  9498. ** available as the function user-data (sqlite3_user_data()). The
  9499. ** FuncDef.flags variable is set to the value passed as the flags
  9500. ** parameter.
  9501. */
  9502. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  9503. {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
  9504. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9505. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  9506. {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
  9507. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  9508. #define LIKEFUNC(zName, nArg, arg, flags) \
  9509. {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  9510. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  9511. {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
  9512. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  9513. /*
  9514. ** All current savepoints are stored in a linked list starting at
  9515. ** sqlite3.pSavepoint. The first element in the list is the most recently
  9516. ** opened savepoint. Savepoints are added to the list by the vdbe
  9517. ** OP_Savepoint instruction.
  9518. */
  9519. struct Savepoint {
  9520. char *zName; /* Savepoint name (nul-terminated) */
  9521. i64 nDeferredCons; /* Number of deferred fk violations */
  9522. Savepoint *pNext; /* Parent savepoint (if any) */
  9523. };
  9524. /*
  9525. ** The following are used as the second parameter to sqlite3Savepoint(),
  9526. ** and as the P1 argument to the OP_Savepoint instruction.
  9527. */
  9528. #define SAVEPOINT_BEGIN 0
  9529. #define SAVEPOINT_RELEASE 1
  9530. #define SAVEPOINT_ROLLBACK 2
  9531. /*
  9532. ** Each SQLite module (virtual table definition) is defined by an
  9533. ** instance of the following structure, stored in the sqlite3.aModule
  9534. ** hash table.
  9535. */
  9536. struct Module {
  9537. const sqlite3_module *pModule; /* Callback pointers */
  9538. const char *zName; /* Name passed to create_module() */
  9539. void *pAux; /* pAux passed to create_module() */
  9540. void (*xDestroy)(void *); /* Module destructor function */
  9541. };
  9542. /*
  9543. ** information about each column of an SQL table is held in an instance
  9544. ** of this structure.
  9545. */
  9546. struct Column {
  9547. char *zName; /* Name of this column */
  9548. Expr *pDflt; /* Default value of this column */
  9549. char *zDflt; /* Original text of the default value */
  9550. char *zType; /* Data type for this column */
  9551. char *zColl; /* Collating sequence. If NULL, use the default */
  9552. u8 notNull; /* True if there is a NOT NULL constraint */
  9553. u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
  9554. char affinity; /* One of the SQLITE_AFF_... values */
  9555. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9556. u8 isHidden; /* True if this column is 'hidden' */
  9557. #endif
  9558. };
  9559. /*
  9560. ** A "Collating Sequence" is defined by an instance of the following
  9561. ** structure. Conceptually, a collating sequence consists of a name and
  9562. ** a comparison routine that defines the order of that sequence.
  9563. **
  9564. ** There may two separate implementations of the collation function, one
  9565. ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
  9566. ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
  9567. ** native byte order. When a collation sequence is invoked, SQLite selects
  9568. ** the version that will require the least expensive encoding
  9569. ** translations, if any.
  9570. **
  9571. ** The CollSeq.pUser member variable is an extra parameter that passed in
  9572. ** as the first argument to the UTF-8 comparison function, xCmp.
  9573. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
  9574. ** xCmp16.
  9575. **
  9576. ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
  9577. ** collating sequence is undefined. Indices built on an undefined
  9578. ** collating sequence may not be read or written.
  9579. */
  9580. struct CollSeq {
  9581. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  9582. u8 enc; /* Text encoding handled by xCmp() */
  9583. void *pUser; /* First argument to xCmp() */
  9584. int (*xCmp)(void*,int, const void*, int, const void*);
  9585. void (*xDel)(void*); /* Destructor for pUser */
  9586. };
  9587. /*
  9588. ** A sort order can be either ASC or DESC.
  9589. */
  9590. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  9591. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  9592. /*
  9593. ** Column affinity types.
  9594. **
  9595. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  9596. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  9597. ** the speed a little by numbering the values consecutively.
  9598. **
  9599. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  9600. ** when multiple affinity types are concatenated into a string and
  9601. ** used as the P4 operand, they will be more readable.
  9602. **
  9603. ** Note also that the numeric types are grouped together so that testing
  9604. ** for a numeric type is a single comparison.
  9605. */
  9606. #define SQLITE_AFF_TEXT 'a'
  9607. #define SQLITE_AFF_NONE 'b'
  9608. #define SQLITE_AFF_NUMERIC 'c'
  9609. #define SQLITE_AFF_INTEGER 'd'
  9610. #define SQLITE_AFF_REAL 'e'
  9611. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  9612. /*
  9613. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  9614. ** affinity value.
  9615. */
  9616. #define SQLITE_AFF_MASK 0x67
  9617. /*
  9618. ** Additional bit values that can be ORed with an affinity without
  9619. ** changing the affinity.
  9620. */
  9621. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  9622. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  9623. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  9624. /*
  9625. ** An object of this type is created for each virtual table present in
  9626. ** the database schema.
  9627. **
  9628. ** If the database schema is shared, then there is one instance of this
  9629. ** structure for each database connection (sqlite3*) that uses the shared
  9630. ** schema. This is because each database connection requires its own unique
  9631. ** instance of the sqlite3_vtab* handle used to access the virtual table
  9632. ** implementation. sqlite3_vtab* handles can not be shared between
  9633. ** database connections, even when the rest of the in-memory database
  9634. ** schema is shared, as the implementation often stores the database
  9635. ** connection handle passed to it via the xConnect() or xCreate() method
  9636. ** during initialization internally. This database connection handle may
  9637. ** then be used by the virtual table implementation to access real tables
  9638. ** within the database. So that they appear as part of the callers
  9639. ** transaction, these accesses need to be made via the same database
  9640. ** connection as that used to execute SQL operations on the virtual table.
  9641. **
  9642. ** All VTable objects that correspond to a single table in a shared
  9643. ** database schema are initially stored in a linked-list pointed to by
  9644. ** the Table.pVTable member variable of the corresponding Table object.
  9645. ** When an sqlite3_prepare() operation is required to access the virtual
  9646. ** table, it searches the list for the VTable that corresponds to the
  9647. ** database connection doing the preparing so as to use the correct
  9648. ** sqlite3_vtab* handle in the compiled query.
  9649. **
  9650. ** When an in-memory Table object is deleted (for example when the
  9651. ** schema is being reloaded for some reason), the VTable objects are not
  9652. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  9653. ** immediately. Instead, they are moved from the Table.pVTable list to
  9654. ** another linked list headed by the sqlite3.pDisconnect member of the
  9655. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  9656. ** next time a statement is prepared using said sqlite3*. This is done
  9657. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  9658. ** Refer to comments above function sqlite3VtabUnlockList() for an
  9659. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  9660. ** list without holding the corresponding sqlite3.mutex mutex.
  9661. **
  9662. ** The memory for objects of this type is always allocated by
  9663. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  9664. ** the first argument.
  9665. */
  9666. struct VTable {
  9667. sqlite3 *db; /* Database connection associated with this table */
  9668. Module *pMod; /* Pointer to module implementation */
  9669. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  9670. int nRef; /* Number of pointers to this structure */
  9671. u8 bConstraint; /* True if constraints are supported */
  9672. int iSavepoint; /* Depth of the SAVEPOINT stack */
  9673. VTable *pNext; /* Next in linked list (see above) */
  9674. };
  9675. /*
  9676. ** Each SQL table is represented in memory by an instance of the
  9677. ** following structure.
  9678. **
  9679. ** Table.zName is the name of the table. The case of the original
  9680. ** CREATE TABLE statement is stored, but case is not significant for
  9681. ** comparisons.
  9682. **
  9683. ** Table.nCol is the number of columns in this table. Table.aCol is a
  9684. ** pointer to an array of Column structures, one for each column.
  9685. **
  9686. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  9687. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  9688. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  9689. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  9690. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  9691. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  9692. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  9693. **
  9694. ** Table.tnum is the page number for the root BTree page of the table in the
  9695. ** database file. If Table.iDb is the index of the database table backend
  9696. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  9697. ** holds temporary tables and indices. If TF_Ephemeral is set
  9698. ** then the table is stored in a file that is automatically deleted
  9699. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  9700. ** refers VDBE cursor number that holds the table open, not to the root
  9701. ** page number. Transient tables are used to hold the results of a
  9702. ** sub-query that appears instead of a real table name in the FROM clause
  9703. ** of a SELECT statement.
  9704. */
  9705. struct Table {
  9706. char *zName; /* Name of the table or view */
  9707. int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  9708. int nCol; /* Number of columns in this table */
  9709. Column *aCol; /* Information about each column */
  9710. Index *pIndex; /* List of SQL indexes on this table. */
  9711. int tnum; /* Root BTree node for this table (see note above) */
  9712. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  9713. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  9714. u16 nRef; /* Number of pointers to this Table */
  9715. u8 tabFlags; /* Mask of TF_* values */
  9716. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  9717. FKey *pFKey; /* Linked list of all foreign keys in this table */
  9718. char *zColAff; /* String defining the affinity of each column */
  9719. #ifndef SQLITE_OMIT_CHECK
  9720. Expr *pCheck; /* The AND of all CHECK constraints */
  9721. #endif
  9722. #ifndef SQLITE_OMIT_ALTERTABLE
  9723. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  9724. #endif
  9725. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9726. VTable *pVTable; /* List of VTable objects. */
  9727. int nModuleArg; /* Number of arguments to the module */
  9728. char **azModuleArg; /* Text of all module args. [0] is module name */
  9729. #endif
  9730. Trigger *pTrigger; /* List of triggers stored in pSchema */
  9731. Schema *pSchema; /* Schema that contains this table */
  9732. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  9733. };
  9734. /*
  9735. ** Allowed values for Tabe.tabFlags.
  9736. */
  9737. #define TF_Readonly 0x01 /* Read-only system table */
  9738. #define TF_Ephemeral 0x02 /* An ephemeral table */
  9739. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  9740. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  9741. #define TF_Virtual 0x10 /* Is a virtual table */
  9742. #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
  9743. /*
  9744. ** Test to see whether or not a table is a virtual table. This is
  9745. ** done as a macro so that it will be optimized out when virtual
  9746. ** table support is omitted from the build.
  9747. */
  9748. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9749. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  9750. # define IsHiddenColumn(X) ((X)->isHidden)
  9751. #else
  9752. # define IsVirtual(X) 0
  9753. # define IsHiddenColumn(X) 0
  9754. #endif
  9755. /*
  9756. ** Each foreign key constraint is an instance of the following structure.
  9757. **
  9758. ** A foreign key is associated with two tables. The "from" table is
  9759. ** the table that contains the REFERENCES clause that creates the foreign
  9760. ** key. The "to" table is the table that is named in the REFERENCES clause.
  9761. ** Consider this example:
  9762. **
  9763. ** CREATE TABLE ex1(
  9764. ** a INTEGER PRIMARY KEY,
  9765. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  9766. ** );
  9767. **
  9768. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  9769. **
  9770. ** Each REFERENCES clause generates an instance of the following structure
  9771. ** which is attached to the from-table. The to-table need not exist when
  9772. ** the from-table is created. The existence of the to-table is not checked.
  9773. */
  9774. struct FKey {
  9775. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  9776. FKey *pNextFrom; /* Next foreign key in pFrom */
  9777. char *zTo; /* Name of table that the key points to (aka: Parent) */
  9778. FKey *pNextTo; /* Next foreign key on table named zTo */
  9779. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  9780. int nCol; /* Number of columns in this key */
  9781. /* EV: R-30323-21917 */
  9782. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  9783. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  9784. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  9785. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  9786. int iFrom; /* Index of column in pFrom */
  9787. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  9788. } aCol[1]; /* One entry for each of nCol column s */
  9789. };
  9790. /*
  9791. ** SQLite supports many different ways to resolve a constraint
  9792. ** error. ROLLBACK processing means that a constraint violation
  9793. ** causes the operation in process to fail and for the current transaction
  9794. ** to be rolled back. ABORT processing means the operation in process
  9795. ** fails and any prior changes from that one operation are backed out,
  9796. ** but the transaction is not rolled back. FAIL processing means that
  9797. ** the operation in progress stops and returns an error code. But prior
  9798. ** changes due to the same operation are not backed out and no rollback
  9799. ** occurs. IGNORE means that the particular row that caused the constraint
  9800. ** error is not inserted or updated. Processing continues and no error
  9801. ** is returned. REPLACE means that preexisting database rows that caused
  9802. ** a UNIQUE constraint violation are removed so that the new insert or
  9803. ** update can proceed. Processing continues and no error is reported.
  9804. **
  9805. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  9806. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  9807. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  9808. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  9809. ** referenced table row is propagated into the row that holds the
  9810. ** foreign key.
  9811. **
  9812. ** The following symbolic values are used to record which type
  9813. ** of action to take.
  9814. */
  9815. #define OE_None 0 /* There is no constraint to check */
  9816. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  9817. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  9818. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  9819. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  9820. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  9821. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  9822. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  9823. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  9824. #define OE_Cascade 9 /* Cascade the changes */
  9825. #define OE_Default 99 /* Do whatever the default action is */
  9826. /*
  9827. ** An instance of the following structure is passed as the first
  9828. ** argument to sqlite3VdbeKeyCompare and is used to control the
  9829. ** comparison of the two index keys.
  9830. */
  9831. struct KeyInfo {
  9832. sqlite3 *db; /* The database connection */
  9833. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  9834. u16 nField; /* Number of entries in aColl[] */
  9835. u8 *aSortOrder; /* Sort order for each column. May be NULL */
  9836. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  9837. };
  9838. /*
  9839. ** An instance of the following structure holds information about a
  9840. ** single index record that has already been parsed out into individual
  9841. ** values.
  9842. **
  9843. ** A record is an object that contains one or more fields of data.
  9844. ** Records are used to store the content of a table row and to store
  9845. ** the key of an index. A blob encoding of a record is created by
  9846. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  9847. ** OP_Column opcode.
  9848. **
  9849. ** This structure holds a record that has already been disassembled
  9850. ** into its constituent fields.
  9851. */
  9852. struct UnpackedRecord {
  9853. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  9854. u16 nField; /* Number of entries in apMem[] */
  9855. u8 flags; /* Boolean settings. UNPACKED_... below */
  9856. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  9857. Mem *aMem; /* Values */
  9858. };
  9859. /*
  9860. ** Allowed values of UnpackedRecord.flags
  9861. */
  9862. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  9863. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  9864. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  9865. /*
  9866. ** Each SQL index is represented in memory by an
  9867. ** instance of the following structure.
  9868. **
  9869. ** The columns of the table that are to be indexed are described
  9870. ** by the aiColumn[] field of this structure. For example, suppose
  9871. ** we have the following table and index:
  9872. **
  9873. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  9874. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  9875. **
  9876. ** In the Table structure describing Ex1, nCol==3 because there are
  9877. ** three columns in the table. In the Index structure describing
  9878. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  9879. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  9880. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  9881. ** The second column to be indexed (c1) has an index of 0 in
  9882. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  9883. **
  9884. ** The Index.onError field determines whether or not the indexed columns
  9885. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  9886. ** it means this is not a unique index. Otherwise it is a unique index
  9887. ** and the value of Index.onError indicate the which conflict resolution
  9888. ** algorithm to employ whenever an attempt is made to insert a non-unique
  9889. ** element.
  9890. */
  9891. struct Index {
  9892. char *zName; /* Name of this index */
  9893. int nColumn; /* Number of columns in the table used by this index */
  9894. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  9895. tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  9896. Table *pTable; /* The SQL table being indexed */
  9897. int tnum; /* Page containing root of this index in database file */
  9898. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  9899. u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
  9900. u8 bUnordered; /* Use this index for == or IN queries only */
  9901. char *zColAff; /* String defining the affinity of each column */
  9902. Index *pNext; /* The next index associated with the same table */
  9903. Schema *pSchema; /* Schema containing this index */
  9904. u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
  9905. char **azColl; /* Array of collation sequence names for index */
  9906. #ifdef SQLITE_ENABLE_STAT3
  9907. int nSample; /* Number of elements in aSample[] */
  9908. tRowcnt avgEq; /* Average nEq value for key values not in aSample */
  9909. IndexSample *aSample; /* Samples of the left-most key */
  9910. #endif
  9911. };
  9912. /*
  9913. ** Each sample stored in the sqlite_stat3 table is represented in memory
  9914. ** using a structure of this type. See documentation at the top of the
  9915. ** analyze.c source file for additional information.
  9916. */
  9917. struct IndexSample {
  9918. union {
  9919. char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
  9920. double r; /* Value if eType is SQLITE_FLOAT */
  9921. i64 i; /* Value if eType is SQLITE_INTEGER */
  9922. } u;
  9923. u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
  9924. int nByte; /* Size in byte of text or blob. */
  9925. tRowcnt nEq; /* Est. number of rows where the key equals this sample */
  9926. tRowcnt nLt; /* Est. number of rows where key is less than this sample */
  9927. tRowcnt nDLt; /* Est. number of distinct keys less than this sample */
  9928. };
  9929. /*
  9930. ** Each token coming out of the lexer is an instance of
  9931. ** this structure. Tokens are also used as part of an expression.
  9932. **
  9933. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  9934. ** may contain random values. Do not make any assumptions about Token.dyn
  9935. ** and Token.n when Token.z==0.
  9936. */
  9937. struct Token {
  9938. const char *z; /* Text of the token. Not NULL-terminated! */
  9939. unsigned int n; /* Number of characters in this token */
  9940. };
  9941. /*
  9942. ** An instance of this structure contains information needed to generate
  9943. ** code for a SELECT that contains aggregate functions.
  9944. **
  9945. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  9946. ** pointer to this structure. The Expr.iColumn field is the index in
  9947. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  9948. ** code for that node.
  9949. **
  9950. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  9951. ** original Select structure that describes the SELECT statement. These
  9952. ** fields do not need to be freed when deallocating the AggInfo structure.
  9953. */
  9954. struct AggInfo {
  9955. u8 directMode; /* Direct rendering mode means take data directly
  9956. ** from source tables rather than from accumulators */
  9957. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  9958. ** than the source table */
  9959. int sortingIdx; /* Cursor number of the sorting index */
  9960. int sortingIdxPTab; /* Cursor number of pseudo-table */
  9961. ExprList *pGroupBy; /* The group by clause */
  9962. int nSortingColumn; /* Number of columns in the sorting index */
  9963. struct AggInfo_col { /* For each column used in source tables */
  9964. Table *pTab; /* Source table */
  9965. int iTable; /* Cursor number of the source table */
  9966. int iColumn; /* Column number within the source table */
  9967. int iSorterColumn; /* Column number in the sorting index */
  9968. int iMem; /* Memory location that acts as accumulator */
  9969. Expr *pExpr; /* The original expression */
  9970. } *aCol;
  9971. int nColumn; /* Number of used entries in aCol[] */
  9972. int nColumnAlloc; /* Number of slots allocated for aCol[] */
  9973. int nAccumulator; /* Number of columns that show through to the output.
  9974. ** Additional columns are used only as parameters to
  9975. ** aggregate functions */
  9976. struct AggInfo_func { /* For each aggregate function */
  9977. Expr *pExpr; /* Expression encoding the function */
  9978. FuncDef *pFunc; /* The aggregate function implementation */
  9979. int iMem; /* Memory location that acts as accumulator */
  9980. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  9981. } *aFunc;
  9982. int nFunc; /* Number of entries in aFunc[] */
  9983. int nFuncAlloc; /* Number of slots allocated for aFunc[] */
  9984. };
  9985. /*
  9986. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  9987. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  9988. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  9989. ** it uses less memory in the Expr object, which is a big memory user
  9990. ** in systems with lots of prepared statements. And few applications
  9991. ** need more than about 10 or 20 variables. But some extreme users want
  9992. ** to have prepared statements with over 32767 variables, and for them
  9993. ** the option is available (at compile-time).
  9994. */
  9995. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  9996. typedef i16 ynVar;
  9997. #else
  9998. typedef int ynVar;
  9999. #endif
  10000. /*
  10001. ** Each node of an expression in the parse tree is an instance
  10002. ** of this structure.
  10003. **
  10004. ** Expr.op is the opcode. The integer parser token codes are reused
  10005. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10006. ** code representing the ">=" operator. This same integer code is reused
  10007. ** to represent the greater-than-or-equal-to operator in the expression
  10008. ** tree.
  10009. **
  10010. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10011. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10012. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10013. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10014. ** then Expr.token contains the name of the function.
  10015. **
  10016. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10017. ** binary operator. Either or both may be NULL.
  10018. **
  10019. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10020. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10021. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10022. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10023. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10024. ** valid.
  10025. **
  10026. ** An expression of the form ID or ID.ID refers to a column in a table.
  10027. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10028. ** the integer cursor number of a VDBE cursor pointing to that table and
  10029. ** Expr.iColumn is the column number for the specific column. If the
  10030. ** expression is used as a result in an aggregate SELECT, then the
  10031. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10032. ** it can be accessed after all aggregates are computed.
  10033. **
  10034. ** If the expression is an unbound variable marker (a question mark
  10035. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10036. ** number for that variable.
  10037. **
  10038. ** If the expression is a subquery then Expr.iColumn holds an integer
  10039. ** register number containing the result of the subquery. If the
  10040. ** subquery gives a constant result, then iTable is -1. If the subquery
  10041. ** gives a different answer at different times during statement processing
  10042. ** then iTable is the address of a subroutine that computes the subquery.
  10043. **
  10044. ** If the Expr is of type OP_Column, and the table it is selecting from
  10045. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10046. ** corresponding table definition.
  10047. **
  10048. ** ALLOCATION NOTES:
  10049. **
  10050. ** Expr objects can use a lot of memory space in database schema. To
  10051. ** help reduce memory requirements, sometimes an Expr object will be
  10052. ** truncated. And to reduce the number of memory allocations, sometimes
  10053. ** two or more Expr objects will be stored in a single memory allocation,
  10054. ** together with Expr.zToken strings.
  10055. **
  10056. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10057. ** an Expr object is truncated. When EP_Reduced is set, then all
  10058. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  10059. ** are contained within the same memory allocation. Note, however, that
  10060. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  10061. ** allocated, regardless of whether or not EP_Reduced is set.
  10062. */
  10063. struct Expr {
  10064. u8 op; /* Operation performed by this node */
  10065. char affinity; /* The affinity of the column or 0 if not a column */
  10066. u16 flags; /* Various flags. EP_* See below */
  10067. union {
  10068. char *zToken; /* Token value. Zero terminated and dequoted */
  10069. int iValue; /* Non-negative integer value if EP_IntValue */
  10070. } u;
  10071. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  10072. ** space is allocated for the fields below this point. An attempt to
  10073. ** access them will result in a segfault or malfunction.
  10074. *********************************************************************/
  10075. Expr *pLeft; /* Left subnode */
  10076. Expr *pRight; /* Right subnode */
  10077. union {
  10078. ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
  10079. Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
  10080. } x;
  10081. CollSeq *pColl; /* The collation type of the column or 0 */
  10082. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  10083. ** space is allocated for the fields below this point. An attempt to
  10084. ** access them will result in a segfault or malfunction.
  10085. *********************************************************************/
  10086. int iTable; /* TK_COLUMN: cursor number of table holding column
  10087. ** TK_REGISTER: register number
  10088. ** TK_TRIGGER: 1 -> new, 0 -> old */
  10089. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  10090. ** TK_VARIABLE: variable number (always >= 1). */
  10091. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  10092. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  10093. u8 flags2; /* Second set of flags. EP2_... */
  10094. u8 op2; /* If a TK_REGISTER, the original value of Expr.op */
  10095. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  10096. Table *pTab; /* Table for TK_COLUMN expressions. */
  10097. #if SQLITE_MAX_EXPR_DEPTH>0
  10098. int nHeight; /* Height of the tree headed by this node */
  10099. #endif
  10100. };
  10101. /*
  10102. ** The following are the meanings of bits in the Expr.flags field.
  10103. */
  10104. #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  10105. #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
  10106. #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
  10107. #define EP_Error 0x0008 /* Expression contains one or more errors */
  10108. #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
  10109. #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
  10110. #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
  10111. #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
  10112. #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
  10113. #define EP_FixedDest 0x0200 /* Result needed in a specific register */
  10114. #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
  10115. #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
  10116. #define EP_Hint 0x1000 /* Optimizer hint. Not required for correctness */
  10117. #define EP_Reduced 0x2000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
  10118. #define EP_TokenOnly 0x4000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
  10119. #define EP_Static 0x8000 /* Held in memory not obtained from malloc() */
  10120. /*
  10121. ** The following are the meanings of bits in the Expr.flags2 field.
  10122. */
  10123. #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
  10124. #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
  10125. /*
  10126. ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
  10127. ** flag on an expression structure. This flag is used for VV&A only. The
  10128. ** routine is implemented as a macro that only works when in debugging mode,
  10129. ** so as not to burden production code.
  10130. */
  10131. #ifdef SQLITE_DEBUG
  10132. # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
  10133. #else
  10134. # define ExprSetIrreducible(X)
  10135. #endif
  10136. /*
  10137. ** These macros can be used to test, set, or clear bits in the
  10138. ** Expr.flags field.
  10139. */
  10140. #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  10141. #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  10142. #define ExprSetProperty(E,P) (E)->flags|=(P)
  10143. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  10144. /*
  10145. ** Macros to determine the number of bytes required by a normal Expr
  10146. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  10147. ** and an Expr struct with the EP_TokenOnly flag set.
  10148. */
  10149. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  10150. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  10151. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  10152. /*
  10153. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  10154. ** above sqlite3ExprDup() for details.
  10155. */
  10156. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  10157. /*
  10158. ** A list of expressions. Each expression may optionally have a
  10159. ** name. An expr/name combination can be used in several ways, such
  10160. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  10161. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  10162. ** also be used as the argument to a function, in which case the a.zName
  10163. ** field is not used.
  10164. */
  10165. struct ExprList {
  10166. int nExpr; /* Number of expressions on the list */
  10167. int nAlloc; /* Number of entries allocated below */
  10168. int iECursor; /* VDBE Cursor associated with this ExprList */
  10169. struct ExprList_item {
  10170. Expr *pExpr; /* The list of expressions */
  10171. char *zName; /* Token associated with this expression */
  10172. char *zSpan; /* Original text of the expression */
  10173. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  10174. u8 done; /* A flag to indicate when processing is finished */
  10175. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  10176. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  10177. } *a; /* One entry for each expression */
  10178. };
  10179. /*
  10180. ** An instance of this structure is used by the parser to record both
  10181. ** the parse tree for an expression and the span of input text for an
  10182. ** expression.
  10183. */
  10184. struct ExprSpan {
  10185. Expr *pExpr; /* The expression parse tree */
  10186. const char *zStart; /* First character of input text */
  10187. const char *zEnd; /* One character past the end of input text */
  10188. };
  10189. /*
  10190. ** An instance of this structure can hold a simple list of identifiers,
  10191. ** such as the list "a,b,c" in the following statements:
  10192. **
  10193. ** INSERT INTO t(a,b,c) VALUES ...;
  10194. ** CREATE INDEX idx ON t(a,b,c);
  10195. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  10196. **
  10197. ** The IdList.a.idx field is used when the IdList represents the list of
  10198. ** column names after a table name in an INSERT statement. In the statement
  10199. **
  10200. ** INSERT INTO t(a,b,c) ...
  10201. **
  10202. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  10203. */
  10204. struct IdList {
  10205. struct IdList_item {
  10206. char *zName; /* Name of the identifier */
  10207. int idx; /* Index in some Table.aCol[] of a column named zName */
  10208. } *a;
  10209. int nId; /* Number of identifiers on the list */
  10210. int nAlloc; /* Number of entries allocated for a[] below */
  10211. };
  10212. /*
  10213. ** The bitmask datatype defined below is used for various optimizations.
  10214. **
  10215. ** Changing this from a 64-bit to a 32-bit type limits the number of
  10216. ** tables in a join to 32 instead of 64. But it also reduces the size
  10217. ** of the library by 738 bytes on ix86.
  10218. */
  10219. typedef u64 Bitmask;
  10220. /*
  10221. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  10222. */
  10223. #define BMS ((int)(sizeof(Bitmask)*8))
  10224. /*
  10225. ** The following structure describes the FROM clause of a SELECT statement.
  10226. ** Each table or subquery in the FROM clause is a separate element of
  10227. ** the SrcList.a[] array.
  10228. **
  10229. ** With the addition of multiple database support, the following structure
  10230. ** can also be used to describe a particular table such as the table that
  10231. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  10232. ** such a table must be a simple name: ID. But in SQLite, the table can
  10233. ** now be identified by a database name, a dot, then the table name: ID.ID.
  10234. **
  10235. ** The jointype starts out showing the join type between the current table
  10236. ** and the next table on the list. The parser builds the list this way.
  10237. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  10238. ** jointype expresses the join between the table and the previous table.
  10239. **
  10240. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  10241. ** contains more than 63 columns and the 64-th or later column is used.
  10242. */
  10243. struct SrcList {
  10244. i16 nSrc; /* Number of tables or subqueries in the FROM clause */
  10245. i16 nAlloc; /* Number of entries allocated in a[] below */
  10246. struct SrcList_item {
  10247. char *zDatabase; /* Name of database holding this table */
  10248. char *zName; /* Name of the table */
  10249. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  10250. Table *pTab; /* An SQL table corresponding to zName */
  10251. Select *pSelect; /* A SELECT statement used in place of a table name */
  10252. int addrFillSub; /* Address of subroutine to manifest a subquery */
  10253. int regReturn; /* Register holding return address of addrFillSub */
  10254. u8 jointype; /* Type of join between this able and the previous */
  10255. u8 notIndexed; /* True if there is a NOT INDEXED clause */
  10256. u8 isCorrelated; /* True if sub-query is correlated */
  10257. #ifndef SQLITE_OMIT_EXPLAIN
  10258. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  10259. #endif
  10260. int iCursor; /* The VDBE cursor number used to access this table */
  10261. Expr *pOn; /* The ON clause of a join */
  10262. IdList *pUsing; /* The USING clause of a join */
  10263. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  10264. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  10265. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  10266. } a[1]; /* One entry for each identifier on the list */
  10267. };
  10268. /*
  10269. ** Permitted values of the SrcList.a.jointype field
  10270. */
  10271. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  10272. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  10273. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  10274. #define JT_LEFT 0x0008 /* Left outer join */
  10275. #define JT_RIGHT 0x0010 /* Right outer join */
  10276. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  10277. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  10278. /*
  10279. ** A WherePlan object holds information that describes a lookup
  10280. ** strategy.
  10281. **
  10282. ** This object is intended to be opaque outside of the where.c module.
  10283. ** It is included here only so that that compiler will know how big it
  10284. ** is. None of the fields in this object should be used outside of
  10285. ** the where.c module.
  10286. **
  10287. ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
  10288. ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
  10289. ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
  10290. ** case that more than one of these conditions is true.
  10291. */
  10292. struct WherePlan {
  10293. u32 wsFlags; /* WHERE_* flags that describe the strategy */
  10294. u32 nEq; /* Number of == constraints */
  10295. double nRow; /* Estimated number of rows (for EQP) */
  10296. union {
  10297. Index *pIdx; /* Index when WHERE_INDEXED is true */
  10298. struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
  10299. sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
  10300. } u;
  10301. };
  10302. /*
  10303. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  10304. ** structure contains a single instance of this structure. This structure
  10305. ** is intended to be private the the where.c module and should not be
  10306. ** access or modified by other modules.
  10307. **
  10308. ** The pIdxInfo field is used to help pick the best index on a
  10309. ** virtual table. The pIdxInfo pointer contains indexing
  10310. ** information for the i-th table in the FROM clause before reordering.
  10311. ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
  10312. ** All other information in the i-th WhereLevel object for the i-th table
  10313. ** after FROM clause ordering.
  10314. */
  10315. struct WhereLevel {
  10316. WherePlan plan; /* query plan for this element of the FROM clause */
  10317. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  10318. int iTabCur; /* The VDBE cursor used to access the table */
  10319. int iIdxCur; /* The VDBE cursor used to access pIdx */
  10320. int addrBrk; /* Jump here to break out of the loop */
  10321. int addrNxt; /* Jump here to start the next IN combination */
  10322. int addrCont; /* Jump here to continue with the next loop cycle */
  10323. int addrFirst; /* First instruction of interior of the loop */
  10324. u8 iFrom; /* Which entry in the FROM clause */
  10325. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  10326. int p1, p2; /* Operands of the opcode used to ends the loop */
  10327. union { /* Information that depends on plan.wsFlags */
  10328. struct {
  10329. int nIn; /* Number of entries in aInLoop[] */
  10330. struct InLoop {
  10331. int iCur; /* The VDBE cursor used by this IN operator */
  10332. int addrInTop; /* Top of the IN loop */
  10333. } *aInLoop; /* Information about each nested IN operator */
  10334. } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
  10335. } u;
  10336. /* The following field is really not part of the current level. But
  10337. ** we need a place to cache virtual table index information for each
  10338. ** virtual table in the FROM clause and the WhereLevel structure is
  10339. ** a convenient place since there is one WhereLevel for each FROM clause
  10340. ** element.
  10341. */
  10342. sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
  10343. };
  10344. /*
  10345. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  10346. ** and the WhereInfo.wctrlFlags member.
  10347. */
  10348. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  10349. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  10350. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  10351. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  10352. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  10353. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  10354. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  10355. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  10356. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  10357. /*
  10358. ** The WHERE clause processing routine has two halves. The
  10359. ** first part does the start of the WHERE loop and the second
  10360. ** half does the tail of the WHERE loop. An instance of
  10361. ** this structure is returned by the first half and passed
  10362. ** into the second half to give some continuity.
  10363. */
  10364. struct WhereInfo {
  10365. Parse *pParse; /* Parsing and code generating context */
  10366. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  10367. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
  10368. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  10369. u8 eDistinct;
  10370. SrcList *pTabList; /* List of tables in the join */
  10371. int iTop; /* The very beginning of the WHERE loop */
  10372. int iContinue; /* Jump here to continue with next record */
  10373. int iBreak; /* Jump here to break out of the loop */
  10374. int nLevel; /* Number of nested loop */
  10375. struct WhereClause *pWC; /* Decomposition of the WHERE clause */
  10376. double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  10377. double nRowOut; /* Estimated number of output rows */
  10378. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  10379. };
  10380. #define WHERE_DISTINCT_UNIQUE 1
  10381. #define WHERE_DISTINCT_ORDERED 2
  10382. /*
  10383. ** A NameContext defines a context in which to resolve table and column
  10384. ** names. The context consists of a list of tables (the pSrcList) field and
  10385. ** a list of named expression (pEList). The named expression list may
  10386. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  10387. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  10388. ** pEList corresponds to the result set of a SELECT and is NULL for
  10389. ** other statements.
  10390. **
  10391. ** NameContexts can be nested. When resolving names, the inner-most
  10392. ** context is searched first. If no match is found, the next outer
  10393. ** context is checked. If there is still no match, the next context
  10394. ** is checked. This process continues until either a match is found
  10395. ** or all contexts are check. When a match is found, the nRef member of
  10396. ** the context containing the match is incremented.
  10397. **
  10398. ** Each subquery gets a new NameContext. The pNext field points to the
  10399. ** NameContext in the parent query. Thus the process of scanning the
  10400. ** NameContext list corresponds to searching through successively outer
  10401. ** subqueries looking for a match.
  10402. */
  10403. struct NameContext {
  10404. Parse *pParse; /* The parser */
  10405. SrcList *pSrcList; /* One or more tables used to resolve names */
  10406. ExprList *pEList; /* Optional list of named expressions */
  10407. int nRef; /* Number of names resolved by this context */
  10408. int nErr; /* Number of errors encountered while resolving names */
  10409. u8 allowAgg; /* Aggregate functions allowed here */
  10410. u8 hasAgg; /* True if aggregates are seen */
  10411. u8 isCheck; /* True if resolving names in a CHECK constraint */
  10412. int nDepth; /* Depth of subquery recursion. 1 for no recursion */
  10413. AggInfo *pAggInfo; /* Information about aggregates at this level */
  10414. NameContext *pNext; /* Next outer name context. NULL for outermost */
  10415. };
  10416. /*
  10417. ** An instance of the following structure contains all information
  10418. ** needed to generate code for a single SELECT statement.
  10419. **
  10420. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  10421. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  10422. ** limit and nOffset to the value of the offset (or 0 if there is not
  10423. ** offset). But later on, nLimit and nOffset become the memory locations
  10424. ** in the VDBE that record the limit and offset counters.
  10425. **
  10426. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  10427. ** These addresses must be stored so that we can go back and fill in
  10428. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  10429. ** the number of columns in P2 can be computed at the same time
  10430. ** as the OP_OpenEphm instruction is coded because not
  10431. ** enough information about the compound query is known at that point.
  10432. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  10433. ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
  10434. ** sequences for the ORDER BY clause.
  10435. */
  10436. struct Select {
  10437. ExprList *pEList; /* The fields of the result */
  10438. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  10439. char affinity; /* MakeRecord with this affinity for SRT_Set */
  10440. u16 selFlags; /* Various SF_* values */
  10441. SrcList *pSrc; /* The FROM clause */
  10442. Expr *pWhere; /* The WHERE clause */
  10443. ExprList *pGroupBy; /* The GROUP BY clause */
  10444. Expr *pHaving; /* The HAVING clause */
  10445. ExprList *pOrderBy; /* The ORDER BY clause */
  10446. Select *pPrior; /* Prior select in a compound select statement */
  10447. Select *pNext; /* Next select to the left in a compound */
  10448. Select *pRightmost; /* Right-most select in a compound select statement */
  10449. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  10450. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  10451. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  10452. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  10453. double nSelectRow; /* Estimated number of result rows */
  10454. };
  10455. /*
  10456. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  10457. ** "Select Flag".
  10458. */
  10459. #define SF_Distinct 0x01 /* Output should be DISTINCT */
  10460. #define SF_Resolved 0x02 /* Identifiers have been resolved */
  10461. #define SF_Aggregate 0x04 /* Contains aggregate functions */
  10462. #define SF_UsesEphemeral 0x08 /* Uses the OpenEphemeral opcode */
  10463. #define SF_Expanded 0x10 /* sqlite3SelectExpand() called on this */
  10464. #define SF_HasTypeInfo 0x20 /* FROM subqueries have Table metadata */
  10465. #define SF_UseSorter 0x40 /* Sort using a sorter */
  10466. /*
  10467. ** The results of a select can be distributed in several ways. The
  10468. ** "SRT" prefix means "SELECT Result Type".
  10469. */
  10470. #define SRT_Union 1 /* Store result as keys in an index */
  10471. #define SRT_Except 2 /* Remove result from a UNION index */
  10472. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  10473. #define SRT_Discard 4 /* Do not save the results anywhere */
  10474. /* The ORDER BY clause is ignored for all of the above */
  10475. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  10476. #define SRT_Output 5 /* Output each row of result */
  10477. #define SRT_Mem 6 /* Store result in a memory cell */
  10478. #define SRT_Set 7 /* Store results as keys in an index */
  10479. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  10480. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  10481. #define SRT_Coroutine 10 /* Generate a single row of result */
  10482. /*
  10483. ** A structure used to customize the behavior of sqlite3Select(). See
  10484. ** comments above sqlite3Select() for details.
  10485. */
  10486. typedef struct SelectDest SelectDest;
  10487. struct SelectDest {
  10488. u8 eDest; /* How to dispose of the results */
  10489. u8 affinity; /* Affinity used when eDest==SRT_Set */
  10490. int iParm; /* A parameter used by the eDest disposal method */
  10491. int iMem; /* Base register where results are written */
  10492. int nMem; /* Number of registers allocated */
  10493. };
  10494. /*
  10495. ** During code generation of statements that do inserts into AUTOINCREMENT
  10496. ** tables, the following information is attached to the Table.u.autoInc.p
  10497. ** pointer of each autoincrement table to record some side information that
  10498. ** the code generator needs. We have to keep per-table autoincrement
  10499. ** information in case inserts are down within triggers. Triggers do not
  10500. ** normally coordinate their activities, but we do need to coordinate the
  10501. ** loading and saving of autoincrement information.
  10502. */
  10503. struct AutoincInfo {
  10504. AutoincInfo *pNext; /* Next info block in a list of them all */
  10505. Table *pTab; /* Table this info block refers to */
  10506. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  10507. int regCtr; /* Memory register holding the rowid counter */
  10508. };
  10509. /*
  10510. ** Size of the column cache
  10511. */
  10512. #ifndef SQLITE_N_COLCACHE
  10513. # define SQLITE_N_COLCACHE 10
  10514. #endif
  10515. /*
  10516. ** At least one instance of the following structure is created for each
  10517. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  10518. ** statement. All such objects are stored in the linked list headed at
  10519. ** Parse.pTriggerPrg and deleted once statement compilation has been
  10520. ** completed.
  10521. **
  10522. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  10523. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  10524. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  10525. ** The Parse.pTriggerPrg list never contains two entries with the same
  10526. ** values for both pTrigger and orconf.
  10527. **
  10528. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  10529. ** accessed (or set to 0 for triggers fired as a result of INSERT
  10530. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  10531. ** a mask of new.* columns used by the program.
  10532. */
  10533. struct TriggerPrg {
  10534. Trigger *pTrigger; /* Trigger this program was coded from */
  10535. int orconf; /* Default ON CONFLICT policy */
  10536. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  10537. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  10538. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  10539. };
  10540. /*
  10541. ** The yDbMask datatype for the bitmask of all attached databases.
  10542. */
  10543. #if SQLITE_MAX_ATTACHED>30
  10544. typedef sqlite3_uint64 yDbMask;
  10545. #else
  10546. typedef unsigned int yDbMask;
  10547. #endif
  10548. /*
  10549. ** An SQL parser context. A copy of this structure is passed through
  10550. ** the parser and down into all the parser action routine in order to
  10551. ** carry around information that is global to the entire parse.
  10552. **
  10553. ** The structure is divided into two parts. When the parser and code
  10554. ** generate call themselves recursively, the first part of the structure
  10555. ** is constant but the second part is reset at the beginning and end of
  10556. ** each recursion.
  10557. **
  10558. ** The nTableLock and aTableLock variables are only used if the shared-cache
  10559. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  10560. ** used to store the set of table-locks required by the statement being
  10561. ** compiled. Function sqlite3TableLock() is used to add entries to the
  10562. ** list.
  10563. */
  10564. struct Parse {
  10565. sqlite3 *db; /* The main database structure */
  10566. int rc; /* Return code from execution */
  10567. char *zErrMsg; /* An error message */
  10568. Vdbe *pVdbe; /* An engine for executing database bytecode */
  10569. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  10570. u8 checkSchema; /* Causes schema cookie check after an error */
  10571. u8 nested; /* Number of nested calls to the parser/code generator */
  10572. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  10573. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  10574. int aTempReg[8]; /* Holding area for temporary registers */
  10575. int nRangeReg; /* Size of the temporary register block */
  10576. int iRangeReg; /* First register in temporary register block */
  10577. int nErr; /* Number of errors seen */
  10578. int nTab; /* Number of previously allocated VDBE cursors */
  10579. int nMem; /* Number of memory cells used so far */
  10580. int nSet; /* Number of sets used so far */
  10581. int nOnce; /* Number of OP_Once instructions so far */
  10582. int ckBase; /* Base register of data during check constraints */
  10583. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  10584. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  10585. u8 nColCache; /* Number of entries in aColCache[] */
  10586. u8 iColCache; /* Next entry in aColCache[] to replace */
  10587. struct yColCache {
  10588. int iTable; /* Table cursor number */
  10589. int iColumn; /* Table column number */
  10590. u8 tempReg; /* iReg is a temp register that needs to be freed */
  10591. int iLevel; /* Nesting level */
  10592. int iReg; /* Reg with value of this column. 0 means none. */
  10593. int lru; /* Least recently used entry has the smallest value */
  10594. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  10595. yDbMask writeMask; /* Start a write transaction on these databases */
  10596. yDbMask cookieMask; /* Bitmask of schema verified databases */
  10597. u8 isMultiWrite; /* True if statement may affect/insert multiple rows */
  10598. u8 mayAbort; /* True if statement may throw an ABORT exception */
  10599. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  10600. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  10601. #ifndef SQLITE_OMIT_SHARED_CACHE
  10602. int nTableLock; /* Number of locks in aTableLock */
  10603. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  10604. #endif
  10605. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  10606. int regRoot; /* Register holding root page number for new objects */
  10607. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  10608. int nMaxArg; /* Max args passed to user function by sub-program */
  10609. /* Information used while coding trigger programs. */
  10610. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  10611. Table *pTriggerTab; /* Table triggers are being coded for */
  10612. u32 oldmask; /* Mask of old.* columns referenced */
  10613. u32 newmask; /* Mask of new.* columns referenced */
  10614. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  10615. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  10616. u8 disableTriggers; /* True to disable triggers */
  10617. double nQueryLoop; /* Estimated number of iterations of a query */
  10618. /* Above is constant between recursions. Below is reset before and after
  10619. ** each recursion */
  10620. int nVar; /* Number of '?' variables seen in the SQL so far */
  10621. int nzVar; /* Number of available slots in azVar[] */
  10622. char **azVar; /* Pointers to names of parameters */
  10623. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  10624. int nAlias; /* Number of aliased result set columns */
  10625. int *aAlias; /* Register used to hold aliased result */
  10626. u8 explain; /* True if the EXPLAIN flag is found on the query */
  10627. Token sNameToken; /* Token with unqualified schema object name */
  10628. Token sLastToken; /* The last token parsed */
  10629. const char *zTail; /* All SQL text past the last semicolon parsed */
  10630. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  10631. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  10632. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  10633. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10634. Token sArg; /* Complete text of a module argument */
  10635. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  10636. int nVtabLock; /* Number of virtual tables to lock */
  10637. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  10638. #endif
  10639. int nHeight; /* Expression tree height of current sub-select */
  10640. Table *pZombieTab; /* List of Table objects to delete after code gen */
  10641. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  10642. #ifndef SQLITE_OMIT_EXPLAIN
  10643. int iSelectId;
  10644. int iNextSelectId;
  10645. #endif
  10646. };
  10647. #ifdef SQLITE_OMIT_VIRTUALTABLE
  10648. #define IN_DECLARE_VTAB 0
  10649. #else
  10650. #define IN_DECLARE_VTAB (pParse->declareVtab)
  10651. #endif
  10652. /*
  10653. ** An instance of the following structure can be declared on a stack and used
  10654. ** to save the Parse.zAuthContext value so that it can be restored later.
  10655. */
  10656. struct AuthContext {
  10657. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  10658. Parse *pParse; /* The Parse structure */
  10659. };
  10660. /*
  10661. ** Bitfield flags for P5 value in OP_Insert and OP_Delete
  10662. */
  10663. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  10664. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  10665. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  10666. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  10667. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  10668. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  10669. /*
  10670. * Each trigger present in the database schema is stored as an instance of
  10671. * struct Trigger.
  10672. *
  10673. * Pointers to instances of struct Trigger are stored in two ways.
  10674. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  10675. * database). This allows Trigger structures to be retrieved by name.
  10676. * 2. All triggers associated with a single table form a linked list, using the
  10677. * pNext member of struct Trigger. A pointer to the first element of the
  10678. * linked list is stored as the "pTrigger" member of the associated
  10679. * struct Table.
  10680. *
  10681. * The "step_list" member points to the first element of a linked list
  10682. * containing the SQL statements specified as the trigger program.
  10683. */
  10684. struct Trigger {
  10685. char *zName; /* The name of the trigger */
  10686. char *table; /* The table or view to which the trigger applies */
  10687. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  10688. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  10689. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  10690. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  10691. the <column-list> is stored here */
  10692. Schema *pSchema; /* Schema containing the trigger */
  10693. Schema *pTabSchema; /* Schema containing the table */
  10694. TriggerStep *step_list; /* Link list of trigger program steps */
  10695. Trigger *pNext; /* Next trigger associated with the table */
  10696. };
  10697. /*
  10698. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  10699. ** determine which.
  10700. **
  10701. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  10702. ** In that cases, the constants below can be ORed together.
  10703. */
  10704. #define TRIGGER_BEFORE 1
  10705. #define TRIGGER_AFTER 2
  10706. /*
  10707. * An instance of struct TriggerStep is used to store a single SQL statement
  10708. * that is a part of a trigger-program.
  10709. *
  10710. * Instances of struct TriggerStep are stored in a singly linked list (linked
  10711. * using the "pNext" member) referenced by the "step_list" member of the
  10712. * associated struct Trigger instance. The first element of the linked list is
  10713. * the first step of the trigger-program.
  10714. *
  10715. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  10716. * "SELECT" statement. The meanings of the other members is determined by the
  10717. * value of "op" as follows:
  10718. *
  10719. * (op == TK_INSERT)
  10720. * orconf -> stores the ON CONFLICT algorithm
  10721. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  10722. * this stores a pointer to the SELECT statement. Otherwise NULL.
  10723. * target -> A token holding the quoted name of the table to insert into.
  10724. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  10725. * this stores values to be inserted. Otherwise NULL.
  10726. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  10727. * statement, then this stores the column-names to be
  10728. * inserted into.
  10729. *
  10730. * (op == TK_DELETE)
  10731. * target -> A token holding the quoted name of the table to delete from.
  10732. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  10733. * Otherwise NULL.
  10734. *
  10735. * (op == TK_UPDATE)
  10736. * target -> A token holding the quoted name of the table to update rows of.
  10737. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  10738. * Otherwise NULL.
  10739. * pExprList -> A list of the columns to update and the expressions to update
  10740. * them to. See sqlite3Update() documentation of "pChanges"
  10741. * argument.
  10742. *
  10743. */
  10744. struct TriggerStep {
  10745. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  10746. u8 orconf; /* OE_Rollback etc. */
  10747. Trigger *pTrig; /* The trigger that this step is a part of */
  10748. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  10749. Token target; /* Target table for DELETE, UPDATE, INSERT */
  10750. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  10751. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  10752. IdList *pIdList; /* Column names for INSERT */
  10753. TriggerStep *pNext; /* Next in the link-list */
  10754. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  10755. };
  10756. /*
  10757. ** The following structure contains information used by the sqliteFix...
  10758. ** routines as they walk the parse tree to make database references
  10759. ** explicit.
  10760. */
  10761. typedef struct DbFixer DbFixer;
  10762. struct DbFixer {
  10763. Parse *pParse; /* The parsing context. Error messages written here */
  10764. const char *zDb; /* Make sure all objects are contained in this database */
  10765. const char *zType; /* Type of the container - used for error messages */
  10766. const Token *pName; /* Name of the container - used for error messages */
  10767. };
  10768. /*
  10769. ** An objected used to accumulate the text of a string where we
  10770. ** do not necessarily know how big the string will be in the end.
  10771. */
  10772. struct StrAccum {
  10773. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  10774. char *zBase; /* A base allocation. Not from malloc. */
  10775. char *zText; /* The string collected so far */
  10776. int nChar; /* Length of the string so far */
  10777. int nAlloc; /* Amount of space allocated in zText */
  10778. int mxAlloc; /* Maximum allowed string length */
  10779. u8 mallocFailed; /* Becomes true if any memory allocation fails */
  10780. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  10781. u8 tooBig; /* Becomes true if string size exceeds limits */
  10782. };
  10783. /*
  10784. ** A pointer to this structure is used to communicate information
  10785. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  10786. */
  10787. typedef struct {
  10788. sqlite3 *db; /* The database being initialized */
  10789. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  10790. char **pzErrMsg; /* Error message stored here */
  10791. int rc; /* Result code stored here */
  10792. } InitData;
  10793. /*
  10794. ** Structure containing global configuration data for the SQLite library.
  10795. **
  10796. ** This structure also contains some state information.
  10797. */
  10798. struct Sqlite3Config {
  10799. int bMemstat; /* True to enable memory status */
  10800. int bCoreMutex; /* True to enable core mutexing */
  10801. int bFullMutex; /* True to enable full mutexing */
  10802. int bOpenUri; /* True to interpret filenames as URIs */
  10803. int mxStrlen; /* Maximum string length */
  10804. int szLookaside; /* Default lookaside buffer size */
  10805. int nLookaside; /* Default lookaside buffer count */
  10806. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  10807. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  10808. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  10809. void *pHeap; /* Heap storage space */
  10810. int nHeap; /* Size of pHeap[] */
  10811. int mnReq, mxReq; /* Min and max heap requests sizes */
  10812. void *pScratch; /* Scratch memory */
  10813. int szScratch; /* Size of each scratch buffer */
  10814. int nScratch; /* Number of scratch buffers */
  10815. void *pPage; /* Page cache memory */
  10816. int szPage; /* Size of each page in pPage[] */
  10817. int nPage; /* Number of pages in pPage[] */
  10818. int mxParserStack; /* maximum depth of the parser stack */
  10819. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  10820. /* The above might be initialized to non-zero. The following need to always
  10821. ** initially be zero, however. */
  10822. int isInit; /* True after initialization has finished */
  10823. int inProgress; /* True while initialization in progress */
  10824. int isMutexInit; /* True after mutexes are initialized */
  10825. int isMallocInit; /* True after malloc is initialized */
  10826. int isPCacheInit; /* True after malloc is initialized */
  10827. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  10828. int nRefInitMutex; /* Number of users of pInitMutex */
  10829. void (*xLog)(void*,int,const char*); /* Function for logging */
  10830. void *pLogArg; /* First argument to xLog() */
  10831. int bLocaltimeFault; /* True to fail localtime() calls */
  10832. };
  10833. /*
  10834. ** Context pointer passed down through the tree-walk.
  10835. */
  10836. struct Walker {
  10837. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  10838. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  10839. Parse *pParse; /* Parser context. */
  10840. union { /* Extra data for callback */
  10841. NameContext *pNC; /* Naming context */
  10842. int i; /* Integer value */
  10843. } u;
  10844. };
  10845. /* Forward declarations */
  10846. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  10847. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  10848. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  10849. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  10850. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  10851. /*
  10852. ** Return code from the parse-tree walking primitives and their
  10853. ** callbacks.
  10854. */
  10855. #define WRC_Continue 0 /* Continue down into children */
  10856. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  10857. #define WRC_Abort 2 /* Abandon the tree walk */
  10858. /*
  10859. ** Assuming zIn points to the first byte of a UTF-8 character,
  10860. ** advance zIn to point to the first byte of the next UTF-8 character.
  10861. */
  10862. #define SQLITE_SKIP_UTF8(zIn) { \
  10863. if( (*(zIn++))>=0xc0 ){ \
  10864. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  10865. } \
  10866. }
  10867. /*
  10868. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  10869. ** the same name but without the _BKPT suffix. These macros invoke
  10870. ** routines that report the line-number on which the error originated
  10871. ** using sqlite3_log(). The routines also provide a convenient place
  10872. ** to set a debugger breakpoint.
  10873. */
  10874. SQLITE_PRIVATE int sqlite3CorruptError(int);
  10875. SQLITE_PRIVATE int sqlite3MisuseError(int);
  10876. SQLITE_PRIVATE int sqlite3CantopenError(int);
  10877. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  10878. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  10879. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  10880. /*
  10881. ** FTS4 is really an extension for FTS3. It is enabled using the
  10882. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  10883. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  10884. */
  10885. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  10886. # define SQLITE_ENABLE_FTS3
  10887. #endif
  10888. /*
  10889. ** The ctype.h header is needed for non-ASCII systems. It is also
  10890. ** needed by FTS3 when FTS3 is included in the amalgamation.
  10891. */
  10892. #if !defined(SQLITE_ASCII) || \
  10893. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  10894. # include <ctype.h>
  10895. #endif
  10896. /*
  10897. ** The following macros mimic the standard library functions toupper(),
  10898. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  10899. ** sqlite versions only work for ASCII characters, regardless of locale.
  10900. */
  10901. #ifdef SQLITE_ASCII
  10902. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  10903. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  10904. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  10905. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  10906. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  10907. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  10908. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  10909. #else
  10910. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  10911. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  10912. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  10913. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  10914. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  10915. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  10916. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  10917. #endif
  10918. /*
  10919. ** Internal function prototypes
  10920. */
  10921. SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
  10922. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  10923. #define sqlite3StrNICmp sqlite3_strnicmp
  10924. SQLITE_PRIVATE int sqlite3MallocInit(void);
  10925. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  10926. SQLITE_PRIVATE void *sqlite3Malloc(int);
  10927. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  10928. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  10929. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  10930. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  10931. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  10932. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  10933. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  10934. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  10935. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  10936. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  10937. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  10938. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  10939. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  10940. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  10941. SQLITE_PRIVATE void sqlite3PageFree(void*);
  10942. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  10943. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  10944. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  10945. /*
  10946. ** On systems with ample stack space and that support alloca(), make
  10947. ** use of alloca() to obtain space for large automatic objects. By default,
  10948. ** obtain space from malloc().
  10949. **
  10950. ** The alloca() routine never returns NULL. This will cause code paths
  10951. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  10952. */
  10953. #ifdef SQLITE_USE_ALLOCA
  10954. # define sqlite3StackAllocRaw(D,N) alloca(N)
  10955. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  10956. # define sqlite3StackFree(D,P)
  10957. #else
  10958. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  10959. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  10960. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  10961. #endif
  10962. #ifdef SQLITE_ENABLE_MEMSYS3
  10963. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  10964. #endif
  10965. #ifdef SQLITE_ENABLE_MEMSYS5
  10966. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  10967. #endif
  10968. #ifndef SQLITE_MUTEX_OMIT
  10969. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  10970. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  10971. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  10972. SQLITE_PRIVATE int sqlite3MutexInit(void);
  10973. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  10974. #endif
  10975. SQLITE_PRIVATE int sqlite3StatusValue(int);
  10976. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  10977. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  10978. #ifndef SQLITE_OMIT_FLOATING_POINT
  10979. SQLITE_PRIVATE int sqlite3IsNaN(double);
  10980. #else
  10981. # define sqlite3IsNaN(X) 0
  10982. #endif
  10983. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  10984. #ifndef SQLITE_OMIT_TRACE
  10985. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  10986. #endif
  10987. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  10988. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  10989. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  10990. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  10991. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  10992. #endif
  10993. #if defined(SQLITE_TEST)
  10994. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  10995. #endif
  10996. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  10997. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  10998. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
  10999. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  11000. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
  11001. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
  11002. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
  11003. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
  11004. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
  11005. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
  11006. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
  11007. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
  11008. #else
  11009. # define sqlite3ExplainBegin(X)
  11010. # define sqlite3ExplainSelect(A,B)
  11011. # define sqlite3ExplainExpr(A,B)
  11012. # define sqlite3ExplainExprList(A,B)
  11013. # define sqlite3ExplainFinish(X)
  11014. # define sqlite3VdbeExplanation(X) 0
  11015. #endif
  11016. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  11017. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  11018. SQLITE_PRIVATE int sqlite3Dequote(char*);
  11019. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  11020. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  11021. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  11022. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  11023. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  11024. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  11025. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  11026. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  11027. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  11028. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  11029. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  11030. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  11031. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  11032. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  11033. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  11034. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  11035. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  11036. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  11037. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  11038. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  11039. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  11040. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  11041. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  11042. SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
  11043. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  11044. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  11045. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  11046. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  11047. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  11048. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  11049. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  11050. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  11051. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  11052. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  11053. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  11054. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  11055. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  11056. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  11057. sqlite3_vfs**,char**,char **);
  11058. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  11059. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  11060. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  11061. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  11062. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  11063. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  11064. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  11065. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  11066. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  11067. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  11068. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  11069. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  11070. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  11071. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  11072. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  11073. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  11074. #else
  11075. # define sqlite3ViewGetColumnNames(A,B) 0
  11076. #endif
  11077. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  11078. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  11079. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  11080. #ifndef SQLITE_OMIT_AUTOINCREMENT
  11081. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  11082. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  11083. #else
  11084. # define sqlite3AutoincrementBegin(X)
  11085. # define sqlite3AutoincrementEnd(X)
  11086. #endif
  11087. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  11088. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
  11089. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  11090. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  11091. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  11092. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  11093. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  11094. Token*, Select*, Expr*, IdList*);
  11095. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  11096. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  11097. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  11098. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  11099. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  11100. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  11101. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  11102. Token*, int, int);
  11103. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  11104. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  11105. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  11106. Expr*,ExprList*,int,Expr*,Expr*);
  11107. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  11108. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  11109. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  11110. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  11111. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  11112. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
  11113. #endif
  11114. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  11115. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  11116. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
  11117. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  11118. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
  11119. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  11120. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  11121. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
  11122. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  11123. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  11124. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  11125. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  11126. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  11127. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  11128. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  11129. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  11130. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  11131. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  11132. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  11133. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  11134. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  11135. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  11136. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  11137. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  11138. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  11139. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  11140. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  11141. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  11142. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  11143. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  11144. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
  11145. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
  11146. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  11147. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  11148. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  11149. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  11150. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  11151. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  11152. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
  11153. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  11154. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  11155. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  11156. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  11157. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  11158. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  11159. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  11160. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  11161. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  11162. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  11163. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  11164. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  11165. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  11166. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  11167. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  11168. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  11169. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  11170. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  11171. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  11172. int*,int,int,int,int,int*);
  11173. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  11174. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  11175. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  11176. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  11177. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  11178. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
  11179. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  11180. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  11181. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  11182. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  11183. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  11184. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  11185. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
  11186. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  11187. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  11188. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  11189. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  11190. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  11191. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  11192. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  11193. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  11194. #endif
  11195. #ifndef SQLITE_OMIT_TRIGGER
  11196. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  11197. Expr*,int, int);
  11198. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  11199. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  11200. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  11201. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  11202. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  11203. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  11204. int, int, int);
  11205. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  11206. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  11207. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  11208. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  11209. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  11210. ExprList*,Select*,u8);
  11211. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  11212. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  11213. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  11214. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  11215. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  11216. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  11217. #else
  11218. # define sqlite3TriggersExist(B,C,D,E,F) 0
  11219. # define sqlite3DeleteTrigger(A,B)
  11220. # define sqlite3DropTriggerPtr(A,B)
  11221. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  11222. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  11223. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  11224. # define sqlite3TriggerList(X, Y) 0
  11225. # define sqlite3ParseToplevel(p) p
  11226. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  11227. #endif
  11228. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  11229. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  11230. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  11231. #ifndef SQLITE_OMIT_AUTHORIZATION
  11232. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  11233. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  11234. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  11235. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  11236. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  11237. #else
  11238. # define sqlite3AuthRead(a,b,c,d)
  11239. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  11240. # define sqlite3AuthContextPush(a,b,c)
  11241. # define sqlite3AuthContextPop(a) ((void)(a))
  11242. #endif
  11243. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  11244. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  11245. SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  11246. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  11247. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  11248. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  11249. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  11250. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  11251. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  11252. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  11253. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  11254. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  11255. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  11256. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
  11257. /*
  11258. ** Routines to read and write variable-length integers. These used to
  11259. ** be defined locally, but now we use the varint routines in the util.c
  11260. ** file. Code should use the MACRO forms below, as the Varint32 versions
  11261. ** are coded to assume the single byte case is already handled (which
  11262. ** the MACRO form does).
  11263. */
  11264. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  11265. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  11266. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  11267. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  11268. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  11269. /*
  11270. ** The header of a record consists of a sequence variable-length integers.
  11271. ** These integers are almost always small and are encoded as a single byte.
  11272. ** The following macros take advantage this fact to provide a fast encode
  11273. ** and decode of the integers in a record header. It is faster for the common
  11274. ** case where the integer is a single byte. It is a little slower when the
  11275. ** integer is two or more bytes. But overall it is faster.
  11276. **
  11277. ** The following expressions are equivalent:
  11278. **
  11279. ** x = sqlite3GetVarint32( A, &B );
  11280. ** x = sqlite3PutVarint32( A, B );
  11281. **
  11282. ** x = getVarint32( A, B );
  11283. ** x = putVarint32( A, B );
  11284. **
  11285. */
  11286. #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
  11287. #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
  11288. #define getVarint sqlite3GetVarint
  11289. #define putVarint sqlite3PutVarint
  11290. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  11291. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  11292. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  11293. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  11294. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  11295. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  11296. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  11297. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  11298. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  11299. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  11300. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  11301. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  11302. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  11303. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  11304. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  11305. SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
  11306. SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
  11307. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  11308. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  11309. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  11310. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  11311. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  11312. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  11313. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  11314. #ifdef SQLITE_ENABLE_8_3_NAMES
  11315. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  11316. #else
  11317. # define sqlite3FileSuffix3(X,Y)
  11318. #endif
  11319. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z);
  11320. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  11321. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  11322. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  11323. void(*)(void*));
  11324. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  11325. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  11326. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  11327. #ifdef SQLITE_ENABLE_STAT3
  11328. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
  11329. #endif
  11330. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  11331. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  11332. #ifndef SQLITE_AMALGAMATION
  11333. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  11334. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  11335. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  11336. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  11337. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  11338. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11339. #ifndef SQLITE_OMIT_WSD
  11340. SQLITE_PRIVATE int sqlite3PendingByte;
  11341. #endif
  11342. #endif
  11343. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  11344. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  11345. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  11346. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  11347. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  11348. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  11349. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  11350. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  11351. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  11352. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  11353. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  11354. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  11355. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  11356. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  11357. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  11358. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
  11359. SQLITE_PRIVATE char sqlite3AffinityType(const char*);
  11360. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  11361. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  11362. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  11363. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  11364. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  11365. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  11366. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  11367. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  11368. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  11369. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  11370. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  11371. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  11372. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  11373. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  11374. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  11375. void (*)(sqlite3_context*,int,sqlite3_value **),
  11376. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  11377. FuncDestructor *pDestructor
  11378. );
  11379. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  11380. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  11381. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  11382. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  11383. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  11384. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  11385. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  11386. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  11387. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  11388. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  11389. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  11390. /*
  11391. ** The interface to the LEMON-generated parser
  11392. */
  11393. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  11394. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  11395. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  11396. #ifdef YYTRACKMAXSTACKDEPTH
  11397. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  11398. #endif
  11399. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  11400. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11401. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  11402. #else
  11403. # define sqlite3CloseExtensions(X)
  11404. #endif
  11405. #ifndef SQLITE_OMIT_SHARED_CACHE
  11406. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  11407. #else
  11408. #define sqlite3TableLock(v,w,x,y,z)
  11409. #endif
  11410. #ifdef SQLITE_TEST
  11411. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  11412. #endif
  11413. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11414. # define sqlite3VtabClear(Y)
  11415. # define sqlite3VtabSync(X,Y) SQLITE_OK
  11416. # define sqlite3VtabRollback(X)
  11417. # define sqlite3VtabCommit(X)
  11418. # define sqlite3VtabInSync(db) 0
  11419. # define sqlite3VtabLock(X)
  11420. # define sqlite3VtabUnlock(X)
  11421. # define sqlite3VtabUnlockList(X)
  11422. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  11423. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  11424. #else
  11425. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  11426. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
  11427. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  11428. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  11429. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  11430. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  11431. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  11432. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  11433. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  11434. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  11435. #endif
  11436. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  11437. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
  11438. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  11439. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  11440. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  11441. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  11442. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  11443. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  11444. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  11445. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  11446. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  11447. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  11448. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  11449. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  11450. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  11451. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  11452. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  11453. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  11454. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  11455. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  11456. /* Declarations for functions in fkey.c. All of these are replaced by
  11457. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  11458. ** key functionality is available. If OMIT_TRIGGER is defined but
  11459. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  11460. ** this case foreign keys are parsed, but no other functionality is
  11461. ** provided (enforcement of FK constraints requires the triggers sub-system).
  11462. */
  11463. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  11464. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
  11465. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  11466. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
  11467. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  11468. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  11469. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  11470. #else
  11471. #define sqlite3FkActions(a,b,c,d)
  11472. #define sqlite3FkCheck(a,b,c,d)
  11473. #define sqlite3FkDropTable(a,b,c)
  11474. #define sqlite3FkOldmask(a,b) 0
  11475. #define sqlite3FkRequired(a,b,c,d) 0
  11476. #endif
  11477. #ifndef SQLITE_OMIT_FOREIGN_KEY
  11478. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  11479. #else
  11480. #define sqlite3FkDelete(a,b)
  11481. #endif
  11482. /*
  11483. ** Available fault injectors. Should be numbered beginning with 0.
  11484. */
  11485. #define SQLITE_FAULTINJECTOR_MALLOC 0
  11486. #define SQLITE_FAULTINJECTOR_COUNT 1
  11487. /*
  11488. ** The interface to the code in fault.c used for identifying "benign"
  11489. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  11490. ** is not defined.
  11491. */
  11492. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11493. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  11494. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  11495. #else
  11496. #define sqlite3BeginBenignMalloc()
  11497. #define sqlite3EndBenignMalloc()
  11498. #endif
  11499. #define IN_INDEX_ROWID 1
  11500. #define IN_INDEX_EPH 2
  11501. #define IN_INDEX_INDEX 3
  11502. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  11503. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11504. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  11505. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  11506. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  11507. #else
  11508. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  11509. #endif
  11510. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  11511. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  11512. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  11513. #if SQLITE_MAX_EXPR_DEPTH>0
  11514. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  11515. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  11516. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  11517. #else
  11518. #define sqlite3ExprSetHeight(x,y)
  11519. #define sqlite3SelectExprHeight(x) 0
  11520. #define sqlite3ExprCheckHeight(x,y)
  11521. #endif
  11522. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  11523. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  11524. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11525. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  11526. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  11527. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  11528. #else
  11529. #define sqlite3ConnectionBlocked(x,y)
  11530. #define sqlite3ConnectionUnlocked(x)
  11531. #define sqlite3ConnectionClosed(x)
  11532. #endif
  11533. #ifdef SQLITE_DEBUG
  11534. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  11535. #endif
  11536. /*
  11537. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  11538. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  11539. ** print I/O tracing messages.
  11540. */
  11541. #ifdef SQLITE_ENABLE_IOTRACE
  11542. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  11543. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  11544. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  11545. #else
  11546. # define IOTRACE(A)
  11547. # define sqlite3VdbeIOTraceSql(X)
  11548. #endif
  11549. /*
  11550. ** These routines are available for the mem2.c debugging memory allocator
  11551. ** only. They are used to verify that different "types" of memory
  11552. ** allocations are properly tracked by the system.
  11553. **
  11554. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  11555. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  11556. ** a single bit set.
  11557. **
  11558. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  11559. ** argument match the type set by the previous sqlite3MemdebugSetType().
  11560. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  11561. **
  11562. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  11563. ** argument match the type set by the previous sqlite3MemdebugSetType().
  11564. **
  11565. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  11566. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  11567. ** it might have been allocated by lookaside, except the allocation was
  11568. ** too large or lookaside was already full. It is important to verify
  11569. ** that allocations that might have been satisfied by lookaside are not
  11570. ** passed back to non-lookaside free() routines. Asserts such as the
  11571. ** example above are placed on the non-lookaside free() routines to verify
  11572. ** this constraint.
  11573. **
  11574. ** All of this is no-op for a production build. It only comes into
  11575. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  11576. */
  11577. #ifdef SQLITE_MEMDEBUG
  11578. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  11579. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  11580. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  11581. #else
  11582. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  11583. # define sqlite3MemdebugHasType(X,Y) 1
  11584. # define sqlite3MemdebugNoType(X,Y) 1
  11585. #endif
  11586. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  11587. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  11588. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  11589. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  11590. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  11591. #endif /* _SQLITEINT_H_ */
  11592. /************** End of sqliteInt.h *******************************************/
  11593. /************** Begin file global.c ******************************************/
  11594. /*
  11595. ** 2008 June 13
  11596. **
  11597. ** The author disclaims copyright to this source code. In place of
  11598. ** a legal notice, here is a blessing:
  11599. **
  11600. ** May you do good and not evil.
  11601. ** May you find forgiveness for yourself and forgive others.
  11602. ** May you share freely, never taking more than you give.
  11603. **
  11604. *************************************************************************
  11605. **
  11606. ** This file contains definitions of global variables and contants.
  11607. */
  11608. /* An array to map all upper-case characters into their corresponding
  11609. ** lower-case character.
  11610. **
  11611. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  11612. ** handle case conversions for the UTF character set since the tables
  11613. ** involved are nearly as big or bigger than SQLite itself.
  11614. */
  11615. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  11616. #ifdef SQLITE_ASCII
  11617. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  11618. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  11619. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  11620. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  11621. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  11622. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  11623. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  11624. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  11625. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  11626. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  11627. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  11628. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  11629. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  11630. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  11631. 252,253,254,255
  11632. #endif
  11633. #ifdef SQLITE_EBCDIC
  11634. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  11635. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  11636. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  11637. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  11638. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  11639. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  11640. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  11641. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  11642. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  11643. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  11644. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  11645. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  11646. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  11647. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  11648. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  11649. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  11650. #endif
  11651. };
  11652. /*
  11653. ** The following 256 byte lookup table is used to support SQLites built-in
  11654. ** equivalents to the following standard library functions:
  11655. **
  11656. ** isspace() 0x01
  11657. ** isalpha() 0x02
  11658. ** isdigit() 0x04
  11659. ** isalnum() 0x06
  11660. ** isxdigit() 0x08
  11661. ** toupper() 0x20
  11662. ** SQLite identifier character 0x40
  11663. **
  11664. ** Bit 0x20 is set if the mapped character requires translation to upper
  11665. ** case. i.e. if the character is a lower-case ASCII character.
  11666. ** If x is a lower-case ASCII character, then its upper-case equivalent
  11667. ** is (x - 0x20). Therefore toupper() can be implemented as:
  11668. **
  11669. ** (x & ~(map[x]&0x20))
  11670. **
  11671. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  11672. ** array. tolower() is used more often than toupper() by SQLite.
  11673. **
  11674. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  11675. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  11676. ** non-ASCII UTF character. Hence the test for whether or not a character is
  11677. ** part of an identifier is 0x46.
  11678. **
  11679. ** SQLite's versions are identical to the standard versions assuming a
  11680. ** locale of "C". They are implemented as macros in sqliteInt.h.
  11681. */
  11682. #ifdef SQLITE_ASCII
  11683. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  11684. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  11685. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  11686. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  11687. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  11688. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  11689. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  11690. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  11691. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  11692. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  11693. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  11694. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  11695. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  11696. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  11697. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  11698. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  11699. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  11700. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  11701. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  11702. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  11703. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  11704. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  11705. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  11706. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  11707. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  11708. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  11709. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  11710. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  11711. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  11712. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  11713. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  11714. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  11715. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  11716. };
  11717. #endif
  11718. #ifndef SQLITE_USE_URI
  11719. # define SQLITE_USE_URI 0
  11720. #endif
  11721. /*
  11722. ** The following singleton contains the global configuration for
  11723. ** the SQLite library.
  11724. */
  11725. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  11726. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  11727. 1, /* bCoreMutex */
  11728. SQLITE_THREADSAFE==1, /* bFullMutex */
  11729. SQLITE_USE_URI, /* bOpenUri */
  11730. 0x7ffffffe, /* mxStrlen */
  11731. 128, /* szLookaside */
  11732. 500, /* nLookaside */
  11733. {0,0,0,0,0,0,0,0}, /* m */
  11734. {0,0,0,0,0,0,0,0,0}, /* mutex */
  11735. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  11736. (void*)0, /* pHeap */
  11737. 0, /* nHeap */
  11738. 0, 0, /* mnHeap, mxHeap */
  11739. (void*)0, /* pScratch */
  11740. 0, /* szScratch */
  11741. 0, /* nScratch */
  11742. (void*)0, /* pPage */
  11743. 0, /* szPage */
  11744. 0, /* nPage */
  11745. 0, /* mxParserStack */
  11746. 0, /* sharedCacheEnabled */
  11747. /* All the rest should always be initialized to zero */
  11748. 0, /* isInit */
  11749. 0, /* inProgress */
  11750. 0, /* isMutexInit */
  11751. 0, /* isMallocInit */
  11752. 0, /* isPCacheInit */
  11753. 0, /* pInitMutex */
  11754. 0, /* nRefInitMutex */
  11755. 0, /* xLog */
  11756. 0, /* pLogArg */
  11757. 0, /* bLocaltimeFault */
  11758. };
  11759. /*
  11760. ** Hash table for global functions - functions common to all
  11761. ** database connections. After initialization, this table is
  11762. ** read-only.
  11763. */
  11764. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11765. /*
  11766. ** Constant tokens for values 0 and 1.
  11767. */
  11768. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  11769. { "0", 1 },
  11770. { "1", 1 }
  11771. };
  11772. /*
  11773. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  11774. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  11775. ** the database page that contains the pending byte. It never attempts
  11776. ** to read or write that page. The pending byte page is set assign
  11777. ** for use by the VFS layers as space for managing file locks.
  11778. **
  11779. ** During testing, it is often desirable to move the pending byte to
  11780. ** a different position in the file. This allows code that has to
  11781. ** deal with the pending byte to run on files that are much smaller
  11782. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  11783. ** move the pending byte.
  11784. **
  11785. ** IMPORTANT: Changing the pending byte to any value other than
  11786. ** 0x40000000 results in an incompatible database file format!
  11787. ** Changing the pending byte during operating results in undefined
  11788. ** and dileterious behavior.
  11789. */
  11790. #ifndef SQLITE_OMIT_WSD
  11791. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  11792. #endif
  11793. /*
  11794. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  11795. ** created by mkopcodeh.awk during compilation. Data is obtained
  11796. ** from the comments following the "case OP_xxxx:" statements in
  11797. ** the vdbe.c file.
  11798. */
  11799. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  11800. /************** End of global.c **********************************************/
  11801. /************** Begin file ctime.c *******************************************/
  11802. /*
  11803. ** 2010 February 23
  11804. **
  11805. ** The author disclaims copyright to this source code. In place of
  11806. ** a legal notice, here is a blessing:
  11807. **
  11808. ** May you do good and not evil.
  11809. ** May you find forgiveness for yourself and forgive others.
  11810. ** May you share freely, never taking more than you give.
  11811. **
  11812. *************************************************************************
  11813. **
  11814. ** This file implements routines used to report what compile-time options
  11815. ** SQLite was built with.
  11816. */
  11817. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  11818. /*
  11819. ** An array of names of all compile-time options. This array should
  11820. ** be sorted A-Z.
  11821. **
  11822. ** This array looks large, but in a typical installation actually uses
  11823. ** only a handful of compile-time options, so most times this array is usually
  11824. ** rather short and uses little memory space.
  11825. */
  11826. static const char * const azCompileOpt[] = {
  11827. /* These macros are provided to "stringify" the value of the define
  11828. ** for those options in which the value is meaningful. */
  11829. #define CTIMEOPT_VAL_(opt) #opt
  11830. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  11831. #ifdef SQLITE_32BIT_ROWID
  11832. "32BIT_ROWID",
  11833. #endif
  11834. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  11835. "4_BYTE_ALIGNED_MALLOC",
  11836. #endif
  11837. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  11838. "CASE_SENSITIVE_LIKE",
  11839. #endif
  11840. #ifdef SQLITE_CHECK_PAGES
  11841. "CHECK_PAGES",
  11842. #endif
  11843. #ifdef SQLITE_COVERAGE_TEST
  11844. "COVERAGE_TEST",
  11845. #endif
  11846. #ifdef SQLITE_DEBUG
  11847. "DEBUG",
  11848. #endif
  11849. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  11850. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  11851. #endif
  11852. #ifdef SQLITE_DISABLE_DIRSYNC
  11853. "DISABLE_DIRSYNC",
  11854. #endif
  11855. #ifdef SQLITE_DISABLE_LFS
  11856. "DISABLE_LFS",
  11857. #endif
  11858. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11859. "ENABLE_ATOMIC_WRITE",
  11860. #endif
  11861. #ifdef SQLITE_ENABLE_CEROD
  11862. "ENABLE_CEROD",
  11863. #endif
  11864. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  11865. "ENABLE_COLUMN_METADATA",
  11866. #endif
  11867. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  11868. "ENABLE_EXPENSIVE_ASSERT",
  11869. #endif
  11870. #ifdef SQLITE_ENABLE_FTS1
  11871. "ENABLE_FTS1",
  11872. #endif
  11873. #ifdef SQLITE_ENABLE_FTS2
  11874. "ENABLE_FTS2",
  11875. #endif
  11876. #ifdef SQLITE_ENABLE_FTS3
  11877. "ENABLE_FTS3",
  11878. #endif
  11879. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  11880. "ENABLE_FTS3_PARENTHESIS",
  11881. #endif
  11882. #ifdef SQLITE_ENABLE_FTS4
  11883. "ENABLE_FTS4",
  11884. #endif
  11885. #ifdef SQLITE_ENABLE_ICU
  11886. "ENABLE_ICU",
  11887. #endif
  11888. #ifdef SQLITE_ENABLE_IOTRACE
  11889. "ENABLE_IOTRACE",
  11890. #endif
  11891. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  11892. "ENABLE_LOAD_EXTENSION",
  11893. #endif
  11894. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  11895. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  11896. #endif
  11897. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  11898. "ENABLE_MEMORY_MANAGEMENT",
  11899. #endif
  11900. #ifdef SQLITE_ENABLE_MEMSYS3
  11901. "ENABLE_MEMSYS3",
  11902. #endif
  11903. #ifdef SQLITE_ENABLE_MEMSYS5
  11904. "ENABLE_MEMSYS5",
  11905. #endif
  11906. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  11907. "ENABLE_OVERSIZE_CELL_CHECK",
  11908. #endif
  11909. #ifdef SQLITE_ENABLE_RTREE
  11910. "ENABLE_RTREE",
  11911. #endif
  11912. #ifdef SQLITE_ENABLE_STAT3
  11913. "ENABLE_STAT3",
  11914. #endif
  11915. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11916. "ENABLE_UNLOCK_NOTIFY",
  11917. #endif
  11918. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  11919. "ENABLE_UPDATE_DELETE_LIMIT",
  11920. #endif
  11921. #ifdef SQLITE_HAS_CODEC
  11922. "HAS_CODEC",
  11923. #endif
  11924. #ifdef SQLITE_HAVE_ISNAN
  11925. "HAVE_ISNAN",
  11926. #endif
  11927. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  11928. "HOMEGROWN_RECURSIVE_MUTEX",
  11929. #endif
  11930. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  11931. "IGNORE_AFP_LOCK_ERRORS",
  11932. #endif
  11933. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  11934. "IGNORE_FLOCK_LOCK_ERRORS",
  11935. #endif
  11936. #ifdef SQLITE_INT64_TYPE
  11937. "INT64_TYPE",
  11938. #endif
  11939. #ifdef SQLITE_LOCK_TRACE
  11940. "LOCK_TRACE",
  11941. #endif
  11942. #ifdef SQLITE_MAX_SCHEMA_RETRY
  11943. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  11944. #endif
  11945. #ifdef SQLITE_MEMDEBUG
  11946. "MEMDEBUG",
  11947. #endif
  11948. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  11949. "MIXED_ENDIAN_64BIT_FLOAT",
  11950. #endif
  11951. #ifdef SQLITE_NO_SYNC
  11952. "NO_SYNC",
  11953. #endif
  11954. #ifdef SQLITE_OMIT_ALTERTABLE
  11955. "OMIT_ALTERTABLE",
  11956. #endif
  11957. #ifdef SQLITE_OMIT_ANALYZE
  11958. "OMIT_ANALYZE",
  11959. #endif
  11960. #ifdef SQLITE_OMIT_ATTACH
  11961. "OMIT_ATTACH",
  11962. #endif
  11963. #ifdef SQLITE_OMIT_AUTHORIZATION
  11964. "OMIT_AUTHORIZATION",
  11965. #endif
  11966. #ifdef SQLITE_OMIT_AUTOINCREMENT
  11967. "OMIT_AUTOINCREMENT",
  11968. #endif
  11969. #ifdef SQLITE_OMIT_AUTOINIT
  11970. "OMIT_AUTOINIT",
  11971. #endif
  11972. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  11973. "OMIT_AUTOMATIC_INDEX",
  11974. #endif
  11975. #ifdef SQLITE_OMIT_AUTORESET
  11976. "OMIT_AUTORESET",
  11977. #endif
  11978. #ifdef SQLITE_OMIT_AUTOVACUUM
  11979. "OMIT_AUTOVACUUM",
  11980. #endif
  11981. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  11982. "OMIT_BETWEEN_OPTIMIZATION",
  11983. #endif
  11984. #ifdef SQLITE_OMIT_BLOB_LITERAL
  11985. "OMIT_BLOB_LITERAL",
  11986. #endif
  11987. #ifdef SQLITE_OMIT_BTREECOUNT
  11988. "OMIT_BTREECOUNT",
  11989. #endif
  11990. #ifdef SQLITE_OMIT_BUILTIN_TEST
  11991. "OMIT_BUILTIN_TEST",
  11992. #endif
  11993. #ifdef SQLITE_OMIT_CAST
  11994. "OMIT_CAST",
  11995. #endif
  11996. #ifdef SQLITE_OMIT_CHECK
  11997. "OMIT_CHECK",
  11998. #endif
  11999. /* // redundant
  12000. ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12001. ** "OMIT_COMPILEOPTION_DIAGS",
  12002. ** #endif
  12003. */
  12004. #ifdef SQLITE_OMIT_COMPLETE
  12005. "OMIT_COMPLETE",
  12006. #endif
  12007. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  12008. "OMIT_COMPOUND_SELECT",
  12009. #endif
  12010. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  12011. "OMIT_DATETIME_FUNCS",
  12012. #endif
  12013. #ifdef SQLITE_OMIT_DECLTYPE
  12014. "OMIT_DECLTYPE",
  12015. #endif
  12016. #ifdef SQLITE_OMIT_DEPRECATED
  12017. "OMIT_DEPRECATED",
  12018. #endif
  12019. #ifdef SQLITE_OMIT_DISKIO
  12020. "OMIT_DISKIO",
  12021. #endif
  12022. #ifdef SQLITE_OMIT_EXPLAIN
  12023. "OMIT_EXPLAIN",
  12024. #endif
  12025. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  12026. "OMIT_FLAG_PRAGMAS",
  12027. #endif
  12028. #ifdef SQLITE_OMIT_FLOATING_POINT
  12029. "OMIT_FLOATING_POINT",
  12030. #endif
  12031. #ifdef SQLITE_OMIT_FOREIGN_KEY
  12032. "OMIT_FOREIGN_KEY",
  12033. #endif
  12034. #ifdef SQLITE_OMIT_GET_TABLE
  12035. "OMIT_GET_TABLE",
  12036. #endif
  12037. #ifdef SQLITE_OMIT_INCRBLOB
  12038. "OMIT_INCRBLOB",
  12039. #endif
  12040. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  12041. "OMIT_INTEGRITY_CHECK",
  12042. #endif
  12043. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  12044. "OMIT_LIKE_OPTIMIZATION",
  12045. #endif
  12046. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  12047. "OMIT_LOAD_EXTENSION",
  12048. #endif
  12049. #ifdef SQLITE_OMIT_LOCALTIME
  12050. "OMIT_LOCALTIME",
  12051. #endif
  12052. #ifdef SQLITE_OMIT_LOOKASIDE
  12053. "OMIT_LOOKASIDE",
  12054. #endif
  12055. #ifdef SQLITE_OMIT_MEMORYDB
  12056. "OMIT_MEMORYDB",
  12057. #endif
  12058. #ifdef SQLITE_OMIT_MERGE_SORT
  12059. "OMIT_MERGE_SORT",
  12060. #endif
  12061. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  12062. "OMIT_OR_OPTIMIZATION",
  12063. #endif
  12064. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  12065. "OMIT_PAGER_PRAGMAS",
  12066. #endif
  12067. #ifdef SQLITE_OMIT_PRAGMA
  12068. "OMIT_PRAGMA",
  12069. #endif
  12070. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  12071. "OMIT_PROGRESS_CALLBACK",
  12072. #endif
  12073. #ifdef SQLITE_OMIT_QUICKBALANCE
  12074. "OMIT_QUICKBALANCE",
  12075. #endif
  12076. #ifdef SQLITE_OMIT_REINDEX
  12077. "OMIT_REINDEX",
  12078. #endif
  12079. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  12080. "OMIT_SCHEMA_PRAGMAS",
  12081. #endif
  12082. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  12083. "OMIT_SCHEMA_VERSION_PRAGMAS",
  12084. #endif
  12085. #ifdef SQLITE_OMIT_SHARED_CACHE
  12086. "OMIT_SHARED_CACHE",
  12087. #endif
  12088. #ifdef SQLITE_OMIT_SUBQUERY
  12089. "OMIT_SUBQUERY",
  12090. #endif
  12091. #ifdef SQLITE_OMIT_TCL_VARIABLE
  12092. "OMIT_TCL_VARIABLE",
  12093. #endif
  12094. #ifdef SQLITE_OMIT_TEMPDB
  12095. "OMIT_TEMPDB",
  12096. #endif
  12097. #ifdef SQLITE_OMIT_TRACE
  12098. "OMIT_TRACE",
  12099. #endif
  12100. #ifdef SQLITE_OMIT_TRIGGER
  12101. "OMIT_TRIGGER",
  12102. #endif
  12103. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  12104. "OMIT_TRUNCATE_OPTIMIZATION",
  12105. #endif
  12106. #ifdef SQLITE_OMIT_UTF16
  12107. "OMIT_UTF16",
  12108. #endif
  12109. #ifdef SQLITE_OMIT_VACUUM
  12110. "OMIT_VACUUM",
  12111. #endif
  12112. #ifdef SQLITE_OMIT_VIEW
  12113. "OMIT_VIEW",
  12114. #endif
  12115. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12116. "OMIT_VIRTUALTABLE",
  12117. #endif
  12118. #ifdef SQLITE_OMIT_WAL
  12119. "OMIT_WAL",
  12120. #endif
  12121. #ifdef SQLITE_OMIT_WSD
  12122. "OMIT_WSD",
  12123. #endif
  12124. #ifdef SQLITE_OMIT_XFER_OPT
  12125. "OMIT_XFER_OPT",
  12126. #endif
  12127. #ifdef SQLITE_PERFORMANCE_TRACE
  12128. "PERFORMANCE_TRACE",
  12129. #endif
  12130. #ifdef SQLITE_PROXY_DEBUG
  12131. "PROXY_DEBUG",
  12132. #endif
  12133. #ifdef SQLITE_SECURE_DELETE
  12134. "SECURE_DELETE",
  12135. #endif
  12136. #ifdef SQLITE_SMALL_STACK
  12137. "SMALL_STACK",
  12138. #endif
  12139. #ifdef SQLITE_SOUNDEX
  12140. "SOUNDEX",
  12141. #endif
  12142. #ifdef SQLITE_TCL
  12143. "TCL",
  12144. #endif
  12145. #ifdef SQLITE_TEMP_STORE
  12146. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  12147. #endif
  12148. #ifdef SQLITE_TEST
  12149. "TEST",
  12150. #endif
  12151. #ifdef SQLITE_THREADSAFE
  12152. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  12153. #endif
  12154. #ifdef SQLITE_USE_ALLOCA
  12155. "USE_ALLOCA",
  12156. #endif
  12157. #ifdef SQLITE_ZERO_MALLOC
  12158. "ZERO_MALLOC"
  12159. #endif
  12160. };
  12161. /*
  12162. ** Given the name of a compile-time option, return true if that option
  12163. ** was used and false if not.
  12164. **
  12165. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  12166. ** is not required for a match.
  12167. */
  12168. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  12169. int i, n;
  12170. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  12171. n = sqlite3Strlen30(zOptName);
  12172. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  12173. ** linear search is adequate. No need for a binary search. */
  12174. for(i=0; i<ArraySize(azCompileOpt); i++){
  12175. if( (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
  12176. && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
  12177. }
  12178. return 0;
  12179. }
  12180. /*
  12181. ** Return the N-th compile-time option string. If N is out of range,
  12182. ** return a NULL pointer.
  12183. */
  12184. SQLITE_API const char *sqlite3_compileoption_get(int N){
  12185. if( N>=0 && N<ArraySize(azCompileOpt) ){
  12186. return azCompileOpt[N];
  12187. }
  12188. return 0;
  12189. }
  12190. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  12191. /************** End of ctime.c ***********************************************/
  12192. /************** Begin file status.c ******************************************/
  12193. /*
  12194. ** 2008 June 18
  12195. **
  12196. ** The author disclaims copyright to this source code. In place of
  12197. ** a legal notice, here is a blessing:
  12198. **
  12199. ** May you do good and not evil.
  12200. ** May you find forgiveness for yourself and forgive others.
  12201. ** May you share freely, never taking more than you give.
  12202. **
  12203. *************************************************************************
  12204. **
  12205. ** This module implements the sqlite3_status() interface and related
  12206. ** functionality.
  12207. */
  12208. /************** Include vdbeInt.h in the middle of status.c ******************/
  12209. /************** Begin file vdbeInt.h *****************************************/
  12210. /*
  12211. ** 2003 September 6
  12212. **
  12213. ** The author disclaims copyright to this source code. In place of
  12214. ** a legal notice, here is a blessing:
  12215. **
  12216. ** May you do good and not evil.
  12217. ** May you find forgiveness for yourself and forgive others.
  12218. ** May you share freely, never taking more than you give.
  12219. **
  12220. *************************************************************************
  12221. ** This is the header file for information that is private to the
  12222. ** VDBE. This information used to all be at the top of the single
  12223. ** source code file "vdbe.c". When that file became too big (over
  12224. ** 6000 lines long) it was split up into several smaller files and
  12225. ** this header information was factored out.
  12226. */
  12227. #ifndef _VDBEINT_H_
  12228. #define _VDBEINT_H_
  12229. /*
  12230. ** SQL is translated into a sequence of instructions to be
  12231. ** executed by a virtual machine. Each instruction is an instance
  12232. ** of the following structure.
  12233. */
  12234. typedef struct VdbeOp Op;
  12235. /*
  12236. ** Boolean values
  12237. */
  12238. typedef unsigned char Bool;
  12239. /* Opaque type used by code in vdbesort.c */
  12240. typedef struct VdbeSorter VdbeSorter;
  12241. /* Opaque type used by the explainer */
  12242. typedef struct Explain Explain;
  12243. /*
  12244. ** A cursor is a pointer into a single BTree within a database file.
  12245. ** The cursor can seek to a BTree entry with a particular key, or
  12246. ** loop over all entries of the Btree. You can also insert new BTree
  12247. ** entries or retrieve the key or data from the entry that the cursor
  12248. ** is currently pointing to.
  12249. **
  12250. ** Every cursor that the virtual machine has open is represented by an
  12251. ** instance of the following structure.
  12252. */
  12253. struct VdbeCursor {
  12254. BtCursor *pCursor; /* The cursor structure of the backend */
  12255. Btree *pBt; /* Separate file holding temporary table */
  12256. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  12257. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  12258. int pseudoTableReg; /* Register holding pseudotable content. */
  12259. int nField; /* Number of fields in the header */
  12260. Bool zeroed; /* True if zeroed out and ready for reuse */
  12261. Bool rowidIsValid; /* True if lastRowid is valid */
  12262. Bool atFirst; /* True if pointing to first entry */
  12263. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  12264. Bool nullRow; /* True if pointing to a row with no data */
  12265. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  12266. Bool isTable; /* True if a table requiring integer keys */
  12267. Bool isIndex; /* True if an index containing keys only - no data */
  12268. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  12269. Bool isSorter; /* True if a new-style sorter */
  12270. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  12271. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  12272. i64 seqCount; /* Sequence counter */
  12273. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  12274. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  12275. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  12276. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  12277. ** OP_IsUnique opcode on this cursor. */
  12278. int seekResult;
  12279. /* Cached information about the header for the data record that the
  12280. ** cursor is currently pointing to. Only valid if cacheStatus matches
  12281. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  12282. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  12283. ** the cache is out of date.
  12284. **
  12285. ** aRow might point to (ephemeral) data for the current row, or it might
  12286. ** be NULL.
  12287. */
  12288. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  12289. int payloadSize; /* Total number of bytes in the record */
  12290. u32 *aType; /* Type values for all entries in the record */
  12291. u32 *aOffset; /* Cached offsets to the start of each columns data */
  12292. u8 *aRow; /* Data for the current row, if all on one page */
  12293. };
  12294. typedef struct VdbeCursor VdbeCursor;
  12295. /*
  12296. ** When a sub-program is executed (OP_Program), a structure of this type
  12297. ** is allocated to store the current value of the program counter, as
  12298. ** well as the current memory cell array and various other frame specific
  12299. ** values stored in the Vdbe struct. When the sub-program is finished,
  12300. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  12301. ** restoring the state of the VM to as it was before the sub-program
  12302. ** began executing.
  12303. **
  12304. ** The memory for a VdbeFrame object is allocated and managed by a memory
  12305. ** cell in the parent (calling) frame. When the memory cell is deleted or
  12306. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  12307. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  12308. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  12309. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  12310. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  12311. ** child frame are released.
  12312. **
  12313. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  12314. ** set to NULL if the currently executing frame is the main program.
  12315. */
  12316. typedef struct VdbeFrame VdbeFrame;
  12317. struct VdbeFrame {
  12318. Vdbe *v; /* VM this frame belongs to */
  12319. int pc; /* Program Counter in parent (calling) frame */
  12320. Op *aOp; /* Program instructions for parent frame */
  12321. int nOp; /* Size of aOp array */
  12322. Mem *aMem; /* Array of memory cells for parent frame */
  12323. int nMem; /* Number of entries in aMem */
  12324. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  12325. int nOnceFlag; /* Number of entries in aOnceFlag */
  12326. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  12327. u16 nCursor; /* Number of entries in apCsr */
  12328. void *token; /* Copy of SubProgram.token */
  12329. int nChildMem; /* Number of memory cells for child frame */
  12330. int nChildCsr; /* Number of cursors for child frame */
  12331. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  12332. int nChange; /* Statement changes (Vdbe.nChanges) */
  12333. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  12334. };
  12335. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  12336. /*
  12337. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  12338. */
  12339. #define CACHE_STALE 0
  12340. /*
  12341. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  12342. ** structures. Each Mem struct may cache multiple representations (string,
  12343. ** integer etc.) of the same value.
  12344. */
  12345. struct Mem {
  12346. sqlite3 *db; /* The associated database connection */
  12347. char *z; /* String or BLOB value */
  12348. double r; /* Real value */
  12349. union {
  12350. i64 i; /* Integer value used when MEM_Int is set in flags */
  12351. int nZero; /* Used when bit MEM_Zero is set in flags */
  12352. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  12353. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  12354. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  12355. } u;
  12356. int n; /* Number of characters in string value, excluding '\0' */
  12357. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  12358. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  12359. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  12360. #ifdef SQLITE_DEBUG
  12361. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  12362. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  12363. #endif
  12364. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  12365. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  12366. };
  12367. /* One or more of the following flags are set to indicate the validOK
  12368. ** representations of the value stored in the Mem struct.
  12369. **
  12370. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  12371. ** No other flags may be set in this case.
  12372. **
  12373. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  12374. ** Usually this is encoded in the same unicode encoding as the main
  12375. ** database (see below for exceptions). If the MEM_Term flag is also
  12376. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  12377. ** flags may coexist with the MEM_Str flag.
  12378. */
  12379. #define MEM_Null 0x0001 /* Value is NULL */
  12380. #define MEM_Str 0x0002 /* Value is a string */
  12381. #define MEM_Int 0x0004 /* Value is an integer */
  12382. #define MEM_Real 0x0008 /* Value is a real number */
  12383. #define MEM_Blob 0x0010 /* Value is a BLOB */
  12384. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  12385. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  12386. #define MEM_Invalid 0x0080 /* Value is undefined */
  12387. #define MEM_TypeMask 0x00ff /* Mask of type bits */
  12388. /* Whenever Mem contains a valid string or blob representation, one of
  12389. ** the following flags must be set to determine the memory management
  12390. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  12391. ** string is \000 or \u0000 terminated
  12392. */
  12393. #define MEM_Term 0x0200 /* String rep is nul terminated */
  12394. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  12395. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  12396. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  12397. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  12398. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  12399. #ifdef SQLITE_OMIT_INCRBLOB
  12400. #undef MEM_Zero
  12401. #define MEM_Zero 0x0000
  12402. #endif
  12403. /*
  12404. ** Clear any existing type flags from a Mem and replace them with f
  12405. */
  12406. #define MemSetTypeFlag(p, f) \
  12407. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  12408. /*
  12409. ** Return true if a memory cell is not marked as invalid. This macro
  12410. ** is for use inside assert() statements only.
  12411. */
  12412. #ifdef SQLITE_DEBUG
  12413. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  12414. #endif
  12415. /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
  12416. ** additional information about auxiliary information bound to arguments
  12417. ** of the function. This is used to implement the sqlite3_get_auxdata()
  12418. ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
  12419. ** that can be associated with a constant argument to a function. This
  12420. ** allows functions such as "regexp" to compile their constant regular
  12421. ** expression argument once and reused the compiled code for multiple
  12422. ** invocations.
  12423. */
  12424. struct VdbeFunc {
  12425. FuncDef *pFunc; /* The definition of the function */
  12426. int nAux; /* Number of entries allocated for apAux[] */
  12427. struct AuxData {
  12428. void *pAux; /* Aux data for the i-th argument */
  12429. void (*xDelete)(void *); /* Destructor for the aux data */
  12430. } apAux[1]; /* One slot for each function argument */
  12431. };
  12432. /*
  12433. ** The "context" argument for a installable function. A pointer to an
  12434. ** instance of this structure is the first argument to the routines used
  12435. ** implement the SQL functions.
  12436. **
  12437. ** There is a typedef for this structure in sqlite.h. So all routines,
  12438. ** even the public interface to SQLite, can use a pointer to this structure.
  12439. ** But this file is the only place where the internal details of this
  12440. ** structure are known.
  12441. **
  12442. ** This structure is defined inside of vdbeInt.h because it uses substructures
  12443. ** (Mem) which are only defined there.
  12444. */
  12445. struct sqlite3_context {
  12446. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  12447. VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
  12448. Mem s; /* The return value is stored here */
  12449. Mem *pMem; /* Memory cell used to store aggregate context */
  12450. int isError; /* Error code returned by the function. */
  12451. CollSeq *pColl; /* Collating sequence */
  12452. };
  12453. /*
  12454. ** An Explain object accumulates indented output which is helpful
  12455. ** in describing recursive data structures.
  12456. */
  12457. struct Explain {
  12458. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  12459. StrAccum str; /* The string being accumulated */
  12460. int nIndent; /* Number of elements in aIndent */
  12461. u16 aIndent[100]; /* Levels of indentation */
  12462. char zBase[100]; /* Initial space */
  12463. };
  12464. /*
  12465. ** An instance of the virtual machine. This structure contains the complete
  12466. ** state of the virtual machine.
  12467. **
  12468. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  12469. ** is really a pointer to an instance of this structure.
  12470. **
  12471. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  12472. ** any virtual table method invocations made by the vdbe program. It is
  12473. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  12474. ** variable is used for two purposes: to allow xDestroy methods to execute
  12475. ** "DROP TABLE" statements and to prevent some nasty side effects of
  12476. ** malloc failure when SQLite is invoked recursively by a virtual table
  12477. ** method function.
  12478. */
  12479. struct Vdbe {
  12480. sqlite3 *db; /* The database connection that owns this statement */
  12481. Op *aOp; /* Space to hold the virtual machine's program */
  12482. Mem *aMem; /* The memory locations */
  12483. Mem **apArg; /* Arguments to currently executing user function */
  12484. Mem *aColName; /* Column names to return */
  12485. Mem *pResultSet; /* Pointer to an array of results */
  12486. int nMem; /* Number of memory locations currently allocated */
  12487. int nOp; /* Number of instructions in the program */
  12488. int nOpAlloc; /* Number of slots allocated for aOp[] */
  12489. int nLabel; /* Number of labels used */
  12490. int nLabelAlloc; /* Number of slots allocated in aLabel[] */
  12491. int *aLabel; /* Space to hold the labels */
  12492. u16 nResColumn; /* Number of columns in one row of the result set */
  12493. u16 nCursor; /* Number of slots in apCsr[] */
  12494. u32 magic; /* Magic number for sanity checking */
  12495. char *zErrMsg; /* Error message written here */
  12496. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  12497. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  12498. Mem *aVar; /* Values for the OP_Variable opcode. */
  12499. char **azVar; /* Name of variables */
  12500. ynVar nVar; /* Number of entries in aVar[] */
  12501. ynVar nzVar; /* Number of entries in azVar[] */
  12502. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  12503. int pc; /* The program counter */
  12504. int rc; /* Value to return */
  12505. u8 errorAction; /* Recovery action to do in case of an error */
  12506. u8 explain; /* True if EXPLAIN present on SQL command */
  12507. u8 changeCntOn; /* True to update the change-counter */
  12508. u8 expired; /* True if the VM needs to be recompiled */
  12509. u8 runOnlyOnce; /* Automatically expire on reset */
  12510. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  12511. u8 inVtabMethod; /* See comments above */
  12512. u8 usesStmtJournal; /* True if uses a statement journal */
  12513. u8 readOnly; /* True for read-only statements */
  12514. u8 isPrepareV2; /* True if prepared with prepare_v2() */
  12515. int nChange; /* Number of db changes made since last reset */
  12516. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  12517. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  12518. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  12519. int aCounter[3]; /* Counters used by sqlite3_stmt_status() */
  12520. #ifndef SQLITE_OMIT_TRACE
  12521. i64 startTime; /* Time when query started - used for profiling */
  12522. #endif
  12523. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  12524. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  12525. char *zSql; /* Text of the SQL statement that generated this */
  12526. void *pFree; /* Free this when deleting the vdbe */
  12527. #ifdef SQLITE_DEBUG
  12528. FILE *trace; /* Write an execution trace here, if not NULL */
  12529. #endif
  12530. #ifdef SQLITE_ENABLE_TREE_EXPLAIN
  12531. Explain *pExplain; /* The explainer */
  12532. char *zExplain; /* Explanation of data structures */
  12533. #endif
  12534. VdbeFrame *pFrame; /* Parent frame */
  12535. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  12536. int nFrame; /* Number of frames in pFrame list */
  12537. u32 expmask; /* Binding to these vars invalidates VM */
  12538. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  12539. int nOnceFlag; /* Size of array aOnceFlag[] */
  12540. u8 *aOnceFlag; /* Flags for OP_Once */
  12541. };
  12542. /*
  12543. ** The following are allowed values for Vdbe.magic
  12544. */
  12545. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  12546. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  12547. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  12548. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  12549. /*
  12550. ** Function prototypes
  12551. */
  12552. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  12553. void sqliteVdbePopStack(Vdbe*,int);
  12554. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  12555. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  12556. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  12557. #endif
  12558. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  12559. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  12560. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  12561. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  12562. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
  12563. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  12564. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  12565. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  12566. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  12567. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  12568. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  12569. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  12570. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  12571. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  12572. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  12573. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  12574. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  12575. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  12576. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  12577. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  12578. #ifdef SQLITE_OMIT_FLOATING_POINT
  12579. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  12580. #else
  12581. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  12582. #endif
  12583. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  12584. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  12585. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  12586. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  12587. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  12588. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  12589. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  12590. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  12591. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  12592. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  12593. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  12594. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  12595. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  12596. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  12597. #define VdbeMemRelease(X) \
  12598. if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
  12599. sqlite3VdbeMemReleaseExternal(X);
  12600. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  12601. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  12602. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  12603. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  12604. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  12605. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  12606. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  12607. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  12608. #ifdef SQLITE_OMIT_MERGE_SORT
  12609. # define sqlite3VdbeSorterInit(Y,Z) SQLITE_OK
  12610. # define sqlite3VdbeSorterWrite(X,Y,Z) SQLITE_OK
  12611. # define sqlite3VdbeSorterClose(Y,Z)
  12612. # define sqlite3VdbeSorterRowkey(Y,Z) SQLITE_OK
  12613. # define sqlite3VdbeSorterRewind(X,Y,Z) SQLITE_OK
  12614. # define sqlite3VdbeSorterNext(X,Y,Z) SQLITE_OK
  12615. # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
  12616. #else
  12617. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
  12618. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  12619. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *, Mem *);
  12620. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, VdbeCursor *, int *);
  12621. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, VdbeCursor *, int *);
  12622. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, VdbeCursor *, Mem *);
  12623. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
  12624. #endif
  12625. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  12626. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  12627. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  12628. #else
  12629. # define sqlite3VdbeEnter(X)
  12630. # define sqlite3VdbeLeave(X)
  12631. #endif
  12632. #ifdef SQLITE_DEBUG
  12633. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  12634. #endif
  12635. #ifndef SQLITE_OMIT_FOREIGN_KEY
  12636. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  12637. #else
  12638. # define sqlite3VdbeCheckFk(p,i) 0
  12639. #endif
  12640. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  12641. #ifdef SQLITE_DEBUG
  12642. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  12643. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  12644. #endif
  12645. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  12646. #ifndef SQLITE_OMIT_INCRBLOB
  12647. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  12648. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  12649. #else
  12650. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  12651. #define ExpandBlob(P) SQLITE_OK
  12652. #endif
  12653. #endif /* !defined(_VDBEINT_H_) */
  12654. /************** End of vdbeInt.h *********************************************/
  12655. /************** Continuing where we left off in status.c *********************/
  12656. /*
  12657. ** Variables in which to record status information.
  12658. */
  12659. typedef struct sqlite3StatType sqlite3StatType;
  12660. static SQLITE_WSD struct sqlite3StatType {
  12661. int nowValue[10]; /* Current value */
  12662. int mxValue[10]; /* Maximum value */
  12663. } sqlite3Stat = { {0,}, {0,} };
  12664. /* The "wsdStat" macro will resolve to the status information
  12665. ** state vector. If writable static data is unsupported on the target,
  12666. ** we have to locate the state vector at run-time. In the more common
  12667. ** case where writable static data is supported, wsdStat can refer directly
  12668. ** to the "sqlite3Stat" state vector declared above.
  12669. */
  12670. #ifdef SQLITE_OMIT_WSD
  12671. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  12672. # define wsdStat x[0]
  12673. #else
  12674. # define wsdStatInit
  12675. # define wsdStat sqlite3Stat
  12676. #endif
  12677. /*
  12678. ** Return the current value of a status parameter.
  12679. */
  12680. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  12681. wsdStatInit;
  12682. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12683. return wsdStat.nowValue[op];
  12684. }
  12685. /*
  12686. ** Add N to the value of a status record. It is assumed that the
  12687. ** caller holds appropriate locks.
  12688. */
  12689. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  12690. wsdStatInit;
  12691. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12692. wsdStat.nowValue[op] += N;
  12693. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  12694. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12695. }
  12696. }
  12697. /*
  12698. ** Set the value of a status to X.
  12699. */
  12700. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  12701. wsdStatInit;
  12702. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12703. wsdStat.nowValue[op] = X;
  12704. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  12705. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12706. }
  12707. }
  12708. /*
  12709. ** Query status information.
  12710. **
  12711. ** This implementation assumes that reading or writing an aligned
  12712. ** 32-bit integer is an atomic operation. If that assumption is not true,
  12713. ** then this routine is not threadsafe.
  12714. */
  12715. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  12716. wsdStatInit;
  12717. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  12718. return SQLITE_MISUSE_BKPT;
  12719. }
  12720. *pCurrent = wsdStat.nowValue[op];
  12721. *pHighwater = wsdStat.mxValue[op];
  12722. if( resetFlag ){
  12723. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12724. }
  12725. return SQLITE_OK;
  12726. }
  12727. /*
  12728. ** Query status information for a single database connection
  12729. */
  12730. SQLITE_API int sqlite3_db_status(
  12731. sqlite3 *db, /* The database connection whose status is desired */
  12732. int op, /* Status verb */
  12733. int *pCurrent, /* Write current value here */
  12734. int *pHighwater, /* Write high-water mark here */
  12735. int resetFlag /* Reset high-water mark if true */
  12736. ){
  12737. int rc = SQLITE_OK; /* Return code */
  12738. sqlite3_mutex_enter(db->mutex);
  12739. switch( op ){
  12740. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  12741. *pCurrent = db->lookaside.nOut;
  12742. *pHighwater = db->lookaside.mxOut;
  12743. if( resetFlag ){
  12744. db->lookaside.mxOut = db->lookaside.nOut;
  12745. }
  12746. break;
  12747. }
  12748. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  12749. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  12750. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  12751. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  12752. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  12753. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  12754. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  12755. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  12756. *pCurrent = 0;
  12757. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  12758. if( resetFlag ){
  12759. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  12760. }
  12761. break;
  12762. }
  12763. /*
  12764. ** Return an approximation for the amount of memory currently used
  12765. ** by all pagers associated with the given database connection. The
  12766. ** highwater mark is meaningless and is returned as zero.
  12767. */
  12768. case SQLITE_DBSTATUS_CACHE_USED: {
  12769. int totalUsed = 0;
  12770. int i;
  12771. sqlite3BtreeEnterAll(db);
  12772. for(i=0; i<db->nDb; i++){
  12773. Btree *pBt = db->aDb[i].pBt;
  12774. if( pBt ){
  12775. Pager *pPager = sqlite3BtreePager(pBt);
  12776. totalUsed += sqlite3PagerMemUsed(pPager);
  12777. }
  12778. }
  12779. sqlite3BtreeLeaveAll(db);
  12780. *pCurrent = totalUsed;
  12781. *pHighwater = 0;
  12782. break;
  12783. }
  12784. /*
  12785. ** *pCurrent gets an accurate estimate of the amount of memory used
  12786. ** to store the schema for all databases (main, temp, and any ATTACHed
  12787. ** databases. *pHighwater is set to zero.
  12788. */
  12789. case SQLITE_DBSTATUS_SCHEMA_USED: {
  12790. int i; /* Used to iterate through schemas */
  12791. int nByte = 0; /* Used to accumulate return value */
  12792. sqlite3BtreeEnterAll(db);
  12793. db->pnBytesFreed = &nByte;
  12794. for(i=0; i<db->nDb; i++){
  12795. Schema *pSchema = db->aDb[i].pSchema;
  12796. if( ALWAYS(pSchema!=0) ){
  12797. HashElem *p;
  12798. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  12799. pSchema->tblHash.count
  12800. + pSchema->trigHash.count
  12801. + pSchema->idxHash.count
  12802. + pSchema->fkeyHash.count
  12803. );
  12804. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  12805. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  12806. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  12807. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  12808. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  12809. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  12810. }
  12811. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  12812. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  12813. }
  12814. }
  12815. }
  12816. db->pnBytesFreed = 0;
  12817. sqlite3BtreeLeaveAll(db);
  12818. *pHighwater = 0;
  12819. *pCurrent = nByte;
  12820. break;
  12821. }
  12822. /*
  12823. ** *pCurrent gets an accurate estimate of the amount of memory used
  12824. ** to store all prepared statements.
  12825. ** *pHighwater is set to zero.
  12826. */
  12827. case SQLITE_DBSTATUS_STMT_USED: {
  12828. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  12829. int nByte = 0; /* Used to accumulate return value */
  12830. db->pnBytesFreed = &nByte;
  12831. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  12832. sqlite3VdbeDeleteObject(db, pVdbe);
  12833. }
  12834. db->pnBytesFreed = 0;
  12835. *pHighwater = 0;
  12836. *pCurrent = nByte;
  12837. break;
  12838. }
  12839. /*
  12840. ** Set *pCurrent to the total cache hits or misses encountered by all
  12841. ** pagers the database handle is connected to. *pHighwater is always set
  12842. ** to zero.
  12843. */
  12844. case SQLITE_DBSTATUS_CACHE_HIT:
  12845. case SQLITE_DBSTATUS_CACHE_MISS: {
  12846. int i;
  12847. int nRet = 0;
  12848. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  12849. for(i=0; i<db->nDb; i++){
  12850. if( db->aDb[i].pBt ){
  12851. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  12852. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  12853. }
  12854. }
  12855. *pHighwater = 0;
  12856. *pCurrent = nRet;
  12857. break;
  12858. }
  12859. default: {
  12860. rc = SQLITE_ERROR;
  12861. }
  12862. }
  12863. sqlite3_mutex_leave(db->mutex);
  12864. return rc;
  12865. }
  12866. /************** End of status.c **********************************************/
  12867. /************** Begin file date.c ********************************************/
  12868. /*
  12869. ** 2003 October 31
  12870. **
  12871. ** The author disclaims copyright to this source code. In place of
  12872. ** a legal notice, here is a blessing:
  12873. **
  12874. ** May you do good and not evil.
  12875. ** May you find forgiveness for yourself and forgive others.
  12876. ** May you share freely, never taking more than you give.
  12877. **
  12878. *************************************************************************
  12879. ** This file contains the C functions that implement date and time
  12880. ** functions for SQLite.
  12881. **
  12882. ** There is only one exported symbol in this file - the function
  12883. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  12884. ** All other code has file scope.
  12885. **
  12886. ** SQLite processes all times and dates as Julian Day numbers. The
  12887. ** dates and times are stored as the number of days since noon
  12888. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  12889. ** calendar system.
  12890. **
  12891. ** 1970-01-01 00:00:00 is JD 2440587.5
  12892. ** 2000-01-01 00:00:00 is JD 2451544.5
  12893. **
  12894. ** This implemention requires years to be expressed as a 4-digit number
  12895. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  12896. ** be represented, even though julian day numbers allow a much wider
  12897. ** range of dates.
  12898. **
  12899. ** The Gregorian calendar system is used for all dates and times,
  12900. ** even those that predate the Gregorian calendar. Historians usually
  12901. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  12902. ** dates afterwards, depending on locale. Beware of this difference.
  12903. **
  12904. ** The conversion algorithms are implemented based on descriptions
  12905. ** in the following text:
  12906. **
  12907. ** Jean Meeus
  12908. ** Astronomical Algorithms, 2nd Edition, 1998
  12909. ** ISBM 0-943396-61-1
  12910. ** Willmann-Bell, Inc
  12911. ** Richmond, Virginia (USA)
  12912. */
  12913. /* #include <stdlib.h> */
  12914. /* #include <assert.h> */
  12915. #include <time.h>
  12916. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  12917. /*
  12918. ** A structure for holding a single date and time.
  12919. */
  12920. typedef struct DateTime DateTime;
  12921. struct DateTime {
  12922. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  12923. int Y, M, D; /* Year, month, and day */
  12924. int h, m; /* Hour and minutes */
  12925. int tz; /* Timezone offset in minutes */
  12926. double s; /* Seconds */
  12927. char validYMD; /* True (1) if Y,M,D are valid */
  12928. char validHMS; /* True (1) if h,m,s are valid */
  12929. char validJD; /* True (1) if iJD is valid */
  12930. char validTZ; /* True (1) if tz is valid */
  12931. };
  12932. /*
  12933. ** Convert zDate into one or more integers. Additional arguments
  12934. ** come in groups of 5 as follows:
  12935. **
  12936. ** N number of digits in the integer
  12937. ** min minimum allowed value of the integer
  12938. ** max maximum allowed value of the integer
  12939. ** nextC first character after the integer
  12940. ** pVal where to write the integers value.
  12941. **
  12942. ** Conversions continue until one with nextC==0 is encountered.
  12943. ** The function returns the number of successful conversions.
  12944. */
  12945. static int getDigits(const char *zDate, ...){
  12946. va_list ap;
  12947. int val;
  12948. int N;
  12949. int min;
  12950. int max;
  12951. int nextC;
  12952. int *pVal;
  12953. int cnt = 0;
  12954. va_start(ap, zDate);
  12955. do{
  12956. N = va_arg(ap, int);
  12957. min = va_arg(ap, int);
  12958. max = va_arg(ap, int);
  12959. nextC = va_arg(ap, int);
  12960. pVal = va_arg(ap, int*);
  12961. val = 0;
  12962. while( N-- ){
  12963. if( !sqlite3Isdigit(*zDate) ){
  12964. goto end_getDigits;
  12965. }
  12966. val = val*10 + *zDate - '0';
  12967. zDate++;
  12968. }
  12969. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  12970. goto end_getDigits;
  12971. }
  12972. *pVal = val;
  12973. zDate++;
  12974. cnt++;
  12975. }while( nextC );
  12976. end_getDigits:
  12977. va_end(ap);
  12978. return cnt;
  12979. }
  12980. /*
  12981. ** Parse a timezone extension on the end of a date-time.
  12982. ** The extension is of the form:
  12983. **
  12984. ** (+/-)HH:MM
  12985. **
  12986. ** Or the "zulu" notation:
  12987. **
  12988. ** Z
  12989. **
  12990. ** If the parse is successful, write the number of minutes
  12991. ** of change in p->tz and return 0. If a parser error occurs,
  12992. ** return non-zero.
  12993. **
  12994. ** A missing specifier is not considered an error.
  12995. */
  12996. static int parseTimezone(const char *zDate, DateTime *p){
  12997. int sgn = 0;
  12998. int nHr, nMn;
  12999. int c;
  13000. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13001. p->tz = 0;
  13002. c = *zDate;
  13003. if( c=='-' ){
  13004. sgn = -1;
  13005. }else if( c=='+' ){
  13006. sgn = +1;
  13007. }else if( c=='Z' || c=='z' ){
  13008. zDate++;
  13009. goto zulu_time;
  13010. }else{
  13011. return c!=0;
  13012. }
  13013. zDate++;
  13014. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  13015. return 1;
  13016. }
  13017. zDate += 5;
  13018. p->tz = sgn*(nMn + nHr*60);
  13019. zulu_time:
  13020. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13021. return *zDate!=0;
  13022. }
  13023. /*
  13024. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  13025. ** The HH, MM, and SS must each be exactly 2 digits. The
  13026. ** fractional seconds FFFF can be one or more digits.
  13027. **
  13028. ** Return 1 if there is a parsing error and 0 on success.
  13029. */
  13030. static int parseHhMmSs(const char *zDate, DateTime *p){
  13031. int h, m, s;
  13032. double ms = 0.0;
  13033. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  13034. return 1;
  13035. }
  13036. zDate += 5;
  13037. if( *zDate==':' ){
  13038. zDate++;
  13039. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  13040. return 1;
  13041. }
  13042. zDate += 2;
  13043. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  13044. double rScale = 1.0;
  13045. zDate++;
  13046. while( sqlite3Isdigit(*zDate) ){
  13047. ms = ms*10.0 + *zDate - '0';
  13048. rScale *= 10.0;
  13049. zDate++;
  13050. }
  13051. ms /= rScale;
  13052. }
  13053. }else{
  13054. s = 0;
  13055. }
  13056. p->validJD = 0;
  13057. p->validHMS = 1;
  13058. p->h = h;
  13059. p->m = m;
  13060. p->s = s + ms;
  13061. if( parseTimezone(zDate, p) ) return 1;
  13062. p->validTZ = (p->tz!=0)?1:0;
  13063. return 0;
  13064. }
  13065. /*
  13066. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  13067. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  13068. **
  13069. ** Reference: Meeus page 61
  13070. */
  13071. static void computeJD(DateTime *p){
  13072. int Y, M, D, A, B, X1, X2;
  13073. if( p->validJD ) return;
  13074. if( p->validYMD ){
  13075. Y = p->Y;
  13076. M = p->M;
  13077. D = p->D;
  13078. }else{
  13079. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  13080. M = 1;
  13081. D = 1;
  13082. }
  13083. if( M<=2 ){
  13084. Y--;
  13085. M += 12;
  13086. }
  13087. A = Y/100;
  13088. B = 2 - A + (A/4);
  13089. X1 = 36525*(Y+4716)/100;
  13090. X2 = 306001*(M+1)/10000;
  13091. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  13092. p->validJD = 1;
  13093. if( p->validHMS ){
  13094. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  13095. if( p->validTZ ){
  13096. p->iJD -= p->tz*60000;
  13097. p->validYMD = 0;
  13098. p->validHMS = 0;
  13099. p->validTZ = 0;
  13100. }
  13101. }
  13102. }
  13103. /*
  13104. ** Parse dates of the form
  13105. **
  13106. ** YYYY-MM-DD HH:MM:SS.FFF
  13107. ** YYYY-MM-DD HH:MM:SS
  13108. ** YYYY-MM-DD HH:MM
  13109. ** YYYY-MM-DD
  13110. **
  13111. ** Write the result into the DateTime structure and return 0
  13112. ** on success and 1 if the input string is not a well-formed
  13113. ** date.
  13114. */
  13115. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  13116. int Y, M, D, neg;
  13117. if( zDate[0]=='-' ){
  13118. zDate++;
  13119. neg = 1;
  13120. }else{
  13121. neg = 0;
  13122. }
  13123. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  13124. return 1;
  13125. }
  13126. zDate += 10;
  13127. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  13128. if( parseHhMmSs(zDate, p)==0 ){
  13129. /* We got the time */
  13130. }else if( *zDate==0 ){
  13131. p->validHMS = 0;
  13132. }else{
  13133. return 1;
  13134. }
  13135. p->validJD = 0;
  13136. p->validYMD = 1;
  13137. p->Y = neg ? -Y : Y;
  13138. p->M = M;
  13139. p->D = D;
  13140. if( p->validTZ ){
  13141. computeJD(p);
  13142. }
  13143. return 0;
  13144. }
  13145. /*
  13146. ** Set the time to the current time reported by the VFS.
  13147. **
  13148. ** Return the number of errors.
  13149. */
  13150. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  13151. sqlite3 *db = sqlite3_context_db_handle(context);
  13152. if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
  13153. p->validJD = 1;
  13154. return 0;
  13155. }else{
  13156. return 1;
  13157. }
  13158. }
  13159. /*
  13160. ** Attempt to parse the given string into a Julian Day Number. Return
  13161. ** the number of errors.
  13162. **
  13163. ** The following are acceptable forms for the input string:
  13164. **
  13165. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  13166. ** DDDD.DD
  13167. ** now
  13168. **
  13169. ** In the first form, the +/-HH:MM is always optional. The fractional
  13170. ** seconds extension (the ".FFF") is optional. The seconds portion
  13171. ** (":SS.FFF") is option. The year and date can be omitted as long
  13172. ** as there is a time string. The time string can be omitted as long
  13173. ** as there is a year and date.
  13174. */
  13175. static int parseDateOrTime(
  13176. sqlite3_context *context,
  13177. const char *zDate,
  13178. DateTime *p
  13179. ){
  13180. double r;
  13181. if( parseYyyyMmDd(zDate,p)==0 ){
  13182. return 0;
  13183. }else if( parseHhMmSs(zDate, p)==0 ){
  13184. return 0;
  13185. }else if( sqlite3StrICmp(zDate,"now")==0){
  13186. return setDateTimeToCurrent(context, p);
  13187. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  13188. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  13189. p->validJD = 1;
  13190. return 0;
  13191. }
  13192. return 1;
  13193. }
  13194. /*
  13195. ** Compute the Year, Month, and Day from the julian day number.
  13196. */
  13197. static void computeYMD(DateTime *p){
  13198. int Z, A, B, C, D, E, X1;
  13199. if( p->validYMD ) return;
  13200. if( !p->validJD ){
  13201. p->Y = 2000;
  13202. p->M = 1;
  13203. p->D = 1;
  13204. }else{
  13205. Z = (int)((p->iJD + 43200000)/86400000);
  13206. A = (int)((Z - 1867216.25)/36524.25);
  13207. A = Z + 1 + A - (A/4);
  13208. B = A + 1524;
  13209. C = (int)((B - 122.1)/365.25);
  13210. D = (36525*C)/100;
  13211. E = (int)((B-D)/30.6001);
  13212. X1 = (int)(30.6001*E);
  13213. p->D = B - D - X1;
  13214. p->M = E<14 ? E-1 : E-13;
  13215. p->Y = p->M>2 ? C - 4716 : C - 4715;
  13216. }
  13217. p->validYMD = 1;
  13218. }
  13219. /*
  13220. ** Compute the Hour, Minute, and Seconds from the julian day number.
  13221. */
  13222. static void computeHMS(DateTime *p){
  13223. int s;
  13224. if( p->validHMS ) return;
  13225. computeJD(p);
  13226. s = (int)((p->iJD + 43200000) % 86400000);
  13227. p->s = s/1000.0;
  13228. s = (int)p->s;
  13229. p->s -= s;
  13230. p->h = s/3600;
  13231. s -= p->h*3600;
  13232. p->m = s/60;
  13233. p->s += s - p->m*60;
  13234. p->validHMS = 1;
  13235. }
  13236. /*
  13237. ** Compute both YMD and HMS
  13238. */
  13239. static void computeYMD_HMS(DateTime *p){
  13240. computeYMD(p);
  13241. computeHMS(p);
  13242. }
  13243. /*
  13244. ** Clear the YMD and HMS and the TZ
  13245. */
  13246. static void clearYMD_HMS_TZ(DateTime *p){
  13247. p->validYMD = 0;
  13248. p->validHMS = 0;
  13249. p->validTZ = 0;
  13250. }
  13251. /*
  13252. ** On recent Windows platforms, the localtime_s() function is available
  13253. ** as part of the "Secure CRT". It is essentially equivalent to
  13254. ** localtime_r() available under most POSIX platforms, except that the
  13255. ** order of the parameters is reversed.
  13256. **
  13257. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  13258. **
  13259. ** If the user has not indicated to use localtime_r() or localtime_s()
  13260. ** already, check for an MSVC build environment that provides
  13261. ** localtime_s().
  13262. */
  13263. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  13264. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  13265. #define HAVE_LOCALTIME_S 1
  13266. #endif
  13267. #ifndef SQLITE_OMIT_LOCALTIME
  13268. /*
  13269. ** The following routine implements the rough equivalent of localtime_r()
  13270. ** using whatever operating-system specific localtime facility that
  13271. ** is available. This routine returns 0 on success and
  13272. ** non-zero on any kind of error.
  13273. **
  13274. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  13275. ** routine will always fail.
  13276. */
  13277. static int osLocaltime(time_t *t, struct tm *pTm){
  13278. int rc;
  13279. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  13280. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  13281. struct tm *pX;
  13282. #if SQLITE_THREADSAFE>0
  13283. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13284. #endif
  13285. sqlite3_mutex_enter(mutex);
  13286. pX = localtime(t);
  13287. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13288. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  13289. #endif
  13290. if( pX ) *pTm = *pX;
  13291. sqlite3_mutex_leave(mutex);
  13292. rc = pX==0;
  13293. #else
  13294. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13295. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  13296. #endif
  13297. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  13298. rc = localtime_r(t, pTm)==0;
  13299. #else
  13300. rc = localtime_s(pTm, t);
  13301. #endif /* HAVE_LOCALTIME_R */
  13302. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  13303. return rc;
  13304. }
  13305. #endif /* SQLITE_OMIT_LOCALTIME */
  13306. #ifndef SQLITE_OMIT_LOCALTIME
  13307. /*
  13308. ** Compute the difference (in milliseconds) between localtime and UTC
  13309. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  13310. ** return this value and set *pRc to SQLITE_OK.
  13311. **
  13312. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  13313. ** is undefined in this case.
  13314. */
  13315. static sqlite3_int64 localtimeOffset(
  13316. DateTime *p, /* Date at which to calculate offset */
  13317. sqlite3_context *pCtx, /* Write error here if one occurs */
  13318. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  13319. ){
  13320. DateTime x, y;
  13321. time_t t;
  13322. struct tm sLocal;
  13323. /* Initialize the contents of sLocal to avoid a compiler warning. */
  13324. memset(&sLocal, 0, sizeof(sLocal));
  13325. x = *p;
  13326. computeYMD_HMS(&x);
  13327. if( x.Y<1971 || x.Y>=2038 ){
  13328. x.Y = 2000;
  13329. x.M = 1;
  13330. x.D = 1;
  13331. x.h = 0;
  13332. x.m = 0;
  13333. x.s = 0.0;
  13334. } else {
  13335. int s = (int)(x.s + 0.5);
  13336. x.s = s;
  13337. }
  13338. x.tz = 0;
  13339. x.validJD = 0;
  13340. computeJD(&x);
  13341. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  13342. if( osLocaltime(&t, &sLocal) ){
  13343. sqlite3_result_error(pCtx, "local time unavailable", -1);
  13344. *pRc = SQLITE_ERROR;
  13345. return 0;
  13346. }
  13347. y.Y = sLocal.tm_year + 1900;
  13348. y.M = sLocal.tm_mon + 1;
  13349. y.D = sLocal.tm_mday;
  13350. y.h = sLocal.tm_hour;
  13351. y.m = sLocal.tm_min;
  13352. y.s = sLocal.tm_sec;
  13353. y.validYMD = 1;
  13354. y.validHMS = 1;
  13355. y.validJD = 0;
  13356. y.validTZ = 0;
  13357. computeJD(&y);
  13358. *pRc = SQLITE_OK;
  13359. return y.iJD - x.iJD;
  13360. }
  13361. #endif /* SQLITE_OMIT_LOCALTIME */
  13362. /*
  13363. ** Process a modifier to a date-time stamp. The modifiers are
  13364. ** as follows:
  13365. **
  13366. ** NNN days
  13367. ** NNN hours
  13368. ** NNN minutes
  13369. ** NNN.NNNN seconds
  13370. ** NNN months
  13371. ** NNN years
  13372. ** start of month
  13373. ** start of year
  13374. ** start of week
  13375. ** start of day
  13376. ** weekday N
  13377. ** unixepoch
  13378. ** localtime
  13379. ** utc
  13380. **
  13381. ** Return 0 on success and 1 if there is any kind of error. If the error
  13382. ** is in a system call (i.e. localtime()), then an error message is written
  13383. ** to context pCtx. If the error is an unrecognized modifier, no error is
  13384. ** written to pCtx.
  13385. */
  13386. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  13387. int rc = 1;
  13388. int n;
  13389. double r;
  13390. char *z, zBuf[30];
  13391. z = zBuf;
  13392. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  13393. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  13394. }
  13395. z[n] = 0;
  13396. switch( z[0] ){
  13397. #ifndef SQLITE_OMIT_LOCALTIME
  13398. case 'l': {
  13399. /* localtime
  13400. **
  13401. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  13402. ** show local time.
  13403. */
  13404. if( strcmp(z, "localtime")==0 ){
  13405. computeJD(p);
  13406. p->iJD += localtimeOffset(p, pCtx, &rc);
  13407. clearYMD_HMS_TZ(p);
  13408. }
  13409. break;
  13410. }
  13411. #endif
  13412. case 'u': {
  13413. /*
  13414. ** unixepoch
  13415. **
  13416. ** Treat the current value of p->iJD as the number of
  13417. ** seconds since 1970. Convert to a real julian day number.
  13418. */
  13419. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  13420. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  13421. clearYMD_HMS_TZ(p);
  13422. rc = 0;
  13423. }
  13424. #ifndef SQLITE_OMIT_LOCALTIME
  13425. else if( strcmp(z, "utc")==0 ){
  13426. sqlite3_int64 c1;
  13427. computeJD(p);
  13428. c1 = localtimeOffset(p, pCtx, &rc);
  13429. if( rc==SQLITE_OK ){
  13430. p->iJD -= c1;
  13431. clearYMD_HMS_TZ(p);
  13432. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  13433. }
  13434. }
  13435. #endif
  13436. break;
  13437. }
  13438. case 'w': {
  13439. /*
  13440. ** weekday N
  13441. **
  13442. ** Move the date to the same time on the next occurrence of
  13443. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  13444. ** date is already on the appropriate weekday, this is a no-op.
  13445. */
  13446. if( strncmp(z, "weekday ", 8)==0
  13447. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  13448. && (n=(int)r)==r && n>=0 && r<7 ){
  13449. sqlite3_int64 Z;
  13450. computeYMD_HMS(p);
  13451. p->validTZ = 0;
  13452. p->validJD = 0;
  13453. computeJD(p);
  13454. Z = ((p->iJD + 129600000)/86400000) % 7;
  13455. if( Z>n ) Z -= 7;
  13456. p->iJD += (n - Z)*86400000;
  13457. clearYMD_HMS_TZ(p);
  13458. rc = 0;
  13459. }
  13460. break;
  13461. }
  13462. case 's': {
  13463. /*
  13464. ** start of TTTTT
  13465. **
  13466. ** Move the date backwards to the beginning of the current day,
  13467. ** or month or year.
  13468. */
  13469. if( strncmp(z, "start of ", 9)!=0 ) break;
  13470. z += 9;
  13471. computeYMD(p);
  13472. p->validHMS = 1;
  13473. p->h = p->m = 0;
  13474. p->s = 0.0;
  13475. p->validTZ = 0;
  13476. p->validJD = 0;
  13477. if( strcmp(z,"month")==0 ){
  13478. p->D = 1;
  13479. rc = 0;
  13480. }else if( strcmp(z,"year")==0 ){
  13481. computeYMD(p);
  13482. p->M = 1;
  13483. p->D = 1;
  13484. rc = 0;
  13485. }else if( strcmp(z,"day")==0 ){
  13486. rc = 0;
  13487. }
  13488. break;
  13489. }
  13490. case '+':
  13491. case '-':
  13492. case '0':
  13493. case '1':
  13494. case '2':
  13495. case '3':
  13496. case '4':
  13497. case '5':
  13498. case '6':
  13499. case '7':
  13500. case '8':
  13501. case '9': {
  13502. double rRounder;
  13503. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  13504. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  13505. rc = 1;
  13506. break;
  13507. }
  13508. if( z[n]==':' ){
  13509. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  13510. ** specified number of hours, minutes, seconds, and fractional seconds
  13511. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  13512. ** omitted.
  13513. */
  13514. const char *z2 = z;
  13515. DateTime tx;
  13516. sqlite3_int64 day;
  13517. if( !sqlite3Isdigit(*z2) ) z2++;
  13518. memset(&tx, 0, sizeof(tx));
  13519. if( parseHhMmSs(z2, &tx) ) break;
  13520. computeJD(&tx);
  13521. tx.iJD -= 43200000;
  13522. day = tx.iJD/86400000;
  13523. tx.iJD -= day*86400000;
  13524. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  13525. computeJD(p);
  13526. clearYMD_HMS_TZ(p);
  13527. p->iJD += tx.iJD;
  13528. rc = 0;
  13529. break;
  13530. }
  13531. z += n;
  13532. while( sqlite3Isspace(*z) ) z++;
  13533. n = sqlite3Strlen30(z);
  13534. if( n>10 || n<3 ) break;
  13535. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  13536. computeJD(p);
  13537. rc = 0;
  13538. rRounder = r<0 ? -0.5 : +0.5;
  13539. if( n==3 && strcmp(z,"day")==0 ){
  13540. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  13541. }else if( n==4 && strcmp(z,"hour")==0 ){
  13542. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  13543. }else if( n==6 && strcmp(z,"minute")==0 ){
  13544. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  13545. }else if( n==6 && strcmp(z,"second")==0 ){
  13546. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  13547. }else if( n==5 && strcmp(z,"month")==0 ){
  13548. int x, y;
  13549. computeYMD_HMS(p);
  13550. p->M += (int)r;
  13551. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  13552. p->Y += x;
  13553. p->M -= x*12;
  13554. p->validJD = 0;
  13555. computeJD(p);
  13556. y = (int)r;
  13557. if( y!=r ){
  13558. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  13559. }
  13560. }else if( n==4 && strcmp(z,"year")==0 ){
  13561. int y = (int)r;
  13562. computeYMD_HMS(p);
  13563. p->Y += y;
  13564. p->validJD = 0;
  13565. computeJD(p);
  13566. if( y!=r ){
  13567. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  13568. }
  13569. }else{
  13570. rc = 1;
  13571. }
  13572. clearYMD_HMS_TZ(p);
  13573. break;
  13574. }
  13575. default: {
  13576. break;
  13577. }
  13578. }
  13579. return rc;
  13580. }
  13581. /*
  13582. ** Process time function arguments. argv[0] is a date-time stamp.
  13583. ** argv[1] and following are modifiers. Parse them all and write
  13584. ** the resulting time into the DateTime structure p. Return 0
  13585. ** on success and 1 if there are any errors.
  13586. **
  13587. ** If there are zero parameters (if even argv[0] is undefined)
  13588. ** then assume a default value of "now" for argv[0].
  13589. */
  13590. static int isDate(
  13591. sqlite3_context *context,
  13592. int argc,
  13593. sqlite3_value **argv,
  13594. DateTime *p
  13595. ){
  13596. int i;
  13597. const unsigned char *z;
  13598. int eType;
  13599. memset(p, 0, sizeof(*p));
  13600. if( argc==0 ){
  13601. return setDateTimeToCurrent(context, p);
  13602. }
  13603. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  13604. || eType==SQLITE_INTEGER ){
  13605. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  13606. p->validJD = 1;
  13607. }else{
  13608. z = sqlite3_value_text(argv[0]);
  13609. if( !z || parseDateOrTime(context, (char*)z, p) ){
  13610. return 1;
  13611. }
  13612. }
  13613. for(i=1; i<argc; i++){
  13614. z = sqlite3_value_text(argv[i]);
  13615. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  13616. }
  13617. return 0;
  13618. }
  13619. /*
  13620. ** The following routines implement the various date and time functions
  13621. ** of SQLite.
  13622. */
  13623. /*
  13624. ** julianday( TIMESTRING, MOD, MOD, ...)
  13625. **
  13626. ** Return the julian day number of the date specified in the arguments
  13627. */
  13628. static void juliandayFunc(
  13629. sqlite3_context *context,
  13630. int argc,
  13631. sqlite3_value **argv
  13632. ){
  13633. DateTime x;
  13634. if( isDate(context, argc, argv, &x)==0 ){
  13635. computeJD(&x);
  13636. sqlite3_result_double(context, x.iJD/86400000.0);
  13637. }
  13638. }
  13639. /*
  13640. ** datetime( TIMESTRING, MOD, MOD, ...)
  13641. **
  13642. ** Return YYYY-MM-DD HH:MM:SS
  13643. */
  13644. static void datetimeFunc(
  13645. sqlite3_context *context,
  13646. int argc,
  13647. sqlite3_value **argv
  13648. ){
  13649. DateTime x;
  13650. if( isDate(context, argc, argv, &x)==0 ){
  13651. char zBuf[100];
  13652. computeYMD_HMS(&x);
  13653. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  13654. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  13655. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13656. }
  13657. }
  13658. /*
  13659. ** time( TIMESTRING, MOD, MOD, ...)
  13660. **
  13661. ** Return HH:MM:SS
  13662. */
  13663. static void timeFunc(
  13664. sqlite3_context *context,
  13665. int argc,
  13666. sqlite3_value **argv
  13667. ){
  13668. DateTime x;
  13669. if( isDate(context, argc, argv, &x)==0 ){
  13670. char zBuf[100];
  13671. computeHMS(&x);
  13672. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  13673. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13674. }
  13675. }
  13676. /*
  13677. ** date( TIMESTRING, MOD, MOD, ...)
  13678. **
  13679. ** Return YYYY-MM-DD
  13680. */
  13681. static void dateFunc(
  13682. sqlite3_context *context,
  13683. int argc,
  13684. sqlite3_value **argv
  13685. ){
  13686. DateTime x;
  13687. if( isDate(context, argc, argv, &x)==0 ){
  13688. char zBuf[100];
  13689. computeYMD(&x);
  13690. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  13691. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13692. }
  13693. }
  13694. /*
  13695. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  13696. **
  13697. ** Return a string described by FORMAT. Conversions as follows:
  13698. **
  13699. ** %d day of month
  13700. ** %f ** fractional seconds SS.SSS
  13701. ** %H hour 00-24
  13702. ** %j day of year 000-366
  13703. ** %J ** Julian day number
  13704. ** %m month 01-12
  13705. ** %M minute 00-59
  13706. ** %s seconds since 1970-01-01
  13707. ** %S seconds 00-59
  13708. ** %w day of week 0-6 sunday==0
  13709. ** %W week of year 00-53
  13710. ** %Y year 0000-9999
  13711. ** %% %
  13712. */
  13713. static void strftimeFunc(
  13714. sqlite3_context *context,
  13715. int argc,
  13716. sqlite3_value **argv
  13717. ){
  13718. DateTime x;
  13719. u64 n;
  13720. size_t i,j;
  13721. char *z;
  13722. sqlite3 *db;
  13723. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  13724. char zBuf[100];
  13725. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  13726. db = sqlite3_context_db_handle(context);
  13727. for(i=0, n=1; zFmt[i]; i++, n++){
  13728. if( zFmt[i]=='%' ){
  13729. switch( zFmt[i+1] ){
  13730. case 'd':
  13731. case 'H':
  13732. case 'm':
  13733. case 'M':
  13734. case 'S':
  13735. case 'W':
  13736. n++;
  13737. /* fall thru */
  13738. case 'w':
  13739. case '%':
  13740. break;
  13741. case 'f':
  13742. n += 8;
  13743. break;
  13744. case 'j':
  13745. n += 3;
  13746. break;
  13747. case 'Y':
  13748. n += 8;
  13749. break;
  13750. case 's':
  13751. case 'J':
  13752. n += 50;
  13753. break;
  13754. default:
  13755. return; /* ERROR. return a NULL */
  13756. }
  13757. i++;
  13758. }
  13759. }
  13760. testcase( n==sizeof(zBuf)-1 );
  13761. testcase( n==sizeof(zBuf) );
  13762. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  13763. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  13764. if( n<sizeof(zBuf) ){
  13765. z = zBuf;
  13766. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  13767. sqlite3_result_error_toobig(context);
  13768. return;
  13769. }else{
  13770. z = sqlite3DbMallocRaw(db, (int)n);
  13771. if( z==0 ){
  13772. sqlite3_result_error_nomem(context);
  13773. return;
  13774. }
  13775. }
  13776. computeJD(&x);
  13777. computeYMD_HMS(&x);
  13778. for(i=j=0; zFmt[i]; i++){
  13779. if( zFmt[i]!='%' ){
  13780. z[j++] = zFmt[i];
  13781. }else{
  13782. i++;
  13783. switch( zFmt[i] ){
  13784. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  13785. case 'f': {
  13786. double s = x.s;
  13787. if( s>59.999 ) s = 59.999;
  13788. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  13789. j += sqlite3Strlen30(&z[j]);
  13790. break;
  13791. }
  13792. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  13793. case 'W': /* Fall thru */
  13794. case 'j': {
  13795. int nDay; /* Number of days since 1st day of year */
  13796. DateTime y = x;
  13797. y.validJD = 0;
  13798. y.M = 1;
  13799. y.D = 1;
  13800. computeJD(&y);
  13801. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  13802. if( zFmt[i]=='W' ){
  13803. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  13804. wd = (int)(((x.iJD+43200000)/86400000)%7);
  13805. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  13806. j += 2;
  13807. }else{
  13808. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  13809. j += 3;
  13810. }
  13811. break;
  13812. }
  13813. case 'J': {
  13814. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  13815. j+=sqlite3Strlen30(&z[j]);
  13816. break;
  13817. }
  13818. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  13819. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  13820. case 's': {
  13821. sqlite3_snprintf(30,&z[j],"%lld",
  13822. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  13823. j += sqlite3Strlen30(&z[j]);
  13824. break;
  13825. }
  13826. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  13827. case 'w': {
  13828. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  13829. break;
  13830. }
  13831. case 'Y': {
  13832. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  13833. break;
  13834. }
  13835. default: z[j++] = '%'; break;
  13836. }
  13837. }
  13838. }
  13839. z[j] = 0;
  13840. sqlite3_result_text(context, z, -1,
  13841. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  13842. }
  13843. /*
  13844. ** current_time()
  13845. **
  13846. ** This function returns the same value as time('now').
  13847. */
  13848. static void ctimeFunc(
  13849. sqlite3_context *context,
  13850. int NotUsed,
  13851. sqlite3_value **NotUsed2
  13852. ){
  13853. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  13854. timeFunc(context, 0, 0);
  13855. }
  13856. /*
  13857. ** current_date()
  13858. **
  13859. ** This function returns the same value as date('now').
  13860. */
  13861. static void cdateFunc(
  13862. sqlite3_context *context,
  13863. int NotUsed,
  13864. sqlite3_value **NotUsed2
  13865. ){
  13866. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  13867. dateFunc(context, 0, 0);
  13868. }
  13869. /*
  13870. ** current_timestamp()
  13871. **
  13872. ** This function returns the same value as datetime('now').
  13873. */
  13874. static void ctimestampFunc(
  13875. sqlite3_context *context,
  13876. int NotUsed,
  13877. sqlite3_value **NotUsed2
  13878. ){
  13879. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  13880. datetimeFunc(context, 0, 0);
  13881. }
  13882. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  13883. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  13884. /*
  13885. ** If the library is compiled to omit the full-scale date and time
  13886. ** handling (to get a smaller binary), the following minimal version
  13887. ** of the functions current_time(), current_date() and current_timestamp()
  13888. ** are included instead. This is to support column declarations that
  13889. ** include "DEFAULT CURRENT_TIME" etc.
  13890. **
  13891. ** This function uses the C-library functions time(), gmtime()
  13892. ** and strftime(). The format string to pass to strftime() is supplied
  13893. ** as the user-data for the function.
  13894. */
  13895. static void currentTimeFunc(
  13896. sqlite3_context *context,
  13897. int argc,
  13898. sqlite3_value **argv
  13899. ){
  13900. time_t t;
  13901. char *zFormat = (char *)sqlite3_user_data(context);
  13902. sqlite3 *db;
  13903. sqlite3_int64 iT;
  13904. struct tm *pTm;
  13905. struct tm sNow;
  13906. char zBuf[20];
  13907. UNUSED_PARAMETER(argc);
  13908. UNUSED_PARAMETER(argv);
  13909. db = sqlite3_context_db_handle(context);
  13910. if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
  13911. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  13912. #ifdef HAVE_GMTIME_R
  13913. pTm = gmtime_r(&t, &sNow);
  13914. #else
  13915. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  13916. pTm = gmtime(&t);
  13917. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  13918. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  13919. #endif
  13920. if( pTm ){
  13921. strftime(zBuf, 20, zFormat, &sNow);
  13922. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13923. }
  13924. }
  13925. #endif
  13926. /*
  13927. ** This function registered all of the above C functions as SQL
  13928. ** functions. This should be the only routine in this file with
  13929. ** external linkage.
  13930. */
  13931. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  13932. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  13933. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13934. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  13935. FUNCTION(date, -1, 0, 0, dateFunc ),
  13936. FUNCTION(time, -1, 0, 0, timeFunc ),
  13937. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  13938. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  13939. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  13940. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  13941. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  13942. #else
  13943. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  13944. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  13945. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  13946. #endif
  13947. };
  13948. int i;
  13949. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  13950. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  13951. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  13952. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  13953. }
  13954. }
  13955. /************** End of date.c ************************************************/
  13956. /************** Begin file os.c **********************************************/
  13957. /*
  13958. ** 2005 November 29
  13959. **
  13960. ** The author disclaims copyright to this source code. In place of
  13961. ** a legal notice, here is a blessing:
  13962. **
  13963. ** May you do good and not evil.
  13964. ** May you find forgiveness for yourself and forgive others.
  13965. ** May you share freely, never taking more than you give.
  13966. **
  13967. ******************************************************************************
  13968. **
  13969. ** This file contains OS interface code that is common to all
  13970. ** architectures.
  13971. */
  13972. #define _SQLITE_OS_C_ 1
  13973. #undef _SQLITE_OS_C_
  13974. /*
  13975. ** The default SQLite sqlite3_vfs implementations do not allocate
  13976. ** memory (actually, os_unix.c allocates a small amount of memory
  13977. ** from within OsOpen()), but some third-party implementations may.
  13978. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  13979. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  13980. **
  13981. ** The following functions are instrumented for malloc() failure
  13982. ** testing:
  13983. **
  13984. ** sqlite3OsRead()
  13985. ** sqlite3OsWrite()
  13986. ** sqlite3OsSync()
  13987. ** sqlite3OsFileSize()
  13988. ** sqlite3OsLock()
  13989. ** sqlite3OsCheckReservedLock()
  13990. ** sqlite3OsFileControl()
  13991. ** sqlite3OsShmMap()
  13992. ** sqlite3OsOpen()
  13993. ** sqlite3OsDelete()
  13994. ** sqlite3OsAccess()
  13995. ** sqlite3OsFullPathname()
  13996. **
  13997. */
  13998. #if defined(SQLITE_TEST)
  13999. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  14000. #define DO_OS_MALLOC_TEST(x) \
  14001. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  14002. void *pTstAlloc = sqlite3Malloc(10); \
  14003. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  14004. sqlite3_free(pTstAlloc); \
  14005. }
  14006. #else
  14007. #define DO_OS_MALLOC_TEST(x)
  14008. #endif
  14009. /*
  14010. ** The following routines are convenience wrappers around methods
  14011. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  14012. ** of this would be completely automatic if SQLite were coded using
  14013. ** C++ instead of plain old C.
  14014. */
  14015. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  14016. int rc = SQLITE_OK;
  14017. if( pId->pMethods ){
  14018. rc = pId->pMethods->xClose(pId);
  14019. pId->pMethods = 0;
  14020. }
  14021. return rc;
  14022. }
  14023. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  14024. DO_OS_MALLOC_TEST(id);
  14025. return id->pMethods->xRead(id, pBuf, amt, offset);
  14026. }
  14027. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  14028. DO_OS_MALLOC_TEST(id);
  14029. return id->pMethods->xWrite(id, pBuf, amt, offset);
  14030. }
  14031. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  14032. return id->pMethods->xTruncate(id, size);
  14033. }
  14034. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  14035. DO_OS_MALLOC_TEST(id);
  14036. return id->pMethods->xSync(id, flags);
  14037. }
  14038. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  14039. DO_OS_MALLOC_TEST(id);
  14040. return id->pMethods->xFileSize(id, pSize);
  14041. }
  14042. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  14043. DO_OS_MALLOC_TEST(id);
  14044. return id->pMethods->xLock(id, lockType);
  14045. }
  14046. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  14047. return id->pMethods->xUnlock(id, lockType);
  14048. }
  14049. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  14050. DO_OS_MALLOC_TEST(id);
  14051. return id->pMethods->xCheckReservedLock(id, pResOut);
  14052. }
  14053. /*
  14054. ** Use sqlite3OsFileControl() when we are doing something that might fail
  14055. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  14056. ** when simply tossing information over the wall to the VFS and we do not
  14057. ** really care if the VFS receives and understands the information since it
  14058. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  14059. ** routine has no return value since the return value would be meaningless.
  14060. */
  14061. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  14062. DO_OS_MALLOC_TEST(id);
  14063. return id->pMethods->xFileControl(id, op, pArg);
  14064. }
  14065. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  14066. (void)id->pMethods->xFileControl(id, op, pArg);
  14067. }
  14068. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  14069. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  14070. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  14071. }
  14072. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  14073. return id->pMethods->xDeviceCharacteristics(id);
  14074. }
  14075. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  14076. return id->pMethods->xShmLock(id, offset, n, flags);
  14077. }
  14078. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  14079. id->pMethods->xShmBarrier(id);
  14080. }
  14081. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  14082. return id->pMethods->xShmUnmap(id, deleteFlag);
  14083. }
  14084. SQLITE_PRIVATE int sqlite3OsShmMap(
  14085. sqlite3_file *id, /* Database file handle */
  14086. int iPage,
  14087. int pgsz,
  14088. int bExtend, /* True to extend file if necessary */
  14089. void volatile **pp /* OUT: Pointer to mapping */
  14090. ){
  14091. DO_OS_MALLOC_TEST(id);
  14092. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  14093. }
  14094. /*
  14095. ** The next group of routines are convenience wrappers around the
  14096. ** VFS methods.
  14097. */
  14098. SQLITE_PRIVATE int sqlite3OsOpen(
  14099. sqlite3_vfs *pVfs,
  14100. const char *zPath,
  14101. sqlite3_file *pFile,
  14102. int flags,
  14103. int *pFlagsOut
  14104. ){
  14105. int rc;
  14106. DO_OS_MALLOC_TEST(0);
  14107. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  14108. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  14109. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  14110. ** reaching the VFS. */
  14111. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  14112. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  14113. return rc;
  14114. }
  14115. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  14116. DO_OS_MALLOC_TEST(0);
  14117. assert( dirSync==0 || dirSync==1 );
  14118. return pVfs->xDelete(pVfs, zPath, dirSync);
  14119. }
  14120. SQLITE_PRIVATE int sqlite3OsAccess(
  14121. sqlite3_vfs *pVfs,
  14122. const char *zPath,
  14123. int flags,
  14124. int *pResOut
  14125. ){
  14126. DO_OS_MALLOC_TEST(0);
  14127. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  14128. }
  14129. SQLITE_PRIVATE int sqlite3OsFullPathname(
  14130. sqlite3_vfs *pVfs,
  14131. const char *zPath,
  14132. int nPathOut,
  14133. char *zPathOut
  14134. ){
  14135. DO_OS_MALLOC_TEST(0);
  14136. zPathOut[0] = 0;
  14137. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  14138. }
  14139. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14140. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  14141. return pVfs->xDlOpen(pVfs, zPath);
  14142. }
  14143. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14144. pVfs->xDlError(pVfs, nByte, zBufOut);
  14145. }
  14146. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  14147. return pVfs->xDlSym(pVfs, pHdle, zSym);
  14148. }
  14149. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  14150. pVfs->xDlClose(pVfs, pHandle);
  14151. }
  14152. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14153. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14154. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  14155. }
  14156. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  14157. return pVfs->xSleep(pVfs, nMicro);
  14158. }
  14159. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  14160. int rc;
  14161. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  14162. ** method to get the current date and time if that method is available
  14163. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  14164. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  14165. ** unavailable.
  14166. */
  14167. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  14168. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  14169. }else{
  14170. double r;
  14171. rc = pVfs->xCurrentTime(pVfs, &r);
  14172. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  14173. }
  14174. return rc;
  14175. }
  14176. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  14177. sqlite3_vfs *pVfs,
  14178. const char *zFile,
  14179. sqlite3_file **ppFile,
  14180. int flags,
  14181. int *pOutFlags
  14182. ){
  14183. int rc = SQLITE_NOMEM;
  14184. sqlite3_file *pFile;
  14185. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  14186. if( pFile ){
  14187. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  14188. if( rc!=SQLITE_OK ){
  14189. sqlite3_free(pFile);
  14190. }else{
  14191. *ppFile = pFile;
  14192. }
  14193. }
  14194. return rc;
  14195. }
  14196. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  14197. int rc = SQLITE_OK;
  14198. assert( pFile );
  14199. rc = sqlite3OsClose(pFile);
  14200. sqlite3_free(pFile);
  14201. return rc;
  14202. }
  14203. /*
  14204. ** This function is a wrapper around the OS specific implementation of
  14205. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  14206. ** ability to simulate a malloc failure, so that the handling of an
  14207. ** error in sqlite3_os_init() by the upper layers can be tested.
  14208. */
  14209. SQLITE_PRIVATE int sqlite3OsInit(void){
  14210. void *p = sqlite3_malloc(10);
  14211. if( p==0 ) return SQLITE_NOMEM;
  14212. sqlite3_free(p);
  14213. return sqlite3_os_init();
  14214. }
  14215. /*
  14216. ** The list of all registered VFS implementations.
  14217. */
  14218. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  14219. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  14220. /*
  14221. ** Locate a VFS by name. If no name is given, simply return the
  14222. ** first VFS on the list.
  14223. */
  14224. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  14225. sqlite3_vfs *pVfs = 0;
  14226. #if SQLITE_THREADSAFE
  14227. sqlite3_mutex *mutex;
  14228. #endif
  14229. #ifndef SQLITE_OMIT_AUTOINIT
  14230. int rc = sqlite3_initialize();
  14231. if( rc ) return 0;
  14232. #endif
  14233. #if SQLITE_THREADSAFE
  14234. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14235. #endif
  14236. sqlite3_mutex_enter(mutex);
  14237. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  14238. if( zVfs==0 ) break;
  14239. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  14240. }
  14241. sqlite3_mutex_leave(mutex);
  14242. return pVfs;
  14243. }
  14244. /*
  14245. ** Unlink a VFS from the linked list
  14246. */
  14247. static void vfsUnlink(sqlite3_vfs *pVfs){
  14248. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  14249. if( pVfs==0 ){
  14250. /* No-op */
  14251. }else if( vfsList==pVfs ){
  14252. vfsList = pVfs->pNext;
  14253. }else if( vfsList ){
  14254. sqlite3_vfs *p = vfsList;
  14255. while( p->pNext && p->pNext!=pVfs ){
  14256. p = p->pNext;
  14257. }
  14258. if( p->pNext==pVfs ){
  14259. p->pNext = pVfs->pNext;
  14260. }
  14261. }
  14262. }
  14263. /*
  14264. ** Register a VFS with the system. It is harmless to register the same
  14265. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  14266. ** true.
  14267. */
  14268. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  14269. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  14270. #ifndef SQLITE_OMIT_AUTOINIT
  14271. int rc = sqlite3_initialize();
  14272. if( rc ) return rc;
  14273. #endif
  14274. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  14275. sqlite3_mutex_enter(mutex);
  14276. vfsUnlink(pVfs);
  14277. if( makeDflt || vfsList==0 ){
  14278. pVfs->pNext = vfsList;
  14279. vfsList = pVfs;
  14280. }else{
  14281. pVfs->pNext = vfsList->pNext;
  14282. vfsList->pNext = pVfs;
  14283. }
  14284. assert(vfsList);
  14285. sqlite3_mutex_leave(mutex);
  14286. return SQLITE_OK;
  14287. }
  14288. /*
  14289. ** Unregister a VFS so that it is no longer accessible.
  14290. */
  14291. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  14292. #if SQLITE_THREADSAFE
  14293. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14294. #endif
  14295. sqlite3_mutex_enter(mutex);
  14296. vfsUnlink(pVfs);
  14297. sqlite3_mutex_leave(mutex);
  14298. return SQLITE_OK;
  14299. }
  14300. /************** End of os.c **************************************************/
  14301. /************** Begin file fault.c *******************************************/
  14302. /*
  14303. ** 2008 Jan 22
  14304. **
  14305. ** The author disclaims copyright to this source code. In place of
  14306. ** a legal notice, here is a blessing:
  14307. **
  14308. ** May you do good and not evil.
  14309. ** May you find forgiveness for yourself and forgive others.
  14310. ** May you share freely, never taking more than you give.
  14311. **
  14312. *************************************************************************
  14313. **
  14314. ** This file contains code to support the concept of "benign"
  14315. ** malloc failures (when the xMalloc() or xRealloc() method of the
  14316. ** sqlite3_mem_methods structure fails to allocate a block of memory
  14317. ** and returns 0).
  14318. **
  14319. ** Most malloc failures are non-benign. After they occur, SQLite
  14320. ** abandons the current operation and returns an error code (usually
  14321. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  14322. ** fatal. For example, if a malloc fails while resizing a hash table, this
  14323. ** is completely recoverable simply by not carrying out the resize. The
  14324. ** hash table will continue to function normally. So a malloc failure
  14325. ** during a hash table resize is a benign fault.
  14326. */
  14327. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14328. /*
  14329. ** Global variables.
  14330. */
  14331. typedef struct BenignMallocHooks BenignMallocHooks;
  14332. static SQLITE_WSD struct BenignMallocHooks {
  14333. void (*xBenignBegin)(void);
  14334. void (*xBenignEnd)(void);
  14335. } sqlite3Hooks = { 0, 0 };
  14336. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  14337. ** structure. If writable static data is unsupported on the target,
  14338. ** we have to locate the state vector at run-time. In the more common
  14339. ** case where writable static data is supported, wsdHooks can refer directly
  14340. ** to the "sqlite3Hooks" state vector declared above.
  14341. */
  14342. #ifdef SQLITE_OMIT_WSD
  14343. # define wsdHooksInit \
  14344. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  14345. # define wsdHooks x[0]
  14346. #else
  14347. # define wsdHooksInit
  14348. # define wsdHooks sqlite3Hooks
  14349. #endif
  14350. /*
  14351. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  14352. ** sqlite3EndBenignMalloc() are called, respectively.
  14353. */
  14354. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  14355. void (*xBenignBegin)(void),
  14356. void (*xBenignEnd)(void)
  14357. ){
  14358. wsdHooksInit;
  14359. wsdHooks.xBenignBegin = xBenignBegin;
  14360. wsdHooks.xBenignEnd = xBenignEnd;
  14361. }
  14362. /*
  14363. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  14364. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  14365. ** indicates that subsequent malloc failures are non-benign.
  14366. */
  14367. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  14368. wsdHooksInit;
  14369. if( wsdHooks.xBenignBegin ){
  14370. wsdHooks.xBenignBegin();
  14371. }
  14372. }
  14373. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  14374. wsdHooksInit;
  14375. if( wsdHooks.xBenignEnd ){
  14376. wsdHooks.xBenignEnd();
  14377. }
  14378. }
  14379. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  14380. /************** End of fault.c ***********************************************/
  14381. /************** Begin file mem0.c ********************************************/
  14382. /*
  14383. ** 2008 October 28
  14384. **
  14385. ** The author disclaims copyright to this source code. In place of
  14386. ** a legal notice, here is a blessing:
  14387. **
  14388. ** May you do good and not evil.
  14389. ** May you find forgiveness for yourself and forgive others.
  14390. ** May you share freely, never taking more than you give.
  14391. **
  14392. *************************************************************************
  14393. **
  14394. ** This file contains a no-op memory allocation drivers for use when
  14395. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  14396. ** here always fail. SQLite will not operate with these drivers. These
  14397. ** are merely placeholders. Real drivers must be substituted using
  14398. ** sqlite3_config() before SQLite will operate.
  14399. */
  14400. /*
  14401. ** This version of the memory allocator is the default. It is
  14402. ** used when no other memory allocator is specified using compile-time
  14403. ** macros.
  14404. */
  14405. #ifdef SQLITE_ZERO_MALLOC
  14406. /*
  14407. ** No-op versions of all memory allocation routines
  14408. */
  14409. static void *sqlite3MemMalloc(int nByte){ return 0; }
  14410. static void sqlite3MemFree(void *pPrior){ return; }
  14411. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  14412. static int sqlite3MemSize(void *pPrior){ return 0; }
  14413. static int sqlite3MemRoundup(int n){ return n; }
  14414. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  14415. static void sqlite3MemShutdown(void *NotUsed){ return; }
  14416. /*
  14417. ** This routine is the only routine in this file with external linkage.
  14418. **
  14419. ** Populate the low-level memory allocation function pointers in
  14420. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14421. */
  14422. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14423. static const sqlite3_mem_methods defaultMethods = {
  14424. sqlite3MemMalloc,
  14425. sqlite3MemFree,
  14426. sqlite3MemRealloc,
  14427. sqlite3MemSize,
  14428. sqlite3MemRoundup,
  14429. sqlite3MemInit,
  14430. sqlite3MemShutdown,
  14431. 0
  14432. };
  14433. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14434. }
  14435. #endif /* SQLITE_ZERO_MALLOC */
  14436. /************** End of mem0.c ************************************************/
  14437. /************** Begin file mem1.c ********************************************/
  14438. /*
  14439. ** 2007 August 14
  14440. **
  14441. ** The author disclaims copyright to this source code. In place of
  14442. ** a legal notice, here is a blessing:
  14443. **
  14444. ** May you do good and not evil.
  14445. ** May you find forgiveness for yourself and forgive others.
  14446. ** May you share freely, never taking more than you give.
  14447. **
  14448. *************************************************************************
  14449. **
  14450. ** This file contains low-level memory allocation drivers for when
  14451. ** SQLite will use the standard C-library malloc/realloc/free interface
  14452. ** to obtain the memory it needs.
  14453. **
  14454. ** This file contains implementations of the low-level memory allocation
  14455. ** routines specified in the sqlite3_mem_methods object.
  14456. */
  14457. /*
  14458. ** This version of the memory allocator is the default. It is
  14459. ** used when no other memory allocator is specified using compile-time
  14460. ** macros.
  14461. */
  14462. #ifdef SQLITE_SYSTEM_MALLOC
  14463. /*
  14464. ** Windows systems have malloc_usable_size() but it is called _msize()
  14465. */
  14466. #if !defined(HAVE_MALLOC_USABLE_SIZE) && SQLITE_OS_WIN
  14467. # define HAVE_MALLOC_USABLE_SIZE 1
  14468. # define malloc_usable_size _msize
  14469. #endif
  14470. #if defined(__APPLE__)
  14471. /*
  14472. ** Use the zone allocator available on apple products
  14473. */
  14474. #include <sys/sysctl.h>
  14475. #include <malloc/malloc.h>
  14476. #include <libkern/OSAtomic.h>
  14477. static malloc_zone_t* _sqliteZone_;
  14478. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  14479. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  14480. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  14481. #define SQLITE_MALLOCSIZE(x) \
  14482. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  14483. #else /* if not __APPLE__ */
  14484. /*
  14485. ** Use standard C library malloc and free on non-Apple systems.
  14486. */
  14487. #define SQLITE_MALLOC(x) malloc(x)
  14488. #define SQLITE_FREE(x) free(x)
  14489. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  14490. #ifdef HAVE_MALLOC_USABLE_SIZE
  14491. #include <malloc.h>
  14492. #define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  14493. #else
  14494. #undef SQLITE_MALLOCSIZE
  14495. #endif
  14496. #endif /* __APPLE__ or not __APPLE__ */
  14497. /*
  14498. ** Like malloc(), but remember the size of the allocation
  14499. ** so that we can find it later using sqlite3MemSize().
  14500. **
  14501. ** For this low-level routine, we are guaranteed that nByte>0 because
  14502. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  14503. ** routines.
  14504. */
  14505. static void *sqlite3MemMalloc(int nByte){
  14506. #ifdef SQLITE_MALLOCSIZE
  14507. void *p = SQLITE_MALLOC( nByte );
  14508. if( p==0 ){
  14509. testcase( sqlite3GlobalConfig.xLog!=0 );
  14510. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  14511. }
  14512. return p;
  14513. #else
  14514. sqlite3_int64 *p;
  14515. assert( nByte>0 );
  14516. nByte = ROUND8(nByte);
  14517. p = SQLITE_MALLOC( nByte+8 );
  14518. if( p ){
  14519. p[0] = nByte;
  14520. p++;
  14521. }else{
  14522. testcase( sqlite3GlobalConfig.xLog!=0 );
  14523. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  14524. }
  14525. return (void *)p;
  14526. #endif
  14527. }
  14528. /*
  14529. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  14530. ** or sqlite3MemRealloc().
  14531. **
  14532. ** For this low-level routine, we already know that pPrior!=0 since
  14533. ** cases where pPrior==0 will have been intecepted and dealt with
  14534. ** by higher-level routines.
  14535. */
  14536. static void sqlite3MemFree(void *pPrior){
  14537. #ifdef SQLITE_MALLOCSIZE
  14538. SQLITE_FREE(pPrior);
  14539. #else
  14540. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  14541. assert( pPrior!=0 );
  14542. p--;
  14543. SQLITE_FREE(p);
  14544. #endif
  14545. }
  14546. /*
  14547. ** Report the allocated size of a prior return from xMalloc()
  14548. ** or xRealloc().
  14549. */
  14550. static int sqlite3MemSize(void *pPrior){
  14551. #ifdef SQLITE_MALLOCSIZE
  14552. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  14553. #else
  14554. sqlite3_int64 *p;
  14555. if( pPrior==0 ) return 0;
  14556. p = (sqlite3_int64*)pPrior;
  14557. p--;
  14558. return (int)p[0];
  14559. #endif
  14560. }
  14561. /*
  14562. ** Like realloc(). Resize an allocation previously obtained from
  14563. ** sqlite3MemMalloc().
  14564. **
  14565. ** For this low-level interface, we know that pPrior!=0. Cases where
  14566. ** pPrior==0 while have been intercepted by higher-level routine and
  14567. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  14568. ** cases where nByte<=0 will have been intercepted by higher-level
  14569. ** routines and redirected to xFree.
  14570. */
  14571. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  14572. #ifdef SQLITE_MALLOCSIZE
  14573. void *p = SQLITE_REALLOC(pPrior, nByte);
  14574. if( p==0 ){
  14575. testcase( sqlite3GlobalConfig.xLog!=0 );
  14576. sqlite3_log(SQLITE_NOMEM,
  14577. "failed memory resize %u to %u bytes",
  14578. SQLITE_MALLOCSIZE(pPrior), nByte);
  14579. }
  14580. return p;
  14581. #else
  14582. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  14583. assert( pPrior!=0 && nByte>0 );
  14584. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  14585. p--;
  14586. p = SQLITE_REALLOC(p, nByte+8 );
  14587. if( p ){
  14588. p[0] = nByte;
  14589. p++;
  14590. }else{
  14591. testcase( sqlite3GlobalConfig.xLog!=0 );
  14592. sqlite3_log(SQLITE_NOMEM,
  14593. "failed memory resize %u to %u bytes",
  14594. sqlite3MemSize(pPrior), nByte);
  14595. }
  14596. return (void*)p;
  14597. #endif
  14598. }
  14599. /*
  14600. ** Round up a request size to the next valid allocation size.
  14601. */
  14602. static int sqlite3MemRoundup(int n){
  14603. return ROUND8(n);
  14604. }
  14605. /*
  14606. ** Initialize this module.
  14607. */
  14608. static int sqlite3MemInit(void *NotUsed){
  14609. #if defined(__APPLE__)
  14610. int cpuCount;
  14611. size_t len;
  14612. if( _sqliteZone_ ){
  14613. return SQLITE_OK;
  14614. }
  14615. len = sizeof(cpuCount);
  14616. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  14617. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  14618. if( cpuCount>1 ){
  14619. /* defer MT decisions to system malloc */
  14620. _sqliteZone_ = malloc_default_zone();
  14621. }else{
  14622. /* only 1 core, use our own zone to contention over global locks,
  14623. ** e.g. we have our own dedicated locks */
  14624. bool success;
  14625. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  14626. malloc_set_zone_name(newzone, "Sqlite_Heap");
  14627. do{
  14628. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  14629. (void * volatile *)&_sqliteZone_);
  14630. }while(!_sqliteZone_);
  14631. if( !success ){
  14632. /* somebody registered a zone first */
  14633. malloc_destroy_zone(newzone);
  14634. }
  14635. }
  14636. #endif
  14637. UNUSED_PARAMETER(NotUsed);
  14638. return SQLITE_OK;
  14639. }
  14640. /*
  14641. ** Deinitialize this module.
  14642. */
  14643. static void sqlite3MemShutdown(void *NotUsed){
  14644. UNUSED_PARAMETER(NotUsed);
  14645. return;
  14646. }
  14647. /*
  14648. ** This routine is the only routine in this file with external linkage.
  14649. **
  14650. ** Populate the low-level memory allocation function pointers in
  14651. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14652. */
  14653. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14654. static const sqlite3_mem_methods defaultMethods = {
  14655. sqlite3MemMalloc,
  14656. sqlite3MemFree,
  14657. sqlite3MemRealloc,
  14658. sqlite3MemSize,
  14659. sqlite3MemRoundup,
  14660. sqlite3MemInit,
  14661. sqlite3MemShutdown,
  14662. 0
  14663. };
  14664. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14665. }
  14666. #endif /* SQLITE_SYSTEM_MALLOC */
  14667. /************** End of mem1.c ************************************************/
  14668. /************** Begin file mem2.c ********************************************/
  14669. /*
  14670. ** 2007 August 15
  14671. **
  14672. ** The author disclaims copyright to this source code. In place of
  14673. ** a legal notice, here is a blessing:
  14674. **
  14675. ** May you do good and not evil.
  14676. ** May you find forgiveness for yourself and forgive others.
  14677. ** May you share freely, never taking more than you give.
  14678. **
  14679. *************************************************************************
  14680. **
  14681. ** This file contains low-level memory allocation drivers for when
  14682. ** SQLite will use the standard C-library malloc/realloc/free interface
  14683. ** to obtain the memory it needs while adding lots of additional debugging
  14684. ** information to each allocation in order to help detect and fix memory
  14685. ** leaks and memory usage errors.
  14686. **
  14687. ** This file contains implementations of the low-level memory allocation
  14688. ** routines specified in the sqlite3_mem_methods object.
  14689. */
  14690. /*
  14691. ** This version of the memory allocator is used only if the
  14692. ** SQLITE_MEMDEBUG macro is defined
  14693. */
  14694. #ifdef SQLITE_MEMDEBUG
  14695. /*
  14696. ** The backtrace functionality is only available with GLIBC
  14697. */
  14698. #ifdef __GLIBC__
  14699. extern int backtrace(void**,int);
  14700. extern void backtrace_symbols_fd(void*const*,int,int);
  14701. #else
  14702. # define backtrace(A,B) 1
  14703. # define backtrace_symbols_fd(A,B,C)
  14704. #endif
  14705. /* #include <stdio.h> */
  14706. /*
  14707. ** Each memory allocation looks like this:
  14708. **
  14709. ** ------------------------------------------------------------------------
  14710. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  14711. ** ------------------------------------------------------------------------
  14712. **
  14713. ** The application code sees only a pointer to the allocation. We have
  14714. ** to back up from the allocation pointer to find the MemBlockHdr. The
  14715. ** MemBlockHdr tells us the size of the allocation and the number of
  14716. ** backtrace pointers. There is also a guard word at the end of the
  14717. ** MemBlockHdr.
  14718. */
  14719. struct MemBlockHdr {
  14720. i64 iSize; /* Size of this allocation */
  14721. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  14722. char nBacktrace; /* Number of backtraces on this alloc */
  14723. char nBacktraceSlots; /* Available backtrace slots */
  14724. u8 nTitle; /* Bytes of title; includes '\0' */
  14725. u8 eType; /* Allocation type code */
  14726. int iForeGuard; /* Guard word for sanity */
  14727. };
  14728. /*
  14729. ** Guard words
  14730. */
  14731. #define FOREGUARD 0x80F5E153
  14732. #define REARGUARD 0xE4676B53
  14733. /*
  14734. ** Number of malloc size increments to track.
  14735. */
  14736. #define NCSIZE 1000
  14737. /*
  14738. ** All of the static variables used by this module are collected
  14739. ** into a single structure named "mem". This is to keep the
  14740. ** static variables organized and to reduce namespace pollution
  14741. ** when this module is combined with other in the amalgamation.
  14742. */
  14743. static struct {
  14744. /*
  14745. ** Mutex to control access to the memory allocation subsystem.
  14746. */
  14747. sqlite3_mutex *mutex;
  14748. /*
  14749. ** Head and tail of a linked list of all outstanding allocations
  14750. */
  14751. struct MemBlockHdr *pFirst;
  14752. struct MemBlockHdr *pLast;
  14753. /*
  14754. ** The number of levels of backtrace to save in new allocations.
  14755. */
  14756. int nBacktrace;
  14757. void (*xBacktrace)(int, int, void **);
  14758. /*
  14759. ** Title text to insert in front of each block
  14760. */
  14761. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  14762. char zTitle[100]; /* The title text */
  14763. /*
  14764. ** sqlite3MallocDisallow() increments the following counter.
  14765. ** sqlite3MallocAllow() decrements it.
  14766. */
  14767. int disallow; /* Do not allow memory allocation */
  14768. /*
  14769. ** Gather statistics on the sizes of memory allocations.
  14770. ** nAlloc[i] is the number of allocation attempts of i*8
  14771. ** bytes. i==NCSIZE is the number of allocation attempts for
  14772. ** sizes more than NCSIZE*8 bytes.
  14773. */
  14774. int nAlloc[NCSIZE]; /* Total number of allocations */
  14775. int nCurrent[NCSIZE]; /* Current number of allocations */
  14776. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  14777. } mem;
  14778. /*
  14779. ** Adjust memory usage statistics
  14780. */
  14781. static void adjustStats(int iSize, int increment){
  14782. int i = ROUND8(iSize)/8;
  14783. if( i>NCSIZE-1 ){
  14784. i = NCSIZE - 1;
  14785. }
  14786. if( increment>0 ){
  14787. mem.nAlloc[i]++;
  14788. mem.nCurrent[i]++;
  14789. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  14790. mem.mxCurrent[i] = mem.nCurrent[i];
  14791. }
  14792. }else{
  14793. mem.nCurrent[i]--;
  14794. assert( mem.nCurrent[i]>=0 );
  14795. }
  14796. }
  14797. /*
  14798. ** Given an allocation, find the MemBlockHdr for that allocation.
  14799. **
  14800. ** This routine checks the guards at either end of the allocation and
  14801. ** if they are incorrect it asserts.
  14802. */
  14803. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  14804. struct MemBlockHdr *p;
  14805. int *pInt;
  14806. u8 *pU8;
  14807. int nReserve;
  14808. p = (struct MemBlockHdr*)pAllocation;
  14809. p--;
  14810. assert( p->iForeGuard==(int)FOREGUARD );
  14811. nReserve = ROUND8(p->iSize);
  14812. pInt = (int*)pAllocation;
  14813. pU8 = (u8*)pAllocation;
  14814. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  14815. /* This checks any of the "extra" bytes allocated due
  14816. ** to rounding up to an 8 byte boundary to ensure
  14817. ** they haven't been overwritten.
  14818. */
  14819. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  14820. return p;
  14821. }
  14822. /*
  14823. ** Return the number of bytes currently allocated at address p.
  14824. */
  14825. static int sqlite3MemSize(void *p){
  14826. struct MemBlockHdr *pHdr;
  14827. if( !p ){
  14828. return 0;
  14829. }
  14830. pHdr = sqlite3MemsysGetHeader(p);
  14831. return pHdr->iSize;
  14832. }
  14833. /*
  14834. ** Initialize the memory allocation subsystem.
  14835. */
  14836. static int sqlite3MemInit(void *NotUsed){
  14837. UNUSED_PARAMETER(NotUsed);
  14838. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  14839. if( !sqlite3GlobalConfig.bMemstat ){
  14840. /* If memory status is enabled, then the malloc.c wrapper will already
  14841. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  14842. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  14843. }
  14844. return SQLITE_OK;
  14845. }
  14846. /*
  14847. ** Deinitialize the memory allocation subsystem.
  14848. */
  14849. static void sqlite3MemShutdown(void *NotUsed){
  14850. UNUSED_PARAMETER(NotUsed);
  14851. mem.mutex = 0;
  14852. }
  14853. /*
  14854. ** Round up a request size to the next valid allocation size.
  14855. */
  14856. static int sqlite3MemRoundup(int n){
  14857. return ROUND8(n);
  14858. }
  14859. /*
  14860. ** Fill a buffer with pseudo-random bytes. This is used to preset
  14861. ** the content of a new memory allocation to unpredictable values and
  14862. ** to clear the content of a freed allocation to unpredictable values.
  14863. */
  14864. static void randomFill(char *pBuf, int nByte){
  14865. unsigned int x, y, r;
  14866. x = SQLITE_PTR_TO_INT(pBuf);
  14867. y = nByte | 1;
  14868. while( nByte >= 4 ){
  14869. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  14870. y = y*1103515245 + 12345;
  14871. r = x ^ y;
  14872. *(int*)pBuf = r;
  14873. pBuf += 4;
  14874. nByte -= 4;
  14875. }
  14876. while( nByte-- > 0 ){
  14877. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  14878. y = y*1103515245 + 12345;
  14879. r = x ^ y;
  14880. *(pBuf++) = r & 0xff;
  14881. }
  14882. }
  14883. /*
  14884. ** Allocate nByte bytes of memory.
  14885. */
  14886. static void *sqlite3MemMalloc(int nByte){
  14887. struct MemBlockHdr *pHdr;
  14888. void **pBt;
  14889. char *z;
  14890. int *pInt;
  14891. void *p = 0;
  14892. int totalSize;
  14893. int nReserve;
  14894. sqlite3_mutex_enter(mem.mutex);
  14895. assert( mem.disallow==0 );
  14896. nReserve = ROUND8(nByte);
  14897. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  14898. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  14899. p = malloc(totalSize);
  14900. if( p ){
  14901. z = p;
  14902. pBt = (void**)&z[mem.nTitle];
  14903. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  14904. pHdr->pNext = 0;
  14905. pHdr->pPrev = mem.pLast;
  14906. if( mem.pLast ){
  14907. mem.pLast->pNext = pHdr;
  14908. }else{
  14909. mem.pFirst = pHdr;
  14910. }
  14911. mem.pLast = pHdr;
  14912. pHdr->iForeGuard = FOREGUARD;
  14913. pHdr->eType = MEMTYPE_HEAP;
  14914. pHdr->nBacktraceSlots = mem.nBacktrace;
  14915. pHdr->nTitle = mem.nTitle;
  14916. if( mem.nBacktrace ){
  14917. void *aAddr[40];
  14918. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  14919. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  14920. assert(pBt[0]);
  14921. if( mem.xBacktrace ){
  14922. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  14923. }
  14924. }else{
  14925. pHdr->nBacktrace = 0;
  14926. }
  14927. if( mem.nTitle ){
  14928. memcpy(z, mem.zTitle, mem.nTitle);
  14929. }
  14930. pHdr->iSize = nByte;
  14931. adjustStats(nByte, +1);
  14932. pInt = (int*)&pHdr[1];
  14933. pInt[nReserve/sizeof(int)] = REARGUARD;
  14934. randomFill((char*)pInt, nByte);
  14935. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  14936. p = (void*)pInt;
  14937. }
  14938. sqlite3_mutex_leave(mem.mutex);
  14939. return p;
  14940. }
  14941. /*
  14942. ** Free memory.
  14943. */
  14944. static void sqlite3MemFree(void *pPrior){
  14945. struct MemBlockHdr *pHdr;
  14946. void **pBt;
  14947. char *z;
  14948. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  14949. || mem.mutex!=0 );
  14950. pHdr = sqlite3MemsysGetHeader(pPrior);
  14951. pBt = (void**)pHdr;
  14952. pBt -= pHdr->nBacktraceSlots;
  14953. sqlite3_mutex_enter(mem.mutex);
  14954. if( pHdr->pPrev ){
  14955. assert( pHdr->pPrev->pNext==pHdr );
  14956. pHdr->pPrev->pNext = pHdr->pNext;
  14957. }else{
  14958. assert( mem.pFirst==pHdr );
  14959. mem.pFirst = pHdr->pNext;
  14960. }
  14961. if( pHdr->pNext ){
  14962. assert( pHdr->pNext->pPrev==pHdr );
  14963. pHdr->pNext->pPrev = pHdr->pPrev;
  14964. }else{
  14965. assert( mem.pLast==pHdr );
  14966. mem.pLast = pHdr->pPrev;
  14967. }
  14968. z = (char*)pBt;
  14969. z -= pHdr->nTitle;
  14970. adjustStats(pHdr->iSize, -1);
  14971. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  14972. pHdr->iSize + sizeof(int) + pHdr->nTitle);
  14973. free(z);
  14974. sqlite3_mutex_leave(mem.mutex);
  14975. }
  14976. /*
  14977. ** Change the size of an existing memory allocation.
  14978. **
  14979. ** For this debugging implementation, we *always* make a copy of the
  14980. ** allocation into a new place in memory. In this way, if the
  14981. ** higher level code is using pointer to the old allocation, it is
  14982. ** much more likely to break and we are much more liking to find
  14983. ** the error.
  14984. */
  14985. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  14986. struct MemBlockHdr *pOldHdr;
  14987. void *pNew;
  14988. assert( mem.disallow==0 );
  14989. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  14990. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  14991. pNew = sqlite3MemMalloc(nByte);
  14992. if( pNew ){
  14993. memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
  14994. if( nByte>pOldHdr->iSize ){
  14995. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
  14996. }
  14997. sqlite3MemFree(pPrior);
  14998. }
  14999. return pNew;
  15000. }
  15001. /*
  15002. ** Populate the low-level memory allocation function pointers in
  15003. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15004. */
  15005. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15006. static const sqlite3_mem_methods defaultMethods = {
  15007. sqlite3MemMalloc,
  15008. sqlite3MemFree,
  15009. sqlite3MemRealloc,
  15010. sqlite3MemSize,
  15011. sqlite3MemRoundup,
  15012. sqlite3MemInit,
  15013. sqlite3MemShutdown,
  15014. 0
  15015. };
  15016. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15017. }
  15018. /*
  15019. ** Set the "type" of an allocation.
  15020. */
  15021. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  15022. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15023. struct MemBlockHdr *pHdr;
  15024. pHdr = sqlite3MemsysGetHeader(p);
  15025. assert( pHdr->iForeGuard==FOREGUARD );
  15026. pHdr->eType = eType;
  15027. }
  15028. }
  15029. /*
  15030. ** Return TRUE if the mask of type in eType matches the type of the
  15031. ** allocation p. Also return true if p==NULL.
  15032. **
  15033. ** This routine is designed for use within an assert() statement, to
  15034. ** verify the type of an allocation. For example:
  15035. **
  15036. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  15037. */
  15038. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  15039. int rc = 1;
  15040. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15041. struct MemBlockHdr *pHdr;
  15042. pHdr = sqlite3MemsysGetHeader(p);
  15043. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15044. if( (pHdr->eType&eType)==0 ){
  15045. rc = 0;
  15046. }
  15047. }
  15048. return rc;
  15049. }
  15050. /*
  15051. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  15052. ** allocation p. Also return true if p==NULL.
  15053. **
  15054. ** This routine is designed for use within an assert() statement, to
  15055. ** verify the type of an allocation. For example:
  15056. **
  15057. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  15058. */
  15059. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  15060. int rc = 1;
  15061. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15062. struct MemBlockHdr *pHdr;
  15063. pHdr = sqlite3MemsysGetHeader(p);
  15064. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15065. if( (pHdr->eType&eType)!=0 ){
  15066. rc = 0;
  15067. }
  15068. }
  15069. return rc;
  15070. }
  15071. /*
  15072. ** Set the number of backtrace levels kept for each allocation.
  15073. ** A value of zero turns off backtracing. The number is always rounded
  15074. ** up to a multiple of 2.
  15075. */
  15076. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  15077. if( depth<0 ){ depth = 0; }
  15078. if( depth>20 ){ depth = 20; }
  15079. depth = (depth+1)&0xfe;
  15080. mem.nBacktrace = depth;
  15081. }
  15082. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  15083. mem.xBacktrace = xBacktrace;
  15084. }
  15085. /*
  15086. ** Set the title string for subsequent allocations.
  15087. */
  15088. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  15089. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  15090. sqlite3_mutex_enter(mem.mutex);
  15091. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  15092. memcpy(mem.zTitle, zTitle, n);
  15093. mem.zTitle[n] = 0;
  15094. mem.nTitle = ROUND8(n);
  15095. sqlite3_mutex_leave(mem.mutex);
  15096. }
  15097. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  15098. struct MemBlockHdr *pHdr;
  15099. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15100. void **pBt = (void**)pHdr;
  15101. pBt -= pHdr->nBacktraceSlots;
  15102. mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  15103. }
  15104. }
  15105. /*
  15106. ** Open the file indicated and write a log of all unfreed memory
  15107. ** allocations into that log.
  15108. */
  15109. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  15110. FILE *out;
  15111. struct MemBlockHdr *pHdr;
  15112. void **pBt;
  15113. int i;
  15114. out = fopen(zFilename, "w");
  15115. if( out==0 ){
  15116. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15117. zFilename);
  15118. return;
  15119. }
  15120. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15121. char *z = (char*)pHdr;
  15122. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  15123. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  15124. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  15125. if( pHdr->nBacktrace ){
  15126. fflush(out);
  15127. pBt = (void**)pHdr;
  15128. pBt -= pHdr->nBacktraceSlots;
  15129. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  15130. fprintf(out, "\n");
  15131. }
  15132. }
  15133. fprintf(out, "COUNTS:\n");
  15134. for(i=0; i<NCSIZE-1; i++){
  15135. if( mem.nAlloc[i] ){
  15136. fprintf(out, " %5d: %10d %10d %10d\n",
  15137. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  15138. }
  15139. }
  15140. if( mem.nAlloc[NCSIZE-1] ){
  15141. fprintf(out, " %5d: %10d %10d %10d\n",
  15142. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  15143. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  15144. }
  15145. fclose(out);
  15146. }
  15147. /*
  15148. ** Return the number of times sqlite3MemMalloc() has been called.
  15149. */
  15150. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  15151. int i;
  15152. int nTotal = 0;
  15153. for(i=0; i<NCSIZE; i++){
  15154. nTotal += mem.nAlloc[i];
  15155. }
  15156. return nTotal;
  15157. }
  15158. #endif /* SQLITE_MEMDEBUG */
  15159. /************** End of mem2.c ************************************************/
  15160. /************** Begin file mem3.c ********************************************/
  15161. /*
  15162. ** 2007 October 14
  15163. **
  15164. ** The author disclaims copyright to this source code. In place of
  15165. ** a legal notice, here is a blessing:
  15166. **
  15167. ** May you do good and not evil.
  15168. ** May you find forgiveness for yourself and forgive others.
  15169. ** May you share freely, never taking more than you give.
  15170. **
  15171. *************************************************************************
  15172. ** This file contains the C functions that implement a memory
  15173. ** allocation subsystem for use by SQLite.
  15174. **
  15175. ** This version of the memory allocation subsystem omits all
  15176. ** use of malloc(). The SQLite user supplies a block of memory
  15177. ** before calling sqlite3_initialize() from which allocations
  15178. ** are made and returned by the xMalloc() and xRealloc()
  15179. ** implementations. Once sqlite3_initialize() has been called,
  15180. ** the amount of memory available to SQLite is fixed and cannot
  15181. ** be changed.
  15182. **
  15183. ** This version of the memory allocation subsystem is included
  15184. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  15185. */
  15186. /*
  15187. ** This version of the memory allocator is only built into the library
  15188. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  15189. ** mean that the library will use a memory-pool by default, just that
  15190. ** it is available. The mempool allocator is activated by calling
  15191. ** sqlite3_config().
  15192. */
  15193. #ifdef SQLITE_ENABLE_MEMSYS3
  15194. /*
  15195. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  15196. */
  15197. #define MX_SMALL 10
  15198. /*
  15199. ** Number of freelist hash slots
  15200. */
  15201. #define N_HASH 61
  15202. /*
  15203. ** A memory allocation (also called a "chunk") consists of two or
  15204. ** more blocks where each block is 8 bytes. The first 8 bytes are
  15205. ** a header that is not returned to the user.
  15206. **
  15207. ** A chunk is two or more blocks that is either checked out or
  15208. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  15209. ** size of the allocation in blocks if the allocation is free.
  15210. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  15211. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  15212. ** is true if the previous chunk is checked out and false if the
  15213. ** previous chunk is free. The u.hdr.prevSize field is the size of
  15214. ** the previous chunk in blocks if the previous chunk is on the
  15215. ** freelist. If the previous chunk is checked out, then
  15216. ** u.hdr.prevSize can be part of the data for that chunk and should
  15217. ** not be read or written.
  15218. **
  15219. ** We often identify a chunk by its index in mem3.aPool[]. When
  15220. ** this is done, the chunk index refers to the second block of
  15221. ** the chunk. In this way, the first chunk has an index of 1.
  15222. ** A chunk index of 0 means "no such chunk" and is the equivalent
  15223. ** of a NULL pointer.
  15224. **
  15225. ** The second block of free chunks is of the form u.list. The
  15226. ** two fields form a double-linked list of chunks of related sizes.
  15227. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  15228. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  15229. **
  15230. ** The second block of a chunk is user data if the chunk is checked
  15231. ** out. If a chunk is checked out, the user data may extend into
  15232. ** the u.hdr.prevSize value of the following chunk.
  15233. */
  15234. typedef struct Mem3Block Mem3Block;
  15235. struct Mem3Block {
  15236. union {
  15237. struct {
  15238. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  15239. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  15240. } hdr;
  15241. struct {
  15242. u32 next; /* Index in mem3.aPool[] of next free chunk */
  15243. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  15244. } list;
  15245. } u;
  15246. };
  15247. /*
  15248. ** All of the static variables used by this module are collected
  15249. ** into a single structure named "mem3". This is to keep the
  15250. ** static variables organized and to reduce namespace pollution
  15251. ** when this module is combined with other in the amalgamation.
  15252. */
  15253. static SQLITE_WSD struct Mem3Global {
  15254. /*
  15255. ** Memory available for allocation. nPool is the size of the array
  15256. ** (in Mem3Blocks) pointed to by aPool less 2.
  15257. */
  15258. u32 nPool;
  15259. Mem3Block *aPool;
  15260. /*
  15261. ** True if we are evaluating an out-of-memory callback.
  15262. */
  15263. int alarmBusy;
  15264. /*
  15265. ** Mutex to control access to the memory allocation subsystem.
  15266. */
  15267. sqlite3_mutex *mutex;
  15268. /*
  15269. ** The minimum amount of free space that we have seen.
  15270. */
  15271. u32 mnMaster;
  15272. /*
  15273. ** iMaster is the index of the master chunk. Most new allocations
  15274. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  15275. ** of the current master. iMaster is 0 if there is not master chunk.
  15276. ** The master chunk is not in either the aiHash[] or aiSmall[].
  15277. */
  15278. u32 iMaster;
  15279. u32 szMaster;
  15280. /*
  15281. ** Array of lists of free blocks according to the block size
  15282. ** for smaller chunks, or a hash on the block size for larger
  15283. ** chunks.
  15284. */
  15285. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  15286. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  15287. } mem3 = { 97535575 };
  15288. #define mem3 GLOBAL(struct Mem3Global, mem3)
  15289. /*
  15290. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  15291. ** on. *pRoot is the list that i is a member of.
  15292. */
  15293. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  15294. u32 next = mem3.aPool[i].u.list.next;
  15295. u32 prev = mem3.aPool[i].u.list.prev;
  15296. assert( sqlite3_mutex_held(mem3.mutex) );
  15297. if( prev==0 ){
  15298. *pRoot = next;
  15299. }else{
  15300. mem3.aPool[prev].u.list.next = next;
  15301. }
  15302. if( next ){
  15303. mem3.aPool[next].u.list.prev = prev;
  15304. }
  15305. mem3.aPool[i].u.list.next = 0;
  15306. mem3.aPool[i].u.list.prev = 0;
  15307. }
  15308. /*
  15309. ** Unlink the chunk at index i from
  15310. ** whatever list is currently a member of.
  15311. */
  15312. static void memsys3Unlink(u32 i){
  15313. u32 size, hash;
  15314. assert( sqlite3_mutex_held(mem3.mutex) );
  15315. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15316. assert( i>=1 );
  15317. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15318. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15319. assert( size>=2 );
  15320. if( size <= MX_SMALL ){
  15321. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  15322. }else{
  15323. hash = size % N_HASH;
  15324. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15325. }
  15326. }
  15327. /*
  15328. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  15329. ** at *pRoot.
  15330. */
  15331. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  15332. assert( sqlite3_mutex_held(mem3.mutex) );
  15333. mem3.aPool[i].u.list.next = *pRoot;
  15334. mem3.aPool[i].u.list.prev = 0;
  15335. if( *pRoot ){
  15336. mem3.aPool[*pRoot].u.list.prev = i;
  15337. }
  15338. *pRoot = i;
  15339. }
  15340. /*
  15341. ** Link the chunk at index i into either the appropriate
  15342. ** small chunk list, or into the large chunk hash table.
  15343. */
  15344. static void memsys3Link(u32 i){
  15345. u32 size, hash;
  15346. assert( sqlite3_mutex_held(mem3.mutex) );
  15347. assert( i>=1 );
  15348. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15349. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15350. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15351. assert( size>=2 );
  15352. if( size <= MX_SMALL ){
  15353. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  15354. }else{
  15355. hash = size % N_HASH;
  15356. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  15357. }
  15358. }
  15359. /*
  15360. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15361. ** will already be held (obtained by code in malloc.c) if
  15362. ** sqlite3GlobalConfig.bMemStat is true.
  15363. */
  15364. static void memsys3Enter(void){
  15365. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  15366. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15367. }
  15368. sqlite3_mutex_enter(mem3.mutex);
  15369. }
  15370. static void memsys3Leave(void){
  15371. sqlite3_mutex_leave(mem3.mutex);
  15372. }
  15373. /*
  15374. ** Called when we are unable to satisfy an allocation of nBytes.
  15375. */
  15376. static void memsys3OutOfMemory(int nByte){
  15377. if( !mem3.alarmBusy ){
  15378. mem3.alarmBusy = 1;
  15379. assert( sqlite3_mutex_held(mem3.mutex) );
  15380. sqlite3_mutex_leave(mem3.mutex);
  15381. sqlite3_release_memory(nByte);
  15382. sqlite3_mutex_enter(mem3.mutex);
  15383. mem3.alarmBusy = 0;
  15384. }
  15385. }
  15386. /*
  15387. ** Chunk i is a free chunk that has been unlinked. Adjust its
  15388. ** size parameters for check-out and return a pointer to the
  15389. ** user portion of the chunk.
  15390. */
  15391. static void *memsys3Checkout(u32 i, u32 nBlock){
  15392. u32 x;
  15393. assert( sqlite3_mutex_held(mem3.mutex) );
  15394. assert( i>=1 );
  15395. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  15396. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  15397. x = mem3.aPool[i-1].u.hdr.size4x;
  15398. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  15399. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  15400. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  15401. return &mem3.aPool[i];
  15402. }
  15403. /*
  15404. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  15405. ** Return a pointer to the new allocation. Or, if the master chunk
  15406. ** is not large enough, return 0.
  15407. */
  15408. static void *memsys3FromMaster(u32 nBlock){
  15409. assert( sqlite3_mutex_held(mem3.mutex) );
  15410. assert( mem3.szMaster>=nBlock );
  15411. if( nBlock>=mem3.szMaster-1 ){
  15412. /* Use the entire master */
  15413. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  15414. mem3.iMaster = 0;
  15415. mem3.szMaster = 0;
  15416. mem3.mnMaster = 0;
  15417. return p;
  15418. }else{
  15419. /* Split the master block. Return the tail. */
  15420. u32 newi, x;
  15421. newi = mem3.iMaster + mem3.szMaster - nBlock;
  15422. assert( newi > mem3.iMaster+1 );
  15423. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  15424. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  15425. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  15426. mem3.szMaster -= nBlock;
  15427. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  15428. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15429. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15430. if( mem3.szMaster < mem3.mnMaster ){
  15431. mem3.mnMaster = mem3.szMaster;
  15432. }
  15433. return (void*)&mem3.aPool[newi];
  15434. }
  15435. }
  15436. /*
  15437. ** *pRoot is the head of a list of free chunks of the same size
  15438. ** or same size hash. In other words, *pRoot is an entry in either
  15439. ** mem3.aiSmall[] or mem3.aiHash[].
  15440. **
  15441. ** This routine examines all entries on the given list and tries
  15442. ** to coalesce each entries with adjacent free chunks.
  15443. **
  15444. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  15445. ** the current mem3.iMaster with the new larger chunk. In order for
  15446. ** this mem3.iMaster replacement to work, the master chunk must be
  15447. ** linked into the hash tables. That is not the normal state of
  15448. ** affairs, of course. The calling routine must link the master
  15449. ** chunk before invoking this routine, then must unlink the (possibly
  15450. ** changed) master chunk once this routine has finished.
  15451. */
  15452. static void memsys3Merge(u32 *pRoot){
  15453. u32 iNext, prev, size, i, x;
  15454. assert( sqlite3_mutex_held(mem3.mutex) );
  15455. for(i=*pRoot; i>0; i=iNext){
  15456. iNext = mem3.aPool[i].u.list.next;
  15457. size = mem3.aPool[i-1].u.hdr.size4x;
  15458. assert( (size&1)==0 );
  15459. if( (size&2)==0 ){
  15460. memsys3UnlinkFromList(i, pRoot);
  15461. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  15462. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  15463. if( prev==iNext ){
  15464. iNext = mem3.aPool[prev].u.list.next;
  15465. }
  15466. memsys3Unlink(prev);
  15467. size = i + size/4 - prev;
  15468. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  15469. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  15470. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  15471. memsys3Link(prev);
  15472. i = prev;
  15473. }else{
  15474. size /= 4;
  15475. }
  15476. if( size>mem3.szMaster ){
  15477. mem3.iMaster = i;
  15478. mem3.szMaster = size;
  15479. }
  15480. }
  15481. }
  15482. /*
  15483. ** Return a block of memory of at least nBytes in size.
  15484. ** Return NULL if unable.
  15485. **
  15486. ** This function assumes that the necessary mutexes, if any, are
  15487. ** already held by the caller. Hence "Unsafe".
  15488. */
  15489. static void *memsys3MallocUnsafe(int nByte){
  15490. u32 i;
  15491. u32 nBlock;
  15492. u32 toFree;
  15493. assert( sqlite3_mutex_held(mem3.mutex) );
  15494. assert( sizeof(Mem3Block)==8 );
  15495. if( nByte<=12 ){
  15496. nBlock = 2;
  15497. }else{
  15498. nBlock = (nByte + 11)/8;
  15499. }
  15500. assert( nBlock>=2 );
  15501. /* STEP 1:
  15502. ** Look for an entry of the correct size in either the small
  15503. ** chunk table or in the large chunk hash table. This is
  15504. ** successful most of the time (about 9 times out of 10).
  15505. */
  15506. if( nBlock <= MX_SMALL ){
  15507. i = mem3.aiSmall[nBlock-2];
  15508. if( i>0 ){
  15509. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  15510. return memsys3Checkout(i, nBlock);
  15511. }
  15512. }else{
  15513. int hash = nBlock % N_HASH;
  15514. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  15515. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  15516. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15517. return memsys3Checkout(i, nBlock);
  15518. }
  15519. }
  15520. }
  15521. /* STEP 2:
  15522. ** Try to satisfy the allocation by carving a piece off of the end
  15523. ** of the master chunk. This step usually works if step 1 fails.
  15524. */
  15525. if( mem3.szMaster>=nBlock ){
  15526. return memsys3FromMaster(nBlock);
  15527. }
  15528. /* STEP 3:
  15529. ** Loop through the entire memory pool. Coalesce adjacent free
  15530. ** chunks. Recompute the master chunk as the largest free chunk.
  15531. ** Then try again to satisfy the allocation by carving a piece off
  15532. ** of the end of the master chunk. This step happens very
  15533. ** rarely (we hope!)
  15534. */
  15535. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  15536. memsys3OutOfMemory(toFree);
  15537. if( mem3.iMaster ){
  15538. memsys3Link(mem3.iMaster);
  15539. mem3.iMaster = 0;
  15540. mem3.szMaster = 0;
  15541. }
  15542. for(i=0; i<N_HASH; i++){
  15543. memsys3Merge(&mem3.aiHash[i]);
  15544. }
  15545. for(i=0; i<MX_SMALL-1; i++){
  15546. memsys3Merge(&mem3.aiSmall[i]);
  15547. }
  15548. if( mem3.szMaster ){
  15549. memsys3Unlink(mem3.iMaster);
  15550. if( mem3.szMaster>=nBlock ){
  15551. return memsys3FromMaster(nBlock);
  15552. }
  15553. }
  15554. }
  15555. /* If none of the above worked, then we fail. */
  15556. return 0;
  15557. }
  15558. /*
  15559. ** Free an outstanding memory allocation.
  15560. **
  15561. ** This function assumes that the necessary mutexes, if any, are
  15562. ** already held by the caller. Hence "Unsafe".
  15563. */
  15564. static void memsys3FreeUnsafe(void *pOld){
  15565. Mem3Block *p = (Mem3Block*)pOld;
  15566. int i;
  15567. u32 size, x;
  15568. assert( sqlite3_mutex_held(mem3.mutex) );
  15569. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  15570. i = p - mem3.aPool;
  15571. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  15572. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15573. assert( i+size<=mem3.nPool+1 );
  15574. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  15575. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  15576. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  15577. memsys3Link(i);
  15578. /* Try to expand the master using the newly freed chunk */
  15579. if( mem3.iMaster ){
  15580. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  15581. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  15582. mem3.iMaster -= size;
  15583. mem3.szMaster += size;
  15584. memsys3Unlink(mem3.iMaster);
  15585. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15586. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15587. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  15588. }
  15589. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  15590. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  15591. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  15592. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  15593. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  15594. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  15595. }
  15596. }
  15597. }
  15598. /*
  15599. ** Return the size of an outstanding allocation, in bytes. The
  15600. ** size returned omits the 8-byte header overhead. This only
  15601. ** works for chunks that are currently checked out.
  15602. */
  15603. static int memsys3Size(void *p){
  15604. Mem3Block *pBlock;
  15605. if( p==0 ) return 0;
  15606. pBlock = (Mem3Block*)p;
  15607. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  15608. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  15609. }
  15610. /*
  15611. ** Round up a request size to the next valid allocation size.
  15612. */
  15613. static int memsys3Roundup(int n){
  15614. if( n<=12 ){
  15615. return 12;
  15616. }else{
  15617. return ((n+11)&~7) - 4;
  15618. }
  15619. }
  15620. /*
  15621. ** Allocate nBytes of memory.
  15622. */
  15623. static void *memsys3Malloc(int nBytes){
  15624. sqlite3_int64 *p;
  15625. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  15626. memsys3Enter();
  15627. p = memsys3MallocUnsafe(nBytes);
  15628. memsys3Leave();
  15629. return (void*)p;
  15630. }
  15631. /*
  15632. ** Free memory.
  15633. */
  15634. static void memsys3Free(void *pPrior){
  15635. assert( pPrior );
  15636. memsys3Enter();
  15637. memsys3FreeUnsafe(pPrior);
  15638. memsys3Leave();
  15639. }
  15640. /*
  15641. ** Change the size of an existing memory allocation
  15642. */
  15643. static void *memsys3Realloc(void *pPrior, int nBytes){
  15644. int nOld;
  15645. void *p;
  15646. if( pPrior==0 ){
  15647. return sqlite3_malloc(nBytes);
  15648. }
  15649. if( nBytes<=0 ){
  15650. sqlite3_free(pPrior);
  15651. return 0;
  15652. }
  15653. nOld = memsys3Size(pPrior);
  15654. if( nBytes<=nOld && nBytes>=nOld-128 ){
  15655. return pPrior;
  15656. }
  15657. memsys3Enter();
  15658. p = memsys3MallocUnsafe(nBytes);
  15659. if( p ){
  15660. if( nOld<nBytes ){
  15661. memcpy(p, pPrior, nOld);
  15662. }else{
  15663. memcpy(p, pPrior, nBytes);
  15664. }
  15665. memsys3FreeUnsafe(pPrior);
  15666. }
  15667. memsys3Leave();
  15668. return p;
  15669. }
  15670. /*
  15671. ** Initialize this module.
  15672. */
  15673. static int memsys3Init(void *NotUsed){
  15674. UNUSED_PARAMETER(NotUsed);
  15675. if( !sqlite3GlobalConfig.pHeap ){
  15676. return SQLITE_ERROR;
  15677. }
  15678. /* Store a pointer to the memory block in global structure mem3. */
  15679. assert( sizeof(Mem3Block)==8 );
  15680. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  15681. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  15682. /* Initialize the master block. */
  15683. mem3.szMaster = mem3.nPool;
  15684. mem3.mnMaster = mem3.szMaster;
  15685. mem3.iMaster = 1;
  15686. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  15687. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  15688. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  15689. return SQLITE_OK;
  15690. }
  15691. /*
  15692. ** Deinitialize this module.
  15693. */
  15694. static void memsys3Shutdown(void *NotUsed){
  15695. UNUSED_PARAMETER(NotUsed);
  15696. mem3.mutex = 0;
  15697. return;
  15698. }
  15699. /*
  15700. ** Open the file indicated and write a log of all unfreed memory
  15701. ** allocations into that log.
  15702. */
  15703. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  15704. #ifdef SQLITE_DEBUG
  15705. FILE *out;
  15706. u32 i, j;
  15707. u32 size;
  15708. if( zFilename==0 || zFilename[0]==0 ){
  15709. out = stdout;
  15710. }else{
  15711. out = fopen(zFilename, "w");
  15712. if( out==0 ){
  15713. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15714. zFilename);
  15715. return;
  15716. }
  15717. }
  15718. memsys3Enter();
  15719. fprintf(out, "CHUNKS:\n");
  15720. for(i=1; i<=mem3.nPool; i+=size/4){
  15721. size = mem3.aPool[i-1].u.hdr.size4x;
  15722. if( size/4<=1 ){
  15723. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  15724. assert( 0 );
  15725. break;
  15726. }
  15727. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  15728. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  15729. assert( 0 );
  15730. break;
  15731. }
  15732. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  15733. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  15734. assert( 0 );
  15735. break;
  15736. }
  15737. if( size&1 ){
  15738. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  15739. }else{
  15740. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  15741. i==mem3.iMaster ? " **master**" : "");
  15742. }
  15743. }
  15744. for(i=0; i<MX_SMALL-1; i++){
  15745. if( mem3.aiSmall[i]==0 ) continue;
  15746. fprintf(out, "small(%2d):", i);
  15747. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  15748. fprintf(out, " %p(%d)", &mem3.aPool[j],
  15749. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  15750. }
  15751. fprintf(out, "\n");
  15752. }
  15753. for(i=0; i<N_HASH; i++){
  15754. if( mem3.aiHash[i]==0 ) continue;
  15755. fprintf(out, "hash(%2d):", i);
  15756. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  15757. fprintf(out, " %p(%d)", &mem3.aPool[j],
  15758. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  15759. }
  15760. fprintf(out, "\n");
  15761. }
  15762. fprintf(out, "master=%d\n", mem3.iMaster);
  15763. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  15764. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  15765. sqlite3_mutex_leave(mem3.mutex);
  15766. if( out==stdout ){
  15767. fflush(stdout);
  15768. }else{
  15769. fclose(out);
  15770. }
  15771. #else
  15772. UNUSED_PARAMETER(zFilename);
  15773. #endif
  15774. }
  15775. /*
  15776. ** This routine is the only routine in this file with external
  15777. ** linkage.
  15778. **
  15779. ** Populate the low-level memory allocation function pointers in
  15780. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  15781. ** arguments specify the block of memory to manage.
  15782. **
  15783. ** This routine is only called by sqlite3_config(), and therefore
  15784. ** is not required to be threadsafe (it is not).
  15785. */
  15786. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  15787. static const sqlite3_mem_methods mempoolMethods = {
  15788. memsys3Malloc,
  15789. memsys3Free,
  15790. memsys3Realloc,
  15791. memsys3Size,
  15792. memsys3Roundup,
  15793. memsys3Init,
  15794. memsys3Shutdown,
  15795. 0
  15796. };
  15797. return &mempoolMethods;
  15798. }
  15799. #endif /* SQLITE_ENABLE_MEMSYS3 */
  15800. /************** End of mem3.c ************************************************/
  15801. /************** Begin file mem5.c ********************************************/
  15802. /*
  15803. ** 2007 October 14
  15804. **
  15805. ** The author disclaims copyright to this source code. In place of
  15806. ** a legal notice, here is a blessing:
  15807. **
  15808. ** May you do good and not evil.
  15809. ** May you find forgiveness for yourself and forgive others.
  15810. ** May you share freely, never taking more than you give.
  15811. **
  15812. *************************************************************************
  15813. ** This file contains the C functions that implement a memory
  15814. ** allocation subsystem for use by SQLite.
  15815. **
  15816. ** This version of the memory allocation subsystem omits all
  15817. ** use of malloc(). The application gives SQLite a block of memory
  15818. ** before calling sqlite3_initialize() from which allocations
  15819. ** are made and returned by the xMalloc() and xRealloc()
  15820. ** implementations. Once sqlite3_initialize() has been called,
  15821. ** the amount of memory available to SQLite is fixed and cannot
  15822. ** be changed.
  15823. **
  15824. ** This version of the memory allocation subsystem is included
  15825. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  15826. **
  15827. ** This memory allocator uses the following algorithm:
  15828. **
  15829. ** 1. All memory allocations sizes are rounded up to a power of 2.
  15830. **
  15831. ** 2. If two adjacent free blocks are the halves of a larger block,
  15832. ** then the two blocks are coalesed into the single larger block.
  15833. **
  15834. ** 3. New memory is allocated from the first available free block.
  15835. **
  15836. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  15837. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  15838. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  15839. **
  15840. ** Let n be the size of the largest allocation divided by the minimum
  15841. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  15842. ** be the maximum amount of memory ever outstanding at one time. Let
  15843. ** N be the total amount of memory available for allocation. Robson
  15844. ** proved that this memory allocator will never breakdown due to
  15845. ** fragmentation as long as the following constraint holds:
  15846. **
  15847. ** N >= M*(1 + log2(n)/2) - n + 1
  15848. **
  15849. ** The sqlite3_status() logic tracks the maximum values of n and M so
  15850. ** that an application can, at any time, verify this constraint.
  15851. */
  15852. /*
  15853. ** This version of the memory allocator is used only when
  15854. ** SQLITE_ENABLE_MEMSYS5 is defined.
  15855. */
  15856. #ifdef SQLITE_ENABLE_MEMSYS5
  15857. /*
  15858. ** A minimum allocation is an instance of the following structure.
  15859. ** Larger allocations are an array of these structures where the
  15860. ** size of the array is a power of 2.
  15861. **
  15862. ** The size of this object must be a power of two. That fact is
  15863. ** verified in memsys5Init().
  15864. */
  15865. typedef struct Mem5Link Mem5Link;
  15866. struct Mem5Link {
  15867. int next; /* Index of next free chunk */
  15868. int prev; /* Index of previous free chunk */
  15869. };
  15870. /*
  15871. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  15872. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  15873. ** it is not actually possible to reach this limit.
  15874. */
  15875. #define LOGMAX 30
  15876. /*
  15877. ** Masks used for mem5.aCtrl[] elements.
  15878. */
  15879. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  15880. #define CTRL_FREE 0x20 /* True if not checked out */
  15881. /*
  15882. ** All of the static variables used by this module are collected
  15883. ** into a single structure named "mem5". This is to keep the
  15884. ** static variables organized and to reduce namespace pollution
  15885. ** when this module is combined with other in the amalgamation.
  15886. */
  15887. static SQLITE_WSD struct Mem5Global {
  15888. /*
  15889. ** Memory available for allocation
  15890. */
  15891. int szAtom; /* Smallest possible allocation in bytes */
  15892. int nBlock; /* Number of szAtom sized blocks in zPool */
  15893. u8 *zPool; /* Memory available to be allocated */
  15894. /*
  15895. ** Mutex to control access to the memory allocation subsystem.
  15896. */
  15897. sqlite3_mutex *mutex;
  15898. /*
  15899. ** Performance statistics
  15900. */
  15901. u64 nAlloc; /* Total number of calls to malloc */
  15902. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  15903. u64 totalExcess; /* Total internal fragmentation */
  15904. u32 currentOut; /* Current checkout, including internal fragmentation */
  15905. u32 currentCount; /* Current number of distinct checkouts */
  15906. u32 maxOut; /* Maximum instantaneous currentOut */
  15907. u32 maxCount; /* Maximum instantaneous currentCount */
  15908. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  15909. /*
  15910. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  15911. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  15912. ** and so forth.
  15913. */
  15914. int aiFreelist[LOGMAX+1];
  15915. /*
  15916. ** Space for tracking which blocks are checked out and the size
  15917. ** of each block. One byte per block.
  15918. */
  15919. u8 *aCtrl;
  15920. } mem5;
  15921. /*
  15922. ** Access the static variable through a macro for SQLITE_OMIT_WSD
  15923. */
  15924. #define mem5 GLOBAL(struct Mem5Global, mem5)
  15925. /*
  15926. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  15927. ** structures, return a pointer to the idx-th such lik.
  15928. */
  15929. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  15930. /*
  15931. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  15932. ** on. It should be found on mem5.aiFreelist[iLogsize].
  15933. */
  15934. static void memsys5Unlink(int i, int iLogsize){
  15935. int next, prev;
  15936. assert( i>=0 && i<mem5.nBlock );
  15937. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  15938. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  15939. next = MEM5LINK(i)->next;
  15940. prev = MEM5LINK(i)->prev;
  15941. if( prev<0 ){
  15942. mem5.aiFreelist[iLogsize] = next;
  15943. }else{
  15944. MEM5LINK(prev)->next = next;
  15945. }
  15946. if( next>=0 ){
  15947. MEM5LINK(next)->prev = prev;
  15948. }
  15949. }
  15950. /*
  15951. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  15952. ** free list.
  15953. */
  15954. static void memsys5Link(int i, int iLogsize){
  15955. int x;
  15956. assert( sqlite3_mutex_held(mem5.mutex) );
  15957. assert( i>=0 && i<mem5.nBlock );
  15958. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  15959. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  15960. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  15961. MEM5LINK(i)->prev = -1;
  15962. if( x>=0 ){
  15963. assert( x<mem5.nBlock );
  15964. MEM5LINK(x)->prev = i;
  15965. }
  15966. mem5.aiFreelist[iLogsize] = i;
  15967. }
  15968. /*
  15969. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15970. ** will already be held (obtained by code in malloc.c) if
  15971. ** sqlite3GlobalConfig.bMemStat is true.
  15972. */
  15973. static void memsys5Enter(void){
  15974. sqlite3_mutex_enter(mem5.mutex);
  15975. }
  15976. static void memsys5Leave(void){
  15977. sqlite3_mutex_leave(mem5.mutex);
  15978. }
  15979. /*
  15980. ** Return the size of an outstanding allocation, in bytes. The
  15981. ** size returned omits the 8-byte header overhead. This only
  15982. ** works for chunks that are currently checked out.
  15983. */
  15984. static int memsys5Size(void *p){
  15985. int iSize = 0;
  15986. if( p ){
  15987. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  15988. assert( i>=0 && i<mem5.nBlock );
  15989. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  15990. }
  15991. return iSize;
  15992. }
  15993. /*
  15994. ** Find the first entry on the freelist iLogsize. Unlink that
  15995. ** entry and return its index.
  15996. */
  15997. static int memsys5UnlinkFirst(int iLogsize){
  15998. int i;
  15999. int iFirst;
  16000. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16001. i = iFirst = mem5.aiFreelist[iLogsize];
  16002. assert( iFirst>=0 );
  16003. while( i>0 ){
  16004. if( i<iFirst ) iFirst = i;
  16005. i = MEM5LINK(i)->next;
  16006. }
  16007. memsys5Unlink(iFirst, iLogsize);
  16008. return iFirst;
  16009. }
  16010. /*
  16011. ** Return a block of memory of at least nBytes in size.
  16012. ** Return NULL if unable. Return NULL if nBytes==0.
  16013. **
  16014. ** The caller guarantees that nByte positive.
  16015. **
  16016. ** The caller has obtained a mutex prior to invoking this
  16017. ** routine so there is never any chance that two or more
  16018. ** threads can be in this routine at the same time.
  16019. */
  16020. static void *memsys5MallocUnsafe(int nByte){
  16021. int i; /* Index of a mem5.aPool[] slot */
  16022. int iBin; /* Index into mem5.aiFreelist[] */
  16023. int iFullSz; /* Size of allocation rounded up to power of 2 */
  16024. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  16025. /* nByte must be a positive */
  16026. assert( nByte>0 );
  16027. /* Keep track of the maximum allocation request. Even unfulfilled
  16028. ** requests are counted */
  16029. if( (u32)nByte>mem5.maxRequest ){
  16030. mem5.maxRequest = nByte;
  16031. }
  16032. /* Abort if the requested allocation size is larger than the largest
  16033. ** power of two that we can represent using 32-bit signed integers.
  16034. */
  16035. if( nByte > 0x40000000 ){
  16036. return 0;
  16037. }
  16038. /* Round nByte up to the next valid power of two */
  16039. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  16040. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  16041. ** block. If not, then split a block of the next larger power of
  16042. ** two in order to create a new free block of size iLogsize.
  16043. */
  16044. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  16045. if( iBin>LOGMAX ){
  16046. testcase( sqlite3GlobalConfig.xLog!=0 );
  16047. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  16048. return 0;
  16049. }
  16050. i = memsys5UnlinkFirst(iBin);
  16051. while( iBin>iLogsize ){
  16052. int newSize;
  16053. iBin--;
  16054. newSize = 1 << iBin;
  16055. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  16056. memsys5Link(i+newSize, iBin);
  16057. }
  16058. mem5.aCtrl[i] = iLogsize;
  16059. /* Update allocator performance statistics. */
  16060. mem5.nAlloc++;
  16061. mem5.totalAlloc += iFullSz;
  16062. mem5.totalExcess += iFullSz - nByte;
  16063. mem5.currentCount++;
  16064. mem5.currentOut += iFullSz;
  16065. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  16066. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  16067. /* Return a pointer to the allocated memory. */
  16068. return (void*)&mem5.zPool[i*mem5.szAtom];
  16069. }
  16070. /*
  16071. ** Free an outstanding memory allocation.
  16072. */
  16073. static void memsys5FreeUnsafe(void *pOld){
  16074. u32 size, iLogsize;
  16075. int iBlock;
  16076. /* Set iBlock to the index of the block pointed to by pOld in
  16077. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  16078. */
  16079. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  16080. /* Check that the pointer pOld points to a valid, non-free block. */
  16081. assert( iBlock>=0 && iBlock<mem5.nBlock );
  16082. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  16083. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  16084. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  16085. size = 1<<iLogsize;
  16086. assert( iBlock+size-1<(u32)mem5.nBlock );
  16087. mem5.aCtrl[iBlock] |= CTRL_FREE;
  16088. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  16089. assert( mem5.currentCount>0 );
  16090. assert( mem5.currentOut>=(size*mem5.szAtom) );
  16091. mem5.currentCount--;
  16092. mem5.currentOut -= size*mem5.szAtom;
  16093. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  16094. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  16095. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16096. while( ALWAYS(iLogsize<LOGMAX) ){
  16097. int iBuddy;
  16098. if( (iBlock>>iLogsize) & 1 ){
  16099. iBuddy = iBlock - size;
  16100. }else{
  16101. iBuddy = iBlock + size;
  16102. }
  16103. assert( iBuddy>=0 );
  16104. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  16105. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  16106. memsys5Unlink(iBuddy, iLogsize);
  16107. iLogsize++;
  16108. if( iBuddy<iBlock ){
  16109. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  16110. mem5.aCtrl[iBlock] = 0;
  16111. iBlock = iBuddy;
  16112. }else{
  16113. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16114. mem5.aCtrl[iBuddy] = 0;
  16115. }
  16116. size *= 2;
  16117. }
  16118. memsys5Link(iBlock, iLogsize);
  16119. }
  16120. /*
  16121. ** Allocate nBytes of memory
  16122. */
  16123. static void *memsys5Malloc(int nBytes){
  16124. sqlite3_int64 *p = 0;
  16125. if( nBytes>0 ){
  16126. memsys5Enter();
  16127. p = memsys5MallocUnsafe(nBytes);
  16128. memsys5Leave();
  16129. }
  16130. return (void*)p;
  16131. }
  16132. /*
  16133. ** Free memory.
  16134. **
  16135. ** The outer layer memory allocator prevents this routine from
  16136. ** being called with pPrior==0.
  16137. */
  16138. static void memsys5Free(void *pPrior){
  16139. assert( pPrior!=0 );
  16140. memsys5Enter();
  16141. memsys5FreeUnsafe(pPrior);
  16142. memsys5Leave();
  16143. }
  16144. /*
  16145. ** Change the size of an existing memory allocation.
  16146. **
  16147. ** The outer layer memory allocator prevents this routine from
  16148. ** being called with pPrior==0.
  16149. **
  16150. ** nBytes is always a value obtained from a prior call to
  16151. ** memsys5Round(). Hence nBytes is always a non-negative power
  16152. ** of two. If nBytes==0 that means that an oversize allocation
  16153. ** (an allocation larger than 0x40000000) was requested and this
  16154. ** routine should return 0 without freeing pPrior.
  16155. */
  16156. static void *memsys5Realloc(void *pPrior, int nBytes){
  16157. int nOld;
  16158. void *p;
  16159. assert( pPrior!=0 );
  16160. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  16161. assert( nBytes>=0 );
  16162. if( nBytes==0 ){
  16163. return 0;
  16164. }
  16165. nOld = memsys5Size(pPrior);
  16166. if( nBytes<=nOld ){
  16167. return pPrior;
  16168. }
  16169. memsys5Enter();
  16170. p = memsys5MallocUnsafe(nBytes);
  16171. if( p ){
  16172. memcpy(p, pPrior, nOld);
  16173. memsys5FreeUnsafe(pPrior);
  16174. }
  16175. memsys5Leave();
  16176. return p;
  16177. }
  16178. /*
  16179. ** Round up a request size to the next valid allocation size. If
  16180. ** the allocation is too large to be handled by this allocation system,
  16181. ** return 0.
  16182. **
  16183. ** All allocations must be a power of two and must be expressed by a
  16184. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  16185. ** or 1073741824 bytes.
  16186. */
  16187. static int memsys5Roundup(int n){
  16188. int iFullSz;
  16189. if( n > 0x40000000 ) return 0;
  16190. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  16191. return iFullSz;
  16192. }
  16193. /*
  16194. ** Return the ceiling of the logarithm base 2 of iValue.
  16195. **
  16196. ** Examples: memsys5Log(1) -> 0
  16197. ** memsys5Log(2) -> 1
  16198. ** memsys5Log(4) -> 2
  16199. ** memsys5Log(5) -> 3
  16200. ** memsys5Log(8) -> 3
  16201. ** memsys5Log(9) -> 4
  16202. */
  16203. static int memsys5Log(int iValue){
  16204. int iLog;
  16205. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  16206. return iLog;
  16207. }
  16208. /*
  16209. ** Initialize the memory allocator.
  16210. **
  16211. ** This routine is not threadsafe. The caller must be holding a mutex
  16212. ** to prevent multiple threads from entering at the same time.
  16213. */
  16214. static int memsys5Init(void *NotUsed){
  16215. int ii; /* Loop counter */
  16216. int nByte; /* Number of bytes of memory available to this allocator */
  16217. u8 *zByte; /* Memory usable by this allocator */
  16218. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  16219. int iOffset; /* An offset into mem5.aCtrl[] */
  16220. UNUSED_PARAMETER(NotUsed);
  16221. /* For the purposes of this routine, disable the mutex */
  16222. mem5.mutex = 0;
  16223. /* The size of a Mem5Link object must be a power of two. Verify that
  16224. ** this is case.
  16225. */
  16226. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  16227. nByte = sqlite3GlobalConfig.nHeap;
  16228. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  16229. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  16230. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  16231. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  16232. mem5.szAtom = (1<<nMinLog);
  16233. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  16234. mem5.szAtom = mem5.szAtom << 1;
  16235. }
  16236. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  16237. mem5.zPool = zByte;
  16238. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  16239. for(ii=0; ii<=LOGMAX; ii++){
  16240. mem5.aiFreelist[ii] = -1;
  16241. }
  16242. iOffset = 0;
  16243. for(ii=LOGMAX; ii>=0; ii--){
  16244. int nAlloc = (1<<ii);
  16245. if( (iOffset+nAlloc)<=mem5.nBlock ){
  16246. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  16247. memsys5Link(iOffset, ii);
  16248. iOffset += nAlloc;
  16249. }
  16250. assert((iOffset+nAlloc)>mem5.nBlock);
  16251. }
  16252. /* If a mutex is required for normal operation, allocate one */
  16253. if( sqlite3GlobalConfig.bMemstat==0 ){
  16254. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16255. }
  16256. return SQLITE_OK;
  16257. }
  16258. /*
  16259. ** Deinitialize this module.
  16260. */
  16261. static void memsys5Shutdown(void *NotUsed){
  16262. UNUSED_PARAMETER(NotUsed);
  16263. mem5.mutex = 0;
  16264. return;
  16265. }
  16266. #ifdef SQLITE_TEST
  16267. /*
  16268. ** Open the file indicated and write a log of all unfreed memory
  16269. ** allocations into that log.
  16270. */
  16271. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  16272. FILE *out;
  16273. int i, j, n;
  16274. int nMinLog;
  16275. if( zFilename==0 || zFilename[0]==0 ){
  16276. out = stdout;
  16277. }else{
  16278. out = fopen(zFilename, "w");
  16279. if( out==0 ){
  16280. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16281. zFilename);
  16282. return;
  16283. }
  16284. }
  16285. memsys5Enter();
  16286. nMinLog = memsys5Log(mem5.szAtom);
  16287. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  16288. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  16289. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  16290. }
  16291. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  16292. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  16293. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  16294. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  16295. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  16296. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  16297. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  16298. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  16299. memsys5Leave();
  16300. if( out==stdout ){
  16301. fflush(stdout);
  16302. }else{
  16303. fclose(out);
  16304. }
  16305. }
  16306. #endif
  16307. /*
  16308. ** This routine is the only routine in this file with external
  16309. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  16310. ** struct populated with the memsys5 methods.
  16311. */
  16312. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  16313. static const sqlite3_mem_methods memsys5Methods = {
  16314. memsys5Malloc,
  16315. memsys5Free,
  16316. memsys5Realloc,
  16317. memsys5Size,
  16318. memsys5Roundup,
  16319. memsys5Init,
  16320. memsys5Shutdown,
  16321. 0
  16322. };
  16323. return &memsys5Methods;
  16324. }
  16325. #endif /* SQLITE_ENABLE_MEMSYS5 */
  16326. /************** End of mem5.c ************************************************/
  16327. /************** Begin file mutex.c *******************************************/
  16328. /*
  16329. ** 2007 August 14
  16330. **
  16331. ** The author disclaims copyright to this source code. In place of
  16332. ** a legal notice, here is a blessing:
  16333. **
  16334. ** May you do good and not evil.
  16335. ** May you find forgiveness for yourself and forgive others.
  16336. ** May you share freely, never taking more than you give.
  16337. **
  16338. *************************************************************************
  16339. ** This file contains the C functions that implement mutexes.
  16340. **
  16341. ** This file contains code that is common across all mutex implementations.
  16342. */
  16343. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  16344. /*
  16345. ** For debugging purposes, record when the mutex subsystem is initialized
  16346. ** and uninitialized so that we can assert() if there is an attempt to
  16347. ** allocate a mutex while the system is uninitialized.
  16348. */
  16349. static SQLITE_WSD int mutexIsInit = 0;
  16350. #endif /* SQLITE_DEBUG */
  16351. #ifndef SQLITE_MUTEX_OMIT
  16352. /*
  16353. ** Initialize the mutex system.
  16354. */
  16355. SQLITE_PRIVATE int sqlite3MutexInit(void){
  16356. int rc = SQLITE_OK;
  16357. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  16358. /* If the xMutexAlloc method has not been set, then the user did not
  16359. ** install a mutex implementation via sqlite3_config() prior to
  16360. ** sqlite3_initialize() being called. This block copies pointers to
  16361. ** the default implementation into the sqlite3GlobalConfig structure.
  16362. */
  16363. sqlite3_mutex_methods const *pFrom;
  16364. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  16365. if( sqlite3GlobalConfig.bCoreMutex ){
  16366. pFrom = sqlite3DefaultMutex();
  16367. }else{
  16368. pFrom = sqlite3NoopMutex();
  16369. }
  16370. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  16371. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  16372. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  16373. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  16374. }
  16375. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  16376. #ifdef SQLITE_DEBUG
  16377. GLOBAL(int, mutexIsInit) = 1;
  16378. #endif
  16379. return rc;
  16380. }
  16381. /*
  16382. ** Shutdown the mutex system. This call frees resources allocated by
  16383. ** sqlite3MutexInit().
  16384. */
  16385. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  16386. int rc = SQLITE_OK;
  16387. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  16388. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  16389. }
  16390. #ifdef SQLITE_DEBUG
  16391. GLOBAL(int, mutexIsInit) = 0;
  16392. #endif
  16393. return rc;
  16394. }
  16395. /*
  16396. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  16397. */
  16398. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  16399. #ifndef SQLITE_OMIT_AUTOINIT
  16400. if( sqlite3_initialize() ) return 0;
  16401. #endif
  16402. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16403. }
  16404. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  16405. if( !sqlite3GlobalConfig.bCoreMutex ){
  16406. return 0;
  16407. }
  16408. assert( GLOBAL(int, mutexIsInit) );
  16409. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16410. }
  16411. /*
  16412. ** Free a dynamic mutex.
  16413. */
  16414. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  16415. if( p ){
  16416. sqlite3GlobalConfig.mutex.xMutexFree(p);
  16417. }
  16418. }
  16419. /*
  16420. ** Obtain the mutex p. If some other thread already has the mutex, block
  16421. ** until it can be obtained.
  16422. */
  16423. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  16424. if( p ){
  16425. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  16426. }
  16427. }
  16428. /*
  16429. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  16430. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  16431. */
  16432. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  16433. int rc = SQLITE_OK;
  16434. if( p ){
  16435. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  16436. }
  16437. return rc;
  16438. }
  16439. /*
  16440. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  16441. ** entered by the same thread. The behavior is undefined if the mutex
  16442. ** is not currently entered. If a NULL pointer is passed as an argument
  16443. ** this function is a no-op.
  16444. */
  16445. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  16446. if( p ){
  16447. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  16448. }
  16449. }
  16450. #ifndef NDEBUG
  16451. /*
  16452. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16453. ** intended for use inside assert() statements.
  16454. */
  16455. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  16456. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  16457. }
  16458. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  16459. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  16460. }
  16461. #endif
  16462. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  16463. /************** End of mutex.c ***********************************************/
  16464. /************** Begin file mutex_noop.c **************************************/
  16465. /*
  16466. ** 2008 October 07
  16467. **
  16468. ** The author disclaims copyright to this source code. In place of
  16469. ** a legal notice, here is a blessing:
  16470. **
  16471. ** May you do good and not evil.
  16472. ** May you find forgiveness for yourself and forgive others.
  16473. ** May you share freely, never taking more than you give.
  16474. **
  16475. *************************************************************************
  16476. ** This file contains the C functions that implement mutexes.
  16477. **
  16478. ** This implementation in this file does not provide any mutual
  16479. ** exclusion and is thus suitable for use only in applications
  16480. ** that use SQLite in a single thread. The routines defined
  16481. ** here are place-holders. Applications can substitute working
  16482. ** mutex routines at start-time using the
  16483. **
  16484. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  16485. **
  16486. ** interface.
  16487. **
  16488. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  16489. ** that does error checking on mutexes to make sure they are being
  16490. ** called correctly.
  16491. */
  16492. #ifndef SQLITE_MUTEX_OMIT
  16493. #ifndef SQLITE_DEBUG
  16494. /*
  16495. ** Stub routines for all mutex methods.
  16496. **
  16497. ** This routines provide no mutual exclusion or error checking.
  16498. */
  16499. static int noopMutexInit(void){ return SQLITE_OK; }
  16500. static int noopMutexEnd(void){ return SQLITE_OK; }
  16501. static sqlite3_mutex *noopMutexAlloc(int id){
  16502. UNUSED_PARAMETER(id);
  16503. return (sqlite3_mutex*)8;
  16504. }
  16505. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  16506. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  16507. static int noopMutexTry(sqlite3_mutex *p){
  16508. UNUSED_PARAMETER(p);
  16509. return SQLITE_OK;
  16510. }
  16511. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  16512. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  16513. static const sqlite3_mutex_methods sMutex = {
  16514. noopMutexInit,
  16515. noopMutexEnd,
  16516. noopMutexAlloc,
  16517. noopMutexFree,
  16518. noopMutexEnter,
  16519. noopMutexTry,
  16520. noopMutexLeave,
  16521. 0,
  16522. 0,
  16523. };
  16524. return &sMutex;
  16525. }
  16526. #endif /* !SQLITE_DEBUG */
  16527. #ifdef SQLITE_DEBUG
  16528. /*
  16529. ** In this implementation, error checking is provided for testing
  16530. ** and debugging purposes. The mutexes still do not provide any
  16531. ** mutual exclusion.
  16532. */
  16533. /*
  16534. ** The mutex object
  16535. */
  16536. typedef struct sqlite3_debug_mutex {
  16537. int id; /* The mutex type */
  16538. int cnt; /* Number of entries without a matching leave */
  16539. } sqlite3_debug_mutex;
  16540. /*
  16541. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16542. ** intended for use inside assert() statements.
  16543. */
  16544. static int debugMutexHeld(sqlite3_mutex *pX){
  16545. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16546. return p==0 || p->cnt>0;
  16547. }
  16548. static int debugMutexNotheld(sqlite3_mutex *pX){
  16549. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16550. return p==0 || p->cnt==0;
  16551. }
  16552. /*
  16553. ** Initialize and deinitialize the mutex subsystem.
  16554. */
  16555. static int debugMutexInit(void){ return SQLITE_OK; }
  16556. static int debugMutexEnd(void){ return SQLITE_OK; }
  16557. /*
  16558. ** The sqlite3_mutex_alloc() routine allocates a new
  16559. ** mutex and returns a pointer to it. If it returns NULL
  16560. ** that means that a mutex could not be allocated.
  16561. */
  16562. static sqlite3_mutex *debugMutexAlloc(int id){
  16563. static sqlite3_debug_mutex aStatic[6];
  16564. sqlite3_debug_mutex *pNew = 0;
  16565. switch( id ){
  16566. case SQLITE_MUTEX_FAST:
  16567. case SQLITE_MUTEX_RECURSIVE: {
  16568. pNew = sqlite3Malloc(sizeof(*pNew));
  16569. if( pNew ){
  16570. pNew->id = id;
  16571. pNew->cnt = 0;
  16572. }
  16573. break;
  16574. }
  16575. default: {
  16576. assert( id-2 >= 0 );
  16577. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  16578. pNew = &aStatic[id-2];
  16579. pNew->id = id;
  16580. break;
  16581. }
  16582. }
  16583. return (sqlite3_mutex*)pNew;
  16584. }
  16585. /*
  16586. ** This routine deallocates a previously allocated mutex.
  16587. */
  16588. static void debugMutexFree(sqlite3_mutex *pX){
  16589. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16590. assert( p->cnt==0 );
  16591. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  16592. sqlite3_free(p);
  16593. }
  16594. /*
  16595. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  16596. ** to enter a mutex. If another thread is already within the mutex,
  16597. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  16598. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  16599. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  16600. ** be entered multiple times by the same thread. In such cases the,
  16601. ** mutex must be exited an equal number of times before another thread
  16602. ** can enter. If the same thread tries to enter any other kind of mutex
  16603. ** more than once, the behavior is undefined.
  16604. */
  16605. static void debugMutexEnter(sqlite3_mutex *pX){
  16606. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16607. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  16608. p->cnt++;
  16609. }
  16610. static int debugMutexTry(sqlite3_mutex *pX){
  16611. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16612. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  16613. p->cnt++;
  16614. return SQLITE_OK;
  16615. }
  16616. /*
  16617. ** The sqlite3_mutex_leave() routine exits a mutex that was
  16618. ** previously entered by the same thread. The behavior
  16619. ** is undefined if the mutex is not currently entered or
  16620. ** is not currently allocated. SQLite will never do either.
  16621. */
  16622. static void debugMutexLeave(sqlite3_mutex *pX){
  16623. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  16624. assert( debugMutexHeld(pX) );
  16625. p->cnt--;
  16626. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  16627. }
  16628. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  16629. static const sqlite3_mutex_methods sMutex = {
  16630. debugMutexInit,
  16631. debugMutexEnd,
  16632. debugMutexAlloc,
  16633. debugMutexFree,
  16634. debugMutexEnter,
  16635. debugMutexTry,
  16636. debugMutexLeave,
  16637. debugMutexHeld,
  16638. debugMutexNotheld
  16639. };
  16640. return &sMutex;
  16641. }
  16642. #endif /* SQLITE_DEBUG */
  16643. /*
  16644. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  16645. ** is used regardless of the run-time threadsafety setting.
  16646. */
  16647. #ifdef SQLITE_MUTEX_NOOP
  16648. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  16649. return sqlite3NoopMutex();
  16650. }
  16651. #endif /* defined(SQLITE_MUTEX_NOOP) */
  16652. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  16653. /************** End of mutex_noop.c ******************************************/
  16654. /************** Begin file mutex_os2.c ***************************************/
  16655. /*
  16656. ** 2007 August 28
  16657. **
  16658. ** The author disclaims copyright to this source code. In place of
  16659. ** a legal notice, here is a blessing:
  16660. **
  16661. ** May you do good and not evil.
  16662. ** May you find forgiveness for yourself and forgive others.
  16663. ** May you share freely, never taking more than you give.
  16664. **
  16665. *************************************************************************
  16666. ** This file contains the C functions that implement mutexes for OS/2
  16667. */
  16668. /*
  16669. ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
  16670. ** See the mutex.h file for details.
  16671. */
  16672. #ifdef SQLITE_MUTEX_OS2
  16673. /********************** OS/2 Mutex Implementation **********************
  16674. **
  16675. ** This implementation of mutexes is built using the OS/2 API.
  16676. */
  16677. /*
  16678. ** The mutex object
  16679. ** Each recursive mutex is an instance of the following structure.
  16680. */
  16681. struct sqlite3_mutex {
  16682. HMTX mutex; /* Mutex controlling the lock */
  16683. int id; /* Mutex type */
  16684. #ifdef SQLITE_DEBUG
  16685. int trace; /* True to trace changes */
  16686. #endif
  16687. };
  16688. #ifdef SQLITE_DEBUG
  16689. #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
  16690. #else
  16691. #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
  16692. #endif
  16693. /*
  16694. ** Initialize and deinitialize the mutex subsystem.
  16695. */
  16696. static int os2MutexInit(void){ return SQLITE_OK; }
  16697. static int os2MutexEnd(void){ return SQLITE_OK; }
  16698. /*
  16699. ** The sqlite3_mutex_alloc() routine allocates a new
  16700. ** mutex and returns a pointer to it. If it returns NULL
  16701. ** that means that a mutex could not be allocated.
  16702. ** SQLite will unwind its stack and return an error. The argument
  16703. ** to sqlite3_mutex_alloc() is one of these integer constants:
  16704. **
  16705. ** <ul>
  16706. ** <li> SQLITE_MUTEX_FAST
  16707. ** <li> SQLITE_MUTEX_RECURSIVE
  16708. ** <li> SQLITE_MUTEX_STATIC_MASTER
  16709. ** <li> SQLITE_MUTEX_STATIC_MEM
  16710. ** <li> SQLITE_MUTEX_STATIC_MEM2
  16711. ** <li> SQLITE_MUTEX_STATIC_PRNG
  16712. ** <li> SQLITE_MUTEX_STATIC_LRU
  16713. ** <li> SQLITE_MUTEX_STATIC_LRU2
  16714. ** </ul>
  16715. **
  16716. ** The first two constants cause sqlite3_mutex_alloc() to create
  16717. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  16718. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  16719. ** The mutex implementation does not need to make a distinction
  16720. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  16721. ** not want to. But SQLite will only request a recursive mutex in
  16722. ** cases where it really needs one. If a faster non-recursive mutex
  16723. ** implementation is available on the host platform, the mutex subsystem
  16724. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  16725. **
  16726. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  16727. ** a pointer to a static preexisting mutex. Six static mutexes are
  16728. ** used by the current version of SQLite. Future versions of SQLite
  16729. ** may add additional static mutexes. Static mutexes are for internal
  16730. ** use by SQLite only. Applications that use SQLite mutexes should
  16731. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  16732. ** SQLITE_MUTEX_RECURSIVE.
  16733. **
  16734. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  16735. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  16736. ** returns a different mutex on every call. But for the static
  16737. ** mutex types, the same mutex is returned on every call that has
  16738. ** the same type number.
  16739. */
  16740. static sqlite3_mutex *os2MutexAlloc(int iType){
  16741. sqlite3_mutex *p = NULL;
  16742. switch( iType ){
  16743. case SQLITE_MUTEX_FAST:
  16744. case SQLITE_MUTEX_RECURSIVE: {
  16745. p = sqlite3MallocZero( sizeof(*p) );
  16746. if( p ){
  16747. p->id = iType;
  16748. if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
  16749. sqlite3_free( p );
  16750. p = NULL;
  16751. }
  16752. }
  16753. break;
  16754. }
  16755. default: {
  16756. static volatile int isInit = 0;
  16757. static sqlite3_mutex staticMutexes[6] = {
  16758. SQLITE3_MUTEX_INITIALIZER,
  16759. SQLITE3_MUTEX_INITIALIZER,
  16760. SQLITE3_MUTEX_INITIALIZER,
  16761. SQLITE3_MUTEX_INITIALIZER,
  16762. SQLITE3_MUTEX_INITIALIZER,
  16763. SQLITE3_MUTEX_INITIALIZER,
  16764. };
  16765. if ( !isInit ){
  16766. APIRET rc;
  16767. PTIB ptib;
  16768. PPIB ppib;
  16769. HMTX mutex;
  16770. char name[32];
  16771. DosGetInfoBlocks( &ptib, &ppib );
  16772. sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
  16773. ppib->pib_ulpid );
  16774. while( !isInit ){
  16775. mutex = 0;
  16776. rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
  16777. if( rc == NO_ERROR ){
  16778. unsigned int i;
  16779. if( !isInit ){
  16780. for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
  16781. DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
  16782. }
  16783. isInit = 1;
  16784. }
  16785. DosCloseMutexSem( mutex );
  16786. }else if( rc == ERROR_DUPLICATE_NAME ){
  16787. DosSleep( 1 );
  16788. }else{
  16789. return p;
  16790. }
  16791. }
  16792. }
  16793. assert( iType-2 >= 0 );
  16794. assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
  16795. p = &staticMutexes[iType-2];
  16796. p->id = iType;
  16797. break;
  16798. }
  16799. }
  16800. return p;
  16801. }
  16802. /*
  16803. ** This routine deallocates a previously allocated mutex.
  16804. ** SQLite is careful to deallocate every mutex that it allocates.
  16805. */
  16806. static void os2MutexFree(sqlite3_mutex *p){
  16807. #ifdef SQLITE_DEBUG
  16808. TID tid;
  16809. PID pid;
  16810. ULONG ulCount;
  16811. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16812. assert( ulCount==0 );
  16813. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  16814. #endif
  16815. DosCloseMutexSem( p->mutex );
  16816. sqlite3_free( p );
  16817. }
  16818. #ifdef SQLITE_DEBUG
  16819. /*
  16820. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16821. ** intended for use inside assert() statements.
  16822. */
  16823. static int os2MutexHeld(sqlite3_mutex *p){
  16824. TID tid;
  16825. PID pid;
  16826. ULONG ulCount;
  16827. PTIB ptib;
  16828. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16829. if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
  16830. return 0;
  16831. DosGetInfoBlocks(&ptib, NULL);
  16832. return tid==ptib->tib_ptib2->tib2_ultid;
  16833. }
  16834. static int os2MutexNotheld(sqlite3_mutex *p){
  16835. TID tid;
  16836. PID pid;
  16837. ULONG ulCount;
  16838. PTIB ptib;
  16839. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16840. if( ulCount==0 )
  16841. return 1;
  16842. DosGetInfoBlocks(&ptib, NULL);
  16843. return tid!=ptib->tib_ptib2->tib2_ultid;
  16844. }
  16845. static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
  16846. TID tid;
  16847. PID pid;
  16848. ULONG ulCount;
  16849. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16850. printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
  16851. }
  16852. #endif
  16853. /*
  16854. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  16855. ** to enter a mutex. If another thread is already within the mutex,
  16856. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  16857. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  16858. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  16859. ** be entered multiple times by the same thread. In such cases the,
  16860. ** mutex must be exited an equal number of times before another thread
  16861. ** can enter. If the same thread tries to enter any other kind of mutex
  16862. ** more than once, the behavior is undefined.
  16863. */
  16864. static void os2MutexEnter(sqlite3_mutex *p){
  16865. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  16866. DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
  16867. #ifdef SQLITE_DEBUG
  16868. if( p->trace ) os2MutexTrace(p, "enter");
  16869. #endif
  16870. }
  16871. static int os2MutexTry(sqlite3_mutex *p){
  16872. int rc = SQLITE_BUSY;
  16873. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  16874. if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
  16875. rc = SQLITE_OK;
  16876. #ifdef SQLITE_DEBUG
  16877. if( p->trace ) os2MutexTrace(p, "try");
  16878. #endif
  16879. }
  16880. return rc;
  16881. }
  16882. /*
  16883. ** The sqlite3_mutex_leave() routine exits a mutex that was
  16884. ** previously entered by the same thread. The behavior
  16885. ** is undefined if the mutex is not currently entered or
  16886. ** is not currently allocated. SQLite will never do either.
  16887. */
  16888. static void os2MutexLeave(sqlite3_mutex *p){
  16889. assert( os2MutexHeld(p) );
  16890. DosReleaseMutexSem(p->mutex);
  16891. #ifdef SQLITE_DEBUG
  16892. if( p->trace ) os2MutexTrace(p, "leave");
  16893. #endif
  16894. }
  16895. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  16896. static const sqlite3_mutex_methods sMutex = {
  16897. os2MutexInit,
  16898. os2MutexEnd,
  16899. os2MutexAlloc,
  16900. os2MutexFree,
  16901. os2MutexEnter,
  16902. os2MutexTry,
  16903. os2MutexLeave,
  16904. #ifdef SQLITE_DEBUG
  16905. os2MutexHeld,
  16906. os2MutexNotheld
  16907. #else
  16908. 0,
  16909. 0
  16910. #endif
  16911. };
  16912. return &sMutex;
  16913. }
  16914. #endif /* SQLITE_MUTEX_OS2 */
  16915. /************** End of mutex_os2.c *******************************************/
  16916. /************** Begin file mutex_unix.c **************************************/
  16917. /*
  16918. ** 2007 August 28
  16919. **
  16920. ** The author disclaims copyright to this source code. In place of
  16921. ** a legal notice, here is a blessing:
  16922. **
  16923. ** May you do good and not evil.
  16924. ** May you find forgiveness for yourself and forgive others.
  16925. ** May you share freely, never taking more than you give.
  16926. **
  16927. *************************************************************************
  16928. ** This file contains the C functions that implement mutexes for pthreads
  16929. */
  16930. /*
  16931. ** The code in this file is only used if we are compiling threadsafe
  16932. ** under unix with pthreads.
  16933. **
  16934. ** Note that this implementation requires a version of pthreads that
  16935. ** supports recursive mutexes.
  16936. */
  16937. #ifdef SQLITE_MUTEX_PTHREADS
  16938. #include <pthread.h>
  16939. /*
  16940. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  16941. ** are necessary under two condidtions: (1) Debug builds and (2) using
  16942. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  16943. */
  16944. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  16945. # define SQLITE_MUTEX_NREF 1
  16946. #else
  16947. # define SQLITE_MUTEX_NREF 0
  16948. #endif
  16949. /*
  16950. ** Each recursive mutex is an instance of the following structure.
  16951. */
  16952. struct sqlite3_mutex {
  16953. pthread_mutex_t mutex; /* Mutex controlling the lock */
  16954. #if SQLITE_MUTEX_NREF
  16955. int id; /* Mutex type */
  16956. volatile int nRef; /* Number of entrances */
  16957. volatile pthread_t owner; /* Thread that is within this mutex */
  16958. int trace; /* True to trace changes */
  16959. #endif
  16960. };
  16961. #if SQLITE_MUTEX_NREF
  16962. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  16963. #else
  16964. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  16965. #endif
  16966. /*
  16967. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16968. ** intended for use only inside assert() statements. On some platforms,
  16969. ** there might be race conditions that can cause these routines to
  16970. ** deliver incorrect results. In particular, if pthread_equal() is
  16971. ** not an atomic operation, then these routines might delivery
  16972. ** incorrect results. On most platforms, pthread_equal() is a
  16973. ** comparison of two integers and is therefore atomic. But we are
  16974. ** told that HPUX is not such a platform. If so, then these routines
  16975. ** will not always work correctly on HPUX.
  16976. **
  16977. ** On those platforms where pthread_equal() is not atomic, SQLite
  16978. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  16979. ** make sure no assert() statements are evaluated and hence these
  16980. ** routines are never called.
  16981. */
  16982. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  16983. static int pthreadMutexHeld(sqlite3_mutex *p){
  16984. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  16985. }
  16986. static int pthreadMutexNotheld(sqlite3_mutex *p){
  16987. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  16988. }
  16989. #endif
  16990. /*
  16991. ** Initialize and deinitialize the mutex subsystem.
  16992. */
  16993. static int pthreadMutexInit(void){ return SQLITE_OK; }
  16994. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  16995. /*
  16996. ** The sqlite3_mutex_alloc() routine allocates a new
  16997. ** mutex and returns a pointer to it. If it returns NULL
  16998. ** that means that a mutex could not be allocated. SQLite
  16999. ** will unwind its stack and return an error. The argument
  17000. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17001. **
  17002. ** <ul>
  17003. ** <li> SQLITE_MUTEX_FAST
  17004. ** <li> SQLITE_MUTEX_RECURSIVE
  17005. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17006. ** <li> SQLITE_MUTEX_STATIC_MEM
  17007. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17008. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17009. ** <li> SQLITE_MUTEX_STATIC_LRU
  17010. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17011. ** </ul>
  17012. **
  17013. ** The first two constants cause sqlite3_mutex_alloc() to create
  17014. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17015. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17016. ** The mutex implementation does not need to make a distinction
  17017. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17018. ** not want to. But SQLite will only request a recursive mutex in
  17019. ** cases where it really needs one. If a faster non-recursive mutex
  17020. ** implementation is available on the host platform, the mutex subsystem
  17021. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17022. **
  17023. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17024. ** a pointer to a static preexisting mutex. Six static mutexes are
  17025. ** used by the current version of SQLite. Future versions of SQLite
  17026. ** may add additional static mutexes. Static mutexes are for internal
  17027. ** use by SQLite only. Applications that use SQLite mutexes should
  17028. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17029. ** SQLITE_MUTEX_RECURSIVE.
  17030. **
  17031. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17032. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17033. ** returns a different mutex on every call. But for the static
  17034. ** mutex types, the same mutex is returned on every call that has
  17035. ** the same type number.
  17036. */
  17037. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  17038. static sqlite3_mutex staticMutexes[] = {
  17039. SQLITE3_MUTEX_INITIALIZER,
  17040. SQLITE3_MUTEX_INITIALIZER,
  17041. SQLITE3_MUTEX_INITIALIZER,
  17042. SQLITE3_MUTEX_INITIALIZER,
  17043. SQLITE3_MUTEX_INITIALIZER,
  17044. SQLITE3_MUTEX_INITIALIZER
  17045. };
  17046. sqlite3_mutex *p;
  17047. switch( iType ){
  17048. case SQLITE_MUTEX_RECURSIVE: {
  17049. p = sqlite3MallocZero( sizeof(*p) );
  17050. if( p ){
  17051. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17052. /* If recursive mutexes are not available, we will have to
  17053. ** build our own. See below. */
  17054. pthread_mutex_init(&p->mutex, 0);
  17055. #else
  17056. /* Use a recursive mutex if it is available */
  17057. pthread_mutexattr_t recursiveAttr;
  17058. pthread_mutexattr_init(&recursiveAttr);
  17059. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  17060. pthread_mutex_init(&p->mutex, &recursiveAttr);
  17061. pthread_mutexattr_destroy(&recursiveAttr);
  17062. #endif
  17063. #if SQLITE_MUTEX_NREF
  17064. p->id = iType;
  17065. #endif
  17066. }
  17067. break;
  17068. }
  17069. case SQLITE_MUTEX_FAST: {
  17070. p = sqlite3MallocZero( sizeof(*p) );
  17071. if( p ){
  17072. #if SQLITE_MUTEX_NREF
  17073. p->id = iType;
  17074. #endif
  17075. pthread_mutex_init(&p->mutex, 0);
  17076. }
  17077. break;
  17078. }
  17079. default: {
  17080. assert( iType-2 >= 0 );
  17081. assert( iType-2 < ArraySize(staticMutexes) );
  17082. p = &staticMutexes[iType-2];
  17083. #if SQLITE_MUTEX_NREF
  17084. p->id = iType;
  17085. #endif
  17086. break;
  17087. }
  17088. }
  17089. return p;
  17090. }
  17091. /*
  17092. ** This routine deallocates a previously
  17093. ** allocated mutex. SQLite is careful to deallocate every
  17094. ** mutex that it allocates.
  17095. */
  17096. static void pthreadMutexFree(sqlite3_mutex *p){
  17097. assert( p->nRef==0 );
  17098. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17099. pthread_mutex_destroy(&p->mutex);
  17100. sqlite3_free(p);
  17101. }
  17102. /*
  17103. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17104. ** to enter a mutex. If another thread is already within the mutex,
  17105. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17106. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17107. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17108. ** be entered multiple times by the same thread. In such cases the,
  17109. ** mutex must be exited an equal number of times before another thread
  17110. ** can enter. If the same thread tries to enter any other kind of mutex
  17111. ** more than once, the behavior is undefined.
  17112. */
  17113. static void pthreadMutexEnter(sqlite3_mutex *p){
  17114. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17115. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17116. /* If recursive mutexes are not available, then we have to grow
  17117. ** our own. This implementation assumes that pthread_equal()
  17118. ** is atomic - that it cannot be deceived into thinking self
  17119. ** and p->owner are equal if p->owner changes between two values
  17120. ** that are not equal to self while the comparison is taking place.
  17121. ** This implementation also assumes a coherent cache - that
  17122. ** separate processes cannot read different values from the same
  17123. ** address at the same time. If either of these two conditions
  17124. ** are not met, then the mutexes will fail and problems will result.
  17125. */
  17126. {
  17127. pthread_t self = pthread_self();
  17128. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17129. p->nRef++;
  17130. }else{
  17131. pthread_mutex_lock(&p->mutex);
  17132. assert( p->nRef==0 );
  17133. p->owner = self;
  17134. p->nRef = 1;
  17135. }
  17136. }
  17137. #else
  17138. /* Use the built-in recursive mutexes if they are available.
  17139. */
  17140. pthread_mutex_lock(&p->mutex);
  17141. #if SQLITE_MUTEX_NREF
  17142. assert( p->nRef>0 || p->owner==0 );
  17143. p->owner = pthread_self();
  17144. p->nRef++;
  17145. #endif
  17146. #endif
  17147. #ifdef SQLITE_DEBUG
  17148. if( p->trace ){
  17149. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17150. }
  17151. #endif
  17152. }
  17153. static int pthreadMutexTry(sqlite3_mutex *p){
  17154. int rc;
  17155. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17156. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17157. /* If recursive mutexes are not available, then we have to grow
  17158. ** our own. This implementation assumes that pthread_equal()
  17159. ** is atomic - that it cannot be deceived into thinking self
  17160. ** and p->owner are equal if p->owner changes between two values
  17161. ** that are not equal to self while the comparison is taking place.
  17162. ** This implementation also assumes a coherent cache - that
  17163. ** separate processes cannot read different values from the same
  17164. ** address at the same time. If either of these two conditions
  17165. ** are not met, then the mutexes will fail and problems will result.
  17166. */
  17167. {
  17168. pthread_t self = pthread_self();
  17169. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17170. p->nRef++;
  17171. rc = SQLITE_OK;
  17172. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  17173. assert( p->nRef==0 );
  17174. p->owner = self;
  17175. p->nRef = 1;
  17176. rc = SQLITE_OK;
  17177. }else{
  17178. rc = SQLITE_BUSY;
  17179. }
  17180. }
  17181. #else
  17182. /* Use the built-in recursive mutexes if they are available.
  17183. */
  17184. if( pthread_mutex_trylock(&p->mutex)==0 ){
  17185. #if SQLITE_MUTEX_NREF
  17186. p->owner = pthread_self();
  17187. p->nRef++;
  17188. #endif
  17189. rc = SQLITE_OK;
  17190. }else{
  17191. rc = SQLITE_BUSY;
  17192. }
  17193. #endif
  17194. #ifdef SQLITE_DEBUG
  17195. if( rc==SQLITE_OK && p->trace ){
  17196. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17197. }
  17198. #endif
  17199. return rc;
  17200. }
  17201. /*
  17202. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17203. ** previously entered by the same thread. The behavior
  17204. ** is undefined if the mutex is not currently entered or
  17205. ** is not currently allocated. SQLite will never do either.
  17206. */
  17207. static void pthreadMutexLeave(sqlite3_mutex *p){
  17208. assert( pthreadMutexHeld(p) );
  17209. #if SQLITE_MUTEX_NREF
  17210. p->nRef--;
  17211. if( p->nRef==0 ) p->owner = 0;
  17212. #endif
  17213. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17214. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17215. if( p->nRef==0 ){
  17216. pthread_mutex_unlock(&p->mutex);
  17217. }
  17218. #else
  17219. pthread_mutex_unlock(&p->mutex);
  17220. #endif
  17221. #ifdef SQLITE_DEBUG
  17222. if( p->trace ){
  17223. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17224. }
  17225. #endif
  17226. }
  17227. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17228. static const sqlite3_mutex_methods sMutex = {
  17229. pthreadMutexInit,
  17230. pthreadMutexEnd,
  17231. pthreadMutexAlloc,
  17232. pthreadMutexFree,
  17233. pthreadMutexEnter,
  17234. pthreadMutexTry,
  17235. pthreadMutexLeave,
  17236. #ifdef SQLITE_DEBUG
  17237. pthreadMutexHeld,
  17238. pthreadMutexNotheld
  17239. #else
  17240. 0,
  17241. 0
  17242. #endif
  17243. };
  17244. return &sMutex;
  17245. }
  17246. #endif /* SQLITE_MUTEX_PTHREADS */
  17247. /************** End of mutex_unix.c ******************************************/
  17248. /************** Begin file mutex_w32.c ***************************************/
  17249. /*
  17250. ** 2007 August 14
  17251. **
  17252. ** The author disclaims copyright to this source code. In place of
  17253. ** a legal notice, here is a blessing:
  17254. **
  17255. ** May you do good and not evil.
  17256. ** May you find forgiveness for yourself and forgive others.
  17257. ** May you share freely, never taking more than you give.
  17258. **
  17259. *************************************************************************
  17260. ** This file contains the C functions that implement mutexes for win32
  17261. */
  17262. /*
  17263. ** The code in this file is only used if we are compiling multithreaded
  17264. ** on a win32 system.
  17265. */
  17266. #ifdef SQLITE_MUTEX_W32
  17267. /*
  17268. ** Each recursive mutex is an instance of the following structure.
  17269. */
  17270. struct sqlite3_mutex {
  17271. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  17272. int id; /* Mutex type */
  17273. #ifdef SQLITE_DEBUG
  17274. volatile int nRef; /* Number of enterances */
  17275. volatile DWORD owner; /* Thread holding this mutex */
  17276. int trace; /* True to trace changes */
  17277. #endif
  17278. };
  17279. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  17280. #ifdef SQLITE_DEBUG
  17281. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
  17282. #else
  17283. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  17284. #endif
  17285. /*
  17286. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  17287. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  17288. **
  17289. ** Here is an interesting observation: Win95, Win98, and WinME lack
  17290. ** the LockFileEx() API. But we can still statically link against that
  17291. ** API as long as we don't call it win running Win95/98/ME. A call to
  17292. ** this routine is used to determine if the host is Win95/98/ME or
  17293. ** WinNT/2K/XP so that we will know whether or not we can safely call
  17294. ** the LockFileEx() API.
  17295. **
  17296. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  17297. ** which is only available if your application was compiled with
  17298. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  17299. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  17300. ** this out as well.
  17301. */
  17302. #if 0
  17303. #if SQLITE_OS_WINCE
  17304. # define mutexIsNT() (1)
  17305. #else
  17306. static int mutexIsNT(void){
  17307. static int osType = 0;
  17308. if( osType==0 ){
  17309. OSVERSIONINFO sInfo;
  17310. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  17311. GetVersionEx(&sInfo);
  17312. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  17313. }
  17314. return osType==2;
  17315. }
  17316. #endif /* SQLITE_OS_WINCE */
  17317. #endif
  17318. #ifdef SQLITE_DEBUG
  17319. /*
  17320. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17321. ** intended for use only inside assert() statements.
  17322. */
  17323. static int winMutexHeld(sqlite3_mutex *p){
  17324. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  17325. }
  17326. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  17327. return p->nRef==0 || p->owner!=tid;
  17328. }
  17329. static int winMutexNotheld(sqlite3_mutex *p){
  17330. DWORD tid = GetCurrentThreadId();
  17331. return winMutexNotheld2(p, tid);
  17332. }
  17333. #endif
  17334. /*
  17335. ** Initialize and deinitialize the mutex subsystem.
  17336. */
  17337. static sqlite3_mutex winMutex_staticMutexes[6] = {
  17338. SQLITE3_MUTEX_INITIALIZER,
  17339. SQLITE3_MUTEX_INITIALIZER,
  17340. SQLITE3_MUTEX_INITIALIZER,
  17341. SQLITE3_MUTEX_INITIALIZER,
  17342. SQLITE3_MUTEX_INITIALIZER,
  17343. SQLITE3_MUTEX_INITIALIZER
  17344. };
  17345. static int winMutex_isInit = 0;
  17346. /* As winMutexInit() and winMutexEnd() are called as part
  17347. ** of the sqlite3_initialize and sqlite3_shutdown()
  17348. ** processing, the "interlocked" magic is probably not
  17349. ** strictly necessary.
  17350. */
  17351. static long winMutex_lock = 0;
  17352. static int winMutexInit(void){
  17353. /* The first to increment to 1 does actual initialization */
  17354. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  17355. int i;
  17356. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17357. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  17358. }
  17359. winMutex_isInit = 1;
  17360. }else{
  17361. /* Someone else is in the process of initing the static mutexes */
  17362. while( !winMutex_isInit ){
  17363. Sleep(1);
  17364. }
  17365. }
  17366. return SQLITE_OK;
  17367. }
  17368. static int winMutexEnd(void){
  17369. /* The first to decrement to 0 does actual shutdown
  17370. ** (which should be the last to shutdown.) */
  17371. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  17372. if( winMutex_isInit==1 ){
  17373. int i;
  17374. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17375. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  17376. }
  17377. winMutex_isInit = 0;
  17378. }
  17379. }
  17380. return SQLITE_OK;
  17381. }
  17382. /*
  17383. ** The sqlite3_mutex_alloc() routine allocates a new
  17384. ** mutex and returns a pointer to it. If it returns NULL
  17385. ** that means that a mutex could not be allocated. SQLite
  17386. ** will unwind its stack and return an error. The argument
  17387. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17388. **
  17389. ** <ul>
  17390. ** <li> SQLITE_MUTEX_FAST
  17391. ** <li> SQLITE_MUTEX_RECURSIVE
  17392. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17393. ** <li> SQLITE_MUTEX_STATIC_MEM
  17394. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17395. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17396. ** <li> SQLITE_MUTEX_STATIC_LRU
  17397. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17398. ** </ul>
  17399. **
  17400. ** The first two constants cause sqlite3_mutex_alloc() to create
  17401. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17402. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17403. ** The mutex implementation does not need to make a distinction
  17404. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17405. ** not want to. But SQLite will only request a recursive mutex in
  17406. ** cases where it really needs one. If a faster non-recursive mutex
  17407. ** implementation is available on the host platform, the mutex subsystem
  17408. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17409. **
  17410. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17411. ** a pointer to a static preexisting mutex. Six static mutexes are
  17412. ** used by the current version of SQLite. Future versions of SQLite
  17413. ** may add additional static mutexes. Static mutexes are for internal
  17414. ** use by SQLite only. Applications that use SQLite mutexes should
  17415. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17416. ** SQLITE_MUTEX_RECURSIVE.
  17417. **
  17418. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17419. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17420. ** returns a different mutex on every call. But for the static
  17421. ** mutex types, the same mutex is returned on every call that has
  17422. ** the same type number.
  17423. */
  17424. static sqlite3_mutex *winMutexAlloc(int iType){
  17425. sqlite3_mutex *p;
  17426. switch( iType ){
  17427. case SQLITE_MUTEX_FAST:
  17428. case SQLITE_MUTEX_RECURSIVE: {
  17429. p = sqlite3MallocZero( sizeof(*p) );
  17430. if( p ){
  17431. #ifdef SQLITE_DEBUG
  17432. p->id = iType;
  17433. #endif
  17434. InitializeCriticalSection(&p->mutex);
  17435. }
  17436. break;
  17437. }
  17438. default: {
  17439. assert( winMutex_isInit==1 );
  17440. assert( iType-2 >= 0 );
  17441. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  17442. p = &winMutex_staticMutexes[iType-2];
  17443. #ifdef SQLITE_DEBUG
  17444. p->id = iType;
  17445. #endif
  17446. break;
  17447. }
  17448. }
  17449. return p;
  17450. }
  17451. /*
  17452. ** This routine deallocates a previously
  17453. ** allocated mutex. SQLite is careful to deallocate every
  17454. ** mutex that it allocates.
  17455. */
  17456. static void winMutexFree(sqlite3_mutex *p){
  17457. assert( p );
  17458. assert( p->nRef==0 && p->owner==0 );
  17459. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17460. DeleteCriticalSection(&p->mutex);
  17461. sqlite3_free(p);
  17462. }
  17463. /*
  17464. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17465. ** to enter a mutex. If another thread is already within the mutex,
  17466. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17467. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17468. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17469. ** be entered multiple times by the same thread. In such cases the,
  17470. ** mutex must be exited an equal number of times before another thread
  17471. ** can enter. If the same thread tries to enter any other kind of mutex
  17472. ** more than once, the behavior is undefined.
  17473. */
  17474. static void winMutexEnter(sqlite3_mutex *p){
  17475. #ifdef SQLITE_DEBUG
  17476. DWORD tid = GetCurrentThreadId();
  17477. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17478. #endif
  17479. EnterCriticalSection(&p->mutex);
  17480. #ifdef SQLITE_DEBUG
  17481. assert( p->nRef>0 || p->owner==0 );
  17482. p->owner = tid;
  17483. p->nRef++;
  17484. if( p->trace ){
  17485. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17486. }
  17487. #endif
  17488. }
  17489. static int winMutexTry(sqlite3_mutex *p){
  17490. #ifndef NDEBUG
  17491. DWORD tid = GetCurrentThreadId();
  17492. #endif
  17493. int rc = SQLITE_BUSY;
  17494. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17495. /*
  17496. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  17497. ** is used it is merely an optimization. So it is OK for it to always
  17498. ** fail.
  17499. **
  17500. ** The TryEnterCriticalSection() interface is only available on WinNT.
  17501. ** And some windows compilers complain if you try to use it without
  17502. ** first doing some #defines that prevent SQLite from building on Win98.
  17503. ** For that reason, we will omit this optimization for now. See
  17504. ** ticket #2685.
  17505. */
  17506. #if 0
  17507. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  17508. p->owner = tid;
  17509. p->nRef++;
  17510. rc = SQLITE_OK;
  17511. }
  17512. #else
  17513. UNUSED_PARAMETER(p);
  17514. #endif
  17515. #ifdef SQLITE_DEBUG
  17516. if( rc==SQLITE_OK && p->trace ){
  17517. printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17518. }
  17519. #endif
  17520. return rc;
  17521. }
  17522. /*
  17523. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17524. ** previously entered by the same thread. The behavior
  17525. ** is undefined if the mutex is not currently entered or
  17526. ** is not currently allocated. SQLite will never do either.
  17527. */
  17528. static void winMutexLeave(sqlite3_mutex *p){
  17529. #ifndef NDEBUG
  17530. DWORD tid = GetCurrentThreadId();
  17531. assert( p->nRef>0 );
  17532. assert( p->owner==tid );
  17533. p->nRef--;
  17534. if( p->nRef==0 ) p->owner = 0;
  17535. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17536. #endif
  17537. LeaveCriticalSection(&p->mutex);
  17538. #ifdef SQLITE_DEBUG
  17539. if( p->trace ){
  17540. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17541. }
  17542. #endif
  17543. }
  17544. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17545. static const sqlite3_mutex_methods sMutex = {
  17546. winMutexInit,
  17547. winMutexEnd,
  17548. winMutexAlloc,
  17549. winMutexFree,
  17550. winMutexEnter,
  17551. winMutexTry,
  17552. winMutexLeave,
  17553. #ifdef SQLITE_DEBUG
  17554. winMutexHeld,
  17555. winMutexNotheld
  17556. #else
  17557. 0,
  17558. 0
  17559. #endif
  17560. };
  17561. return &sMutex;
  17562. }
  17563. #endif /* SQLITE_MUTEX_W32 */
  17564. /************** End of mutex_w32.c *******************************************/
  17565. /************** Begin file malloc.c ******************************************/
  17566. /*
  17567. ** 2001 September 15
  17568. **
  17569. ** The author disclaims copyright to this source code. In place of
  17570. ** a legal notice, here is a blessing:
  17571. **
  17572. ** May you do good and not evil.
  17573. ** May you find forgiveness for yourself and forgive others.
  17574. ** May you share freely, never taking more than you give.
  17575. **
  17576. *************************************************************************
  17577. **
  17578. ** Memory allocation functions used throughout sqlite.
  17579. */
  17580. /* #include <stdarg.h> */
  17581. /*
  17582. ** Attempt to release up to n bytes of non-essential memory currently
  17583. ** held by SQLite. An example of non-essential memory is memory used to
  17584. ** cache database pages that are not currently in use.
  17585. */
  17586. SQLITE_API int sqlite3_release_memory(int n){
  17587. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17588. return sqlite3PcacheReleaseMemory(n);
  17589. #else
  17590. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  17591. ** is a no-op returning zero if SQLite is not compiled with
  17592. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  17593. UNUSED_PARAMETER(n);
  17594. return 0;
  17595. #endif
  17596. }
  17597. /*
  17598. ** An instance of the following object records the location of
  17599. ** each unused scratch buffer.
  17600. */
  17601. typedef struct ScratchFreeslot {
  17602. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  17603. } ScratchFreeslot;
  17604. /*
  17605. ** State information local to the memory allocation subsystem.
  17606. */
  17607. static SQLITE_WSD struct Mem0Global {
  17608. sqlite3_mutex *mutex; /* Mutex to serialize access */
  17609. /*
  17610. ** The alarm callback and its arguments. The mem0.mutex lock will
  17611. ** be held while the callback is running. Recursive calls into
  17612. ** the memory subsystem are allowed, but no new callbacks will be
  17613. ** issued.
  17614. */
  17615. sqlite3_int64 alarmThreshold;
  17616. void (*alarmCallback)(void*, sqlite3_int64,int);
  17617. void *alarmArg;
  17618. /*
  17619. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  17620. ** (so that a range test can be used to determine if an allocation
  17621. ** being freed came from pScratch) and a pointer to the list of
  17622. ** unused scratch allocations.
  17623. */
  17624. void *pScratchEnd;
  17625. ScratchFreeslot *pScratchFree;
  17626. u32 nScratchFree;
  17627. /*
  17628. ** True if heap is nearly "full" where "full" is defined by the
  17629. ** sqlite3_soft_heap_limit() setting.
  17630. */
  17631. int nearlyFull;
  17632. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  17633. #define mem0 GLOBAL(struct Mem0Global, mem0)
  17634. /*
  17635. ** This routine runs when the memory allocator sees that the
  17636. ** total memory allocation is about to exceed the soft heap
  17637. ** limit.
  17638. */
  17639. static void softHeapLimitEnforcer(
  17640. void *NotUsed,
  17641. sqlite3_int64 NotUsed2,
  17642. int allocSize
  17643. ){
  17644. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  17645. sqlite3_release_memory(allocSize);
  17646. }
  17647. /*
  17648. ** Change the alarm callback
  17649. */
  17650. static int sqlite3MemoryAlarm(
  17651. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17652. void *pArg,
  17653. sqlite3_int64 iThreshold
  17654. ){
  17655. int nUsed;
  17656. sqlite3_mutex_enter(mem0.mutex);
  17657. mem0.alarmCallback = xCallback;
  17658. mem0.alarmArg = pArg;
  17659. mem0.alarmThreshold = iThreshold;
  17660. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17661. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  17662. sqlite3_mutex_leave(mem0.mutex);
  17663. return SQLITE_OK;
  17664. }
  17665. #ifndef SQLITE_OMIT_DEPRECATED
  17666. /*
  17667. ** Deprecated external interface. Internal/core SQLite code
  17668. ** should call sqlite3MemoryAlarm.
  17669. */
  17670. SQLITE_API int sqlite3_memory_alarm(
  17671. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  17672. void *pArg,
  17673. sqlite3_int64 iThreshold
  17674. ){
  17675. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  17676. }
  17677. #endif
  17678. /*
  17679. ** Set the soft heap-size limit for the library. Passing a zero or
  17680. ** negative value indicates no limit.
  17681. */
  17682. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  17683. sqlite3_int64 priorLimit;
  17684. sqlite3_int64 excess;
  17685. #ifndef SQLITE_OMIT_AUTOINIT
  17686. int rc = sqlite3_initialize();
  17687. if( rc ) return -1;
  17688. #endif
  17689. sqlite3_mutex_enter(mem0.mutex);
  17690. priorLimit = mem0.alarmThreshold;
  17691. sqlite3_mutex_leave(mem0.mutex);
  17692. if( n<0 ) return priorLimit;
  17693. if( n>0 ){
  17694. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  17695. }else{
  17696. sqlite3MemoryAlarm(0, 0, 0);
  17697. }
  17698. excess = sqlite3_memory_used() - n;
  17699. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  17700. return priorLimit;
  17701. }
  17702. SQLITE_API void sqlite3_soft_heap_limit(int n){
  17703. if( n<0 ) n = 0;
  17704. sqlite3_soft_heap_limit64(n);
  17705. }
  17706. /*
  17707. ** Initialize the memory allocation subsystem.
  17708. */
  17709. SQLITE_PRIVATE int sqlite3MallocInit(void){
  17710. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  17711. sqlite3MemSetDefault();
  17712. }
  17713. memset(&mem0, 0, sizeof(mem0));
  17714. if( sqlite3GlobalConfig.bCoreMutex ){
  17715. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17716. }
  17717. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  17718. && sqlite3GlobalConfig.nScratch>0 ){
  17719. int i, n, sz;
  17720. ScratchFreeslot *pSlot;
  17721. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  17722. sqlite3GlobalConfig.szScratch = sz;
  17723. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  17724. n = sqlite3GlobalConfig.nScratch;
  17725. mem0.pScratchFree = pSlot;
  17726. mem0.nScratchFree = n;
  17727. for(i=0; i<n-1; i++){
  17728. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  17729. pSlot = pSlot->pNext;
  17730. }
  17731. pSlot->pNext = 0;
  17732. mem0.pScratchEnd = (void*)&pSlot[1];
  17733. }else{
  17734. mem0.pScratchEnd = 0;
  17735. sqlite3GlobalConfig.pScratch = 0;
  17736. sqlite3GlobalConfig.szScratch = 0;
  17737. sqlite3GlobalConfig.nScratch = 0;
  17738. }
  17739. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  17740. || sqlite3GlobalConfig.nPage<1 ){
  17741. sqlite3GlobalConfig.pPage = 0;
  17742. sqlite3GlobalConfig.szPage = 0;
  17743. sqlite3GlobalConfig.nPage = 0;
  17744. }
  17745. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  17746. }
  17747. /*
  17748. ** Return true if the heap is currently under memory pressure - in other
  17749. ** words if the amount of heap used is close to the limit set by
  17750. ** sqlite3_soft_heap_limit().
  17751. */
  17752. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  17753. return mem0.nearlyFull;
  17754. }
  17755. /*
  17756. ** Deinitialize the memory allocation subsystem.
  17757. */
  17758. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  17759. if( sqlite3GlobalConfig.m.xShutdown ){
  17760. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  17761. }
  17762. memset(&mem0, 0, sizeof(mem0));
  17763. }
  17764. /*
  17765. ** Return the amount of memory currently checked out.
  17766. */
  17767. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  17768. int n, mx;
  17769. sqlite3_int64 res;
  17770. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  17771. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  17772. return res;
  17773. }
  17774. /*
  17775. ** Return the maximum amount of memory that has ever been
  17776. ** checked out since either the beginning of this process
  17777. ** or since the most recent reset.
  17778. */
  17779. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  17780. int n, mx;
  17781. sqlite3_int64 res;
  17782. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  17783. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  17784. return res;
  17785. }
  17786. /*
  17787. ** Trigger the alarm
  17788. */
  17789. static void sqlite3MallocAlarm(int nByte){
  17790. void (*xCallback)(void*,sqlite3_int64,int);
  17791. sqlite3_int64 nowUsed;
  17792. void *pArg;
  17793. if( mem0.alarmCallback==0 ) return;
  17794. xCallback = mem0.alarmCallback;
  17795. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17796. pArg = mem0.alarmArg;
  17797. mem0.alarmCallback = 0;
  17798. sqlite3_mutex_leave(mem0.mutex);
  17799. xCallback(pArg, nowUsed, nByte);
  17800. sqlite3_mutex_enter(mem0.mutex);
  17801. mem0.alarmCallback = xCallback;
  17802. mem0.alarmArg = pArg;
  17803. }
  17804. /*
  17805. ** Do a memory allocation with statistics and alarms. Assume the
  17806. ** lock is already held.
  17807. */
  17808. static int mallocWithAlarm(int n, void **pp){
  17809. int nFull;
  17810. void *p;
  17811. assert( sqlite3_mutex_held(mem0.mutex) );
  17812. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  17813. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  17814. if( mem0.alarmCallback!=0 ){
  17815. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17816. if( nUsed >= mem0.alarmThreshold - nFull ){
  17817. mem0.nearlyFull = 1;
  17818. sqlite3MallocAlarm(nFull);
  17819. }else{
  17820. mem0.nearlyFull = 0;
  17821. }
  17822. }
  17823. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17824. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17825. if( p==0 && mem0.alarmCallback ){
  17826. sqlite3MallocAlarm(nFull);
  17827. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17828. }
  17829. #endif
  17830. if( p ){
  17831. nFull = sqlite3MallocSize(p);
  17832. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  17833. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  17834. }
  17835. *pp = p;
  17836. return nFull;
  17837. }
  17838. /*
  17839. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  17840. ** assumes the memory subsystem has already been initialized.
  17841. */
  17842. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  17843. void *p;
  17844. if( n<=0 /* IMP: R-65312-04917 */
  17845. || n>=0x7fffff00
  17846. ){
  17847. /* A memory allocation of a number of bytes which is near the maximum
  17848. ** signed integer value might cause an integer overflow inside of the
  17849. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  17850. ** 255 bytes of overhead. SQLite itself will never use anything near
  17851. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  17852. p = 0;
  17853. }else if( sqlite3GlobalConfig.bMemstat ){
  17854. sqlite3_mutex_enter(mem0.mutex);
  17855. mallocWithAlarm(n, &p);
  17856. sqlite3_mutex_leave(mem0.mutex);
  17857. }else{
  17858. p = sqlite3GlobalConfig.m.xMalloc(n);
  17859. }
  17860. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  17861. return p;
  17862. }
  17863. /*
  17864. ** This version of the memory allocation is for use by the application.
  17865. ** First make sure the memory subsystem is initialized, then do the
  17866. ** allocation.
  17867. */
  17868. SQLITE_API void *sqlite3_malloc(int n){
  17869. #ifndef SQLITE_OMIT_AUTOINIT
  17870. if( sqlite3_initialize() ) return 0;
  17871. #endif
  17872. return sqlite3Malloc(n);
  17873. }
  17874. /*
  17875. ** Each thread may only have a single outstanding allocation from
  17876. ** xScratchMalloc(). We verify this constraint in the single-threaded
  17877. ** case by setting scratchAllocOut to 1 when an allocation
  17878. ** is outstanding clearing it when the allocation is freed.
  17879. */
  17880. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17881. static int scratchAllocOut = 0;
  17882. #endif
  17883. /*
  17884. ** Allocate memory that is to be used and released right away.
  17885. ** This routine is similar to alloca() in that it is not intended
  17886. ** for situations where the memory might be held long-term. This
  17887. ** routine is intended to get memory to old large transient data
  17888. ** structures that would not normally fit on the stack of an
  17889. ** embedded processor.
  17890. */
  17891. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  17892. void *p;
  17893. assert( n>0 );
  17894. sqlite3_mutex_enter(mem0.mutex);
  17895. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  17896. p = mem0.pScratchFree;
  17897. mem0.pScratchFree = mem0.pScratchFree->pNext;
  17898. mem0.nScratchFree--;
  17899. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  17900. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17901. sqlite3_mutex_leave(mem0.mutex);
  17902. }else{
  17903. if( sqlite3GlobalConfig.bMemstat ){
  17904. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17905. n = mallocWithAlarm(n, &p);
  17906. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  17907. sqlite3_mutex_leave(mem0.mutex);
  17908. }else{
  17909. sqlite3_mutex_leave(mem0.mutex);
  17910. p = sqlite3GlobalConfig.m.xMalloc(n);
  17911. }
  17912. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  17913. }
  17914. assert( sqlite3_mutex_notheld(mem0.mutex) );
  17915. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17916. /* Verify that no more than two scratch allocations per thread
  17917. ** are outstanding at one time. (This is only checked in the
  17918. ** single-threaded case since checking in the multi-threaded case
  17919. ** would be much more complicated.) */
  17920. assert( scratchAllocOut<=1 );
  17921. if( p ) scratchAllocOut++;
  17922. #endif
  17923. return p;
  17924. }
  17925. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  17926. if( p ){
  17927. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17928. /* Verify that no more than two scratch allocation per thread
  17929. ** is outstanding at one time. (This is only checked in the
  17930. ** single-threaded case since checking in the multi-threaded case
  17931. ** would be much more complicated.) */
  17932. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  17933. scratchAllocOut--;
  17934. #endif
  17935. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  17936. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  17937. ScratchFreeslot *pSlot;
  17938. pSlot = (ScratchFreeslot*)p;
  17939. sqlite3_mutex_enter(mem0.mutex);
  17940. pSlot->pNext = mem0.pScratchFree;
  17941. mem0.pScratchFree = pSlot;
  17942. mem0.nScratchFree++;
  17943. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  17944. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  17945. sqlite3_mutex_leave(mem0.mutex);
  17946. }else{
  17947. /* Release memory back to the heap */
  17948. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  17949. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  17950. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  17951. if( sqlite3GlobalConfig.bMemstat ){
  17952. int iSize = sqlite3MallocSize(p);
  17953. sqlite3_mutex_enter(mem0.mutex);
  17954. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  17955. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  17956. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  17957. sqlite3GlobalConfig.m.xFree(p);
  17958. sqlite3_mutex_leave(mem0.mutex);
  17959. }else{
  17960. sqlite3GlobalConfig.m.xFree(p);
  17961. }
  17962. }
  17963. }
  17964. }
  17965. /*
  17966. ** TRUE if p is a lookaside memory allocation from db
  17967. */
  17968. #ifndef SQLITE_OMIT_LOOKASIDE
  17969. static int isLookaside(sqlite3 *db, void *p){
  17970. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  17971. }
  17972. #else
  17973. #define isLookaside(A,B) 0
  17974. #endif
  17975. /*
  17976. ** Return the size of a memory allocation previously obtained from
  17977. ** sqlite3Malloc() or sqlite3_malloc().
  17978. */
  17979. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  17980. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  17981. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  17982. return sqlite3GlobalConfig.m.xSize(p);
  17983. }
  17984. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  17985. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  17986. if( db && isLookaside(db, p) ){
  17987. return db->lookaside.sz;
  17988. }else{
  17989. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  17990. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  17991. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  17992. return sqlite3GlobalConfig.m.xSize(p);
  17993. }
  17994. }
  17995. /*
  17996. ** Free memory previously obtained from sqlite3Malloc().
  17997. */
  17998. SQLITE_API void sqlite3_free(void *p){
  17999. if( p==0 ) return; /* IMP: R-49053-54554 */
  18000. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18001. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18002. if( sqlite3GlobalConfig.bMemstat ){
  18003. sqlite3_mutex_enter(mem0.mutex);
  18004. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  18005. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18006. sqlite3GlobalConfig.m.xFree(p);
  18007. sqlite3_mutex_leave(mem0.mutex);
  18008. }else{
  18009. sqlite3GlobalConfig.m.xFree(p);
  18010. }
  18011. }
  18012. /*
  18013. ** Free memory that might be associated with a particular database
  18014. ** connection.
  18015. */
  18016. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  18017. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18018. if( db ){
  18019. if( db->pnBytesFreed ){
  18020. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  18021. return;
  18022. }
  18023. if( isLookaside(db, p) ){
  18024. LookasideSlot *pBuf = (LookasideSlot*)p;
  18025. pBuf->pNext = db->lookaside.pFree;
  18026. db->lookaside.pFree = pBuf;
  18027. db->lookaside.nOut--;
  18028. return;
  18029. }
  18030. }
  18031. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18032. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18033. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18034. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18035. sqlite3_free(p);
  18036. }
  18037. /*
  18038. ** Change the size of an existing memory allocation
  18039. */
  18040. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  18041. int nOld, nNew, nDiff;
  18042. void *pNew;
  18043. if( pOld==0 ){
  18044. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  18045. }
  18046. if( nBytes<=0 ){
  18047. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  18048. return 0;
  18049. }
  18050. if( nBytes>=0x7fffff00 ){
  18051. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  18052. return 0;
  18053. }
  18054. nOld = sqlite3MallocSize(pOld);
  18055. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  18056. ** argument to xRealloc is always a value returned by a prior call to
  18057. ** xRoundup. */
  18058. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  18059. if( nOld==nNew ){
  18060. pNew = pOld;
  18061. }else if( sqlite3GlobalConfig.bMemstat ){
  18062. sqlite3_mutex_enter(mem0.mutex);
  18063. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  18064. nDiff = nNew - nOld;
  18065. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  18066. mem0.alarmThreshold-nDiff ){
  18067. sqlite3MallocAlarm(nDiff);
  18068. }
  18069. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  18070. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  18071. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18072. if( pNew==0 && mem0.alarmCallback ){
  18073. sqlite3MallocAlarm(nBytes);
  18074. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18075. }
  18076. if( pNew ){
  18077. nNew = sqlite3MallocSize(pNew);
  18078. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  18079. }
  18080. sqlite3_mutex_leave(mem0.mutex);
  18081. }else{
  18082. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18083. }
  18084. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  18085. return pNew;
  18086. }
  18087. /*
  18088. ** The public interface to sqlite3Realloc. Make sure that the memory
  18089. ** subsystem is initialized prior to invoking sqliteRealloc.
  18090. */
  18091. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  18092. #ifndef SQLITE_OMIT_AUTOINIT
  18093. if( sqlite3_initialize() ) return 0;
  18094. #endif
  18095. return sqlite3Realloc(pOld, n);
  18096. }
  18097. /*
  18098. ** Allocate and zero memory.
  18099. */
  18100. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  18101. void *p = sqlite3Malloc(n);
  18102. if( p ){
  18103. memset(p, 0, n);
  18104. }
  18105. return p;
  18106. }
  18107. /*
  18108. ** Allocate and zero memory. If the allocation fails, make
  18109. ** the mallocFailed flag in the connection pointer.
  18110. */
  18111. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  18112. void *p = sqlite3DbMallocRaw(db, n);
  18113. if( p ){
  18114. memset(p, 0, n);
  18115. }
  18116. return p;
  18117. }
  18118. /*
  18119. ** Allocate and zero memory. If the allocation fails, make
  18120. ** the mallocFailed flag in the connection pointer.
  18121. **
  18122. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  18123. ** failure on the same database connection) then always return 0.
  18124. ** Hence for a particular database connection, once malloc starts
  18125. ** failing, it fails consistently until mallocFailed is reset.
  18126. ** This is an important assumption. There are many places in the
  18127. ** code that do things like this:
  18128. **
  18129. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  18130. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  18131. ** if( b ) a[10] = 9;
  18132. **
  18133. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  18134. ** that all prior mallocs (ex: "a") worked too.
  18135. */
  18136. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  18137. void *p;
  18138. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18139. assert( db==0 || db->pnBytesFreed==0 );
  18140. #ifndef SQLITE_OMIT_LOOKASIDE
  18141. if( db ){
  18142. LookasideSlot *pBuf;
  18143. if( db->mallocFailed ){
  18144. return 0;
  18145. }
  18146. if( db->lookaside.bEnabled ){
  18147. if( n>db->lookaside.sz ){
  18148. db->lookaside.anStat[1]++;
  18149. }else if( (pBuf = db->lookaside.pFree)==0 ){
  18150. db->lookaside.anStat[2]++;
  18151. }else{
  18152. db->lookaside.pFree = pBuf->pNext;
  18153. db->lookaside.nOut++;
  18154. db->lookaside.anStat[0]++;
  18155. if( db->lookaside.nOut>db->lookaside.mxOut ){
  18156. db->lookaside.mxOut = db->lookaside.nOut;
  18157. }
  18158. return (void*)pBuf;
  18159. }
  18160. }
  18161. }
  18162. #else
  18163. if( db && db->mallocFailed ){
  18164. return 0;
  18165. }
  18166. #endif
  18167. p = sqlite3Malloc(n);
  18168. if( !p && db ){
  18169. db->mallocFailed = 1;
  18170. }
  18171. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  18172. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18173. return p;
  18174. }
  18175. /*
  18176. ** Resize the block of memory pointed to by p to n bytes. If the
  18177. ** resize fails, set the mallocFailed flag in the connection object.
  18178. */
  18179. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  18180. void *pNew = 0;
  18181. assert( db!=0 );
  18182. assert( sqlite3_mutex_held(db->mutex) );
  18183. if( db->mallocFailed==0 ){
  18184. if( p==0 ){
  18185. return sqlite3DbMallocRaw(db, n);
  18186. }
  18187. if( isLookaside(db, p) ){
  18188. if( n<=db->lookaside.sz ){
  18189. return p;
  18190. }
  18191. pNew = sqlite3DbMallocRaw(db, n);
  18192. if( pNew ){
  18193. memcpy(pNew, p, db->lookaside.sz);
  18194. sqlite3DbFree(db, p);
  18195. }
  18196. }else{
  18197. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18198. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18199. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18200. pNew = sqlite3_realloc(p, n);
  18201. if( !pNew ){
  18202. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  18203. db->mallocFailed = 1;
  18204. }
  18205. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  18206. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18207. }
  18208. }
  18209. return pNew;
  18210. }
  18211. /*
  18212. ** Attempt to reallocate p. If the reallocation fails, then free p
  18213. ** and set the mallocFailed flag in the database connection.
  18214. */
  18215. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  18216. void *pNew;
  18217. pNew = sqlite3DbRealloc(db, p, n);
  18218. if( !pNew ){
  18219. sqlite3DbFree(db, p);
  18220. }
  18221. return pNew;
  18222. }
  18223. /*
  18224. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  18225. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  18226. ** is because when memory debugging is turned on, these two functions are
  18227. ** called via macros that record the current file and line number in the
  18228. ** ThreadData structure.
  18229. */
  18230. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  18231. char *zNew;
  18232. size_t n;
  18233. if( z==0 ){
  18234. return 0;
  18235. }
  18236. n = sqlite3Strlen30(z) + 1;
  18237. assert( (n&0x7fffffff)==n );
  18238. zNew = sqlite3DbMallocRaw(db, (int)n);
  18239. if( zNew ){
  18240. memcpy(zNew, z, n);
  18241. }
  18242. return zNew;
  18243. }
  18244. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  18245. char *zNew;
  18246. if( z==0 ){
  18247. return 0;
  18248. }
  18249. assert( (n&0x7fffffff)==n );
  18250. zNew = sqlite3DbMallocRaw(db, n+1);
  18251. if( zNew ){
  18252. memcpy(zNew, z, n);
  18253. zNew[n] = 0;
  18254. }
  18255. return zNew;
  18256. }
  18257. /*
  18258. ** Create a string from the zFromat argument and the va_list that follows.
  18259. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  18260. ** point to that string.
  18261. */
  18262. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  18263. va_list ap;
  18264. char *z;
  18265. va_start(ap, zFormat);
  18266. z = sqlite3VMPrintf(db, zFormat, ap);
  18267. va_end(ap);
  18268. sqlite3DbFree(db, *pz);
  18269. *pz = z;
  18270. }
  18271. /*
  18272. ** This function must be called before exiting any API function (i.e.
  18273. ** returning control to the user) that has called sqlite3_malloc or
  18274. ** sqlite3_realloc.
  18275. **
  18276. ** The returned value is normally a copy of the second argument to this
  18277. ** function. However, if a malloc() failure has occurred since the previous
  18278. ** invocation SQLITE_NOMEM is returned instead.
  18279. **
  18280. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  18281. ** then the connection error-code (the value returned by sqlite3_errcode())
  18282. ** is set to SQLITE_NOMEM.
  18283. */
  18284. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  18285. /* If the db handle is not NULL, then we must hold the connection handle
  18286. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  18287. ** is unsafe, as is the call to sqlite3Error().
  18288. */
  18289. assert( !db || sqlite3_mutex_held(db->mutex) );
  18290. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  18291. sqlite3Error(db, SQLITE_NOMEM, 0);
  18292. db->mallocFailed = 0;
  18293. rc = SQLITE_NOMEM;
  18294. }
  18295. return rc & (db ? db->errMask : 0xff);
  18296. }
  18297. /************** End of malloc.c **********************************************/
  18298. /************** Begin file printf.c ******************************************/
  18299. /*
  18300. ** The "printf" code that follows dates from the 1980's. It is in
  18301. ** the public domain. The original comments are included here for
  18302. ** completeness. They are very out-of-date but might be useful as
  18303. ** an historical reference. Most of the "enhancements" have been backed
  18304. ** out so that the functionality is now the same as standard printf().
  18305. **
  18306. **************************************************************************
  18307. **
  18308. ** This file contains code for a set of "printf"-like routines. These
  18309. ** routines format strings much like the printf() from the standard C
  18310. ** library, though the implementation here has enhancements to support
  18311. ** SQLlite.
  18312. */
  18313. /*
  18314. ** Conversion types fall into various categories as defined by the
  18315. ** following enumeration.
  18316. */
  18317. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  18318. #define etFLOAT 2 /* Floating point. %f */
  18319. #define etEXP 3 /* Exponentional notation. %e and %E */
  18320. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  18321. #define etSIZE 5 /* Return number of characters processed so far. %n */
  18322. #define etSTRING 6 /* Strings. %s */
  18323. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  18324. #define etPERCENT 8 /* Percent symbol. %% */
  18325. #define etCHARX 9 /* Characters. %c */
  18326. /* The rest are extensions, not normally found in printf() */
  18327. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  18328. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  18329. NULL pointers replaced by SQL NULL. %Q */
  18330. #define etTOKEN 12 /* a pointer to a Token structure */
  18331. #define etSRCLIST 13 /* a pointer to a SrcList */
  18332. #define etPOINTER 14 /* The %p conversion */
  18333. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  18334. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  18335. #define etINVALID 0 /* Any unrecognized conversion type */
  18336. /*
  18337. ** An "etByte" is an 8-bit unsigned value.
  18338. */
  18339. typedef unsigned char etByte;
  18340. /*
  18341. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  18342. ** by an instance of the following structure
  18343. */
  18344. typedef struct et_info { /* Information about each format field */
  18345. char fmttype; /* The format field code letter */
  18346. etByte base; /* The base for radix conversion */
  18347. etByte flags; /* One or more of FLAG_ constants below */
  18348. etByte type; /* Conversion paradigm */
  18349. etByte charset; /* Offset into aDigits[] of the digits string */
  18350. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  18351. } et_info;
  18352. /*
  18353. ** Allowed values for et_info.flags
  18354. */
  18355. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  18356. #define FLAG_INTERN 2 /* True if for internal use only */
  18357. #define FLAG_STRING 4 /* Allow infinity precision */
  18358. /*
  18359. ** The following table is searched linearly, so it is good to put the
  18360. ** most frequently used conversion types first.
  18361. */
  18362. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  18363. static const char aPrefix[] = "-x0\000X0";
  18364. static const et_info fmtinfo[] = {
  18365. { 'd', 10, 1, etRADIX, 0, 0 },
  18366. { 's', 0, 4, etSTRING, 0, 0 },
  18367. { 'g', 0, 1, etGENERIC, 30, 0 },
  18368. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  18369. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  18370. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  18371. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  18372. { 'c', 0, 0, etCHARX, 0, 0 },
  18373. { 'o', 8, 0, etRADIX, 0, 2 },
  18374. { 'u', 10, 0, etRADIX, 0, 0 },
  18375. { 'x', 16, 0, etRADIX, 16, 1 },
  18376. { 'X', 16, 0, etRADIX, 0, 4 },
  18377. #ifndef SQLITE_OMIT_FLOATING_POINT
  18378. { 'f', 0, 1, etFLOAT, 0, 0 },
  18379. { 'e', 0, 1, etEXP, 30, 0 },
  18380. { 'E', 0, 1, etEXP, 14, 0 },
  18381. { 'G', 0, 1, etGENERIC, 14, 0 },
  18382. #endif
  18383. { 'i', 10, 1, etRADIX, 0, 0 },
  18384. { 'n', 0, 0, etSIZE, 0, 0 },
  18385. { '%', 0, 0, etPERCENT, 0, 0 },
  18386. { 'p', 16, 0, etPOINTER, 0, 1 },
  18387. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  18388. ** use only */
  18389. { 'T', 0, 2, etTOKEN, 0, 0 },
  18390. { 'S', 0, 2, etSRCLIST, 0, 0 },
  18391. { 'r', 10, 3, etORDINAL, 0, 0 },
  18392. };
  18393. /*
  18394. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  18395. ** conversions will work.
  18396. */
  18397. #ifndef SQLITE_OMIT_FLOATING_POINT
  18398. /*
  18399. ** "*val" is a double such that 0.1 <= *val < 10.0
  18400. ** Return the ascii code for the leading digit of *val, then
  18401. ** multiply "*val" by 10.0 to renormalize.
  18402. **
  18403. ** Example:
  18404. ** input: *val = 3.14159
  18405. ** output: *val = 1.4159 function return = '3'
  18406. **
  18407. ** The counter *cnt is incremented each time. After counter exceeds
  18408. ** 16 (the number of significant digits in a 64-bit float) '0' is
  18409. ** always returned.
  18410. */
  18411. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  18412. int digit;
  18413. LONGDOUBLE_TYPE d;
  18414. if( (*cnt)++ >= 16 ) return '0';
  18415. digit = (int)*val;
  18416. d = digit;
  18417. digit += '0';
  18418. *val = (*val - d)*10.0;
  18419. return (char)digit;
  18420. }
  18421. #endif /* SQLITE_OMIT_FLOATING_POINT */
  18422. /*
  18423. ** Append N space characters to the given string buffer.
  18424. */
  18425. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
  18426. static const char zSpaces[] = " ";
  18427. while( N>=(int)sizeof(zSpaces)-1 ){
  18428. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  18429. N -= sizeof(zSpaces)-1;
  18430. }
  18431. if( N>0 ){
  18432. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  18433. }
  18434. }
  18435. /*
  18436. ** On machines with a small stack size, you can redefine the
  18437. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  18438. */
  18439. #ifndef SQLITE_PRINT_BUF_SIZE
  18440. # define SQLITE_PRINT_BUF_SIZE 70
  18441. #endif
  18442. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  18443. /*
  18444. ** Render a string given by "fmt" into the StrAccum object.
  18445. */
  18446. SQLITE_PRIVATE void sqlite3VXPrintf(
  18447. StrAccum *pAccum, /* Accumulate results here */
  18448. int useExtended, /* Allow extended %-conversions */
  18449. const char *fmt, /* Format string */
  18450. va_list ap /* arguments */
  18451. ){
  18452. int c; /* Next character in the format string */
  18453. char *bufpt; /* Pointer to the conversion buffer */
  18454. int precision; /* Precision of the current field */
  18455. int length; /* Length of the field */
  18456. int idx; /* A general purpose loop counter */
  18457. int width; /* Width of the current field */
  18458. etByte flag_leftjustify; /* True if "-" flag is present */
  18459. etByte flag_plussign; /* True if "+" flag is present */
  18460. etByte flag_blanksign; /* True if " " flag is present */
  18461. etByte flag_alternateform; /* True if "#" flag is present */
  18462. etByte flag_altform2; /* True if "!" flag is present */
  18463. etByte flag_zeropad; /* True if field width constant starts with zero */
  18464. etByte flag_long; /* True if "l" flag is present */
  18465. etByte flag_longlong; /* True if the "ll" flag is present */
  18466. etByte done; /* Loop termination flag */
  18467. etByte xtype = 0; /* Conversion paradigm */
  18468. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  18469. sqlite_uint64 longvalue; /* Value for integer types */
  18470. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  18471. const et_info *infop; /* Pointer to the appropriate info structure */
  18472. char *zOut; /* Rendering buffer */
  18473. int nOut; /* Size of the rendering buffer */
  18474. char *zExtra; /* Malloced memory used by some conversion */
  18475. #ifndef SQLITE_OMIT_FLOATING_POINT
  18476. int exp, e2; /* exponent of real numbers */
  18477. int nsd; /* Number of significant digits returned */
  18478. double rounder; /* Used for rounding floating point values */
  18479. etByte flag_dp; /* True if decimal point should be shown */
  18480. etByte flag_rtz; /* True if trailing zeros should be removed */
  18481. #endif
  18482. char buf[etBUFSIZE]; /* Conversion buffer */
  18483. bufpt = 0;
  18484. for(; (c=(*fmt))!=0; ++fmt){
  18485. if( c!='%' ){
  18486. int amt;
  18487. bufpt = (char *)fmt;
  18488. amt = 1;
  18489. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  18490. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  18491. if( c==0 ) break;
  18492. }
  18493. if( (c=(*++fmt))==0 ){
  18494. sqlite3StrAccumAppend(pAccum, "%", 1);
  18495. break;
  18496. }
  18497. /* Find out what flags are present */
  18498. flag_leftjustify = flag_plussign = flag_blanksign =
  18499. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  18500. done = 0;
  18501. do{
  18502. switch( c ){
  18503. case '-': flag_leftjustify = 1; break;
  18504. case '+': flag_plussign = 1; break;
  18505. case ' ': flag_blanksign = 1; break;
  18506. case '#': flag_alternateform = 1; break;
  18507. case '!': flag_altform2 = 1; break;
  18508. case '0': flag_zeropad = 1; break;
  18509. default: done = 1; break;
  18510. }
  18511. }while( !done && (c=(*++fmt))!=0 );
  18512. /* Get the field width */
  18513. width = 0;
  18514. if( c=='*' ){
  18515. width = va_arg(ap,int);
  18516. if( width<0 ){
  18517. flag_leftjustify = 1;
  18518. width = -width;
  18519. }
  18520. c = *++fmt;
  18521. }else{
  18522. while( c>='0' && c<='9' ){
  18523. width = width*10 + c - '0';
  18524. c = *++fmt;
  18525. }
  18526. }
  18527. /* Get the precision */
  18528. if( c=='.' ){
  18529. precision = 0;
  18530. c = *++fmt;
  18531. if( c=='*' ){
  18532. precision = va_arg(ap,int);
  18533. if( precision<0 ) precision = -precision;
  18534. c = *++fmt;
  18535. }else{
  18536. while( c>='0' && c<='9' ){
  18537. precision = precision*10 + c - '0';
  18538. c = *++fmt;
  18539. }
  18540. }
  18541. }else{
  18542. precision = -1;
  18543. }
  18544. /* Get the conversion type modifier */
  18545. if( c=='l' ){
  18546. flag_long = 1;
  18547. c = *++fmt;
  18548. if( c=='l' ){
  18549. flag_longlong = 1;
  18550. c = *++fmt;
  18551. }else{
  18552. flag_longlong = 0;
  18553. }
  18554. }else{
  18555. flag_long = flag_longlong = 0;
  18556. }
  18557. /* Fetch the info entry for the field */
  18558. infop = &fmtinfo[0];
  18559. xtype = etINVALID;
  18560. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  18561. if( c==fmtinfo[idx].fmttype ){
  18562. infop = &fmtinfo[idx];
  18563. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  18564. xtype = infop->type;
  18565. }else{
  18566. return;
  18567. }
  18568. break;
  18569. }
  18570. }
  18571. zExtra = 0;
  18572. /*
  18573. ** At this point, variables are initialized as follows:
  18574. **
  18575. ** flag_alternateform TRUE if a '#' is present.
  18576. ** flag_altform2 TRUE if a '!' is present.
  18577. ** flag_plussign TRUE if a '+' is present.
  18578. ** flag_leftjustify TRUE if a '-' is present or if the
  18579. ** field width was negative.
  18580. ** flag_zeropad TRUE if the width began with 0.
  18581. ** flag_long TRUE if the letter 'l' (ell) prefixed
  18582. ** the conversion character.
  18583. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  18584. ** the conversion character.
  18585. ** flag_blanksign TRUE if a ' ' is present.
  18586. ** width The specified field width. This is
  18587. ** always non-negative. Zero is the default.
  18588. ** precision The specified precision. The default
  18589. ** is -1.
  18590. ** xtype The class of the conversion.
  18591. ** infop Pointer to the appropriate info struct.
  18592. */
  18593. switch( xtype ){
  18594. case etPOINTER:
  18595. flag_longlong = sizeof(char*)==sizeof(i64);
  18596. flag_long = sizeof(char*)==sizeof(long int);
  18597. /* Fall through into the next case */
  18598. case etORDINAL:
  18599. case etRADIX:
  18600. if( infop->flags & FLAG_SIGNED ){
  18601. i64 v;
  18602. if( flag_longlong ){
  18603. v = va_arg(ap,i64);
  18604. }else if( flag_long ){
  18605. v = va_arg(ap,long int);
  18606. }else{
  18607. v = va_arg(ap,int);
  18608. }
  18609. if( v<0 ){
  18610. if( v==SMALLEST_INT64 ){
  18611. longvalue = ((u64)1)<<63;
  18612. }else{
  18613. longvalue = -v;
  18614. }
  18615. prefix = '-';
  18616. }else{
  18617. longvalue = v;
  18618. if( flag_plussign ) prefix = '+';
  18619. else if( flag_blanksign ) prefix = ' ';
  18620. else prefix = 0;
  18621. }
  18622. }else{
  18623. if( flag_longlong ){
  18624. longvalue = va_arg(ap,u64);
  18625. }else if( flag_long ){
  18626. longvalue = va_arg(ap,unsigned long int);
  18627. }else{
  18628. longvalue = va_arg(ap,unsigned int);
  18629. }
  18630. prefix = 0;
  18631. }
  18632. if( longvalue==0 ) flag_alternateform = 0;
  18633. if( flag_zeropad && precision<width-(prefix!=0) ){
  18634. precision = width-(prefix!=0);
  18635. }
  18636. if( precision<etBUFSIZE-10 ){
  18637. nOut = etBUFSIZE;
  18638. zOut = buf;
  18639. }else{
  18640. nOut = precision + 10;
  18641. zOut = zExtra = sqlite3Malloc( nOut );
  18642. if( zOut==0 ){
  18643. pAccum->mallocFailed = 1;
  18644. return;
  18645. }
  18646. }
  18647. bufpt = &zOut[nOut-1];
  18648. if( xtype==etORDINAL ){
  18649. static const char zOrd[] = "thstndrd";
  18650. int x = (int)(longvalue % 10);
  18651. if( x>=4 || (longvalue/10)%10==1 ){
  18652. x = 0;
  18653. }
  18654. *(--bufpt) = zOrd[x*2+1];
  18655. *(--bufpt) = zOrd[x*2];
  18656. }
  18657. {
  18658. register const char *cset; /* Use registers for speed */
  18659. register int base;
  18660. cset = &aDigits[infop->charset];
  18661. base = infop->base;
  18662. do{ /* Convert to ascii */
  18663. *(--bufpt) = cset[longvalue%base];
  18664. longvalue = longvalue/base;
  18665. }while( longvalue>0 );
  18666. }
  18667. length = (int)(&zOut[nOut-1]-bufpt);
  18668. for(idx=precision-length; idx>0; idx--){
  18669. *(--bufpt) = '0'; /* Zero pad */
  18670. }
  18671. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  18672. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  18673. const char *pre;
  18674. char x;
  18675. pre = &aPrefix[infop->prefix];
  18676. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  18677. }
  18678. length = (int)(&zOut[nOut-1]-bufpt);
  18679. break;
  18680. case etFLOAT:
  18681. case etEXP:
  18682. case etGENERIC:
  18683. realvalue = va_arg(ap,double);
  18684. #ifdef SQLITE_OMIT_FLOATING_POINT
  18685. length = 0;
  18686. #else
  18687. if( precision<0 ) precision = 6; /* Set default precision */
  18688. if( realvalue<0.0 ){
  18689. realvalue = -realvalue;
  18690. prefix = '-';
  18691. }else{
  18692. if( flag_plussign ) prefix = '+';
  18693. else if( flag_blanksign ) prefix = ' ';
  18694. else prefix = 0;
  18695. }
  18696. if( xtype==etGENERIC && precision>0 ) precision--;
  18697. #if 0
  18698. /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
  18699. for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
  18700. #else
  18701. /* It makes more sense to use 0.5 */
  18702. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  18703. #endif
  18704. if( xtype==etFLOAT ) realvalue += rounder;
  18705. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  18706. exp = 0;
  18707. if( sqlite3IsNaN((double)realvalue) ){
  18708. bufpt = "NaN";
  18709. length = 3;
  18710. break;
  18711. }
  18712. if( realvalue>0.0 ){
  18713. while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
  18714. while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
  18715. while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
  18716. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  18717. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  18718. if( exp>350 ){
  18719. if( prefix=='-' ){
  18720. bufpt = "-Inf";
  18721. }else if( prefix=='+' ){
  18722. bufpt = "+Inf";
  18723. }else{
  18724. bufpt = "Inf";
  18725. }
  18726. length = sqlite3Strlen30(bufpt);
  18727. break;
  18728. }
  18729. }
  18730. bufpt = buf;
  18731. /*
  18732. ** If the field type is etGENERIC, then convert to either etEXP
  18733. ** or etFLOAT, as appropriate.
  18734. */
  18735. if( xtype!=etFLOAT ){
  18736. realvalue += rounder;
  18737. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  18738. }
  18739. if( xtype==etGENERIC ){
  18740. flag_rtz = !flag_alternateform;
  18741. if( exp<-4 || exp>precision ){
  18742. xtype = etEXP;
  18743. }else{
  18744. precision = precision - exp;
  18745. xtype = etFLOAT;
  18746. }
  18747. }else{
  18748. flag_rtz = 0;
  18749. }
  18750. if( xtype==etEXP ){
  18751. e2 = 0;
  18752. }else{
  18753. e2 = exp;
  18754. }
  18755. if( e2+precision+width > etBUFSIZE - 15 ){
  18756. bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
  18757. if( bufpt==0 ){
  18758. pAccum->mallocFailed = 1;
  18759. return;
  18760. }
  18761. }
  18762. zOut = bufpt;
  18763. nsd = 0;
  18764. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  18765. /* The sign in front of the number */
  18766. if( prefix ){
  18767. *(bufpt++) = prefix;
  18768. }
  18769. /* Digits prior to the decimal point */
  18770. if( e2<0 ){
  18771. *(bufpt++) = '0';
  18772. }else{
  18773. for(; e2>=0; e2--){
  18774. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18775. }
  18776. }
  18777. /* The decimal point */
  18778. if( flag_dp ){
  18779. *(bufpt++) = '.';
  18780. }
  18781. /* "0" digits after the decimal point but before the first
  18782. ** significant digit of the number */
  18783. for(e2++; e2<0; precision--, e2++){
  18784. assert( precision>0 );
  18785. *(bufpt++) = '0';
  18786. }
  18787. /* Significant digits after the decimal point */
  18788. while( (precision--)>0 ){
  18789. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18790. }
  18791. /* Remove trailing zeros and the "." if no digits follow the "." */
  18792. if( flag_rtz && flag_dp ){
  18793. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  18794. assert( bufpt>zOut );
  18795. if( bufpt[-1]=='.' ){
  18796. if( flag_altform2 ){
  18797. *(bufpt++) = '0';
  18798. }else{
  18799. *(--bufpt) = 0;
  18800. }
  18801. }
  18802. }
  18803. /* Add the "eNNN" suffix */
  18804. if( xtype==etEXP ){
  18805. *(bufpt++) = aDigits[infop->charset];
  18806. if( exp<0 ){
  18807. *(bufpt++) = '-'; exp = -exp;
  18808. }else{
  18809. *(bufpt++) = '+';
  18810. }
  18811. if( exp>=100 ){
  18812. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  18813. exp %= 100;
  18814. }
  18815. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  18816. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  18817. }
  18818. *bufpt = 0;
  18819. /* The converted number is in buf[] and zero terminated. Output it.
  18820. ** Note that the number is in the usual order, not reversed as with
  18821. ** integer conversions. */
  18822. length = (int)(bufpt-zOut);
  18823. bufpt = zOut;
  18824. /* Special case: Add leading zeros if the flag_zeropad flag is
  18825. ** set and we are not left justified */
  18826. if( flag_zeropad && !flag_leftjustify && length < width){
  18827. int i;
  18828. int nPad = width - length;
  18829. for(i=width; i>=nPad; i--){
  18830. bufpt[i] = bufpt[i-nPad];
  18831. }
  18832. i = prefix!=0;
  18833. while( nPad-- ) bufpt[i++] = '0';
  18834. length = width;
  18835. }
  18836. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  18837. break;
  18838. case etSIZE:
  18839. *(va_arg(ap,int*)) = pAccum->nChar;
  18840. length = width = 0;
  18841. break;
  18842. case etPERCENT:
  18843. buf[0] = '%';
  18844. bufpt = buf;
  18845. length = 1;
  18846. break;
  18847. case etCHARX:
  18848. c = va_arg(ap,int);
  18849. buf[0] = (char)c;
  18850. if( precision>=0 ){
  18851. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  18852. length = precision;
  18853. }else{
  18854. length =1;
  18855. }
  18856. bufpt = buf;
  18857. break;
  18858. case etSTRING:
  18859. case etDYNSTRING:
  18860. bufpt = va_arg(ap,char*);
  18861. if( bufpt==0 ){
  18862. bufpt = "";
  18863. }else if( xtype==etDYNSTRING ){
  18864. zExtra = bufpt;
  18865. }
  18866. if( precision>=0 ){
  18867. for(length=0; length<precision && bufpt[length]; length++){}
  18868. }else{
  18869. length = sqlite3Strlen30(bufpt);
  18870. }
  18871. break;
  18872. case etSQLESCAPE:
  18873. case etSQLESCAPE2:
  18874. case etSQLESCAPE3: {
  18875. int i, j, k, n, isnull;
  18876. int needQuote;
  18877. char ch;
  18878. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  18879. char *escarg = va_arg(ap,char*);
  18880. isnull = escarg==0;
  18881. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  18882. k = precision;
  18883. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  18884. if( ch==q ) n++;
  18885. }
  18886. needQuote = !isnull && xtype==etSQLESCAPE2;
  18887. n += i + 1 + needQuote*2;
  18888. if( n>etBUFSIZE ){
  18889. bufpt = zExtra = sqlite3Malloc( n );
  18890. if( bufpt==0 ){
  18891. pAccum->mallocFailed = 1;
  18892. return;
  18893. }
  18894. }else{
  18895. bufpt = buf;
  18896. }
  18897. j = 0;
  18898. if( needQuote ) bufpt[j++] = q;
  18899. k = i;
  18900. for(i=0; i<k; i++){
  18901. bufpt[j++] = ch = escarg[i];
  18902. if( ch==q ) bufpt[j++] = ch;
  18903. }
  18904. if( needQuote ) bufpt[j++] = q;
  18905. bufpt[j] = 0;
  18906. length = j;
  18907. /* The precision in %q and %Q means how many input characters to
  18908. ** consume, not the length of the output...
  18909. ** if( precision>=0 && precision<length ) length = precision; */
  18910. break;
  18911. }
  18912. case etTOKEN: {
  18913. Token *pToken = va_arg(ap, Token*);
  18914. if( pToken ){
  18915. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  18916. }
  18917. length = width = 0;
  18918. break;
  18919. }
  18920. case etSRCLIST: {
  18921. SrcList *pSrc = va_arg(ap, SrcList*);
  18922. int k = va_arg(ap, int);
  18923. struct SrcList_item *pItem = &pSrc->a[k];
  18924. assert( k>=0 && k<pSrc->nSrc );
  18925. if( pItem->zDatabase ){
  18926. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  18927. sqlite3StrAccumAppend(pAccum, ".", 1);
  18928. }
  18929. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  18930. length = width = 0;
  18931. break;
  18932. }
  18933. default: {
  18934. assert( xtype==etINVALID );
  18935. return;
  18936. }
  18937. }/* End switch over the format type */
  18938. /*
  18939. ** The text of the conversion is pointed to by "bufpt" and is
  18940. ** "length" characters long. The field width is "width". Do
  18941. ** the output.
  18942. */
  18943. if( !flag_leftjustify ){
  18944. register int nspace;
  18945. nspace = width-length;
  18946. if( nspace>0 ){
  18947. sqlite3AppendSpace(pAccum, nspace);
  18948. }
  18949. }
  18950. if( length>0 ){
  18951. sqlite3StrAccumAppend(pAccum, bufpt, length);
  18952. }
  18953. if( flag_leftjustify ){
  18954. register int nspace;
  18955. nspace = width-length;
  18956. if( nspace>0 ){
  18957. sqlite3AppendSpace(pAccum, nspace);
  18958. }
  18959. }
  18960. sqlite3_free(zExtra);
  18961. }/* End for loop over the format string */
  18962. } /* End of function */
  18963. /*
  18964. ** Append N bytes of text from z to the StrAccum object.
  18965. */
  18966. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  18967. assert( z!=0 || N==0 );
  18968. if( p->tooBig | p->mallocFailed ){
  18969. testcase(p->tooBig);
  18970. testcase(p->mallocFailed);
  18971. return;
  18972. }
  18973. assert( p->zText!=0 || p->nChar==0 );
  18974. if( N<0 ){
  18975. N = sqlite3Strlen30(z);
  18976. }
  18977. if( N==0 || NEVER(z==0) ){
  18978. return;
  18979. }
  18980. if( p->nChar+N >= p->nAlloc ){
  18981. char *zNew;
  18982. if( !p->useMalloc ){
  18983. p->tooBig = 1;
  18984. N = p->nAlloc - p->nChar - 1;
  18985. if( N<=0 ){
  18986. return;
  18987. }
  18988. }else{
  18989. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  18990. i64 szNew = p->nChar;
  18991. szNew += N + 1;
  18992. if( szNew > p->mxAlloc ){
  18993. sqlite3StrAccumReset(p);
  18994. p->tooBig = 1;
  18995. return;
  18996. }else{
  18997. p->nAlloc = (int)szNew;
  18998. }
  18999. if( p->useMalloc==1 ){
  19000. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  19001. }else{
  19002. zNew = sqlite3_realloc(zOld, p->nAlloc);
  19003. }
  19004. if( zNew ){
  19005. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  19006. p->zText = zNew;
  19007. }else{
  19008. p->mallocFailed = 1;
  19009. sqlite3StrAccumReset(p);
  19010. return;
  19011. }
  19012. }
  19013. }
  19014. assert( p->zText );
  19015. memcpy(&p->zText[p->nChar], z, N);
  19016. p->nChar += N;
  19017. }
  19018. /*
  19019. ** Finish off a string by making sure it is zero-terminated.
  19020. ** Return a pointer to the resulting string. Return a NULL
  19021. ** pointer if any kind of error was encountered.
  19022. */
  19023. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  19024. if( p->zText ){
  19025. p->zText[p->nChar] = 0;
  19026. if( p->useMalloc && p->zText==p->zBase ){
  19027. if( p->useMalloc==1 ){
  19028. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  19029. }else{
  19030. p->zText = sqlite3_malloc(p->nChar+1);
  19031. }
  19032. if( p->zText ){
  19033. memcpy(p->zText, p->zBase, p->nChar+1);
  19034. }else{
  19035. p->mallocFailed = 1;
  19036. }
  19037. }
  19038. }
  19039. return p->zText;
  19040. }
  19041. /*
  19042. ** Reset an StrAccum string. Reclaim all malloced memory.
  19043. */
  19044. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  19045. if( p->zText!=p->zBase ){
  19046. if( p->useMalloc==1 ){
  19047. sqlite3DbFree(p->db, p->zText);
  19048. }else{
  19049. sqlite3_free(p->zText);
  19050. }
  19051. }
  19052. p->zText = 0;
  19053. }
  19054. /*
  19055. ** Initialize a string accumulator
  19056. */
  19057. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  19058. p->zText = p->zBase = zBase;
  19059. p->db = 0;
  19060. p->nChar = 0;
  19061. p->nAlloc = n;
  19062. p->mxAlloc = mx;
  19063. p->useMalloc = 1;
  19064. p->tooBig = 0;
  19065. p->mallocFailed = 0;
  19066. }
  19067. /*
  19068. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19069. ** %-conversion extensions.
  19070. */
  19071. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  19072. char *z;
  19073. char zBase[SQLITE_PRINT_BUF_SIZE];
  19074. StrAccum acc;
  19075. assert( db!=0 );
  19076. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  19077. db->aLimit[SQLITE_LIMIT_LENGTH]);
  19078. acc.db = db;
  19079. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  19080. z = sqlite3StrAccumFinish(&acc);
  19081. if( acc.mallocFailed ){
  19082. db->mallocFailed = 1;
  19083. }
  19084. return z;
  19085. }
  19086. /*
  19087. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19088. ** %-conversion extensions.
  19089. */
  19090. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  19091. va_list ap;
  19092. char *z;
  19093. va_start(ap, zFormat);
  19094. z = sqlite3VMPrintf(db, zFormat, ap);
  19095. va_end(ap);
  19096. return z;
  19097. }
  19098. /*
  19099. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  19100. ** the string and before returnning. This routine is intended to be used
  19101. ** to modify an existing string. For example:
  19102. **
  19103. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  19104. **
  19105. */
  19106. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  19107. va_list ap;
  19108. char *z;
  19109. va_start(ap, zFormat);
  19110. z = sqlite3VMPrintf(db, zFormat, ap);
  19111. va_end(ap);
  19112. sqlite3DbFree(db, zStr);
  19113. return z;
  19114. }
  19115. /*
  19116. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  19117. ** %-conversion extensions.
  19118. */
  19119. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  19120. char *z;
  19121. char zBase[SQLITE_PRINT_BUF_SIZE];
  19122. StrAccum acc;
  19123. #ifndef SQLITE_OMIT_AUTOINIT
  19124. if( sqlite3_initialize() ) return 0;
  19125. #endif
  19126. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  19127. acc.useMalloc = 2;
  19128. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19129. z = sqlite3StrAccumFinish(&acc);
  19130. return z;
  19131. }
  19132. /*
  19133. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  19134. ** %-conversion extensions.
  19135. */
  19136. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  19137. va_list ap;
  19138. char *z;
  19139. #ifndef SQLITE_OMIT_AUTOINIT
  19140. if( sqlite3_initialize() ) return 0;
  19141. #endif
  19142. va_start(ap, zFormat);
  19143. z = sqlite3_vmprintf(zFormat, ap);
  19144. va_end(ap);
  19145. return z;
  19146. }
  19147. /*
  19148. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  19149. ** current locale settings. This is important for SQLite because we
  19150. ** are not able to use a "," as the decimal point in place of "." as
  19151. ** specified by some locales.
  19152. **
  19153. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  19154. ** from the snprintf() standard. Unfortunately, it is too late to change
  19155. ** this without breaking compatibility, so we just have to live with the
  19156. ** mistake.
  19157. **
  19158. ** sqlite3_vsnprintf() is the varargs version.
  19159. */
  19160. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  19161. StrAccum acc;
  19162. if( n<=0 ) return zBuf;
  19163. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  19164. acc.useMalloc = 0;
  19165. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19166. return sqlite3StrAccumFinish(&acc);
  19167. }
  19168. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  19169. char *z;
  19170. va_list ap;
  19171. va_start(ap,zFormat);
  19172. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  19173. va_end(ap);
  19174. return z;
  19175. }
  19176. /*
  19177. ** This is the routine that actually formats the sqlite3_log() message.
  19178. ** We house it in a separate routine from sqlite3_log() to avoid using
  19179. ** stack space on small-stack systems when logging is disabled.
  19180. **
  19181. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  19182. ** allocate memory because it might be called while the memory allocator
  19183. ** mutex is held.
  19184. */
  19185. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  19186. StrAccum acc; /* String accumulator */
  19187. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  19188. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  19189. acc.useMalloc = 0;
  19190. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19191. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  19192. sqlite3StrAccumFinish(&acc));
  19193. }
  19194. /*
  19195. ** Format and write a message to the log if logging is enabled.
  19196. */
  19197. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  19198. va_list ap; /* Vararg list */
  19199. if( sqlite3GlobalConfig.xLog ){
  19200. va_start(ap, zFormat);
  19201. renderLogMsg(iErrCode, zFormat, ap);
  19202. va_end(ap);
  19203. }
  19204. }
  19205. #if defined(SQLITE_DEBUG)
  19206. /*
  19207. ** A version of printf() that understands %lld. Used for debugging.
  19208. ** The printf() built into some versions of windows does not understand %lld
  19209. ** and segfaults if you give it a long long int.
  19210. */
  19211. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  19212. va_list ap;
  19213. StrAccum acc;
  19214. char zBuf[500];
  19215. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  19216. acc.useMalloc = 0;
  19217. va_start(ap,zFormat);
  19218. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19219. va_end(ap);
  19220. sqlite3StrAccumFinish(&acc);
  19221. fprintf(stdout,"%s", zBuf);
  19222. fflush(stdout);
  19223. }
  19224. #endif
  19225. #ifndef SQLITE_OMIT_TRACE
  19226. /*
  19227. ** variable-argument wrapper around sqlite3VXPrintf().
  19228. */
  19229. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  19230. va_list ap;
  19231. va_start(ap,zFormat);
  19232. sqlite3VXPrintf(p, 1, zFormat, ap);
  19233. va_end(ap);
  19234. }
  19235. #endif
  19236. /************** End of printf.c **********************************************/
  19237. /************** Begin file random.c ******************************************/
  19238. /*
  19239. ** 2001 September 15
  19240. **
  19241. ** The author disclaims copyright to this source code. In place of
  19242. ** a legal notice, here is a blessing:
  19243. **
  19244. ** May you do good and not evil.
  19245. ** May you find forgiveness for yourself and forgive others.
  19246. ** May you share freely, never taking more than you give.
  19247. **
  19248. *************************************************************************
  19249. ** This file contains code to implement a pseudo-random number
  19250. ** generator (PRNG) for SQLite.
  19251. **
  19252. ** Random numbers are used by some of the database backends in order
  19253. ** to generate random integer keys for tables or random filenames.
  19254. */
  19255. /* All threads share a single random number generator.
  19256. ** This structure is the current state of the generator.
  19257. */
  19258. static SQLITE_WSD struct sqlite3PrngType {
  19259. unsigned char isInit; /* True if initialized */
  19260. unsigned char i, j; /* State variables */
  19261. unsigned char s[256]; /* State variables */
  19262. } sqlite3Prng;
  19263. /*
  19264. ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
  19265. ** must be held while executing this routine.
  19266. **
  19267. ** Why not just use a library random generator like lrand48() for this?
  19268. ** Because the OP_NewRowid opcode in the VDBE depends on having a very
  19269. ** good source of random numbers. The lrand48() library function may
  19270. ** well be good enough. But maybe not. Or maybe lrand48() has some
  19271. ** subtle problems on some systems that could cause problems. It is hard
  19272. ** to know. To minimize the risk of problems due to bad lrand48()
  19273. ** implementations, SQLite uses this random number generator based
  19274. ** on RC4, which we know works very well.
  19275. **
  19276. ** (Later): Actually, OP_NewRowid does not depend on a good source of
  19277. ** randomness any more. But we will leave this code in all the same.
  19278. */
  19279. static u8 randomByte(void){
  19280. unsigned char t;
  19281. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  19282. ** state vector. If writable static data is unsupported on the target,
  19283. ** we have to locate the state vector at run-time. In the more common
  19284. ** case where writable static data is supported, wsdPrng can refer directly
  19285. ** to the "sqlite3Prng" state vector declared above.
  19286. */
  19287. #ifdef SQLITE_OMIT_WSD
  19288. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  19289. # define wsdPrng p[0]
  19290. #else
  19291. # define wsdPrng sqlite3Prng
  19292. #endif
  19293. /* Initialize the state of the random number generator once,
  19294. ** the first time this routine is called. The seed value does
  19295. ** not need to contain a lot of randomness since we are not
  19296. ** trying to do secure encryption or anything like that...
  19297. **
  19298. ** Nothing in this file or anywhere else in SQLite does any kind of
  19299. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  19300. ** number generator) not as an encryption device.
  19301. */
  19302. if( !wsdPrng.isInit ){
  19303. int i;
  19304. char k[256];
  19305. wsdPrng.j = 0;
  19306. wsdPrng.i = 0;
  19307. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  19308. for(i=0; i<256; i++){
  19309. wsdPrng.s[i] = (u8)i;
  19310. }
  19311. for(i=0; i<256; i++){
  19312. wsdPrng.j += wsdPrng.s[i] + k[i];
  19313. t = wsdPrng.s[wsdPrng.j];
  19314. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  19315. wsdPrng.s[i] = t;
  19316. }
  19317. wsdPrng.isInit = 1;
  19318. }
  19319. /* Generate and return single random byte
  19320. */
  19321. wsdPrng.i++;
  19322. t = wsdPrng.s[wsdPrng.i];
  19323. wsdPrng.j += t;
  19324. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  19325. wsdPrng.s[wsdPrng.j] = t;
  19326. t += wsdPrng.s[wsdPrng.i];
  19327. return wsdPrng.s[t];
  19328. }
  19329. /*
  19330. ** Return N random bytes.
  19331. */
  19332. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  19333. unsigned char *zBuf = pBuf;
  19334. #if SQLITE_THREADSAFE
  19335. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  19336. #endif
  19337. sqlite3_mutex_enter(mutex);
  19338. while( N-- ){
  19339. *(zBuf++) = randomByte();
  19340. }
  19341. sqlite3_mutex_leave(mutex);
  19342. }
  19343. #ifndef SQLITE_OMIT_BUILTIN_TEST
  19344. /*
  19345. ** For testing purposes, we sometimes want to preserve the state of
  19346. ** PRNG and restore the PRNG to its saved state at a later time, or
  19347. ** to reset the PRNG to its initial state. These routines accomplish
  19348. ** those tasks.
  19349. **
  19350. ** The sqlite3_test_control() interface calls these routines to
  19351. ** control the PRNG.
  19352. */
  19353. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  19354. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  19355. memcpy(
  19356. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19357. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19358. sizeof(sqlite3Prng)
  19359. );
  19360. }
  19361. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  19362. memcpy(
  19363. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19364. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19365. sizeof(sqlite3Prng)
  19366. );
  19367. }
  19368. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  19369. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  19370. }
  19371. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  19372. /************** End of random.c **********************************************/
  19373. /************** Begin file utf.c *********************************************/
  19374. /*
  19375. ** 2004 April 13
  19376. **
  19377. ** The author disclaims copyright to this source code. In place of
  19378. ** a legal notice, here is a blessing:
  19379. **
  19380. ** May you do good and not evil.
  19381. ** May you find forgiveness for yourself and forgive others.
  19382. ** May you share freely, never taking more than you give.
  19383. **
  19384. *************************************************************************
  19385. ** This file contains routines used to translate between UTF-8,
  19386. ** UTF-16, UTF-16BE, and UTF-16LE.
  19387. **
  19388. ** Notes on UTF-8:
  19389. **
  19390. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  19391. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  19392. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  19393. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  19394. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19395. **
  19396. **
  19397. ** Notes on UTF-16: (with wwww+1==uuuuu)
  19398. **
  19399. ** Word-0 Word-1 Value
  19400. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  19401. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  19402. **
  19403. **
  19404. ** BOM or Byte Order Mark:
  19405. ** 0xff 0xfe little-endian utf-16 follows
  19406. ** 0xfe 0xff big-endian utf-16 follows
  19407. **
  19408. */
  19409. /* #include <assert.h> */
  19410. #ifndef SQLITE_AMALGAMATION
  19411. /*
  19412. ** The following constant value is used by the SQLITE_BIGENDIAN and
  19413. ** SQLITE_LITTLEENDIAN macros.
  19414. */
  19415. SQLITE_PRIVATE const int sqlite3one = 1;
  19416. #endif /* SQLITE_AMALGAMATION */
  19417. /*
  19418. ** This lookup table is used to help decode the first byte of
  19419. ** a multi-byte UTF8 character.
  19420. */
  19421. static const unsigned char sqlite3Utf8Trans1[] = {
  19422. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19423. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19424. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  19425. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  19426. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19427. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  19428. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  19429. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  19430. };
  19431. #define WRITE_UTF8(zOut, c) { \
  19432. if( c<0x00080 ){ \
  19433. *zOut++ = (u8)(c&0xFF); \
  19434. } \
  19435. else if( c<0x00800 ){ \
  19436. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  19437. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19438. } \
  19439. else if( c<0x10000 ){ \
  19440. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  19441. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19442. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19443. }else{ \
  19444. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  19445. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  19446. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  19447. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  19448. } \
  19449. }
  19450. #define WRITE_UTF16LE(zOut, c) { \
  19451. if( c<=0xFFFF ){ \
  19452. *zOut++ = (u8)(c&0x00FF); \
  19453. *zOut++ = (u8)((c>>8)&0x00FF); \
  19454. }else{ \
  19455. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19456. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19457. *zOut++ = (u8)(c&0x00FF); \
  19458. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19459. } \
  19460. }
  19461. #define WRITE_UTF16BE(zOut, c) { \
  19462. if( c<=0xFFFF ){ \
  19463. *zOut++ = (u8)((c>>8)&0x00FF); \
  19464. *zOut++ = (u8)(c&0x00FF); \
  19465. }else{ \
  19466. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  19467. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  19468. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  19469. *zOut++ = (u8)(c&0x00FF); \
  19470. } \
  19471. }
  19472. #define READ_UTF16LE(zIn, TERM, c){ \
  19473. c = (*zIn++); \
  19474. c += ((*zIn++)<<8); \
  19475. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19476. int c2 = (*zIn++); \
  19477. c2 += ((*zIn++)<<8); \
  19478. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19479. } \
  19480. }
  19481. #define READ_UTF16BE(zIn, TERM, c){ \
  19482. c = ((*zIn++)<<8); \
  19483. c += (*zIn++); \
  19484. if( c>=0xD800 && c<0xE000 && TERM ){ \
  19485. int c2 = ((*zIn++)<<8); \
  19486. c2 += (*zIn++); \
  19487. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  19488. } \
  19489. }
  19490. /*
  19491. ** Translate a single UTF-8 character. Return the unicode value.
  19492. **
  19493. ** During translation, assume that the byte that zTerm points
  19494. ** is a 0x00.
  19495. **
  19496. ** Write a pointer to the next unread byte back into *pzNext.
  19497. **
  19498. ** Notes On Invalid UTF-8:
  19499. **
  19500. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  19501. ** be encoded as a multi-byte character. Any multi-byte character that
  19502. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  19503. **
  19504. ** * This routine never allows a UTF16 surrogate value to be encoded.
  19505. ** If a multi-byte character attempts to encode a value between
  19506. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  19507. **
  19508. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  19509. ** byte of a character are interpreted as single-byte characters
  19510. ** and rendered as themselves even though they are technically
  19511. ** invalid characters.
  19512. **
  19513. ** * This routine accepts an infinite number of different UTF8 encodings
  19514. ** for unicode values 0x80 and greater. It do not change over-length
  19515. ** encodings to 0xfffd as some systems recommend.
  19516. */
  19517. #define READ_UTF8(zIn, zTerm, c) \
  19518. c = *(zIn++); \
  19519. if( c>=0xc0 ){ \
  19520. c = sqlite3Utf8Trans1[c-0xc0]; \
  19521. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  19522. c = (c<<6) + (0x3f & *(zIn++)); \
  19523. } \
  19524. if( c<0x80 \
  19525. || (c&0xFFFFF800)==0xD800 \
  19526. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  19527. }
  19528. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  19529. const unsigned char *zIn, /* First byte of UTF-8 character */
  19530. const unsigned char **pzNext /* Write first byte past UTF-8 char here */
  19531. ){
  19532. unsigned int c;
  19533. /* Same as READ_UTF8() above but without the zTerm parameter.
  19534. ** For this routine, we assume the UTF8 string is always zero-terminated.
  19535. */
  19536. c = *(zIn++);
  19537. if( c>=0xc0 ){
  19538. c = sqlite3Utf8Trans1[c-0xc0];
  19539. while( (*zIn & 0xc0)==0x80 ){
  19540. c = (c<<6) + (0x3f & *(zIn++));
  19541. }
  19542. if( c<0x80
  19543. || (c&0xFFFFF800)==0xD800
  19544. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  19545. }
  19546. *pzNext = zIn;
  19547. return c;
  19548. }
  19549. /*
  19550. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  19551. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  19552. */
  19553. /* #define TRANSLATE_TRACE 1 */
  19554. #ifndef SQLITE_OMIT_UTF16
  19555. /*
  19556. ** This routine transforms the internal text encoding used by pMem to
  19557. ** desiredEnc. It is an error if the string is already of the desired
  19558. ** encoding, or if *pMem does not contain a string value.
  19559. */
  19560. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  19561. int len; /* Maximum length of output string in bytes */
  19562. unsigned char *zOut; /* Output buffer */
  19563. unsigned char *zIn; /* Input iterator */
  19564. unsigned char *zTerm; /* End of input */
  19565. unsigned char *z; /* Output iterator */
  19566. unsigned int c;
  19567. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  19568. assert( pMem->flags&MEM_Str );
  19569. assert( pMem->enc!=desiredEnc );
  19570. assert( pMem->enc!=0 );
  19571. assert( pMem->n>=0 );
  19572. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19573. {
  19574. char zBuf[100];
  19575. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19576. fprintf(stderr, "INPUT: %s\n", zBuf);
  19577. }
  19578. #endif
  19579. /* If the translation is between UTF-16 little and big endian, then
  19580. ** all that is required is to swap the byte order. This case is handled
  19581. ** differently from the others.
  19582. */
  19583. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  19584. u8 temp;
  19585. int rc;
  19586. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19587. if( rc!=SQLITE_OK ){
  19588. assert( rc==SQLITE_NOMEM );
  19589. return SQLITE_NOMEM;
  19590. }
  19591. zIn = (u8*)pMem->z;
  19592. zTerm = &zIn[pMem->n&~1];
  19593. while( zIn<zTerm ){
  19594. temp = *zIn;
  19595. *zIn = *(zIn+1);
  19596. zIn++;
  19597. *zIn++ = temp;
  19598. }
  19599. pMem->enc = desiredEnc;
  19600. goto translate_out;
  19601. }
  19602. /* Set len to the maximum number of bytes required in the output buffer. */
  19603. if( desiredEnc==SQLITE_UTF8 ){
  19604. /* When converting from UTF-16, the maximum growth results from
  19605. ** translating a 2-byte character to a 4-byte UTF-8 character.
  19606. ** A single byte is required for the output string
  19607. ** nul-terminator.
  19608. */
  19609. pMem->n &= ~1;
  19610. len = pMem->n * 2 + 1;
  19611. }else{
  19612. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  19613. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  19614. ** character. Two bytes are required in the output buffer for the
  19615. ** nul-terminator.
  19616. */
  19617. len = pMem->n * 2 + 2;
  19618. }
  19619. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  19620. ** byte past the end.
  19621. **
  19622. ** Variable zOut is set to point at the output buffer, space obtained
  19623. ** from sqlite3_malloc().
  19624. */
  19625. zIn = (u8*)pMem->z;
  19626. zTerm = &zIn[pMem->n];
  19627. zOut = sqlite3DbMallocRaw(pMem->db, len);
  19628. if( !zOut ){
  19629. return SQLITE_NOMEM;
  19630. }
  19631. z = zOut;
  19632. if( pMem->enc==SQLITE_UTF8 ){
  19633. if( desiredEnc==SQLITE_UTF16LE ){
  19634. /* UTF-8 -> UTF-16 Little-endian */
  19635. while( zIn<zTerm ){
  19636. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  19637. READ_UTF8(zIn, zTerm, c);
  19638. WRITE_UTF16LE(z, c);
  19639. }
  19640. }else{
  19641. assert( desiredEnc==SQLITE_UTF16BE );
  19642. /* UTF-8 -> UTF-16 Big-endian */
  19643. while( zIn<zTerm ){
  19644. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  19645. READ_UTF8(zIn, zTerm, c);
  19646. WRITE_UTF16BE(z, c);
  19647. }
  19648. }
  19649. pMem->n = (int)(z - zOut);
  19650. *z++ = 0;
  19651. }else{
  19652. assert( desiredEnc==SQLITE_UTF8 );
  19653. if( pMem->enc==SQLITE_UTF16LE ){
  19654. /* UTF-16 Little-endian -> UTF-8 */
  19655. while( zIn<zTerm ){
  19656. READ_UTF16LE(zIn, zIn<zTerm, c);
  19657. WRITE_UTF8(z, c);
  19658. }
  19659. }else{
  19660. /* UTF-16 Big-endian -> UTF-8 */
  19661. while( zIn<zTerm ){
  19662. READ_UTF16BE(zIn, zIn<zTerm, c);
  19663. WRITE_UTF8(z, c);
  19664. }
  19665. }
  19666. pMem->n = (int)(z - zOut);
  19667. }
  19668. *z = 0;
  19669. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  19670. sqlite3VdbeMemRelease(pMem);
  19671. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  19672. pMem->enc = desiredEnc;
  19673. pMem->flags |= (MEM_Term|MEM_Dyn);
  19674. pMem->z = (char*)zOut;
  19675. pMem->zMalloc = pMem->z;
  19676. translate_out:
  19677. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  19678. {
  19679. char zBuf[100];
  19680. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  19681. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  19682. }
  19683. #endif
  19684. return SQLITE_OK;
  19685. }
  19686. /*
  19687. ** This routine checks for a byte-order mark at the beginning of the
  19688. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  19689. ** the encoding of the Mem adjusted. This routine does not do any
  19690. ** byte-swapping, it just sets Mem.enc appropriately.
  19691. **
  19692. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  19693. ** changed by this function.
  19694. */
  19695. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  19696. int rc = SQLITE_OK;
  19697. u8 bom = 0;
  19698. assert( pMem->n>=0 );
  19699. if( pMem->n>1 ){
  19700. u8 b1 = *(u8 *)pMem->z;
  19701. u8 b2 = *(((u8 *)pMem->z) + 1);
  19702. if( b1==0xFE && b2==0xFF ){
  19703. bom = SQLITE_UTF16BE;
  19704. }
  19705. if( b1==0xFF && b2==0xFE ){
  19706. bom = SQLITE_UTF16LE;
  19707. }
  19708. }
  19709. if( bom ){
  19710. rc = sqlite3VdbeMemMakeWriteable(pMem);
  19711. if( rc==SQLITE_OK ){
  19712. pMem->n -= 2;
  19713. memmove(pMem->z, &pMem->z[2], pMem->n);
  19714. pMem->z[pMem->n] = '\0';
  19715. pMem->z[pMem->n+1] = '\0';
  19716. pMem->flags |= MEM_Term;
  19717. pMem->enc = bom;
  19718. }
  19719. }
  19720. return rc;
  19721. }
  19722. #endif /* SQLITE_OMIT_UTF16 */
  19723. /*
  19724. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  19725. ** return the number of unicode characters in pZ up to (but not including)
  19726. ** the first 0x00 byte. If nByte is not less than zero, return the
  19727. ** number of unicode characters in the first nByte of pZ (or up to
  19728. ** the first 0x00, whichever comes first).
  19729. */
  19730. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  19731. int r = 0;
  19732. const u8 *z = (const u8*)zIn;
  19733. const u8 *zTerm;
  19734. if( nByte>=0 ){
  19735. zTerm = &z[nByte];
  19736. }else{
  19737. zTerm = (const u8*)(-1);
  19738. }
  19739. assert( z<=zTerm );
  19740. while( *z!=0 && z<zTerm ){
  19741. SQLITE_SKIP_UTF8(z);
  19742. r++;
  19743. }
  19744. return r;
  19745. }
  19746. /* This test function is not currently used by the automated test-suite.
  19747. ** Hence it is only available in debug builds.
  19748. */
  19749. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  19750. /*
  19751. ** Translate UTF-8 to UTF-8.
  19752. **
  19753. ** This has the effect of making sure that the string is well-formed
  19754. ** UTF-8. Miscoded characters are removed.
  19755. **
  19756. ** The translation is done in-place and aborted if the output
  19757. ** overruns the input.
  19758. */
  19759. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  19760. unsigned char *zOut = zIn;
  19761. unsigned char *zStart = zIn;
  19762. u32 c;
  19763. while( zIn[0] && zOut<=zIn ){
  19764. c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
  19765. if( c!=0xfffd ){
  19766. WRITE_UTF8(zOut, c);
  19767. }
  19768. }
  19769. *zOut = 0;
  19770. return (int)(zOut - zStart);
  19771. }
  19772. #endif
  19773. #ifndef SQLITE_OMIT_UTF16
  19774. /*
  19775. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  19776. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  19777. ** be freed by the calling function.
  19778. **
  19779. ** NULL is returned if there is an allocation error.
  19780. */
  19781. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  19782. Mem m;
  19783. memset(&m, 0, sizeof(m));
  19784. m.db = db;
  19785. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  19786. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  19787. if( db->mallocFailed ){
  19788. sqlite3VdbeMemRelease(&m);
  19789. m.z = 0;
  19790. }
  19791. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  19792. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  19793. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  19794. assert( m.z || db->mallocFailed );
  19795. return m.z;
  19796. }
  19797. /*
  19798. ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
  19799. ** enc. A pointer to the new string is returned, and the value of *pnOut
  19800. ** is set to the length of the returned string in bytes. The call should
  19801. ** arrange to call sqlite3DbFree() on the returned pointer when it is
  19802. ** no longer required.
  19803. **
  19804. ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
  19805. ** flag set.
  19806. */
  19807. #ifdef SQLITE_ENABLE_STAT3
  19808. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
  19809. Mem m;
  19810. memset(&m, 0, sizeof(m));
  19811. m.db = db;
  19812. sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
  19813. if( sqlite3VdbeMemTranslate(&m, enc) ){
  19814. assert( db->mallocFailed );
  19815. return 0;
  19816. }
  19817. assert( m.z==m.zMalloc );
  19818. *pnOut = m.n;
  19819. return m.z;
  19820. }
  19821. #endif
  19822. /*
  19823. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  19824. ** Return the number of bytes in the first nChar unicode characters
  19825. ** in pZ. nChar must be non-negative.
  19826. */
  19827. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  19828. int c;
  19829. unsigned char const *z = zIn;
  19830. int n = 0;
  19831. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  19832. while( n<nChar ){
  19833. READ_UTF16BE(z, 1, c);
  19834. n++;
  19835. }
  19836. }else{
  19837. while( n<nChar ){
  19838. READ_UTF16LE(z, 1, c);
  19839. n++;
  19840. }
  19841. }
  19842. return (int)(z-(unsigned char const *)zIn);
  19843. }
  19844. #if defined(SQLITE_TEST)
  19845. /*
  19846. ** This routine is called from the TCL test function "translate_selftest".
  19847. ** It checks that the primitives for serializing and deserializing
  19848. ** characters in each encoding are inverses of each other.
  19849. */
  19850. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  19851. unsigned int i, t;
  19852. unsigned char zBuf[20];
  19853. unsigned char *z;
  19854. int n;
  19855. unsigned int c;
  19856. for(i=0; i<0x00110000; i++){
  19857. z = zBuf;
  19858. WRITE_UTF8(z, i);
  19859. n = (int)(z-zBuf);
  19860. assert( n>0 && n<=4 );
  19861. z[0] = 0;
  19862. z = zBuf;
  19863. c = sqlite3Utf8Read(z, (const u8**)&z);
  19864. t = i;
  19865. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  19866. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  19867. assert( c==t );
  19868. assert( (z-zBuf)==n );
  19869. }
  19870. for(i=0; i<0x00110000; i++){
  19871. if( i>=0xD800 && i<0xE000 ) continue;
  19872. z = zBuf;
  19873. WRITE_UTF16LE(z, i);
  19874. n = (int)(z-zBuf);
  19875. assert( n>0 && n<=4 );
  19876. z[0] = 0;
  19877. z = zBuf;
  19878. READ_UTF16LE(z, 1, c);
  19879. assert( c==i );
  19880. assert( (z-zBuf)==n );
  19881. }
  19882. for(i=0; i<0x00110000; i++){
  19883. if( i>=0xD800 && i<0xE000 ) continue;
  19884. z = zBuf;
  19885. WRITE_UTF16BE(z, i);
  19886. n = (int)(z-zBuf);
  19887. assert( n>0 && n<=4 );
  19888. z[0] = 0;
  19889. z = zBuf;
  19890. READ_UTF16BE(z, 1, c);
  19891. assert( c==i );
  19892. assert( (z-zBuf)==n );
  19893. }
  19894. }
  19895. #endif /* SQLITE_TEST */
  19896. #endif /* SQLITE_OMIT_UTF16 */
  19897. /************** End of utf.c *************************************************/
  19898. /************** Begin file util.c ********************************************/
  19899. /*
  19900. ** 2001 September 15
  19901. **
  19902. ** The author disclaims copyright to this source code. In place of
  19903. ** a legal notice, here is a blessing:
  19904. **
  19905. ** May you do good and not evil.
  19906. ** May you find forgiveness for yourself and forgive others.
  19907. ** May you share freely, never taking more than you give.
  19908. **
  19909. *************************************************************************
  19910. ** Utility functions used throughout sqlite.
  19911. **
  19912. ** This file contains functions for allocating memory, comparing
  19913. ** strings, and stuff like that.
  19914. **
  19915. */
  19916. /* #include <stdarg.h> */
  19917. #ifdef SQLITE_HAVE_ISNAN
  19918. # include <math.h>
  19919. #endif
  19920. /*
  19921. ** Routine needed to support the testcase() macro.
  19922. */
  19923. #ifdef SQLITE_COVERAGE_TEST
  19924. SQLITE_PRIVATE void sqlite3Coverage(int x){
  19925. static unsigned dummy = 0;
  19926. dummy += (unsigned)x;
  19927. }
  19928. #endif
  19929. #ifndef SQLITE_OMIT_FLOATING_POINT
  19930. /*
  19931. ** Return true if the floating point value is Not a Number (NaN).
  19932. **
  19933. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  19934. ** Otherwise, we have our own implementation that works on most systems.
  19935. */
  19936. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  19937. int rc; /* The value return */
  19938. #if !defined(SQLITE_HAVE_ISNAN)
  19939. /*
  19940. ** Systems that support the isnan() library function should probably
  19941. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  19942. ** found that many systems do not have a working isnan() function so
  19943. ** this implementation is provided as an alternative.
  19944. **
  19945. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  19946. ** On the other hand, the use of -ffast-math comes with the following
  19947. ** warning:
  19948. **
  19949. ** This option [-ffast-math] should never be turned on by any
  19950. ** -O option since it can result in incorrect output for programs
  19951. ** which depend on an exact implementation of IEEE or ISO
  19952. ** rules/specifications for math functions.
  19953. **
  19954. ** Under MSVC, this NaN test may fail if compiled with a floating-
  19955. ** point precision mode other than /fp:precise. From the MSDN
  19956. ** documentation:
  19957. **
  19958. ** The compiler [with /fp:precise] will properly handle comparisons
  19959. ** involving NaN. For example, x != x evaluates to true if x is NaN
  19960. ** ...
  19961. */
  19962. #ifdef __FAST_MATH__
  19963. # error SQLite will not work correctly with the -ffast-math option of GCC.
  19964. #endif
  19965. volatile double y = x;
  19966. volatile double z = y;
  19967. rc = (y!=z);
  19968. #else /* if defined(SQLITE_HAVE_ISNAN) */
  19969. rc = isnan(x);
  19970. #endif /* SQLITE_HAVE_ISNAN */
  19971. testcase( rc );
  19972. return rc;
  19973. }
  19974. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19975. /*
  19976. ** Compute a string length that is limited to what can be stored in
  19977. ** lower 30 bits of a 32-bit signed integer.
  19978. **
  19979. ** The value returned will never be negative. Nor will it ever be greater
  19980. ** than the actual length of the string. For very long strings (greater
  19981. ** than 1GiB) the value returned might be less than the true string length.
  19982. */
  19983. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  19984. const char *z2 = z;
  19985. if( z==0 ) return 0;
  19986. while( *z2 ){ z2++; }
  19987. return 0x3fffffff & (int)(z2 - z);
  19988. }
  19989. /*
  19990. ** Set the most recent error code and error string for the sqlite
  19991. ** handle "db". The error code is set to "err_code".
  19992. **
  19993. ** If it is not NULL, string zFormat specifies the format of the
  19994. ** error string in the style of the printf functions: The following
  19995. ** format characters are allowed:
  19996. **
  19997. ** %s Insert a string
  19998. ** %z A string that should be freed after use
  19999. ** %d Insert an integer
  20000. ** %T Insert a token
  20001. ** %S Insert the first element of a SrcList
  20002. **
  20003. ** zFormat and any string tokens that follow it are assumed to be
  20004. ** encoded in UTF-8.
  20005. **
  20006. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  20007. ** should be called with err_code set to SQLITE_OK and zFormat set
  20008. ** to NULL.
  20009. */
  20010. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  20011. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  20012. db->errCode = err_code;
  20013. if( zFormat ){
  20014. char *z;
  20015. va_list ap;
  20016. va_start(ap, zFormat);
  20017. z = sqlite3VMPrintf(db, zFormat, ap);
  20018. va_end(ap);
  20019. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  20020. }else{
  20021. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  20022. }
  20023. }
  20024. }
  20025. /*
  20026. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  20027. ** The following formatting characters are allowed:
  20028. **
  20029. ** %s Insert a string
  20030. ** %z A string that should be freed after use
  20031. ** %d Insert an integer
  20032. ** %T Insert a token
  20033. ** %S Insert the first element of a SrcList
  20034. **
  20035. ** This function should be used to report any error that occurs whilst
  20036. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  20037. ** last thing the sqlite3_prepare() function does is copy the error
  20038. ** stored by this function into the database handle using sqlite3Error().
  20039. ** Function sqlite3Error() should be used during statement execution
  20040. ** (sqlite3_step() etc.).
  20041. */
  20042. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  20043. char *zMsg;
  20044. va_list ap;
  20045. sqlite3 *db = pParse->db;
  20046. va_start(ap, zFormat);
  20047. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  20048. va_end(ap);
  20049. if( db->suppressErr ){
  20050. sqlite3DbFree(db, zMsg);
  20051. }else{
  20052. pParse->nErr++;
  20053. sqlite3DbFree(db, pParse->zErrMsg);
  20054. pParse->zErrMsg = zMsg;
  20055. pParse->rc = SQLITE_ERROR;
  20056. }
  20057. }
  20058. /*
  20059. ** Convert an SQL-style quoted string into a normal string by removing
  20060. ** the quote characters. The conversion is done in-place. If the
  20061. ** input does not begin with a quote character, then this routine
  20062. ** is a no-op.
  20063. **
  20064. ** The input string must be zero-terminated. A new zero-terminator
  20065. ** is added to the dequoted string.
  20066. **
  20067. ** The return value is -1 if no dequoting occurs or the length of the
  20068. ** dequoted string, exclusive of the zero terminator, if dequoting does
  20069. ** occur.
  20070. **
  20071. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  20072. ** brackets from around identifers. For example: "[a-b-c]" becomes
  20073. ** "a-b-c".
  20074. */
  20075. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  20076. char quote;
  20077. int i, j;
  20078. if( z==0 ) return -1;
  20079. quote = z[0];
  20080. switch( quote ){
  20081. case '\'': break;
  20082. case '"': break;
  20083. case '`': break; /* For MySQL compatibility */
  20084. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  20085. default: return -1;
  20086. }
  20087. for(i=1, j=0; ALWAYS(z[i]); i++){
  20088. if( z[i]==quote ){
  20089. if( z[i+1]==quote ){
  20090. z[j++] = quote;
  20091. i++;
  20092. }else{
  20093. break;
  20094. }
  20095. }else{
  20096. z[j++] = z[i];
  20097. }
  20098. }
  20099. z[j] = 0;
  20100. return j;
  20101. }
  20102. /* Convenient short-hand */
  20103. #define UpperToLower sqlite3UpperToLower
  20104. /*
  20105. ** Some systems have stricmp(). Others have strcasecmp(). Because
  20106. ** there is no consistency, we will define our own.
  20107. **
  20108. ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
  20109. ** applications and extensions to compare the contents of two buffers
  20110. ** containing UTF-8 strings in a case-independent fashion, using the same
  20111. ** definition of case independence that SQLite uses internally when
  20112. ** comparing identifiers.
  20113. */
  20114. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  20115. register unsigned char *a, *b;
  20116. a = (unsigned char *)zLeft;
  20117. b = (unsigned char *)zRight;
  20118. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20119. return UpperToLower[*a] - UpperToLower[*b];
  20120. }
  20121. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  20122. register unsigned char *a, *b;
  20123. a = (unsigned char *)zLeft;
  20124. b = (unsigned char *)zRight;
  20125. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20126. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  20127. }
  20128. /*
  20129. ** The string z[] is an text representation of a real number.
  20130. ** Convert this string to a double and write it into *pResult.
  20131. **
  20132. ** The string z[] is length bytes in length (bytes, not characters) and
  20133. ** uses the encoding enc. The string is not necessarily zero-terminated.
  20134. **
  20135. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  20136. ** if the string is empty or contains extraneous text. Valid numbers
  20137. ** are in one of these formats:
  20138. **
  20139. ** [+-]digits[E[+-]digits]
  20140. ** [+-]digits.[digits][E[+-]digits]
  20141. ** [+-].digits[E[+-]digits]
  20142. **
  20143. ** Leading and trailing whitespace is ignored for the purpose of determining
  20144. ** validity.
  20145. **
  20146. ** If some prefix of the input string is a valid number, this routine
  20147. ** returns FALSE but it still converts the prefix and writes the result
  20148. ** into *pResult.
  20149. */
  20150. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  20151. #ifndef SQLITE_OMIT_FLOATING_POINT
  20152. int incr = (enc==SQLITE_UTF8?1:2);
  20153. const char *zEnd = z + length;
  20154. /* sign * significand * (10 ^ (esign * exponent)) */
  20155. int sign = 1; /* sign of significand */
  20156. i64 s = 0; /* significand */
  20157. int d = 0; /* adjust exponent for shifting decimal point */
  20158. int esign = 1; /* sign of exponent */
  20159. int e = 0; /* exponent */
  20160. int eValid = 1; /* True exponent is either not used or is well-formed */
  20161. double result;
  20162. int nDigits = 0;
  20163. *pResult = 0.0; /* Default return value, in case of an error */
  20164. if( enc==SQLITE_UTF16BE ) z++;
  20165. /* skip leading spaces */
  20166. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20167. if( z>=zEnd ) return 0;
  20168. /* get sign of significand */
  20169. if( *z=='-' ){
  20170. sign = -1;
  20171. z+=incr;
  20172. }else if( *z=='+' ){
  20173. z+=incr;
  20174. }
  20175. /* skip leading zeroes */
  20176. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  20177. /* copy max significant digits to significand */
  20178. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20179. s = s*10 + (*z - '0');
  20180. z+=incr, nDigits++;
  20181. }
  20182. /* skip non-significant significand digits
  20183. ** (increase exponent by d to shift decimal left) */
  20184. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  20185. if( z>=zEnd ) goto do_atof_calc;
  20186. /* if decimal point is present */
  20187. if( *z=='.' ){
  20188. z+=incr;
  20189. /* copy digits from after decimal to significand
  20190. ** (decrease exponent by d to shift decimal right) */
  20191. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20192. s = s*10 + (*z - '0');
  20193. z+=incr, nDigits++, d--;
  20194. }
  20195. /* skip non-significant digits */
  20196. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  20197. }
  20198. if( z>=zEnd ) goto do_atof_calc;
  20199. /* if exponent is present */
  20200. if( *z=='e' || *z=='E' ){
  20201. z+=incr;
  20202. eValid = 0;
  20203. if( z>=zEnd ) goto do_atof_calc;
  20204. /* get sign of exponent */
  20205. if( *z=='-' ){
  20206. esign = -1;
  20207. z+=incr;
  20208. }else if( *z=='+' ){
  20209. z+=incr;
  20210. }
  20211. /* copy digits to exponent */
  20212. while( z<zEnd && sqlite3Isdigit(*z) ){
  20213. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  20214. z+=incr;
  20215. eValid = 1;
  20216. }
  20217. }
  20218. /* skip trailing spaces */
  20219. if( nDigits && eValid ){
  20220. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20221. }
  20222. do_atof_calc:
  20223. /* adjust exponent by d, and update sign */
  20224. e = (e*esign) + d;
  20225. if( e<0 ) {
  20226. esign = -1;
  20227. e *= -1;
  20228. } else {
  20229. esign = 1;
  20230. }
  20231. /* if 0 significand */
  20232. if( !s ) {
  20233. /* In the IEEE 754 standard, zero is signed.
  20234. ** Add the sign if we've seen at least one digit */
  20235. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  20236. } else {
  20237. /* attempt to reduce exponent */
  20238. if( esign>0 ){
  20239. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  20240. }else{
  20241. while( !(s%10) && e>0 ) e--,s/=10;
  20242. }
  20243. /* adjust the sign of significand */
  20244. s = sign<0 ? -s : s;
  20245. /* if exponent, scale significand as appropriate
  20246. ** and store in result. */
  20247. if( e ){
  20248. double scale = 1.0;
  20249. /* attempt to handle extremely small/large numbers better */
  20250. if( e>307 && e<342 ){
  20251. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  20252. if( esign<0 ){
  20253. result = s / scale;
  20254. result /= 1.0e+308;
  20255. }else{
  20256. result = s * scale;
  20257. result *= 1.0e+308;
  20258. }
  20259. }else if( e>=342 ){
  20260. if( esign<0 ){
  20261. result = 0.0*s;
  20262. }else{
  20263. result = 1e308*1e308*s; /* Infinity */
  20264. }
  20265. }else{
  20266. /* 1.0e+22 is the largest power of 10 than can be
  20267. ** represented exactly. */
  20268. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  20269. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  20270. if( esign<0 ){
  20271. result = s / scale;
  20272. }else{
  20273. result = s * scale;
  20274. }
  20275. }
  20276. } else {
  20277. result = (double)s;
  20278. }
  20279. }
  20280. /* store the result */
  20281. *pResult = result;
  20282. /* return true if number and no extra non-whitespace chracters after */
  20283. return z>=zEnd && nDigits>0 && eValid;
  20284. #else
  20285. return !sqlite3Atoi64(z, pResult, length, enc);
  20286. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20287. }
  20288. /*
  20289. ** Compare the 19-character string zNum against the text representation
  20290. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  20291. ** if zNum is less than, equal to, or greater than the string.
  20292. ** Note that zNum must contain exactly 19 characters.
  20293. **
  20294. ** Unlike memcmp() this routine is guaranteed to return the difference
  20295. ** in the values of the last digit if the only difference is in the
  20296. ** last digit. So, for example,
  20297. **
  20298. ** compare2pow63("9223372036854775800", 1)
  20299. **
  20300. ** will return -8.
  20301. */
  20302. static int compare2pow63(const char *zNum, int incr){
  20303. int c = 0;
  20304. int i;
  20305. /* 012345678901234567 */
  20306. const char *pow63 = "922337203685477580";
  20307. for(i=0; c==0 && i<18; i++){
  20308. c = (zNum[i*incr]-pow63[i])*10;
  20309. }
  20310. if( c==0 ){
  20311. c = zNum[18*incr] - '8';
  20312. testcase( c==(-1) );
  20313. testcase( c==0 );
  20314. testcase( c==(+1) );
  20315. }
  20316. return c;
  20317. }
  20318. /*
  20319. ** Convert zNum to a 64-bit signed integer.
  20320. **
  20321. ** If the zNum value is representable as a 64-bit twos-complement
  20322. ** integer, then write that value into *pNum and return 0.
  20323. **
  20324. ** If zNum is exactly 9223372036854665808, return 2. This special
  20325. ** case is broken out because while 9223372036854665808 cannot be a
  20326. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  20327. **
  20328. ** If zNum is too big for a 64-bit integer and is not
  20329. ** 9223372036854665808 then return 1.
  20330. **
  20331. ** length is the number of bytes in the string (bytes, not characters).
  20332. ** The string is not necessarily zero-terminated. The encoding is
  20333. ** given by enc.
  20334. */
  20335. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  20336. int incr = (enc==SQLITE_UTF8?1:2);
  20337. u64 u = 0;
  20338. int neg = 0; /* assume positive */
  20339. int i;
  20340. int c = 0;
  20341. const char *zStart;
  20342. const char *zEnd = zNum + length;
  20343. if( enc==SQLITE_UTF16BE ) zNum++;
  20344. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  20345. if( zNum<zEnd ){
  20346. if( *zNum=='-' ){
  20347. neg = 1;
  20348. zNum+=incr;
  20349. }else if( *zNum=='+' ){
  20350. zNum+=incr;
  20351. }
  20352. }
  20353. zStart = zNum;
  20354. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  20355. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  20356. u = u*10 + c - '0';
  20357. }
  20358. if( u>LARGEST_INT64 ){
  20359. *pNum = SMALLEST_INT64;
  20360. }else if( neg ){
  20361. *pNum = -(i64)u;
  20362. }else{
  20363. *pNum = (i64)u;
  20364. }
  20365. testcase( i==18 );
  20366. testcase( i==19 );
  20367. testcase( i==20 );
  20368. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
  20369. /* zNum is empty or contains non-numeric text or is longer
  20370. ** than 19 digits (thus guaranteeing that it is too large) */
  20371. return 1;
  20372. }else if( i<19*incr ){
  20373. /* Less than 19 digits, so we know that it fits in 64 bits */
  20374. assert( u<=LARGEST_INT64 );
  20375. return 0;
  20376. }else{
  20377. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  20378. c = compare2pow63(zNum, incr);
  20379. if( c<0 ){
  20380. /* zNum is less than 9223372036854775808 so it fits */
  20381. assert( u<=LARGEST_INT64 );
  20382. return 0;
  20383. }else if( c>0 ){
  20384. /* zNum is greater than 9223372036854775808 so it overflows */
  20385. return 1;
  20386. }else{
  20387. /* zNum is exactly 9223372036854775808. Fits if negative. The
  20388. ** special case 2 overflow if positive */
  20389. assert( u-1==LARGEST_INT64 );
  20390. assert( (*pNum)==SMALLEST_INT64 );
  20391. return neg ? 0 : 2;
  20392. }
  20393. }
  20394. }
  20395. /*
  20396. ** If zNum represents an integer that will fit in 32-bits, then set
  20397. ** *pValue to that integer and return true. Otherwise return false.
  20398. **
  20399. ** Any non-numeric characters that following zNum are ignored.
  20400. ** This is different from sqlite3Atoi64() which requires the
  20401. ** input number to be zero-terminated.
  20402. */
  20403. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  20404. sqlite_int64 v = 0;
  20405. int i, c;
  20406. int neg = 0;
  20407. if( zNum[0]=='-' ){
  20408. neg = 1;
  20409. zNum++;
  20410. }else if( zNum[0]=='+' ){
  20411. zNum++;
  20412. }
  20413. while( zNum[0]=='0' ) zNum++;
  20414. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  20415. v = v*10 + c;
  20416. }
  20417. /* The longest decimal representation of a 32 bit integer is 10 digits:
  20418. **
  20419. ** 1234567890
  20420. ** 2^31 -> 2147483648
  20421. */
  20422. testcase( i==10 );
  20423. if( i>10 ){
  20424. return 0;
  20425. }
  20426. testcase( v-neg==2147483647 );
  20427. if( v-neg>2147483647 ){
  20428. return 0;
  20429. }
  20430. if( neg ){
  20431. v = -v;
  20432. }
  20433. *pValue = (int)v;
  20434. return 1;
  20435. }
  20436. /*
  20437. ** Return a 32-bit integer value extracted from a string. If the
  20438. ** string is not an integer, just return 0.
  20439. */
  20440. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  20441. int x = 0;
  20442. if( z ) sqlite3GetInt32(z, &x);
  20443. return x;
  20444. }
  20445. /*
  20446. ** The variable-length integer encoding is as follows:
  20447. **
  20448. ** KEY:
  20449. ** A = 0xxxxxxx 7 bits of data and one flag bit
  20450. ** B = 1xxxxxxx 7 bits of data and one flag bit
  20451. ** C = xxxxxxxx 8 bits of data
  20452. **
  20453. ** 7 bits - A
  20454. ** 14 bits - BA
  20455. ** 21 bits - BBA
  20456. ** 28 bits - BBBA
  20457. ** 35 bits - BBBBA
  20458. ** 42 bits - BBBBBA
  20459. ** 49 bits - BBBBBBA
  20460. ** 56 bits - BBBBBBBA
  20461. ** 64 bits - BBBBBBBBC
  20462. */
  20463. /*
  20464. ** Write a 64-bit variable-length integer to memory starting at p[0].
  20465. ** The length of data write will be between 1 and 9 bytes. The number
  20466. ** of bytes written is returned.
  20467. **
  20468. ** A variable-length integer consists of the lower 7 bits of each byte
  20469. ** for all bytes that have the 8th bit set and one byte with the 8th
  20470. ** bit clear. Except, if we get to the 9th byte, it stores the full
  20471. ** 8 bits and is the last byte.
  20472. */
  20473. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  20474. int i, j, n;
  20475. u8 buf[10];
  20476. if( v & (((u64)0xff000000)<<32) ){
  20477. p[8] = (u8)v;
  20478. v >>= 8;
  20479. for(i=7; i>=0; i--){
  20480. p[i] = (u8)((v & 0x7f) | 0x80);
  20481. v >>= 7;
  20482. }
  20483. return 9;
  20484. }
  20485. n = 0;
  20486. do{
  20487. buf[n++] = (u8)((v & 0x7f) | 0x80);
  20488. v >>= 7;
  20489. }while( v!=0 );
  20490. buf[0] &= 0x7f;
  20491. assert( n<=9 );
  20492. for(i=0, j=n-1; j>=0; j--, i++){
  20493. p[i] = buf[j];
  20494. }
  20495. return n;
  20496. }
  20497. /*
  20498. ** This routine is a faster version of sqlite3PutVarint() that only
  20499. ** works for 32-bit positive integers and which is optimized for
  20500. ** the common case of small integers. A MACRO version, putVarint32,
  20501. ** is provided which inlines the single-byte case. All code should use
  20502. ** the MACRO version as this function assumes the single-byte case has
  20503. ** already been handled.
  20504. */
  20505. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  20506. #ifndef putVarint32
  20507. if( (v & ~0x7f)==0 ){
  20508. p[0] = v;
  20509. return 1;
  20510. }
  20511. #endif
  20512. if( (v & ~0x3fff)==0 ){
  20513. p[0] = (u8)((v>>7) | 0x80);
  20514. p[1] = (u8)(v & 0x7f);
  20515. return 2;
  20516. }
  20517. return sqlite3PutVarint(p, v);
  20518. }
  20519. /*
  20520. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  20521. ** are defined here rather than simply putting the constant expressions
  20522. ** inline in order to work around bugs in the RVT compiler.
  20523. **
  20524. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  20525. **
  20526. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  20527. */
  20528. #define SLOT_2_0 0x001fc07f
  20529. #define SLOT_4_2_0 0xf01fc07f
  20530. /*
  20531. ** Read a 64-bit variable-length integer from memory starting at p[0].
  20532. ** Return the number of bytes read. The value is stored in *v.
  20533. */
  20534. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  20535. u32 a,b,s;
  20536. a = *p;
  20537. /* a: p0 (unmasked) */
  20538. if (!(a&0x80))
  20539. {
  20540. *v = a;
  20541. return 1;
  20542. }
  20543. p++;
  20544. b = *p;
  20545. /* b: p1 (unmasked) */
  20546. if (!(b&0x80))
  20547. {
  20548. a &= 0x7f;
  20549. a = a<<7;
  20550. a |= b;
  20551. *v = a;
  20552. return 2;
  20553. }
  20554. /* Verify that constants are precomputed correctly */
  20555. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  20556. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  20557. p++;
  20558. a = a<<14;
  20559. a |= *p;
  20560. /* a: p0<<14 | p2 (unmasked) */
  20561. if (!(a&0x80))
  20562. {
  20563. a &= SLOT_2_0;
  20564. b &= 0x7f;
  20565. b = b<<7;
  20566. a |= b;
  20567. *v = a;
  20568. return 3;
  20569. }
  20570. /* CSE1 from below */
  20571. a &= SLOT_2_0;
  20572. p++;
  20573. b = b<<14;
  20574. b |= *p;
  20575. /* b: p1<<14 | p3 (unmasked) */
  20576. if (!(b&0x80))
  20577. {
  20578. b &= SLOT_2_0;
  20579. /* moved CSE1 up */
  20580. /* a &= (0x7f<<14)|(0x7f); */
  20581. a = a<<7;
  20582. a |= b;
  20583. *v = a;
  20584. return 4;
  20585. }
  20586. /* a: p0<<14 | p2 (masked) */
  20587. /* b: p1<<14 | p3 (unmasked) */
  20588. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20589. /* moved CSE1 up */
  20590. /* a &= (0x7f<<14)|(0x7f); */
  20591. b &= SLOT_2_0;
  20592. s = a;
  20593. /* s: p0<<14 | p2 (masked) */
  20594. p++;
  20595. a = a<<14;
  20596. a |= *p;
  20597. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20598. if (!(a&0x80))
  20599. {
  20600. /* we can skip these cause they were (effectively) done above in calc'ing s */
  20601. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20602. /* b &= (0x7f<<14)|(0x7f); */
  20603. b = b<<7;
  20604. a |= b;
  20605. s = s>>18;
  20606. *v = ((u64)s)<<32 | a;
  20607. return 5;
  20608. }
  20609. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20610. s = s<<7;
  20611. s |= b;
  20612. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  20613. p++;
  20614. b = b<<14;
  20615. b |= *p;
  20616. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  20617. if (!(b&0x80))
  20618. {
  20619. /* we can skip this cause it was (effectively) done above in calc'ing s */
  20620. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  20621. a &= SLOT_2_0;
  20622. a = a<<7;
  20623. a |= b;
  20624. s = s>>18;
  20625. *v = ((u64)s)<<32 | a;
  20626. return 6;
  20627. }
  20628. p++;
  20629. a = a<<14;
  20630. a |= *p;
  20631. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  20632. if (!(a&0x80))
  20633. {
  20634. a &= SLOT_4_2_0;
  20635. b &= SLOT_2_0;
  20636. b = b<<7;
  20637. a |= b;
  20638. s = s>>11;
  20639. *v = ((u64)s)<<32 | a;
  20640. return 7;
  20641. }
  20642. /* CSE2 from below */
  20643. a &= SLOT_2_0;
  20644. p++;
  20645. b = b<<14;
  20646. b |= *p;
  20647. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  20648. if (!(b&0x80))
  20649. {
  20650. b &= SLOT_4_2_0;
  20651. /* moved CSE2 up */
  20652. /* a &= (0x7f<<14)|(0x7f); */
  20653. a = a<<7;
  20654. a |= b;
  20655. s = s>>4;
  20656. *v = ((u64)s)<<32 | a;
  20657. return 8;
  20658. }
  20659. p++;
  20660. a = a<<15;
  20661. a |= *p;
  20662. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  20663. /* moved CSE2 up */
  20664. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  20665. b &= SLOT_2_0;
  20666. b = b<<8;
  20667. a |= b;
  20668. s = s<<4;
  20669. b = p[-4];
  20670. b &= 0x7f;
  20671. b = b>>3;
  20672. s |= b;
  20673. *v = ((u64)s)<<32 | a;
  20674. return 9;
  20675. }
  20676. /*
  20677. ** Read a 32-bit variable-length integer from memory starting at p[0].
  20678. ** Return the number of bytes read. The value is stored in *v.
  20679. **
  20680. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  20681. ** integer, then set *v to 0xffffffff.
  20682. **
  20683. ** A MACRO version, getVarint32, is provided which inlines the
  20684. ** single-byte case. All code should use the MACRO version as
  20685. ** this function assumes the single-byte case has already been handled.
  20686. */
  20687. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  20688. u32 a,b;
  20689. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  20690. ** by the getVarin32() macro */
  20691. a = *p;
  20692. /* a: p0 (unmasked) */
  20693. #ifndef getVarint32
  20694. if (!(a&0x80))
  20695. {
  20696. /* Values between 0 and 127 */
  20697. *v = a;
  20698. return 1;
  20699. }
  20700. #endif
  20701. /* The 2-byte case */
  20702. p++;
  20703. b = *p;
  20704. /* b: p1 (unmasked) */
  20705. if (!(b&0x80))
  20706. {
  20707. /* Values between 128 and 16383 */
  20708. a &= 0x7f;
  20709. a = a<<7;
  20710. *v = a | b;
  20711. return 2;
  20712. }
  20713. /* The 3-byte case */
  20714. p++;
  20715. a = a<<14;
  20716. a |= *p;
  20717. /* a: p0<<14 | p2 (unmasked) */
  20718. if (!(a&0x80))
  20719. {
  20720. /* Values between 16384 and 2097151 */
  20721. a &= (0x7f<<14)|(0x7f);
  20722. b &= 0x7f;
  20723. b = b<<7;
  20724. *v = a | b;
  20725. return 3;
  20726. }
  20727. /* A 32-bit varint is used to store size information in btrees.
  20728. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  20729. ** A 3-byte varint is sufficient, for example, to record the size
  20730. ** of a 1048569-byte BLOB or string.
  20731. **
  20732. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  20733. ** rare larger cases can be handled by the slower 64-bit varint
  20734. ** routine.
  20735. */
  20736. #if 1
  20737. {
  20738. u64 v64;
  20739. u8 n;
  20740. p -= 2;
  20741. n = sqlite3GetVarint(p, &v64);
  20742. assert( n>3 && n<=9 );
  20743. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  20744. *v = 0xffffffff;
  20745. }else{
  20746. *v = (u32)v64;
  20747. }
  20748. return n;
  20749. }
  20750. #else
  20751. /* For following code (kept for historical record only) shows an
  20752. ** unrolling for the 3- and 4-byte varint cases. This code is
  20753. ** slightly faster, but it is also larger and much harder to test.
  20754. */
  20755. p++;
  20756. b = b<<14;
  20757. b |= *p;
  20758. /* b: p1<<14 | p3 (unmasked) */
  20759. if (!(b&0x80))
  20760. {
  20761. /* Values between 2097152 and 268435455 */
  20762. b &= (0x7f<<14)|(0x7f);
  20763. a &= (0x7f<<14)|(0x7f);
  20764. a = a<<7;
  20765. *v = a | b;
  20766. return 4;
  20767. }
  20768. p++;
  20769. a = a<<14;
  20770. a |= *p;
  20771. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20772. if (!(a&0x80))
  20773. {
  20774. /* Values between 268435456 and 34359738367 */
  20775. a &= SLOT_4_2_0;
  20776. b &= SLOT_4_2_0;
  20777. b = b<<7;
  20778. *v = a | b;
  20779. return 5;
  20780. }
  20781. /* We can only reach this point when reading a corrupt database
  20782. ** file. In that case we are not in any hurry. Use the (relatively
  20783. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  20784. ** value. */
  20785. {
  20786. u64 v64;
  20787. u8 n;
  20788. p -= 4;
  20789. n = sqlite3GetVarint(p, &v64);
  20790. assert( n>5 && n<=9 );
  20791. *v = (u32)v64;
  20792. return n;
  20793. }
  20794. #endif
  20795. }
  20796. /*
  20797. ** Return the number of bytes that will be needed to store the given
  20798. ** 64-bit integer.
  20799. */
  20800. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  20801. int i = 0;
  20802. do{
  20803. i++;
  20804. v >>= 7;
  20805. }while( v!=0 && ALWAYS(i<9) );
  20806. return i;
  20807. }
  20808. /*
  20809. ** Read or write a four-byte big-endian integer value.
  20810. */
  20811. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  20812. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  20813. }
  20814. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  20815. p[0] = (u8)(v>>24);
  20816. p[1] = (u8)(v>>16);
  20817. p[2] = (u8)(v>>8);
  20818. p[3] = (u8)v;
  20819. }
  20820. /*
  20821. ** Translate a single byte of Hex into an integer.
  20822. ** This routine only works if h really is a valid hexadecimal
  20823. ** character: 0..9a..fA..F
  20824. */
  20825. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  20826. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  20827. #ifdef SQLITE_ASCII
  20828. h += 9*(1&(h>>6));
  20829. #endif
  20830. #ifdef SQLITE_EBCDIC
  20831. h += 9*(1&~(h>>4));
  20832. #endif
  20833. return (u8)(h & 0xf);
  20834. }
  20835. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  20836. /*
  20837. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  20838. ** value. Return a pointer to its binary value. Space to hold the
  20839. ** binary value has been obtained from malloc and must be freed by
  20840. ** the calling routine.
  20841. */
  20842. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  20843. char *zBlob;
  20844. int i;
  20845. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  20846. n--;
  20847. if( zBlob ){
  20848. for(i=0; i<n; i+=2){
  20849. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  20850. }
  20851. zBlob[i/2] = 0;
  20852. }
  20853. return zBlob;
  20854. }
  20855. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  20856. /*
  20857. ** Log an error that is an API call on a connection pointer that should
  20858. ** not have been used. The "type" of connection pointer is given as the
  20859. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  20860. */
  20861. static void logBadConnection(const char *zType){
  20862. sqlite3_log(SQLITE_MISUSE,
  20863. "API call with %s database connection pointer",
  20864. zType
  20865. );
  20866. }
  20867. /*
  20868. ** Check to make sure we have a valid db pointer. This test is not
  20869. ** foolproof but it does provide some measure of protection against
  20870. ** misuse of the interface such as passing in db pointers that are
  20871. ** NULL or which have been previously closed. If this routine returns
  20872. ** 1 it means that the db pointer is valid and 0 if it should not be
  20873. ** dereferenced for any reason. The calling function should invoke
  20874. ** SQLITE_MISUSE immediately.
  20875. **
  20876. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  20877. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  20878. ** open properly and is not fit for general use but which can be
  20879. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  20880. */
  20881. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  20882. u32 magic;
  20883. if( db==0 ){
  20884. logBadConnection("NULL");
  20885. return 0;
  20886. }
  20887. magic = db->magic;
  20888. if( magic!=SQLITE_MAGIC_OPEN ){
  20889. if( sqlite3SafetyCheckSickOrOk(db) ){
  20890. testcase( sqlite3GlobalConfig.xLog!=0 );
  20891. logBadConnection("unopened");
  20892. }
  20893. return 0;
  20894. }else{
  20895. return 1;
  20896. }
  20897. }
  20898. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  20899. u32 magic;
  20900. magic = db->magic;
  20901. if( magic!=SQLITE_MAGIC_SICK &&
  20902. magic!=SQLITE_MAGIC_OPEN &&
  20903. magic!=SQLITE_MAGIC_BUSY ){
  20904. testcase( sqlite3GlobalConfig.xLog!=0 );
  20905. logBadConnection("invalid");
  20906. return 0;
  20907. }else{
  20908. return 1;
  20909. }
  20910. }
  20911. /*
  20912. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  20913. ** the other 64-bit signed integer at *pA and store the result in *pA.
  20914. ** Return 0 on success. Or if the operation would have resulted in an
  20915. ** overflow, leave *pA unchanged and return 1.
  20916. */
  20917. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  20918. i64 iA = *pA;
  20919. testcase( iA==0 ); testcase( iA==1 );
  20920. testcase( iB==-1 ); testcase( iB==0 );
  20921. if( iB>=0 ){
  20922. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  20923. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  20924. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  20925. *pA += iB;
  20926. }else{
  20927. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  20928. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  20929. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  20930. *pA += iB;
  20931. }
  20932. return 0;
  20933. }
  20934. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  20935. testcase( iB==SMALLEST_INT64+1 );
  20936. if( iB==SMALLEST_INT64 ){
  20937. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  20938. if( (*pA)>=0 ) return 1;
  20939. *pA -= iB;
  20940. return 0;
  20941. }else{
  20942. return sqlite3AddInt64(pA, -iB);
  20943. }
  20944. }
  20945. #define TWOPOWER32 (((i64)1)<<32)
  20946. #define TWOPOWER31 (((i64)1)<<31)
  20947. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  20948. i64 iA = *pA;
  20949. i64 iA1, iA0, iB1, iB0, r;
  20950. iA1 = iA/TWOPOWER32;
  20951. iA0 = iA % TWOPOWER32;
  20952. iB1 = iB/TWOPOWER32;
  20953. iB0 = iB % TWOPOWER32;
  20954. if( iA1*iB1 != 0 ) return 1;
  20955. assert( iA1*iB0==0 || iA0*iB1==0 );
  20956. r = iA1*iB0 + iA0*iB1;
  20957. testcase( r==(-TWOPOWER31)-1 );
  20958. testcase( r==(-TWOPOWER31) );
  20959. testcase( r==TWOPOWER31 );
  20960. testcase( r==TWOPOWER31-1 );
  20961. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  20962. r *= TWOPOWER32;
  20963. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  20964. *pA = r;
  20965. return 0;
  20966. }
  20967. /*
  20968. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  20969. ** if the integer has a value of -2147483648, return +2147483647
  20970. */
  20971. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  20972. if( x>=0 ) return x;
  20973. if( x==(int)0x80000000 ) return 0x7fffffff;
  20974. return -x;
  20975. }
  20976. #ifdef SQLITE_ENABLE_8_3_NAMES
  20977. /*
  20978. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  20979. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  20980. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  20981. ** three characters, then shorten the suffix on z[] to be the last three
  20982. ** characters of the original suffix.
  20983. **
  20984. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  20985. ** do the suffix shortening regardless of URI parameter.
  20986. **
  20987. ** Examples:
  20988. **
  20989. ** test.db-journal => test.nal
  20990. ** test.db-wal => test.wal
  20991. ** test.db-shm => test.shm
  20992. ** test.db-mj7f3319fa => test.9fa
  20993. */
  20994. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  20995. #if SQLITE_ENABLE_8_3_NAMES<2
  20996. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  20997. #endif
  20998. {
  20999. int i, sz;
  21000. sz = sqlite3Strlen30(z);
  21001. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  21002. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  21003. }
  21004. }
  21005. #endif
  21006. /************** End of util.c ************************************************/
  21007. /************** Begin file hash.c ********************************************/
  21008. /*
  21009. ** 2001 September 22
  21010. **
  21011. ** The author disclaims copyright to this source code. In place of
  21012. ** a legal notice, here is a blessing:
  21013. **
  21014. ** May you do good and not evil.
  21015. ** May you find forgiveness for yourself and forgive others.
  21016. ** May you share freely, never taking more than you give.
  21017. **
  21018. *************************************************************************
  21019. ** This is the implementation of generic hash-tables
  21020. ** used in SQLite.
  21021. */
  21022. /* #include <assert.h> */
  21023. /* Turn bulk memory into a hash table object by initializing the
  21024. ** fields of the Hash structure.
  21025. **
  21026. ** "pNew" is a pointer to the hash table that is to be initialized.
  21027. */
  21028. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  21029. assert( pNew!=0 );
  21030. pNew->first = 0;
  21031. pNew->count = 0;
  21032. pNew->htsize = 0;
  21033. pNew->ht = 0;
  21034. }
  21035. /* Remove all entries from a hash table. Reclaim all memory.
  21036. ** Call this routine to delete a hash table or to reset a hash table
  21037. ** to the empty state.
  21038. */
  21039. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  21040. HashElem *elem; /* For looping over all elements of the table */
  21041. assert( pH!=0 );
  21042. elem = pH->first;
  21043. pH->first = 0;
  21044. sqlite3_free(pH->ht);
  21045. pH->ht = 0;
  21046. pH->htsize = 0;
  21047. while( elem ){
  21048. HashElem *next_elem = elem->next;
  21049. sqlite3_free(elem);
  21050. elem = next_elem;
  21051. }
  21052. pH->count = 0;
  21053. }
  21054. /*
  21055. ** The hashing function.
  21056. */
  21057. static unsigned int strHash(const char *z, int nKey){
  21058. int h = 0;
  21059. assert( nKey>=0 );
  21060. while( nKey > 0 ){
  21061. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  21062. nKey--;
  21063. }
  21064. return h;
  21065. }
  21066. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  21067. ** insert pNew into the pEntry hash bucket.
  21068. */
  21069. static void insertElement(
  21070. Hash *pH, /* The complete hash table */
  21071. struct _ht *pEntry, /* The entry into which pNew is inserted */
  21072. HashElem *pNew /* The element to be inserted */
  21073. ){
  21074. HashElem *pHead; /* First element already in pEntry */
  21075. if( pEntry ){
  21076. pHead = pEntry->count ? pEntry->chain : 0;
  21077. pEntry->count++;
  21078. pEntry->chain = pNew;
  21079. }else{
  21080. pHead = 0;
  21081. }
  21082. if( pHead ){
  21083. pNew->next = pHead;
  21084. pNew->prev = pHead->prev;
  21085. if( pHead->prev ){ pHead->prev->next = pNew; }
  21086. else { pH->first = pNew; }
  21087. pHead->prev = pNew;
  21088. }else{
  21089. pNew->next = pH->first;
  21090. if( pH->first ){ pH->first->prev = pNew; }
  21091. pNew->prev = 0;
  21092. pH->first = pNew;
  21093. }
  21094. }
  21095. /* Resize the hash table so that it cantains "new_size" buckets.
  21096. **
  21097. ** The hash table might fail to resize if sqlite3_malloc() fails or
  21098. ** if the new size is the same as the prior size.
  21099. ** Return TRUE if the resize occurs and false if not.
  21100. */
  21101. static int rehash(Hash *pH, unsigned int new_size){
  21102. struct _ht *new_ht; /* The new hash table */
  21103. HashElem *elem, *next_elem; /* For looping over existing elements */
  21104. #if SQLITE_MALLOC_SOFT_LIMIT>0
  21105. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  21106. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  21107. }
  21108. if( new_size==pH->htsize ) return 0;
  21109. #endif
  21110. /* The inability to allocates space for a larger hash table is
  21111. ** a performance hit but it is not a fatal error. So mark the
  21112. ** allocation as a benign.
  21113. */
  21114. sqlite3BeginBenignMalloc();
  21115. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  21116. sqlite3EndBenignMalloc();
  21117. if( new_ht==0 ) return 0;
  21118. sqlite3_free(pH->ht);
  21119. pH->ht = new_ht;
  21120. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  21121. memset(new_ht, 0, new_size*sizeof(struct _ht));
  21122. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  21123. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  21124. next_elem = elem->next;
  21125. insertElement(pH, &new_ht[h], elem);
  21126. }
  21127. return 1;
  21128. }
  21129. /* This function (for internal use only) locates an element in an
  21130. ** hash table that matches the given key. The hash for this key has
  21131. ** already been computed and is passed as the 4th parameter.
  21132. */
  21133. static HashElem *findElementGivenHash(
  21134. const Hash *pH, /* The pH to be searched */
  21135. const char *pKey, /* The key we are searching for */
  21136. int nKey, /* Bytes in key (not counting zero terminator) */
  21137. unsigned int h /* The hash for this key. */
  21138. ){
  21139. HashElem *elem; /* Used to loop thru the element list */
  21140. int count; /* Number of elements left to test */
  21141. if( pH->ht ){
  21142. struct _ht *pEntry = &pH->ht[h];
  21143. elem = pEntry->chain;
  21144. count = pEntry->count;
  21145. }else{
  21146. elem = pH->first;
  21147. count = pH->count;
  21148. }
  21149. while( count-- && ALWAYS(elem) ){
  21150. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  21151. return elem;
  21152. }
  21153. elem = elem->next;
  21154. }
  21155. return 0;
  21156. }
  21157. /* Remove a single entry from the hash table given a pointer to that
  21158. ** element and a hash on the element's key.
  21159. */
  21160. static void removeElementGivenHash(
  21161. Hash *pH, /* The pH containing "elem" */
  21162. HashElem* elem, /* The element to be removed from the pH */
  21163. unsigned int h /* Hash value for the element */
  21164. ){
  21165. struct _ht *pEntry;
  21166. if( elem->prev ){
  21167. elem->prev->next = elem->next;
  21168. }else{
  21169. pH->first = elem->next;
  21170. }
  21171. if( elem->next ){
  21172. elem->next->prev = elem->prev;
  21173. }
  21174. if( pH->ht ){
  21175. pEntry = &pH->ht[h];
  21176. if( pEntry->chain==elem ){
  21177. pEntry->chain = elem->next;
  21178. }
  21179. pEntry->count--;
  21180. assert( pEntry->count>=0 );
  21181. }
  21182. sqlite3_free( elem );
  21183. pH->count--;
  21184. if( pH->count<=0 ){
  21185. assert( pH->first==0 );
  21186. assert( pH->count==0 );
  21187. sqlite3HashClear(pH);
  21188. }
  21189. }
  21190. /* Attempt to locate an element of the hash table pH with a key
  21191. ** that matches pKey,nKey. Return the data for this element if it is
  21192. ** found, or NULL if there is no match.
  21193. */
  21194. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  21195. HashElem *elem; /* The element that matches key */
  21196. unsigned int h; /* A hash on key */
  21197. assert( pH!=0 );
  21198. assert( pKey!=0 );
  21199. assert( nKey>=0 );
  21200. if( pH->ht ){
  21201. h = strHash(pKey, nKey) % pH->htsize;
  21202. }else{
  21203. h = 0;
  21204. }
  21205. elem = findElementGivenHash(pH, pKey, nKey, h);
  21206. return elem ? elem->data : 0;
  21207. }
  21208. /* Insert an element into the hash table pH. The key is pKey,nKey
  21209. ** and the data is "data".
  21210. **
  21211. ** If no element exists with a matching key, then a new
  21212. ** element is created and NULL is returned.
  21213. **
  21214. ** If another element already exists with the same key, then the
  21215. ** new data replaces the old data and the old data is returned.
  21216. ** The key is not copied in this instance. If a malloc fails, then
  21217. ** the new data is returned and the hash table is unchanged.
  21218. **
  21219. ** If the "data" parameter to this function is NULL, then the
  21220. ** element corresponding to "key" is removed from the hash table.
  21221. */
  21222. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  21223. unsigned int h; /* the hash of the key modulo hash table size */
  21224. HashElem *elem; /* Used to loop thru the element list */
  21225. HashElem *new_elem; /* New element added to the pH */
  21226. assert( pH!=0 );
  21227. assert( pKey!=0 );
  21228. assert( nKey>=0 );
  21229. if( pH->htsize ){
  21230. h = strHash(pKey, nKey) % pH->htsize;
  21231. }else{
  21232. h = 0;
  21233. }
  21234. elem = findElementGivenHash(pH,pKey,nKey,h);
  21235. if( elem ){
  21236. void *old_data = elem->data;
  21237. if( data==0 ){
  21238. removeElementGivenHash(pH,elem,h);
  21239. }else{
  21240. elem->data = data;
  21241. elem->pKey = pKey;
  21242. assert(nKey==elem->nKey);
  21243. }
  21244. return old_data;
  21245. }
  21246. if( data==0 ) return 0;
  21247. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  21248. if( new_elem==0 ) return data;
  21249. new_elem->pKey = pKey;
  21250. new_elem->nKey = nKey;
  21251. new_elem->data = data;
  21252. pH->count++;
  21253. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  21254. if( rehash(pH, pH->count*2) ){
  21255. assert( pH->htsize>0 );
  21256. h = strHash(pKey, nKey) % pH->htsize;
  21257. }
  21258. }
  21259. if( pH->ht ){
  21260. insertElement(pH, &pH->ht[h], new_elem);
  21261. }else{
  21262. insertElement(pH, 0, new_elem);
  21263. }
  21264. return 0;
  21265. }
  21266. /************** End of hash.c ************************************************/
  21267. /************** Begin file opcodes.c *****************************************/
  21268. /* Automatically generated. Do not edit */
  21269. /* See the mkopcodec.awk script for details. */
  21270. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  21271. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  21272. static const char *const azName[] = { "?",
  21273. /* 1 */ "Goto",
  21274. /* 2 */ "Gosub",
  21275. /* 3 */ "Return",
  21276. /* 4 */ "Yield",
  21277. /* 5 */ "HaltIfNull",
  21278. /* 6 */ "Halt",
  21279. /* 7 */ "Integer",
  21280. /* 8 */ "Int64",
  21281. /* 9 */ "String",
  21282. /* 10 */ "Null",
  21283. /* 11 */ "Blob",
  21284. /* 12 */ "Variable",
  21285. /* 13 */ "Move",
  21286. /* 14 */ "Copy",
  21287. /* 15 */ "SCopy",
  21288. /* 16 */ "ResultRow",
  21289. /* 17 */ "CollSeq",
  21290. /* 18 */ "Function",
  21291. /* 19 */ "Not",
  21292. /* 20 */ "AddImm",
  21293. /* 21 */ "MustBeInt",
  21294. /* 22 */ "RealAffinity",
  21295. /* 23 */ "Permutation",
  21296. /* 24 */ "Compare",
  21297. /* 25 */ "Jump",
  21298. /* 26 */ "Once",
  21299. /* 27 */ "If",
  21300. /* 28 */ "IfNot",
  21301. /* 29 */ "Column",
  21302. /* 30 */ "Affinity",
  21303. /* 31 */ "MakeRecord",
  21304. /* 32 */ "Count",
  21305. /* 33 */ "Savepoint",
  21306. /* 34 */ "AutoCommit",
  21307. /* 35 */ "Transaction",
  21308. /* 36 */ "ReadCookie",
  21309. /* 37 */ "SetCookie",
  21310. /* 38 */ "VerifyCookie",
  21311. /* 39 */ "OpenRead",
  21312. /* 40 */ "OpenWrite",
  21313. /* 41 */ "OpenAutoindex",
  21314. /* 42 */ "OpenEphemeral",
  21315. /* 43 */ "SorterOpen",
  21316. /* 44 */ "OpenPseudo",
  21317. /* 45 */ "Close",
  21318. /* 46 */ "SeekLt",
  21319. /* 47 */ "SeekLe",
  21320. /* 48 */ "SeekGe",
  21321. /* 49 */ "SeekGt",
  21322. /* 50 */ "Seek",
  21323. /* 51 */ "NotFound",
  21324. /* 52 */ "Found",
  21325. /* 53 */ "IsUnique",
  21326. /* 54 */ "NotExists",
  21327. /* 55 */ "Sequence",
  21328. /* 56 */ "NewRowid",
  21329. /* 57 */ "Insert",
  21330. /* 58 */ "InsertInt",
  21331. /* 59 */ "Delete",
  21332. /* 60 */ "ResetCount",
  21333. /* 61 */ "SorterCompare",
  21334. /* 62 */ "SorterData",
  21335. /* 63 */ "RowKey",
  21336. /* 64 */ "RowData",
  21337. /* 65 */ "Rowid",
  21338. /* 66 */ "NullRow",
  21339. /* 67 */ "Last",
  21340. /* 68 */ "Or",
  21341. /* 69 */ "And",
  21342. /* 70 */ "SorterSort",
  21343. /* 71 */ "Sort",
  21344. /* 72 */ "Rewind",
  21345. /* 73 */ "IsNull",
  21346. /* 74 */ "NotNull",
  21347. /* 75 */ "Ne",
  21348. /* 76 */ "Eq",
  21349. /* 77 */ "Gt",
  21350. /* 78 */ "Le",
  21351. /* 79 */ "Lt",
  21352. /* 80 */ "Ge",
  21353. /* 81 */ "SorterNext",
  21354. /* 82 */ "BitAnd",
  21355. /* 83 */ "BitOr",
  21356. /* 84 */ "ShiftLeft",
  21357. /* 85 */ "ShiftRight",
  21358. /* 86 */ "Add",
  21359. /* 87 */ "Subtract",
  21360. /* 88 */ "Multiply",
  21361. /* 89 */ "Divide",
  21362. /* 90 */ "Remainder",
  21363. /* 91 */ "Concat",
  21364. /* 92 */ "Prev",
  21365. /* 93 */ "BitNot",
  21366. /* 94 */ "String8",
  21367. /* 95 */ "Next",
  21368. /* 96 */ "SorterInsert",
  21369. /* 97 */ "IdxInsert",
  21370. /* 98 */ "IdxDelete",
  21371. /* 99 */ "IdxRowid",
  21372. /* 100 */ "IdxLT",
  21373. /* 101 */ "IdxGE",
  21374. /* 102 */ "Destroy",
  21375. /* 103 */ "Clear",
  21376. /* 104 */ "CreateIndex",
  21377. /* 105 */ "CreateTable",
  21378. /* 106 */ "ParseSchema",
  21379. /* 107 */ "LoadAnalysis",
  21380. /* 108 */ "DropTable",
  21381. /* 109 */ "DropIndex",
  21382. /* 110 */ "DropTrigger",
  21383. /* 111 */ "IntegrityCk",
  21384. /* 112 */ "RowSetAdd",
  21385. /* 113 */ "RowSetRead",
  21386. /* 114 */ "RowSetTest",
  21387. /* 115 */ "Program",
  21388. /* 116 */ "Param",
  21389. /* 117 */ "FkCounter",
  21390. /* 118 */ "FkIfZero",
  21391. /* 119 */ "MemMax",
  21392. /* 120 */ "IfPos",
  21393. /* 121 */ "IfNeg",
  21394. /* 122 */ "IfZero",
  21395. /* 123 */ "AggStep",
  21396. /* 124 */ "AggFinal",
  21397. /* 125 */ "Checkpoint",
  21398. /* 126 */ "JournalMode",
  21399. /* 127 */ "Vacuum",
  21400. /* 128 */ "IncrVacuum",
  21401. /* 129 */ "Expire",
  21402. /* 130 */ "Real",
  21403. /* 131 */ "TableLock",
  21404. /* 132 */ "VBegin",
  21405. /* 133 */ "VCreate",
  21406. /* 134 */ "VDestroy",
  21407. /* 135 */ "VOpen",
  21408. /* 136 */ "VFilter",
  21409. /* 137 */ "VColumn",
  21410. /* 138 */ "VNext",
  21411. /* 139 */ "VRename",
  21412. /* 140 */ "VUpdate",
  21413. /* 141 */ "ToText",
  21414. /* 142 */ "ToBlob",
  21415. /* 143 */ "ToNumeric",
  21416. /* 144 */ "ToInt",
  21417. /* 145 */ "ToReal",
  21418. /* 146 */ "Pagecount",
  21419. /* 147 */ "MaxPgcnt",
  21420. /* 148 */ "Trace",
  21421. /* 149 */ "Noop",
  21422. /* 150 */ "Explain",
  21423. };
  21424. return azName[i];
  21425. }
  21426. #endif
  21427. /************** End of opcodes.c *********************************************/
  21428. /************** Begin file os_os2.c ******************************************/
  21429. /*
  21430. ** 2006 Feb 14
  21431. **
  21432. ** The author disclaims copyright to this source code. In place of
  21433. ** a legal notice, here is a blessing:
  21434. **
  21435. ** May you do good and not evil.
  21436. ** May you find forgiveness for yourself and forgive others.
  21437. ** May you share freely, never taking more than you give.
  21438. **
  21439. ******************************************************************************
  21440. **
  21441. ** This file contains code that is specific to OS/2.
  21442. */
  21443. #if SQLITE_OS_OS2
  21444. /*
  21445. ** A Note About Memory Allocation:
  21446. **
  21447. ** This driver uses malloc()/free() directly rather than going through
  21448. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  21449. ** are designed for use on embedded systems where memory is scarce and
  21450. ** malloc failures happen frequently. OS/2 does not typically run on
  21451. ** embedded systems, and when it does the developers normally have bigger
  21452. ** problems to worry about than running out of memory. So there is not
  21453. ** a compelling need to use the wrappers.
  21454. **
  21455. ** But there is a good reason to not use the wrappers. If we use the
  21456. ** wrappers then we will get simulated malloc() failures within this
  21457. ** driver. And that causes all kinds of problems for our tests. We
  21458. ** could enhance SQLite to deal with simulated malloc failures within
  21459. ** the OS driver, but the code to deal with those failure would not
  21460. ** be exercised on Linux (which does not need to malloc() in the driver)
  21461. ** and so we would have difficulty writing coverage tests for that
  21462. ** code. Better to leave the code out, we think.
  21463. **
  21464. ** The point of this discussion is as follows: When creating a new
  21465. ** OS layer for an embedded system, if you use this file as an example,
  21466. ** avoid the use of malloc()/free(). Those routines work ok on OS/2
  21467. ** desktops but not so well in embedded systems.
  21468. */
  21469. /*
  21470. ** Macros used to determine whether or not to use threads.
  21471. */
  21472. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
  21473. # define SQLITE_OS2_THREADS 1
  21474. #endif
  21475. /*
  21476. ** Include code that is common to all os_*.c files
  21477. */
  21478. /************** Include os_common.h in the middle of os_os2.c ****************/
  21479. /************** Begin file os_common.h ***************************************/
  21480. /*
  21481. ** 2004 May 22
  21482. **
  21483. ** The author disclaims copyright to this source code. In place of
  21484. ** a legal notice, here is a blessing:
  21485. **
  21486. ** May you do good and not evil.
  21487. ** May you find forgiveness for yourself and forgive others.
  21488. ** May you share freely, never taking more than you give.
  21489. **
  21490. ******************************************************************************
  21491. **
  21492. ** This file contains macros and a little bit of code that is common to
  21493. ** all of the platform-specific files (os_*.c) and is #included into those
  21494. ** files.
  21495. **
  21496. ** This file should be #included by the os_*.c files only. It is not a
  21497. ** general purpose header file.
  21498. */
  21499. #ifndef _OS_COMMON_H_
  21500. #define _OS_COMMON_H_
  21501. /*
  21502. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  21503. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  21504. ** switch. The following code should catch this problem at compile-time.
  21505. */
  21506. #ifdef MEMORY_DEBUG
  21507. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  21508. #endif
  21509. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  21510. # ifndef SQLITE_DEBUG_OS_TRACE
  21511. # define SQLITE_DEBUG_OS_TRACE 0
  21512. # endif
  21513. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  21514. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  21515. #else
  21516. # define OSTRACE(X)
  21517. #endif
  21518. /*
  21519. ** Macros for performance tracing. Normally turned off. Only works
  21520. ** on i486 hardware.
  21521. */
  21522. #ifdef SQLITE_PERFORMANCE_TRACE
  21523. /*
  21524. ** hwtime.h contains inline assembler code for implementing
  21525. ** high-performance timing routines.
  21526. */
  21527. /************** Include hwtime.h in the middle of os_common.h ****************/
  21528. /************** Begin file hwtime.h ******************************************/
  21529. /*
  21530. ** 2008 May 27
  21531. **
  21532. ** The author disclaims copyright to this source code. In place of
  21533. ** a legal notice, here is a blessing:
  21534. **
  21535. ** May you do good and not evil.
  21536. ** May you find forgiveness for yourself and forgive others.
  21537. ** May you share freely, never taking more than you give.
  21538. **
  21539. ******************************************************************************
  21540. **
  21541. ** This file contains inline asm code for retrieving "high-performance"
  21542. ** counters for x86 class CPUs.
  21543. */
  21544. #ifndef _HWTIME_H_
  21545. #define _HWTIME_H_
  21546. /*
  21547. ** The following routine only works on pentium-class (or newer) processors.
  21548. ** It uses the RDTSC opcode to read the cycle count value out of the
  21549. ** processor and returns that value. This can be used for high-res
  21550. ** profiling.
  21551. */
  21552. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  21553. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  21554. #if defined(__GNUC__)
  21555. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21556. unsigned int lo, hi;
  21557. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  21558. return (sqlite_uint64)hi << 32 | lo;
  21559. }
  21560. #elif defined(_MSC_VER)
  21561. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  21562. __asm {
  21563. rdtsc
  21564. ret ; return value at EDX:EAX
  21565. }
  21566. }
  21567. #endif
  21568. #elif (defined(__GNUC__) && defined(__x86_64__))
  21569. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21570. unsigned long val;
  21571. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  21572. return val;
  21573. }
  21574. #elif (defined(__GNUC__) && defined(__ppc__))
  21575. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  21576. unsigned long long retval;
  21577. unsigned long junk;
  21578. __asm__ __volatile__ ("\n\
  21579. 1: mftbu %1\n\
  21580. mftb %L0\n\
  21581. mftbu %0\n\
  21582. cmpw %0,%1\n\
  21583. bne 1b"
  21584. : "=r" (retval), "=r" (junk));
  21585. return retval;
  21586. }
  21587. #else
  21588. #error Need implementation of sqlite3Hwtime() for your platform.
  21589. /*
  21590. ** To compile without implementing sqlite3Hwtime() for your platform,
  21591. ** you can remove the above #error and use the following
  21592. ** stub function. You will lose timing support for many
  21593. ** of the debugging and testing utilities, but it should at
  21594. ** least compile and run.
  21595. */
  21596. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  21597. #endif
  21598. #endif /* !defined(_HWTIME_H_) */
  21599. /************** End of hwtime.h **********************************************/
  21600. /************** Continuing where we left off in os_common.h ******************/
  21601. static sqlite_uint64 g_start;
  21602. static sqlite_uint64 g_elapsed;
  21603. #define TIMER_START g_start=sqlite3Hwtime()
  21604. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  21605. #define TIMER_ELAPSED g_elapsed
  21606. #else
  21607. #define TIMER_START
  21608. #define TIMER_END
  21609. #define TIMER_ELAPSED ((sqlite_uint64)0)
  21610. #endif
  21611. /*
  21612. ** If we compile with the SQLITE_TEST macro set, then the following block
  21613. ** of code will give us the ability to simulate a disk I/O error. This
  21614. ** is used for testing the I/O recovery logic.
  21615. */
  21616. #ifdef SQLITE_TEST
  21617. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  21618. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  21619. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  21620. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  21621. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  21622. SQLITE_API int sqlite3_diskfull_pending = 0;
  21623. SQLITE_API int sqlite3_diskfull = 0;
  21624. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  21625. #define SimulateIOError(CODE) \
  21626. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  21627. || sqlite3_io_error_pending-- == 1 ) \
  21628. { local_ioerr(); CODE; }
  21629. static void local_ioerr(){
  21630. IOTRACE(("IOERR\n"));
  21631. sqlite3_io_error_hit++;
  21632. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  21633. }
  21634. #define SimulateDiskfullError(CODE) \
  21635. if( sqlite3_diskfull_pending ){ \
  21636. if( sqlite3_diskfull_pending == 1 ){ \
  21637. local_ioerr(); \
  21638. sqlite3_diskfull = 1; \
  21639. sqlite3_io_error_hit = 1; \
  21640. CODE; \
  21641. }else{ \
  21642. sqlite3_diskfull_pending--; \
  21643. } \
  21644. }
  21645. #else
  21646. #define SimulateIOErrorBenign(X)
  21647. #define SimulateIOError(A)
  21648. #define SimulateDiskfullError(A)
  21649. #endif
  21650. /*
  21651. ** When testing, keep a count of the number of open files.
  21652. */
  21653. #ifdef SQLITE_TEST
  21654. SQLITE_API int sqlite3_open_file_count = 0;
  21655. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  21656. #else
  21657. #define OpenCounter(X)
  21658. #endif
  21659. #endif /* !defined(_OS_COMMON_H_) */
  21660. /************** End of os_common.h *******************************************/
  21661. /************** Continuing where we left off in os_os2.c *********************/
  21662. /* Forward references */
  21663. typedef struct os2File os2File; /* The file structure */
  21664. typedef struct os2ShmNode os2ShmNode; /* A shared descritive memory node */
  21665. typedef struct os2ShmLink os2ShmLink; /* A connection to shared-memory */
  21666. /*
  21667. ** The os2File structure is subclass of sqlite3_file specific for the OS/2
  21668. ** protability layer.
  21669. */
  21670. struct os2File {
  21671. const sqlite3_io_methods *pMethod; /* Always the first entry */
  21672. HFILE h; /* Handle for accessing the file */
  21673. int flags; /* Flags provided to os2Open() */
  21674. int locktype; /* Type of lock currently held on this file */
  21675. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  21676. char *zFullPathCp; /* Full path name of this file */
  21677. os2ShmLink *pShmLink; /* Instance of shared memory on this file */
  21678. };
  21679. #define LOCK_TIMEOUT 10L /* the default locking timeout */
  21680. /*
  21681. ** Missing from some versions of the OS/2 toolkit -
  21682. ** used to allocate from high memory if possible
  21683. */
  21684. #ifndef OBJ_ANY
  21685. # define OBJ_ANY 0x00000400
  21686. #endif
  21687. /*****************************************************************************
  21688. ** The next group of routines implement the I/O methods specified
  21689. ** by the sqlite3_io_methods object.
  21690. ******************************************************************************/
  21691. /*
  21692. ** Close a file.
  21693. */
  21694. static int os2Close( sqlite3_file *id ){
  21695. APIRET rc;
  21696. os2File *pFile = (os2File*)id;
  21697. assert( id!=0 );
  21698. OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
  21699. rc = DosClose( pFile->h );
  21700. if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
  21701. DosForceDelete( (PSZ)pFile->zFullPathCp );
  21702. free( pFile->zFullPathCp );
  21703. pFile->zFullPathCp = NULL;
  21704. pFile->locktype = NO_LOCK;
  21705. pFile->h = (HFILE)-1;
  21706. pFile->flags = 0;
  21707. OpenCounter( -1 );
  21708. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  21709. }
  21710. /*
  21711. ** Read data from a file into a buffer. Return SQLITE_OK if all
  21712. ** bytes were read successfully and SQLITE_IOERR if anything goes
  21713. ** wrong.
  21714. */
  21715. static int os2Read(
  21716. sqlite3_file *id, /* File to read from */
  21717. void *pBuf, /* Write content into this buffer */
  21718. int amt, /* Number of bytes to read */
  21719. sqlite3_int64 offset /* Begin reading at this offset */
  21720. ){
  21721. ULONG fileLocation = 0L;
  21722. ULONG got;
  21723. os2File *pFile = (os2File*)id;
  21724. assert( id!=0 );
  21725. SimulateIOError( return SQLITE_IOERR_READ );
  21726. OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
  21727. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  21728. return SQLITE_IOERR;
  21729. }
  21730. if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
  21731. return SQLITE_IOERR_READ;
  21732. }
  21733. if( got == (ULONG)amt )
  21734. return SQLITE_OK;
  21735. else {
  21736. /* Unread portions of the input buffer must be zero-filled */
  21737. memset(&((char*)pBuf)[got], 0, amt-got);
  21738. return SQLITE_IOERR_SHORT_READ;
  21739. }
  21740. }
  21741. /*
  21742. ** Write data from a buffer into a file. Return SQLITE_OK on success
  21743. ** or some other error code on failure.
  21744. */
  21745. static int os2Write(
  21746. sqlite3_file *id, /* File to write into */
  21747. const void *pBuf, /* The bytes to be written */
  21748. int amt, /* Number of bytes to write */
  21749. sqlite3_int64 offset /* Offset into the file to begin writing at */
  21750. ){
  21751. ULONG fileLocation = 0L;
  21752. APIRET rc = NO_ERROR;
  21753. ULONG wrote;
  21754. os2File *pFile = (os2File*)id;
  21755. assert( id!=0 );
  21756. SimulateIOError( return SQLITE_IOERR_WRITE );
  21757. SimulateDiskfullError( return SQLITE_FULL );
  21758. OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
  21759. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  21760. return SQLITE_IOERR;
  21761. }
  21762. assert( amt>0 );
  21763. while( amt > 0 &&
  21764. ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
  21765. wrote > 0
  21766. ){
  21767. amt -= wrote;
  21768. pBuf = &((char*)pBuf)[wrote];
  21769. }
  21770. return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
  21771. }
  21772. /*
  21773. ** Truncate an open file to a specified size
  21774. */
  21775. static int os2Truncate( sqlite3_file *id, i64 nByte ){
  21776. APIRET rc;
  21777. os2File *pFile = (os2File*)id;
  21778. assert( id!=0 );
  21779. OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
  21780. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  21781. /* If the user has configured a chunk-size for this file, truncate the
  21782. ** file so that it consists of an integer number of chunks (i.e. the
  21783. ** actual file size after the operation may be larger than the requested
  21784. ** size).
  21785. */
  21786. if( pFile->szChunk ){
  21787. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  21788. }
  21789. rc = DosSetFileSize( pFile->h, nByte );
  21790. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
  21791. }
  21792. #ifdef SQLITE_TEST
  21793. /*
  21794. ** Count the number of fullsyncs and normal syncs. This is used to test
  21795. ** that syncs and fullsyncs are occuring at the right times.
  21796. */
  21797. SQLITE_API int sqlite3_sync_count = 0;
  21798. SQLITE_API int sqlite3_fullsync_count = 0;
  21799. #endif
  21800. /*
  21801. ** Make sure all writes to a particular file are committed to disk.
  21802. */
  21803. static int os2Sync( sqlite3_file *id, int flags ){
  21804. os2File *pFile = (os2File*)id;
  21805. OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
  21806. #ifdef SQLITE_TEST
  21807. if( flags & SQLITE_SYNC_FULL){
  21808. sqlite3_fullsync_count++;
  21809. }
  21810. sqlite3_sync_count++;
  21811. #endif
  21812. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  21813. ** no-op
  21814. */
  21815. #ifdef SQLITE_NO_SYNC
  21816. UNUSED_PARAMETER(pFile);
  21817. return SQLITE_OK;
  21818. #else
  21819. return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  21820. #endif
  21821. }
  21822. /*
  21823. ** Determine the current size of a file in bytes
  21824. */
  21825. static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
  21826. APIRET rc = NO_ERROR;
  21827. FILESTATUS3 fsts3FileInfo;
  21828. memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
  21829. assert( id!=0 );
  21830. SimulateIOError( return SQLITE_IOERR_FSTAT );
  21831. rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
  21832. if( rc == NO_ERROR ){
  21833. *pSize = fsts3FileInfo.cbFile;
  21834. return SQLITE_OK;
  21835. }else{
  21836. return SQLITE_IOERR_FSTAT;
  21837. }
  21838. }
  21839. /*
  21840. ** Acquire a reader lock.
  21841. */
  21842. static int getReadLock( os2File *pFile ){
  21843. FILELOCK LockArea,
  21844. UnlockArea;
  21845. APIRET res;
  21846. memset(&LockArea, 0, sizeof(LockArea));
  21847. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21848. LockArea.lOffset = SHARED_FIRST;
  21849. LockArea.lRange = SHARED_SIZE;
  21850. UnlockArea.lOffset = 0L;
  21851. UnlockArea.lRange = 0L;
  21852. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  21853. OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
  21854. return res;
  21855. }
  21856. /*
  21857. ** Undo a readlock
  21858. */
  21859. static int unlockReadLock( os2File *id ){
  21860. FILELOCK LockArea,
  21861. UnlockArea;
  21862. APIRET res;
  21863. memset(&LockArea, 0, sizeof(LockArea));
  21864. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21865. LockArea.lOffset = 0L;
  21866. LockArea.lRange = 0L;
  21867. UnlockArea.lOffset = SHARED_FIRST;
  21868. UnlockArea.lRange = SHARED_SIZE;
  21869. res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  21870. OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
  21871. return res;
  21872. }
  21873. /*
  21874. ** Lock the file with the lock specified by parameter locktype - one
  21875. ** of the following:
  21876. **
  21877. ** (1) SHARED_LOCK
  21878. ** (2) RESERVED_LOCK
  21879. ** (3) PENDING_LOCK
  21880. ** (4) EXCLUSIVE_LOCK
  21881. **
  21882. ** Sometimes when requesting one lock state, additional lock states
  21883. ** are inserted in between. The locking might fail on one of the later
  21884. ** transitions leaving the lock state different from what it started but
  21885. ** still short of its goal. The following chart shows the allowed
  21886. ** transitions and the inserted intermediate states:
  21887. **
  21888. ** UNLOCKED -> SHARED
  21889. ** SHARED -> RESERVED
  21890. ** SHARED -> (PENDING) -> EXCLUSIVE
  21891. ** RESERVED -> (PENDING) -> EXCLUSIVE
  21892. ** PENDING -> EXCLUSIVE
  21893. **
  21894. ** This routine will only increase a lock. The os2Unlock() routine
  21895. ** erases all locks at once and returns us immediately to locking level 0.
  21896. ** It is not possible to lower the locking level one step at a time. You
  21897. ** must go straight to locking level 0.
  21898. */
  21899. static int os2Lock( sqlite3_file *id, int locktype ){
  21900. int rc = SQLITE_OK; /* Return code from subroutines */
  21901. APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
  21902. int newLocktype; /* Set pFile->locktype to this value before exiting */
  21903. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  21904. FILELOCK LockArea,
  21905. UnlockArea;
  21906. os2File *pFile = (os2File*)id;
  21907. memset(&LockArea, 0, sizeof(LockArea));
  21908. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21909. assert( pFile!=0 );
  21910. OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
  21911. /* If there is already a lock of this type or more restrictive on the
  21912. ** os2File, do nothing. Don't use the end_lock: exit path, as
  21913. ** sqlite3_mutex_enter() hasn't been called yet.
  21914. */
  21915. if( pFile->locktype>=locktype ){
  21916. OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
  21917. return SQLITE_OK;
  21918. }
  21919. /* Make sure the locking sequence is correct
  21920. */
  21921. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  21922. assert( locktype!=PENDING_LOCK );
  21923. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  21924. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  21925. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  21926. ** the PENDING_LOCK byte is temporary.
  21927. */
  21928. newLocktype = pFile->locktype;
  21929. if( pFile->locktype==NO_LOCK
  21930. || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  21931. ){
  21932. LockArea.lOffset = PENDING_BYTE;
  21933. LockArea.lRange = 1L;
  21934. UnlockArea.lOffset = 0L;
  21935. UnlockArea.lRange = 0L;
  21936. /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
  21937. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
  21938. if( res == NO_ERROR ){
  21939. gotPendingLock = 1;
  21940. OSTRACE(( "LOCK %d pending lock boolean set. res=%d\n", pFile->h, res ));
  21941. }
  21942. }
  21943. /* Acquire a shared lock
  21944. */
  21945. if( locktype==SHARED_LOCK && res == NO_ERROR ){
  21946. assert( pFile->locktype==NO_LOCK );
  21947. res = getReadLock(pFile);
  21948. if( res == NO_ERROR ){
  21949. newLocktype = SHARED_LOCK;
  21950. }
  21951. OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
  21952. }
  21953. /* Acquire a RESERVED lock
  21954. */
  21955. if( locktype==RESERVED_LOCK && res == NO_ERROR ){
  21956. assert( pFile->locktype==SHARED_LOCK );
  21957. LockArea.lOffset = RESERVED_BYTE;
  21958. LockArea.lRange = 1L;
  21959. UnlockArea.lOffset = 0L;
  21960. UnlockArea.lRange = 0L;
  21961. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21962. if( res == NO_ERROR ){
  21963. newLocktype = RESERVED_LOCK;
  21964. }
  21965. OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
  21966. }
  21967. /* Acquire a PENDING lock
  21968. */
  21969. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  21970. newLocktype = PENDING_LOCK;
  21971. gotPendingLock = 0;
  21972. OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
  21973. pFile->h ));
  21974. }
  21975. /* Acquire an EXCLUSIVE lock
  21976. */
  21977. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  21978. assert( pFile->locktype>=SHARED_LOCK );
  21979. res = unlockReadLock(pFile);
  21980. OSTRACE(( "unreadlock = %d\n", res ));
  21981. LockArea.lOffset = SHARED_FIRST;
  21982. LockArea.lRange = SHARED_SIZE;
  21983. UnlockArea.lOffset = 0L;
  21984. UnlockArea.lRange = 0L;
  21985. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21986. if( res == NO_ERROR ){
  21987. newLocktype = EXCLUSIVE_LOCK;
  21988. }else{
  21989. OSTRACE(( "OS/2 error-code = %d\n", res ));
  21990. getReadLock(pFile);
  21991. }
  21992. OSTRACE(( "LOCK %d acquire exclusive lock. res=%d\n", pFile->h, res ));
  21993. }
  21994. /* If we are holding a PENDING lock that ought to be released, then
  21995. ** release it now.
  21996. */
  21997. if( gotPendingLock && locktype==SHARED_LOCK ){
  21998. int r;
  21999. LockArea.lOffset = 0L;
  22000. LockArea.lRange = 0L;
  22001. UnlockArea.lOffset = PENDING_BYTE;
  22002. UnlockArea.lRange = 1L;
  22003. r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  22004. OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
  22005. }
  22006. /* Update the state of the lock has held in the file descriptor then
  22007. ** return the appropriate result code.
  22008. */
  22009. if( res == NO_ERROR ){
  22010. rc = SQLITE_OK;
  22011. }else{
  22012. OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  22013. locktype, newLocktype ));
  22014. rc = SQLITE_BUSY;
  22015. }
  22016. pFile->locktype = newLocktype;
  22017. OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
  22018. return rc;
  22019. }
  22020. /*
  22021. ** This routine checks if there is a RESERVED lock held on the specified
  22022. ** file by this or any other process. If such a lock is held, return
  22023. ** non-zero, otherwise zero.
  22024. */
  22025. static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
  22026. int r = 0;
  22027. os2File *pFile = (os2File*)id;
  22028. assert( pFile!=0 );
  22029. if( pFile->locktype>=RESERVED_LOCK ){
  22030. r = 1;
  22031. OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
  22032. }else{
  22033. FILELOCK LockArea,
  22034. UnlockArea;
  22035. APIRET rc = NO_ERROR;
  22036. memset(&LockArea, 0, sizeof(LockArea));
  22037. memset(&UnlockArea, 0, sizeof(UnlockArea));
  22038. LockArea.lOffset = RESERVED_BYTE;
  22039. LockArea.lRange = 1L;
  22040. UnlockArea.lOffset = 0L;
  22041. UnlockArea.lRange = 0L;
  22042. rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  22043. OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
  22044. if( rc == NO_ERROR ){
  22045. APIRET rcu = NO_ERROR; /* return code for unlocking */
  22046. LockArea.lOffset = 0L;
  22047. LockArea.lRange = 0L;
  22048. UnlockArea.lOffset = RESERVED_BYTE;
  22049. UnlockArea.lRange = 1L;
  22050. rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  22051. OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
  22052. }
  22053. r = !(rc == NO_ERROR);
  22054. OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
  22055. }
  22056. *pOut = r;
  22057. return SQLITE_OK;
  22058. }
  22059. /*
  22060. ** Lower the locking level on file descriptor id to locktype. locktype
  22061. ** must be either NO_LOCK or SHARED_LOCK.
  22062. **
  22063. ** If the locking level of the file descriptor is already at or below
  22064. ** the requested locking level, this routine is a no-op.
  22065. **
  22066. ** It is not possible for this routine to fail if the second argument
  22067. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  22068. ** might return SQLITE_IOERR;
  22069. */
  22070. static int os2Unlock( sqlite3_file *id, int locktype ){
  22071. int type;
  22072. os2File *pFile = (os2File*)id;
  22073. APIRET rc = SQLITE_OK;
  22074. APIRET res = NO_ERROR;
  22075. FILELOCK LockArea,
  22076. UnlockArea;
  22077. memset(&LockArea, 0, sizeof(LockArea));
  22078. memset(&UnlockArea, 0, sizeof(UnlockArea));
  22079. assert( pFile!=0 );
  22080. assert( locktype<=SHARED_LOCK );
  22081. OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
  22082. type = pFile->locktype;
  22083. if( type>=EXCLUSIVE_LOCK ){
  22084. LockArea.lOffset = 0L;
  22085. LockArea.lRange = 0L;
  22086. UnlockArea.lOffset = SHARED_FIRST;
  22087. UnlockArea.lRange = SHARED_SIZE;
  22088. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  22089. OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
  22090. if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
  22091. /* This should never happen. We should always be able to
  22092. ** reacquire the read lock */
  22093. OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
  22094. rc = SQLITE_IOERR_UNLOCK;
  22095. }
  22096. }
  22097. if( type>=RESERVED_LOCK ){
  22098. LockArea.lOffset = 0L;
  22099. LockArea.lRange = 0L;
  22100. UnlockArea.lOffset = RESERVED_BYTE;
  22101. UnlockArea.lRange = 1L;
  22102. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  22103. OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
  22104. }
  22105. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  22106. res = unlockReadLock(pFile);
  22107. OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
  22108. pFile->h, type, locktype, res ));
  22109. }
  22110. if( type>=PENDING_LOCK ){
  22111. LockArea.lOffset = 0L;
  22112. LockArea.lRange = 0L;
  22113. UnlockArea.lOffset = PENDING_BYTE;
  22114. UnlockArea.lRange = 1L;
  22115. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  22116. OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
  22117. }
  22118. pFile->locktype = locktype;
  22119. OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
  22120. return rc;
  22121. }
  22122. /*
  22123. ** Control and query of the open file handle.
  22124. */
  22125. static int os2FileControl(sqlite3_file *id, int op, void *pArg){
  22126. switch( op ){
  22127. case SQLITE_FCNTL_LOCKSTATE: {
  22128. *(int*)pArg = ((os2File*)id)->locktype;
  22129. OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
  22130. ((os2File*)id)->h, ((os2File*)id)->locktype ));
  22131. return SQLITE_OK;
  22132. }
  22133. case SQLITE_FCNTL_CHUNK_SIZE: {
  22134. ((os2File*)id)->szChunk = *(int*)pArg;
  22135. return SQLITE_OK;
  22136. }
  22137. case SQLITE_FCNTL_SIZE_HINT: {
  22138. sqlite3_int64 sz = *(sqlite3_int64*)pArg;
  22139. SimulateIOErrorBenign(1);
  22140. os2Truncate(id, sz);
  22141. SimulateIOErrorBenign(0);
  22142. return SQLITE_OK;
  22143. }
  22144. case SQLITE_FCNTL_SYNC_OMITTED: {
  22145. return SQLITE_OK;
  22146. }
  22147. }
  22148. return SQLITE_NOTFOUND;
  22149. }
  22150. /*
  22151. ** Return the sector size in bytes of the underlying block device for
  22152. ** the specified file. This is almost always 512 bytes, but may be
  22153. ** larger for some devices.
  22154. **
  22155. ** SQLite code assumes this function cannot fail. It also assumes that
  22156. ** if two files are created in the same file-system directory (i.e.
  22157. ** a database and its journal file) that the sector size will be the
  22158. ** same for both.
  22159. */
  22160. static int os2SectorSize(sqlite3_file *id){
  22161. UNUSED_PARAMETER(id);
  22162. return SQLITE_DEFAULT_SECTOR_SIZE;
  22163. }
  22164. /*
  22165. ** Return a vector of device characteristics.
  22166. */
  22167. static int os2DeviceCharacteristics(sqlite3_file *id){
  22168. UNUSED_PARAMETER(id);
  22169. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
  22170. }
  22171. /*
  22172. ** Character set conversion objects used by conversion routines.
  22173. */
  22174. static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
  22175. static UconvObject uclCp = NULL; /* convert between local codepage and UCS-2 */
  22176. /*
  22177. ** Helper function to initialize the conversion objects from and to UTF-8.
  22178. */
  22179. static void initUconvObjects( void ){
  22180. if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
  22181. ucUtf8 = NULL;
  22182. if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
  22183. uclCp = NULL;
  22184. }
  22185. /*
  22186. ** Helper function to free the conversion objects from and to UTF-8.
  22187. */
  22188. static void freeUconvObjects( void ){
  22189. if ( ucUtf8 )
  22190. UniFreeUconvObject( ucUtf8 );
  22191. if ( uclCp )
  22192. UniFreeUconvObject( uclCp );
  22193. ucUtf8 = NULL;
  22194. uclCp = NULL;
  22195. }
  22196. /*
  22197. ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
  22198. ** The two-step process: first convert the incoming UTF-8 string
  22199. ** into UCS-2 and then from UCS-2 to the current codepage.
  22200. ** The returned char pointer has to be freed.
  22201. */
  22202. static char *convertUtf8PathToCp( const char *in ){
  22203. UniChar tempPath[CCHMAXPATH];
  22204. char *out = (char *)calloc( CCHMAXPATH, 1 );
  22205. if( !out )
  22206. return NULL;
  22207. if( !ucUtf8 || !uclCp )
  22208. initUconvObjects();
  22209. /* determine string for the conversion of UTF-8 which is CP1208 */
  22210. if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  22211. return out; /* if conversion fails, return the empty string */
  22212. /* conversion for current codepage which can be used for paths */
  22213. UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
  22214. return out;
  22215. }
  22216. /*
  22217. ** Helper function to convert filenames from local codepage to UTF-8.
  22218. ** The two-step process: first convert the incoming codepage-specific
  22219. ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
  22220. ** The returned char pointer has to be freed.
  22221. **
  22222. ** This function is non-static to be able to use this in shell.c and
  22223. ** similar applications that take command line arguments.
  22224. */
  22225. char *convertCpPathToUtf8( const char *in ){
  22226. UniChar tempPath[CCHMAXPATH];
  22227. char *out = (char *)calloc( CCHMAXPATH, 1 );
  22228. if( !out )
  22229. return NULL;
  22230. if( !ucUtf8 || !uclCp )
  22231. initUconvObjects();
  22232. /* conversion for current codepage which can be used for paths */
  22233. if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  22234. return out; /* if conversion fails, return the empty string */
  22235. /* determine string for the conversion of UTF-8 which is CP1208 */
  22236. UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
  22237. return out;
  22238. }
  22239. #ifndef SQLITE_OMIT_WAL
  22240. /*
  22241. ** Use main database file for interprocess locking. If un-defined
  22242. ** a separate file is created for this purpose. The file will be
  22243. ** used only to set file locks. There will be no data written to it.
  22244. */
  22245. #define SQLITE_OS2_NO_WAL_LOCK_FILE
  22246. #if 0
  22247. static void _ERR_TRACE( const char *fmt, ... ) {
  22248. va_list ap;
  22249. va_start(ap, fmt);
  22250. vfprintf(stderr, fmt, ap);
  22251. fflush(stderr);
  22252. }
  22253. #define ERR_TRACE(rc, msg) \
  22254. if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
  22255. #else
  22256. #define ERR_TRACE(rc, msg)
  22257. #endif
  22258. /*
  22259. ** Helper functions to obtain and relinquish the global mutex. The
  22260. ** global mutex is used to protect os2ShmNodeList.
  22261. **
  22262. ** Function os2ShmMutexHeld() is used to assert() that the global mutex
  22263. ** is held when required. This function is only used as part of assert()
  22264. ** statements. e.g.
  22265. **
  22266. ** os2ShmEnterMutex()
  22267. ** assert( os2ShmMutexHeld() );
  22268. ** os2ShmLeaveMutex()
  22269. */
  22270. static void os2ShmEnterMutex(void){
  22271. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22272. }
  22273. static void os2ShmLeaveMutex(void){
  22274. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22275. }
  22276. #ifdef SQLITE_DEBUG
  22277. static int os2ShmMutexHeld(void) {
  22278. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22279. }
  22280. int GetCurrentProcessId(void) {
  22281. PPIB pib;
  22282. DosGetInfoBlocks(NULL, &pib);
  22283. return (int)pib->pib_ulpid;
  22284. }
  22285. #endif
  22286. /*
  22287. ** Object used to represent a the shared memory area for a single log file.
  22288. ** When multiple threads all reference the same log-summary, each thread has
  22289. ** its own os2File object, but they all point to a single instance of this
  22290. ** object. In other words, each log-summary is opened only once per process.
  22291. **
  22292. ** os2ShmMutexHeld() must be true when creating or destroying
  22293. ** this object or while reading or writing the following fields:
  22294. **
  22295. ** nRef
  22296. ** pNext
  22297. **
  22298. ** The following fields are read-only after the object is created:
  22299. **
  22300. ** szRegion
  22301. ** hLockFile
  22302. ** shmBaseName
  22303. **
  22304. ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
  22305. ** os2ShmMutexHeld() is true when reading or writing any other field
  22306. ** in this structure.
  22307. **
  22308. */
  22309. struct os2ShmNode {
  22310. sqlite3_mutex *mutex; /* Mutex to access this object */
  22311. os2ShmNode *pNext; /* Next in list of all os2ShmNode objects */
  22312. int szRegion; /* Size of shared-memory regions */
  22313. int nRegion; /* Size of array apRegion */
  22314. void **apRegion; /* Array of pointers to shared-memory regions */
  22315. int nRef; /* Number of os2ShmLink objects pointing to this */
  22316. os2ShmLink *pFirst; /* First os2ShmLink object pointing to this */
  22317. HFILE hLockFile; /* File used for inter-process memory locking */
  22318. char shmBaseName[1]; /* Name of the memory object !!! must last !!! */
  22319. };
  22320. /*
  22321. ** Structure used internally by this VFS to record the state of an
  22322. ** open shared memory connection.
  22323. **
  22324. ** The following fields are initialized when this object is created and
  22325. ** are read-only thereafter:
  22326. **
  22327. ** os2Shm.pShmNode
  22328. ** os2Shm.id
  22329. **
  22330. ** All other fields are read/write. The os2Shm.pShmNode->mutex must be held
  22331. ** while accessing any read/write fields.
  22332. */
  22333. struct os2ShmLink {
  22334. os2ShmNode *pShmNode; /* The underlying os2ShmNode object */
  22335. os2ShmLink *pNext; /* Next os2Shm with the same os2ShmNode */
  22336. u32 sharedMask; /* Mask of shared locks held */
  22337. u32 exclMask; /* Mask of exclusive locks held */
  22338. #ifdef SQLITE_DEBUG
  22339. u8 id; /* Id of this connection with its os2ShmNode */
  22340. #endif
  22341. };
  22342. /*
  22343. ** A global list of all os2ShmNode objects.
  22344. **
  22345. ** The os2ShmMutexHeld() must be true while reading or writing this list.
  22346. */
  22347. static os2ShmNode *os2ShmNodeList = NULL;
  22348. /*
  22349. ** Constants used for locking
  22350. */
  22351. #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
  22352. #define OS2_SHM_BASE (PENDING_BYTE + 0x10000) /* first lock byte */
  22353. #else
  22354. #define OS2_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  22355. #endif
  22356. #define OS2_SHM_DMS (OS2_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  22357. /*
  22358. ** Apply advisory locks for all n bytes beginning at ofst.
  22359. */
  22360. #define _SHM_UNLCK 1 /* no lock */
  22361. #define _SHM_RDLCK 2 /* shared lock, no wait */
  22362. #define _SHM_WRLCK 3 /* exlusive lock, no wait */
  22363. #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
  22364. static int os2ShmSystemLock(
  22365. os2ShmNode *pNode, /* Apply locks to this open shared-memory segment */
  22366. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
  22367. int ofst, /* Offset to first byte to be locked/unlocked */
  22368. int nByte /* Number of bytes to lock or unlock */
  22369. ){
  22370. APIRET rc;
  22371. FILELOCK area;
  22372. ULONG mode, timeout;
  22373. /* Access to the os2ShmNode object is serialized by the caller */
  22374. assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
  22375. mode = 1; /* shared lock */
  22376. timeout = 0; /* no wait */
  22377. area.lOffset = ofst;
  22378. area.lRange = nByte;
  22379. switch( lockType ) {
  22380. case _SHM_WRLCK_WAIT:
  22381. timeout = (ULONG)-1; /* wait forever */
  22382. case _SHM_WRLCK:
  22383. mode = 0; /* exclusive lock */
  22384. case _SHM_RDLCK:
  22385. rc = DosSetFileLocks(pNode->hLockFile,
  22386. NULL, &area, timeout, mode);
  22387. break;
  22388. /* case _SHM_UNLCK: */
  22389. default:
  22390. rc = DosSetFileLocks(pNode->hLockFile,
  22391. &area, NULL, 0, 0);
  22392. break;
  22393. }
  22394. OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
  22395. pNode->hLockFile,
  22396. rc==SQLITE_OK ? "ok" : "failed",
  22397. lockType==_SHM_UNLCK ? "Unlock" : "Lock",
  22398. rc));
  22399. ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
  22400. return ( rc == 0 ) ? SQLITE_OK : SQLITE_BUSY;
  22401. }
  22402. /*
  22403. ** Find an os2ShmNode in global list or allocate a new one, if not found.
  22404. **
  22405. ** This is not a VFS shared-memory method; it is a utility function called
  22406. ** by VFS shared-memory methods.
  22407. */
  22408. static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
  22409. os2ShmLink *pLink;
  22410. os2ShmNode *pNode;
  22411. int cbShmName, rc = SQLITE_OK;
  22412. char shmName[CCHMAXPATH + 30];
  22413. #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
  22414. ULONG action;
  22415. #endif
  22416. /* We need some additional space at the end to append the region number */
  22417. cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
  22418. if( cbShmName >= CCHMAXPATH-8 )
  22419. return SQLITE_IOERR_SHMOPEN;
  22420. /* Replace colon in file name to form a valid shared memory name */
  22421. shmName[10+1] = '!';
  22422. /* Allocate link object (we free it later in case of failure) */
  22423. pLink = sqlite3_malloc( sizeof(*pLink) );
  22424. if( !pLink )
  22425. return SQLITE_NOMEM;
  22426. /* Access node list */
  22427. os2ShmEnterMutex();
  22428. /* Find node by it's shared memory base name */
  22429. for( pNode = os2ShmNodeList;
  22430. pNode && stricmp(shmName, pNode->shmBaseName) != 0;
  22431. pNode = pNode->pNext ) ;
  22432. /* Not found: allocate a new node */
  22433. if( !pNode ) {
  22434. pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
  22435. if( pNode ) {
  22436. memset(pNode, 0, sizeof(*pNode) );
  22437. pNode->szRegion = szRegion;
  22438. pNode->hLockFile = (HFILE)-1;
  22439. strcpy(pNode->shmBaseName, shmName);
  22440. #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
  22441. if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
  22442. #else
  22443. sprintf(shmName, "%s-lck", fd->zFullPathCp);
  22444. if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
  22445. OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
  22446. OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
  22447. OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
  22448. NULL) != 0 ) {
  22449. #endif
  22450. sqlite3_free(pNode);
  22451. rc = SQLITE_IOERR;
  22452. } else {
  22453. pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  22454. if( !pNode->mutex ) {
  22455. sqlite3_free(pNode);
  22456. rc = SQLITE_NOMEM;
  22457. }
  22458. }
  22459. } else {
  22460. rc = SQLITE_NOMEM;
  22461. }
  22462. if( rc == SQLITE_OK ) {
  22463. pNode->pNext = os2ShmNodeList;
  22464. os2ShmNodeList = pNode;
  22465. } else {
  22466. pNode = NULL;
  22467. }
  22468. } else if( pNode->szRegion != szRegion ) {
  22469. rc = SQLITE_IOERR_SHMSIZE;
  22470. pNode = NULL;
  22471. }
  22472. if( pNode ) {
  22473. sqlite3_mutex_enter(pNode->mutex);
  22474. memset(pLink, 0, sizeof(*pLink));
  22475. pLink->pShmNode = pNode;
  22476. pLink->pNext = pNode->pFirst;
  22477. pNode->pFirst = pLink;
  22478. pNode->nRef++;
  22479. fd->pShmLink = pLink;
  22480. sqlite3_mutex_leave(pNode->mutex);
  22481. } else {
  22482. /* Error occured. Free our link object. */
  22483. sqlite3_free(pLink);
  22484. }
  22485. os2ShmLeaveMutex();
  22486. ERR_TRACE(rc, ("os2OpenSharedMemory: %d %s\n", rc, fd->zFullPathCp))
  22487. return rc;
  22488. }
  22489. /*
  22490. ** Purge the os2ShmNodeList list of all entries with nRef==0.
  22491. **
  22492. ** This is not a VFS shared-memory method; it is a utility function called
  22493. ** by VFS shared-memory methods.
  22494. */
  22495. static void os2PurgeShmNodes( int deleteFlag ) {
  22496. os2ShmNode *pNode;
  22497. os2ShmNode **ppNode;
  22498. os2ShmEnterMutex();
  22499. ppNode = &os2ShmNodeList;
  22500. while( *ppNode ) {
  22501. pNode = *ppNode;
  22502. if( pNode->nRef == 0 ) {
  22503. *ppNode = pNode->pNext;
  22504. if( pNode->apRegion ) {
  22505. /* Prevent other processes from resizing the shared memory */
  22506. os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
  22507. while( pNode->nRegion-- ) {
  22508. #ifdef SQLITE_DEBUG
  22509. int rc =
  22510. #endif
  22511. DosFreeMem(pNode->apRegion[pNode->nRegion]);
  22512. OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
  22513. (int)GetCurrentProcessId(), pNode->nRegion,
  22514. rc == 0 ? "ok" : "failed"));
  22515. }
  22516. /* Allow other processes to resize the shared memory */
  22517. os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
  22518. sqlite3_free(pNode->apRegion);
  22519. }
  22520. DosClose(pNode->hLockFile);
  22521. #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
  22522. if( deleteFlag ) {
  22523. char fileName[CCHMAXPATH];
  22524. /* Skip "\\SHAREMEM\\" */
  22525. sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
  22526. /* restore colon */
  22527. fileName[1] = ':';
  22528. DosForceDelete(fileName);
  22529. }
  22530. #endif
  22531. sqlite3_mutex_free(pNode->mutex);
  22532. sqlite3_free(pNode);
  22533. } else {
  22534. ppNode = &pNode->pNext;
  22535. }
  22536. }
  22537. os2ShmLeaveMutex();
  22538. }
  22539. /*
  22540. ** This function is called to obtain a pointer to region iRegion of the
  22541. ** shared-memory associated with the database file id. Shared-memory regions
  22542. ** are numbered starting from zero. Each shared-memory region is szRegion
  22543. ** bytes in size.
  22544. **
  22545. ** If an error occurs, an error code is returned and *pp is set to NULL.
  22546. **
  22547. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  22548. ** region has not been allocated (by any client, including one running in a
  22549. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  22550. ** bExtend is non-zero and the requested shared-memory region has not yet
  22551. ** been allocated, it is allocated by this function.
  22552. **
  22553. ** If the shared-memory region has already been allocated or is allocated by
  22554. ** this call as described above, then it is mapped into this processes
  22555. ** address space (if it is not already), *pp is set to point to the mapped
  22556. ** memory and SQLITE_OK returned.
  22557. */
  22558. static int os2ShmMap(
  22559. sqlite3_file *id, /* Handle open on database file */
  22560. int iRegion, /* Region to retrieve */
  22561. int szRegion, /* Size of regions */
  22562. int bExtend, /* True to extend block if necessary */
  22563. void volatile **pp /* OUT: Mapped memory */
  22564. ){
  22565. PVOID pvTemp;
  22566. void **apRegion;
  22567. os2ShmNode *pNode;
  22568. int n, rc = SQLITE_OK;
  22569. char shmName[CCHMAXPATH];
  22570. os2File *pFile = (os2File*)id;
  22571. *pp = NULL;
  22572. if( !pFile->pShmLink )
  22573. rc = os2OpenSharedMemory( pFile, szRegion );
  22574. if( rc == SQLITE_OK ) {
  22575. pNode = pFile->pShmLink->pShmNode ;
  22576. sqlite3_mutex_enter(pNode->mutex);
  22577. assert( szRegion==pNode->szRegion );
  22578. /* Unmapped region ? */
  22579. if( iRegion >= pNode->nRegion ) {
  22580. /* Prevent other processes from resizing the shared memory */
  22581. os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
  22582. apRegion = sqlite3_realloc(
  22583. pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
  22584. if( apRegion ) {
  22585. pNode->apRegion = apRegion;
  22586. while( pNode->nRegion <= iRegion ) {
  22587. sprintf(shmName, "%s-%u",
  22588. pNode->shmBaseName, pNode->nRegion);
  22589. if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
  22590. PAG_READ | PAG_WRITE) != NO_ERROR ) {
  22591. if( !bExtend )
  22592. break;
  22593. if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
  22594. PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
  22595. DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
  22596. PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
  22597. rc = SQLITE_NOMEM;
  22598. break;
  22599. }
  22600. }
  22601. apRegion[pNode->nRegion++] = pvTemp;
  22602. }
  22603. /* zero out remaining entries */
  22604. for( n = pNode->nRegion; n <= iRegion; n++ )
  22605. pNode->apRegion[n] = NULL;
  22606. /* Return this region (maybe zero) */
  22607. *pp = pNode->apRegion[iRegion];
  22608. } else {
  22609. rc = SQLITE_NOMEM;
  22610. }
  22611. /* Allow other processes to resize the shared memory */
  22612. os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
  22613. } else {
  22614. /* Region has been mapped previously */
  22615. *pp = pNode->apRegion[iRegion];
  22616. }
  22617. sqlite3_mutex_leave(pNode->mutex);
  22618. }
  22619. ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
  22620. pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
  22621. return rc;
  22622. }
  22623. /*
  22624. ** Close a connection to shared-memory. Delete the underlying
  22625. ** storage if deleteFlag is true.
  22626. **
  22627. ** If there is no shared memory associated with the connection then this
  22628. ** routine is a harmless no-op.
  22629. */
  22630. static int os2ShmUnmap(
  22631. sqlite3_file *id, /* The underlying database file */
  22632. int deleteFlag /* Delete shared-memory if true */
  22633. ){
  22634. os2File *pFile = (os2File*)id;
  22635. os2ShmLink *pLink = pFile->pShmLink;
  22636. if( pLink ) {
  22637. int nRef = -1;
  22638. os2ShmLink **ppLink;
  22639. os2ShmNode *pNode = pLink->pShmNode;
  22640. sqlite3_mutex_enter(pNode->mutex);
  22641. for( ppLink = &pNode->pFirst;
  22642. *ppLink && *ppLink != pLink;
  22643. ppLink = &(*ppLink)->pNext ) ;
  22644. assert(*ppLink);
  22645. if( *ppLink ) {
  22646. *ppLink = pLink->pNext;
  22647. nRef = --pNode->nRef;
  22648. } else {
  22649. ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
  22650. pNode->shmBaseName))
  22651. }
  22652. pFile->pShmLink = NULL;
  22653. sqlite3_free(pLink);
  22654. sqlite3_mutex_leave(pNode->mutex);
  22655. if( nRef == 0 )
  22656. os2PurgeShmNodes( deleteFlag );
  22657. }
  22658. return SQLITE_OK;
  22659. }
  22660. /*
  22661. ** Change the lock state for a shared-memory segment.
  22662. **
  22663. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  22664. ** different here than in posix. In xShmLock(), one can go from unlocked
  22665. ** to shared and back or from unlocked to exclusive and back. But one may
  22666. ** not go from shared to exclusive or from exclusive to shared.
  22667. */
  22668. static int os2ShmLock(
  22669. sqlite3_file *id, /* Database file holding the shared memory */
  22670. int ofst, /* First lock to acquire or release */
  22671. int n, /* Number of locks to acquire or release */
  22672. int flags /* What to do with the lock */
  22673. ){
  22674. u32 mask; /* Mask of locks to take or release */
  22675. int rc = SQLITE_OK; /* Result code */
  22676. os2File *pFile = (os2File*)id;
  22677. os2ShmLink *p = pFile->pShmLink; /* The shared memory being locked */
  22678. os2ShmLink *pX; /* For looping over all siblings */
  22679. os2ShmNode *pShmNode = p->pShmNode; /* Our node */
  22680. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  22681. assert( n>=1 );
  22682. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  22683. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  22684. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  22685. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  22686. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  22687. mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
  22688. assert( n>1 || mask==(1<<ofst) );
  22689. sqlite3_mutex_enter(pShmNode->mutex);
  22690. if( flags & SQLITE_SHM_UNLOCK ){
  22691. u32 allMask = 0; /* Mask of locks held by siblings */
  22692. /* See if any siblings hold this same lock */
  22693. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  22694. if( pX==p ) continue;
  22695. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  22696. allMask |= pX->sharedMask;
  22697. }
  22698. /* Unlock the system-level locks */
  22699. if( (mask & allMask)==0 ){
  22700. rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
  22701. }else{
  22702. rc = SQLITE_OK;
  22703. }
  22704. /* Undo the local locks */
  22705. if( rc==SQLITE_OK ){
  22706. p->exclMask &= ~mask;
  22707. p->sharedMask &= ~mask;
  22708. }
  22709. }else if( flags & SQLITE_SHM_SHARED ){
  22710. u32 allShared = 0; /* Union of locks held by connections other than "p" */
  22711. /* Find out which shared locks are already held by sibling connections.
  22712. ** If any sibling already holds an exclusive lock, go ahead and return
  22713. ** SQLITE_BUSY.
  22714. */
  22715. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  22716. if( (pX->exclMask & mask)!=0 ){
  22717. rc = SQLITE_BUSY;
  22718. break;
  22719. }
  22720. allShared |= pX->sharedMask;
  22721. }
  22722. /* Get shared locks at the system level, if necessary */
  22723. if( rc==SQLITE_OK ){
  22724. if( (allShared & mask)==0 ){
  22725. rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
  22726. }else{
  22727. rc = SQLITE_OK;
  22728. }
  22729. }
  22730. /* Get the local shared locks */
  22731. if( rc==SQLITE_OK ){
  22732. p->sharedMask |= mask;
  22733. }
  22734. }else{
  22735. /* Make sure no sibling connections hold locks that will block this
  22736. ** lock. If any do, return SQLITE_BUSY right away.
  22737. */
  22738. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  22739. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  22740. rc = SQLITE_BUSY;
  22741. break;
  22742. }
  22743. }
  22744. /* Get the exclusive locks at the system level. Then if successful
  22745. ** also mark the local connection as being locked.
  22746. */
  22747. if( rc==SQLITE_OK ){
  22748. rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
  22749. if( rc==SQLITE_OK ){
  22750. assert( (p->sharedMask & mask)==0 );
  22751. p->exclMask |= mask;
  22752. }
  22753. }
  22754. }
  22755. sqlite3_mutex_leave(pShmNode->mutex);
  22756. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
  22757. p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
  22758. rc ? "failed" : "ok"));
  22759. ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
  22760. ofst, n, flags, rc))
  22761. return rc;
  22762. }
  22763. /*
  22764. ** Implement a memory barrier or memory fence on shared memory.
  22765. **
  22766. ** All loads and stores begun before the barrier must complete before
  22767. ** any load or store begun after the barrier.
  22768. */
  22769. static void os2ShmBarrier(
  22770. sqlite3_file *id /* Database file holding the shared memory */
  22771. ){
  22772. UNUSED_PARAMETER(id);
  22773. os2ShmEnterMutex();
  22774. os2ShmLeaveMutex();
  22775. }
  22776. #else
  22777. # define os2ShmMap 0
  22778. # define os2ShmLock 0
  22779. # define os2ShmBarrier 0
  22780. # define os2ShmUnmap 0
  22781. #endif /* #ifndef SQLITE_OMIT_WAL */
  22782. /*
  22783. ** This vector defines all the methods that can operate on an
  22784. ** sqlite3_file for os2.
  22785. */
  22786. static const sqlite3_io_methods os2IoMethod = {
  22787. 2, /* iVersion */
  22788. os2Close, /* xClose */
  22789. os2Read, /* xRead */
  22790. os2Write, /* xWrite */
  22791. os2Truncate, /* xTruncate */
  22792. os2Sync, /* xSync */
  22793. os2FileSize, /* xFileSize */
  22794. os2Lock, /* xLock */
  22795. os2Unlock, /* xUnlock */
  22796. os2CheckReservedLock, /* xCheckReservedLock */
  22797. os2FileControl, /* xFileControl */
  22798. os2SectorSize, /* xSectorSize */
  22799. os2DeviceCharacteristics, /* xDeviceCharacteristics */
  22800. os2ShmMap, /* xShmMap */
  22801. os2ShmLock, /* xShmLock */
  22802. os2ShmBarrier, /* xShmBarrier */
  22803. os2ShmUnmap /* xShmUnmap */
  22804. };
  22805. /***************************************************************************
  22806. ** Here ends the I/O methods that form the sqlite3_io_methods object.
  22807. **
  22808. ** The next block of code implements the VFS methods.
  22809. ****************************************************************************/
  22810. /*
  22811. ** Create a temporary file name in zBuf. zBuf must be big enough to
  22812. ** hold at pVfs->mxPathname characters.
  22813. */
  22814. static int getTempname(int nBuf, char *zBuf ){
  22815. static const char zChars[] =
  22816. "abcdefghijklmnopqrstuvwxyz"
  22817. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  22818. "0123456789";
  22819. int i, j;
  22820. PSZ zTempPathCp;
  22821. char zTempPath[CCHMAXPATH];
  22822. ULONG ulDriveNum, ulDriveMap;
  22823. /* It's odd to simulate an io-error here, but really this is just
  22824. ** using the io-error infrastructure to test that SQLite handles this
  22825. ** function failing.
  22826. */
  22827. SimulateIOError( return SQLITE_IOERR );
  22828. if( sqlite3_temp_directory ) {
  22829. sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
  22830. } else if( DosScanEnv( (PSZ)"TEMP", &zTempPathCp ) == NO_ERROR ||
  22831. DosScanEnv( (PSZ)"TMP", &zTempPathCp ) == NO_ERROR ||
  22832. DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
  22833. char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
  22834. sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
  22835. free( zTempPathUTF );
  22836. } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
  22837. zTempPath[0] = (char)('A' + ulDriveNum - 1);
  22838. zTempPath[1] = ':';
  22839. zTempPath[2] = '\0';
  22840. } else {
  22841. zTempPath[0] = '\0';
  22842. }
  22843. /* Strip off a trailing slashes or backslashes, otherwise we would get *
  22844. * multiple (back)slashes which causes DosOpen() to fail. *
  22845. * Trailing spaces are not allowed, either. */
  22846. j = sqlite3Strlen30(zTempPath);
  22847. while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
  22848. zTempPath[j-1] == ' ' ) ){
  22849. j--;
  22850. }
  22851. zTempPath[j] = '\0';
  22852. /* We use 20 bytes to randomize the name */
  22853. sqlite3_snprintf(nBuf-22, zBuf,
  22854. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
  22855. j = sqlite3Strlen30(zBuf);
  22856. sqlite3_randomness( 20, &zBuf[j] );
  22857. for( i = 0; i < 20; i++, j++ ){
  22858. zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  22859. }
  22860. zBuf[j] = 0;
  22861. OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
  22862. return SQLITE_OK;
  22863. }
  22864. /*
  22865. ** Turn a relative pathname into a full pathname. Write the full
  22866. ** pathname into zFull[]. zFull[] will be at least pVfs->mxPathname
  22867. ** bytes in size.
  22868. */
  22869. static int os2FullPathname(
  22870. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  22871. const char *zRelative, /* Possibly relative input path */
  22872. int nFull, /* Size of output buffer in bytes */
  22873. char *zFull /* Output buffer */
  22874. ){
  22875. char *zRelativeCp = convertUtf8PathToCp( zRelative );
  22876. char zFullCp[CCHMAXPATH] = "\0";
  22877. char *zFullUTF;
  22878. APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
  22879. zFullCp, CCHMAXPATH );
  22880. free( zRelativeCp );
  22881. zFullUTF = convertCpPathToUtf8( zFullCp );
  22882. sqlite3_snprintf( nFull, zFull, zFullUTF );
  22883. free( zFullUTF );
  22884. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  22885. }
  22886. /*
  22887. ** Open a file.
  22888. */
  22889. static int os2Open(
  22890. sqlite3_vfs *pVfs, /* Not used */
  22891. const char *zName, /* Name of the file (UTF-8) */
  22892. sqlite3_file *id, /* Write the SQLite file handle here */
  22893. int flags, /* Open mode flags */
  22894. int *pOutFlags /* Status return flags */
  22895. ){
  22896. HFILE h;
  22897. ULONG ulOpenFlags = 0;
  22898. ULONG ulOpenMode = 0;
  22899. ULONG ulAction = 0;
  22900. ULONG rc;
  22901. os2File *pFile = (os2File*)id;
  22902. const char *zUtf8Name = zName;
  22903. char *zNameCp;
  22904. char zTmpname[CCHMAXPATH];
  22905. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  22906. int isCreate = (flags & SQLITE_OPEN_CREATE);
  22907. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  22908. #ifndef NDEBUG
  22909. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  22910. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  22911. int eType = (flags & 0xFFFFFF00);
  22912. int isOpenJournal = (isCreate && (
  22913. eType==SQLITE_OPEN_MASTER_JOURNAL
  22914. || eType==SQLITE_OPEN_MAIN_JOURNAL
  22915. || eType==SQLITE_OPEN_WAL
  22916. ));
  22917. #endif
  22918. UNUSED_PARAMETER(pVfs);
  22919. assert( id!=0 );
  22920. /* Check the following statements are true:
  22921. **
  22922. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  22923. ** (b) if CREATE is set, then READWRITE must also be set, and
  22924. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  22925. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  22926. */
  22927. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  22928. assert(isCreate==0 || isReadWrite);
  22929. assert(isExclusive==0 || isCreate);
  22930. assert(isDelete==0 || isCreate);
  22931. /* The main DB, main journal, WAL file and master journal are never
  22932. ** automatically deleted. Nor are they ever temporary files. */
  22933. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  22934. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  22935. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  22936. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  22937. /* Assert that the upper layer has set one of the "file-type" flags. */
  22938. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  22939. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  22940. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  22941. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  22942. );
  22943. memset( pFile, 0, sizeof(*pFile) );
  22944. pFile->h = (HFILE)-1;
  22945. /* If the second argument to this function is NULL, generate a
  22946. ** temporary file name to use
  22947. */
  22948. if( !zUtf8Name ){
  22949. assert(isDelete && !isOpenJournal);
  22950. rc = getTempname(CCHMAXPATH, zTmpname);
  22951. if( rc!=SQLITE_OK ){
  22952. return rc;
  22953. }
  22954. zUtf8Name = zTmpname;
  22955. }
  22956. if( isReadWrite ){
  22957. ulOpenMode |= OPEN_ACCESS_READWRITE;
  22958. }else{
  22959. ulOpenMode |= OPEN_ACCESS_READONLY;
  22960. }
  22961. /* Open in random access mode for possibly better speed. Allow full
  22962. ** sharing because file locks will provide exclusive access when needed.
  22963. ** The handle should not be inherited by child processes and we don't
  22964. ** want popups from the critical error handler.
  22965. */
  22966. ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
  22967. OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
  22968. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  22969. ** created. SQLite doesn't use it to indicate "exclusive access"
  22970. ** as it is usually understood.
  22971. */
  22972. if( isExclusive ){
  22973. /* Creates a new file, only if it does not already exist. */
  22974. /* If the file exists, it fails. */
  22975. ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
  22976. }else if( isCreate ){
  22977. /* Open existing file, or create if it doesn't exist */
  22978. ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
  22979. }else{
  22980. /* Opens a file, only if it exists. */
  22981. ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
  22982. }
  22983. zNameCp = convertUtf8PathToCp( zUtf8Name );
  22984. rc = DosOpen( (PSZ)zNameCp,
  22985. &h,
  22986. &ulAction,
  22987. 0L,
  22988. FILE_NORMAL,
  22989. ulOpenFlags,
  22990. ulOpenMode,
  22991. (PEAOP2)NULL );
  22992. free( zNameCp );
  22993. if( rc != NO_ERROR ){
  22994. OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
  22995. rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
  22996. if( isReadWrite ){
  22997. return os2Open( pVfs, zName, id,
  22998. ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  22999. pOutFlags );
  23000. }else{
  23001. return SQLITE_CANTOPEN;
  23002. }
  23003. }
  23004. if( pOutFlags ){
  23005. *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
  23006. }
  23007. os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
  23008. pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
  23009. pFile->pMethod = &os2IoMethod;
  23010. pFile->flags = flags;
  23011. pFile->h = h;
  23012. OpenCounter(+1);
  23013. OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
  23014. return SQLITE_OK;
  23015. }
  23016. /*
  23017. ** Delete the named file.
  23018. */
  23019. static int os2Delete(
  23020. sqlite3_vfs *pVfs, /* Not used on os2 */
  23021. const char *zFilename, /* Name of file to delete */
  23022. int syncDir /* Not used on os2 */
  23023. ){
  23024. APIRET rc;
  23025. char *zFilenameCp;
  23026. SimulateIOError( return SQLITE_IOERR_DELETE );
  23027. zFilenameCp = convertUtf8PathToCp( zFilename );
  23028. rc = DosDelete( (PSZ)zFilenameCp );
  23029. free( zFilenameCp );
  23030. OSTRACE(( "DELETE \"%s\"\n", zFilename ));
  23031. return (rc == NO_ERROR ||
  23032. rc == ERROR_FILE_NOT_FOUND ||
  23033. rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
  23034. }
  23035. /*
  23036. ** Check the existance and status of a file.
  23037. */
  23038. static int os2Access(
  23039. sqlite3_vfs *pVfs, /* Not used on os2 */
  23040. const char *zFilename, /* Name of file to check */
  23041. int flags, /* Type of test to make on this file */
  23042. int *pOut /* Write results here */
  23043. ){
  23044. APIRET rc;
  23045. FILESTATUS3 fsts3ConfigInfo;
  23046. char *zFilenameCp;
  23047. UNUSED_PARAMETER(pVfs);
  23048. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  23049. zFilenameCp = convertUtf8PathToCp( zFilename );
  23050. rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
  23051. &fsts3ConfigInfo, sizeof(FILESTATUS3) );
  23052. free( zFilenameCp );
  23053. OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
  23054. fsts3ConfigInfo.attrFile, flags, rc ));
  23055. switch( flags ){
  23056. case SQLITE_ACCESS_EXISTS:
  23057. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  23058. ** as if it does not exist.
  23059. */
  23060. if( fsts3ConfigInfo.cbFile == 0 )
  23061. rc = ERROR_FILE_NOT_FOUND;
  23062. break;
  23063. case SQLITE_ACCESS_READ:
  23064. break;
  23065. case SQLITE_ACCESS_READWRITE:
  23066. if( fsts3ConfigInfo.attrFile & FILE_READONLY )
  23067. rc = ERROR_ACCESS_DENIED;
  23068. break;
  23069. default:
  23070. rc = ERROR_FILE_NOT_FOUND;
  23071. assert( !"Invalid flags argument" );
  23072. }
  23073. *pOut = (rc == NO_ERROR);
  23074. OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
  23075. return SQLITE_OK;
  23076. }
  23077. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  23078. /*
  23079. ** Interfaces for opening a shared library, finding entry points
  23080. ** within the shared library, and closing the shared library.
  23081. */
  23082. /*
  23083. ** Interfaces for opening a shared library, finding entry points
  23084. ** within the shared library, and closing the shared library.
  23085. */
  23086. static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  23087. HMODULE hmod;
  23088. APIRET rc;
  23089. char *zFilenameCp = convertUtf8PathToCp(zFilename);
  23090. rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
  23091. free(zFilenameCp);
  23092. return rc != NO_ERROR ? 0 : (void*)hmod;
  23093. }
  23094. /*
  23095. ** A no-op since the error code is returned on the DosLoadModule call.
  23096. ** os2Dlopen returns zero if DosLoadModule is not successful.
  23097. */
  23098. static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  23099. /* no-op */
  23100. }
  23101. static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  23102. PFN pfn;
  23103. APIRET rc;
  23104. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
  23105. if( rc != NO_ERROR ){
  23106. /* if the symbol itself was not found, search again for the same
  23107. * symbol with an extra underscore, that might be needed depending
  23108. * on the calling convention */
  23109. char _zSymbol[256] = "_";
  23110. strncat(_zSymbol, zSymbol, 254);
  23111. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
  23112. }
  23113. return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
  23114. }
  23115. static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
  23116. DosFreeModule((HMODULE)pHandle);
  23117. }
  23118. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  23119. #define os2DlOpen 0
  23120. #define os2DlError 0
  23121. #define os2DlSym 0
  23122. #define os2DlClose 0
  23123. #endif
  23124. /*
  23125. ** Write up to nBuf bytes of randomness into zBuf.
  23126. */
  23127. static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
  23128. int n = 0;
  23129. #if defined(SQLITE_TEST)
  23130. n = nBuf;
  23131. memset(zBuf, 0, nBuf);
  23132. #else
  23133. int i;
  23134. PPIB ppib;
  23135. PTIB ptib;
  23136. DATETIME dt;
  23137. static unsigned c = 0;
  23138. /* Ordered by variation probability */
  23139. static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
  23140. QSV_MAXPRMEM, QSV_MAXSHMEM,
  23141. QSV_TOTAVAILMEM, QSV_TOTRESMEM };
  23142. /* 8 bytes; timezone and weekday don't increase the randomness much */
  23143. if( (int)sizeof(dt)-3 <= nBuf - n ){
  23144. c += 0x0100;
  23145. DosGetDateTime(&dt);
  23146. dt.year = (USHORT)((dt.year - 1900) | c);
  23147. memcpy(&zBuf[n], &dt, sizeof(dt)-3);
  23148. n += sizeof(dt)-3;
  23149. }
  23150. /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
  23151. if( (int)sizeof(ULONG) <= nBuf - n ){
  23152. DosGetInfoBlocks(&ptib, &ppib);
  23153. *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
  23154. ptib->tib_ptib2->tib2_ultid);
  23155. n += sizeof(ULONG);
  23156. }
  23157. /* Up to 6 * 4 bytes; variables depend on the system state */
  23158. for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
  23159. DosQuerySysInfo(svIdx[i], svIdx[i],
  23160. (PULONG)&zBuf[n], sizeof(ULONG));
  23161. n += sizeof(ULONG);
  23162. }
  23163. #endif
  23164. return n;
  23165. }
  23166. /*
  23167. ** Sleep for a little while. Return the amount of time slept.
  23168. ** The argument is the number of microseconds we want to sleep.
  23169. ** The return value is the number of microseconds of sleep actually
  23170. ** requested from the underlying operating system, a number which
  23171. ** might be greater than or equal to the argument, but not less
  23172. ** than the argument.
  23173. */
  23174. static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
  23175. DosSleep( (microsec/1000) );
  23176. return microsec;
  23177. }
  23178. /*
  23179. ** The following variable, if set to a non-zero value, becomes the result
  23180. ** returned from sqlite3OsCurrentTime(). This is used for testing.
  23181. */
  23182. #ifdef SQLITE_TEST
  23183. SQLITE_API int sqlite3_current_time = 0;
  23184. #endif
  23185. /*
  23186. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  23187. ** the current time and date as a Julian Day number times 86_400_000. In
  23188. ** other words, write into *piNow the number of milliseconds since the Julian
  23189. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  23190. ** proleptic Gregorian calendar.
  23191. **
  23192. ** On success, return 0. Return 1 if the time and date cannot be found.
  23193. */
  23194. static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  23195. #ifdef SQLITE_TEST
  23196. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  23197. #endif
  23198. int year, month, datepart, timepart;
  23199. DATETIME dt;
  23200. DosGetDateTime( &dt );
  23201. year = dt.year;
  23202. month = dt.month;
  23203. /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
  23204. ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
  23205. ** Calculate the Julian days
  23206. */
  23207. datepart = (int)dt.day - 32076 +
  23208. 1461*(year + 4800 + (month - 14)/12)/4 +
  23209. 367*(month - 2 - (month - 14)/12*12)/12 -
  23210. 3*((year + 4900 + (month - 14)/12)/100)/4;
  23211. /* Time in milliseconds, hours to noon added */
  23212. timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
  23213. ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
  23214. *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
  23215. #ifdef SQLITE_TEST
  23216. if( sqlite3_current_time ){
  23217. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  23218. }
  23219. #endif
  23220. UNUSED_PARAMETER(pVfs);
  23221. return 0;
  23222. }
  23223. /*
  23224. ** Find the current time (in Universal Coordinated Time). Write the
  23225. ** current time and date as a Julian Day number into *prNow and
  23226. ** return 0. Return 1 if the time and date cannot be found.
  23227. */
  23228. static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
  23229. int rc;
  23230. sqlite3_int64 i;
  23231. rc = os2CurrentTimeInt64(pVfs, &i);
  23232. if( !rc ){
  23233. *prNow = i/86400000.0;
  23234. }
  23235. return rc;
  23236. }
  23237. /*
  23238. ** The idea is that this function works like a combination of
  23239. ** GetLastError() and FormatMessage() on windows (or errno and
  23240. ** strerror_r() on unix). After an error is returned by an OS
  23241. ** function, SQLite calls this function with zBuf pointing to
  23242. ** a buffer of nBuf bytes. The OS layer should populate the
  23243. ** buffer with a nul-terminated UTF-8 encoded error message
  23244. ** describing the last IO error to have occurred within the calling
  23245. ** thread.
  23246. **
  23247. ** If the error message is too large for the supplied buffer,
  23248. ** it should be truncated. The return value of xGetLastError
  23249. ** is zero if the error message fits in the buffer, or non-zero
  23250. ** otherwise (if the message was truncated). If non-zero is returned,
  23251. ** then it is not necessary to include the nul-terminator character
  23252. ** in the output buffer.
  23253. **
  23254. ** Not supplying an error message will have no adverse effect
  23255. ** on SQLite. It is fine to have an implementation that never
  23256. ** returns an error message:
  23257. **
  23258. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  23259. ** assert(zBuf[0]=='\0');
  23260. ** return 0;
  23261. ** }
  23262. **
  23263. ** However if an error message is supplied, it will be incorporated
  23264. ** by sqlite into the error message available to the user using
  23265. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  23266. */
  23267. static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  23268. assert(zBuf[0]=='\0');
  23269. return 0;
  23270. }
  23271. /*
  23272. ** Initialize and deinitialize the operating system interface.
  23273. */
  23274. SQLITE_API int sqlite3_os_init(void){
  23275. static sqlite3_vfs os2Vfs = {
  23276. 3, /* iVersion */
  23277. sizeof(os2File), /* szOsFile */
  23278. CCHMAXPATH, /* mxPathname */
  23279. 0, /* pNext */
  23280. "os2", /* zName */
  23281. 0, /* pAppData */
  23282. os2Open, /* xOpen */
  23283. os2Delete, /* xDelete */
  23284. os2Access, /* xAccess */
  23285. os2FullPathname, /* xFullPathname */
  23286. os2DlOpen, /* xDlOpen */
  23287. os2DlError, /* xDlError */
  23288. os2DlSym, /* xDlSym */
  23289. os2DlClose, /* xDlClose */
  23290. os2Randomness, /* xRandomness */
  23291. os2Sleep, /* xSleep */
  23292. os2CurrentTime, /* xCurrentTime */
  23293. os2GetLastError, /* xGetLastError */
  23294. os2CurrentTimeInt64, /* xCurrentTimeInt64 */
  23295. 0, /* xSetSystemCall */
  23296. 0, /* xGetSystemCall */
  23297. 0 /* xNextSystemCall */
  23298. };
  23299. sqlite3_vfs_register(&os2Vfs, 1);
  23300. initUconvObjects();
  23301. /* sqlite3OSTrace = 1; */
  23302. return SQLITE_OK;
  23303. }
  23304. SQLITE_API int sqlite3_os_end(void){
  23305. freeUconvObjects();
  23306. return SQLITE_OK;
  23307. }
  23308. #endif /* SQLITE_OS_OS2 */
  23309. /************** End of os_os2.c **********************************************/
  23310. /************** Begin file os_unix.c *****************************************/
  23311. /*
  23312. ** 2004 May 22
  23313. **
  23314. ** The author disclaims copyright to this source code. In place of
  23315. ** a legal notice, here is a blessing:
  23316. **
  23317. ** May you do good and not evil.
  23318. ** May you find forgiveness for yourself and forgive others.
  23319. ** May you share freely, never taking more than you give.
  23320. **
  23321. ******************************************************************************
  23322. **
  23323. ** This file contains the VFS implementation for unix-like operating systems
  23324. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  23325. **
  23326. ** There are actually several different VFS implementations in this file.
  23327. ** The differences are in the way that file locking is done. The default
  23328. ** implementation uses Posix Advisory Locks. Alternative implementations
  23329. ** use flock(), dot-files, various proprietary locking schemas, or simply
  23330. ** skip locking all together.
  23331. **
  23332. ** This source file is organized into divisions where the logic for various
  23333. ** subfunctions is contained within the appropriate division. PLEASE
  23334. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  23335. ** in the correct division and should be clearly labeled.
  23336. **
  23337. ** The layout of divisions is as follows:
  23338. **
  23339. ** * General-purpose declarations and utility functions.
  23340. ** * Unique file ID logic used by VxWorks.
  23341. ** * Various locking primitive implementations (all except proxy locking):
  23342. ** + for Posix Advisory Locks
  23343. ** + for no-op locks
  23344. ** + for dot-file locks
  23345. ** + for flock() locking
  23346. ** + for named semaphore locks (VxWorks only)
  23347. ** + for AFP filesystem locks (MacOSX only)
  23348. ** * sqlite3_file methods not associated with locking.
  23349. ** * Definitions of sqlite3_io_methods objects for all locking
  23350. ** methods plus "finder" functions for each locking method.
  23351. ** * sqlite3_vfs method implementations.
  23352. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  23353. ** * Definitions of sqlite3_vfs objects for all locking methods
  23354. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  23355. */
  23356. #if SQLITE_OS_UNIX /* This file is used on unix only */
  23357. /*
  23358. ** There are various methods for file locking used for concurrency
  23359. ** control:
  23360. **
  23361. ** 1. POSIX locking (the default),
  23362. ** 2. No locking,
  23363. ** 3. Dot-file locking,
  23364. ** 4. flock() locking,
  23365. ** 5. AFP locking (OSX only),
  23366. ** 6. Named POSIX semaphores (VXWorks only),
  23367. ** 7. proxy locking. (OSX only)
  23368. **
  23369. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  23370. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  23371. ** selection of the appropriate locking style based on the filesystem
  23372. ** where the database is located.
  23373. */
  23374. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  23375. # if defined(__APPLE__)
  23376. # define SQLITE_ENABLE_LOCKING_STYLE 1
  23377. # else
  23378. # define SQLITE_ENABLE_LOCKING_STYLE 0
  23379. # endif
  23380. #endif
  23381. /*
  23382. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  23383. ** vxworks, or 0 otherwise.
  23384. */
  23385. #ifndef OS_VXWORKS
  23386. # if defined(__RTP__) || defined(_WRS_KERNEL)
  23387. # define OS_VXWORKS 1
  23388. # else
  23389. # define OS_VXWORKS 0
  23390. # endif
  23391. #endif
  23392. /*
  23393. ** These #defines should enable >2GB file support on Posix if the
  23394. ** underlying operating system supports it. If the OS lacks
  23395. ** large file support, these should be no-ops.
  23396. **
  23397. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  23398. ** on the compiler command line. This is necessary if you are compiling
  23399. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  23400. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  23401. ** without this option, LFS is enable. But LFS does not exist in the kernel
  23402. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  23403. ** portability you should omit LFS.
  23404. **
  23405. ** The previous paragraph was written in 2005. (This paragraph is written
  23406. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  23407. ** you should probably leave LFS enabled. But some embedded platforms might
  23408. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  23409. */
  23410. #ifndef SQLITE_DISABLE_LFS
  23411. # define _LARGE_FILE 1
  23412. # ifndef _FILE_OFFSET_BITS
  23413. # define _FILE_OFFSET_BITS 64
  23414. # endif
  23415. # define _LARGEFILE_SOURCE 1
  23416. #endif
  23417. /*
  23418. ** standard include files.
  23419. */
  23420. #include <sys/types.h>
  23421. #include <sys/stat.h>
  23422. #include <fcntl.h>
  23423. #include <unistd.h>
  23424. /* #include <time.h> */
  23425. #include <sys/time.h>
  23426. #include <errno.h>
  23427. #ifndef SQLITE_OMIT_WAL
  23428. #include <sys/mman.h>
  23429. #endif
  23430. #if SQLITE_ENABLE_LOCKING_STYLE
  23431. # include <sys/ioctl.h>
  23432. # if OS_VXWORKS
  23433. # include <semaphore.h>
  23434. # include <limits.h>
  23435. # else
  23436. # include <sys/file.h>
  23437. # include <sys/param.h>
  23438. # endif
  23439. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  23440. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  23441. # include <sys/mount.h>
  23442. #endif
  23443. #ifdef HAVE_UTIME
  23444. # include <utime.h>
  23445. #endif
  23446. /*
  23447. ** Allowed values of unixFile.fsFlags
  23448. */
  23449. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  23450. /*
  23451. ** If we are to be thread-safe, include the pthreads header and define
  23452. ** the SQLITE_UNIX_THREADS macro.
  23453. */
  23454. #if SQLITE_THREADSAFE
  23455. /* # include <pthread.h> */
  23456. # define SQLITE_UNIX_THREADS 1
  23457. #endif
  23458. /*
  23459. ** Default permissions when creating a new file
  23460. */
  23461. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  23462. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  23463. #endif
  23464. /*
  23465. ** Default permissions when creating auto proxy dir
  23466. */
  23467. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  23468. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  23469. #endif
  23470. /*
  23471. ** Maximum supported path-length.
  23472. */
  23473. #define MAX_PATHNAME 512
  23474. /*
  23475. ** Only set the lastErrno if the error code is a real error and not
  23476. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  23477. */
  23478. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  23479. /* Forward references */
  23480. typedef struct unixShm unixShm; /* Connection shared memory */
  23481. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  23482. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  23483. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  23484. /*
  23485. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  23486. ** cannot be closed immediately. In these cases, instances of the following
  23487. ** structure are used to store the file descriptor while waiting for an
  23488. ** opportunity to either close or reuse it.
  23489. */
  23490. struct UnixUnusedFd {
  23491. int fd; /* File descriptor to close */
  23492. int flags; /* Flags this file descriptor was opened with */
  23493. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  23494. };
  23495. /*
  23496. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  23497. ** VFS implementations.
  23498. */
  23499. typedef struct unixFile unixFile;
  23500. struct unixFile {
  23501. sqlite3_io_methods const *pMethod; /* Always the first entry */
  23502. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  23503. unixInodeInfo *pInode; /* Info about locks on this inode */
  23504. int h; /* The file descriptor */
  23505. unsigned char eFileLock; /* The type of lock held on this fd */
  23506. unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  23507. int lastErrno; /* The unix errno from last I/O error */
  23508. void *lockingContext; /* Locking style specific state */
  23509. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  23510. const char *zPath; /* Name of the file */
  23511. unixShm *pShm; /* Shared memory segment information */
  23512. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  23513. #if SQLITE_ENABLE_LOCKING_STYLE
  23514. int openFlags; /* The flags specified at open() */
  23515. #endif
  23516. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  23517. unsigned fsFlags; /* cached details from statfs() */
  23518. #endif
  23519. #if OS_VXWORKS
  23520. struct vxworksFileId *pId; /* Unique file ID */
  23521. #endif
  23522. #ifndef NDEBUG
  23523. /* The next group of variables are used to track whether or not the
  23524. ** transaction counter in bytes 24-27 of database files are updated
  23525. ** whenever any part of the database changes. An assertion fault will
  23526. ** occur if a file is updated without also updating the transaction
  23527. ** counter. This test is made to avoid new problems similar to the
  23528. ** one described by ticket #3584.
  23529. */
  23530. unsigned char transCntrChng; /* True if the transaction counter changed */
  23531. unsigned char dbUpdate; /* True if any part of database file changed */
  23532. unsigned char inNormalWrite; /* True if in a normal write operation */
  23533. #endif
  23534. #ifdef SQLITE_TEST
  23535. /* In test mode, increase the size of this structure a bit so that
  23536. ** it is larger than the struct CrashFile defined in test6.c.
  23537. */
  23538. char aPadding[32];
  23539. #endif
  23540. };
  23541. /*
  23542. ** Allowed values for the unixFile.ctrlFlags bitmask:
  23543. */
  23544. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  23545. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  23546. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  23547. #ifndef SQLITE_DISABLE_DIRSYNC
  23548. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  23549. #else
  23550. # define UNIXFILE_DIRSYNC 0x00
  23551. #endif
  23552. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  23553. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  23554. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  23555. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  23556. /*
  23557. ** Include code that is common to all os_*.c files
  23558. */
  23559. /************** Include os_common.h in the middle of os_unix.c ***************/
  23560. /************** Begin file os_common.h ***************************************/
  23561. /*
  23562. ** 2004 May 22
  23563. **
  23564. ** The author disclaims copyright to this source code. In place of
  23565. ** a legal notice, here is a blessing:
  23566. **
  23567. ** May you do good and not evil.
  23568. ** May you find forgiveness for yourself and forgive others.
  23569. ** May you share freely, never taking more than you give.
  23570. **
  23571. ******************************************************************************
  23572. **
  23573. ** This file contains macros and a little bit of code that is common to
  23574. ** all of the platform-specific files (os_*.c) and is #included into those
  23575. ** files.
  23576. **
  23577. ** This file should be #included by the os_*.c files only. It is not a
  23578. ** general purpose header file.
  23579. */
  23580. #ifndef _OS_COMMON_H_
  23581. #define _OS_COMMON_H_
  23582. /*
  23583. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  23584. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  23585. ** switch. The following code should catch this problem at compile-time.
  23586. */
  23587. #ifdef MEMORY_DEBUG
  23588. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  23589. #endif
  23590. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  23591. # ifndef SQLITE_DEBUG_OS_TRACE
  23592. # define SQLITE_DEBUG_OS_TRACE 0
  23593. # endif
  23594. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  23595. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  23596. #else
  23597. # define OSTRACE(X)
  23598. #endif
  23599. /*
  23600. ** Macros for performance tracing. Normally turned off. Only works
  23601. ** on i486 hardware.
  23602. */
  23603. #ifdef SQLITE_PERFORMANCE_TRACE
  23604. /*
  23605. ** hwtime.h contains inline assembler code for implementing
  23606. ** high-performance timing routines.
  23607. */
  23608. /************** Include hwtime.h in the middle of os_common.h ****************/
  23609. /************** Begin file hwtime.h ******************************************/
  23610. /*
  23611. ** 2008 May 27
  23612. **
  23613. ** The author disclaims copyright to this source code. In place of
  23614. ** a legal notice, here is a blessing:
  23615. **
  23616. ** May you do good and not evil.
  23617. ** May you find forgiveness for yourself and forgive others.
  23618. ** May you share freely, never taking more than you give.
  23619. **
  23620. ******************************************************************************
  23621. **
  23622. ** This file contains inline asm code for retrieving "high-performance"
  23623. ** counters for x86 class CPUs.
  23624. */
  23625. #ifndef _HWTIME_H_
  23626. #define _HWTIME_H_
  23627. /*
  23628. ** The following routine only works on pentium-class (or newer) processors.
  23629. ** It uses the RDTSC opcode to read the cycle count value out of the
  23630. ** processor and returns that value. This can be used for high-res
  23631. ** profiling.
  23632. */
  23633. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  23634. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  23635. #if defined(__GNUC__)
  23636. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23637. unsigned int lo, hi;
  23638. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  23639. return (sqlite_uint64)hi << 32 | lo;
  23640. }
  23641. #elif defined(_MSC_VER)
  23642. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  23643. __asm {
  23644. rdtsc
  23645. ret ; return value at EDX:EAX
  23646. }
  23647. }
  23648. #endif
  23649. #elif (defined(__GNUC__) && defined(__x86_64__))
  23650. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23651. unsigned long val;
  23652. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  23653. return val;
  23654. }
  23655. #elif (defined(__GNUC__) && defined(__ppc__))
  23656. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23657. unsigned long long retval;
  23658. unsigned long junk;
  23659. __asm__ __volatile__ ("\n\
  23660. 1: mftbu %1\n\
  23661. mftb %L0\n\
  23662. mftbu %0\n\
  23663. cmpw %0,%1\n\
  23664. bne 1b"
  23665. : "=r" (retval), "=r" (junk));
  23666. return retval;
  23667. }
  23668. #else
  23669. #error Need implementation of sqlite3Hwtime() for your platform.
  23670. /*
  23671. ** To compile without implementing sqlite3Hwtime() for your platform,
  23672. ** you can remove the above #error and use the following
  23673. ** stub function. You will lose timing support for many
  23674. ** of the debugging and testing utilities, but it should at
  23675. ** least compile and run.
  23676. */
  23677. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  23678. #endif
  23679. #endif /* !defined(_HWTIME_H_) */
  23680. /************** End of hwtime.h **********************************************/
  23681. /************** Continuing where we left off in os_common.h ******************/
  23682. static sqlite_uint64 g_start;
  23683. static sqlite_uint64 g_elapsed;
  23684. #define TIMER_START g_start=sqlite3Hwtime()
  23685. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  23686. #define TIMER_ELAPSED g_elapsed
  23687. #else
  23688. #define TIMER_START
  23689. #define TIMER_END
  23690. #define TIMER_ELAPSED ((sqlite_uint64)0)
  23691. #endif
  23692. /*
  23693. ** If we compile with the SQLITE_TEST macro set, then the following block
  23694. ** of code will give us the ability to simulate a disk I/O error. This
  23695. ** is used for testing the I/O recovery logic.
  23696. */
  23697. #ifdef SQLITE_TEST
  23698. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  23699. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  23700. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  23701. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  23702. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  23703. SQLITE_API int sqlite3_diskfull_pending = 0;
  23704. SQLITE_API int sqlite3_diskfull = 0;
  23705. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  23706. #define SimulateIOError(CODE) \
  23707. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  23708. || sqlite3_io_error_pending-- == 1 ) \
  23709. { local_ioerr(); CODE; }
  23710. static void local_ioerr(){
  23711. IOTRACE(("IOERR\n"));
  23712. sqlite3_io_error_hit++;
  23713. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  23714. }
  23715. #define SimulateDiskfullError(CODE) \
  23716. if( sqlite3_diskfull_pending ){ \
  23717. if( sqlite3_diskfull_pending == 1 ){ \
  23718. local_ioerr(); \
  23719. sqlite3_diskfull = 1; \
  23720. sqlite3_io_error_hit = 1; \
  23721. CODE; \
  23722. }else{ \
  23723. sqlite3_diskfull_pending--; \
  23724. } \
  23725. }
  23726. #else
  23727. #define SimulateIOErrorBenign(X)
  23728. #define SimulateIOError(A)
  23729. #define SimulateDiskfullError(A)
  23730. #endif
  23731. /*
  23732. ** When testing, keep a count of the number of open files.
  23733. */
  23734. #ifdef SQLITE_TEST
  23735. SQLITE_API int sqlite3_open_file_count = 0;
  23736. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  23737. #else
  23738. #define OpenCounter(X)
  23739. #endif
  23740. #endif /* !defined(_OS_COMMON_H_) */
  23741. /************** End of os_common.h *******************************************/
  23742. /************** Continuing where we left off in os_unix.c ********************/
  23743. /*
  23744. ** Define various macros that are missing from some systems.
  23745. */
  23746. #ifndef O_LARGEFILE
  23747. # define O_LARGEFILE 0
  23748. #endif
  23749. #ifdef SQLITE_DISABLE_LFS
  23750. # undef O_LARGEFILE
  23751. # define O_LARGEFILE 0
  23752. #endif
  23753. #ifndef O_NOFOLLOW
  23754. # define O_NOFOLLOW 0
  23755. #endif
  23756. #ifndef O_BINARY
  23757. # define O_BINARY 0
  23758. #endif
  23759. /*
  23760. ** The threadid macro resolves to the thread-id or to 0. Used for
  23761. ** testing and debugging only.
  23762. */
  23763. #if SQLITE_THREADSAFE
  23764. #define threadid pthread_self()
  23765. #else
  23766. #define threadid 0
  23767. #endif
  23768. /*
  23769. ** Different Unix systems declare open() in different ways. Same use
  23770. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  23771. ** The difference is important when using a pointer to the function.
  23772. **
  23773. ** The safest way to deal with the problem is to always use this wrapper
  23774. ** which always has the same well-defined interface.
  23775. */
  23776. static int posixOpen(const char *zFile, int flags, int mode){
  23777. return open(zFile, flags, mode);
  23778. }
  23779. /* Forward reference */
  23780. static int openDirectory(const char*, int*);
  23781. /*
  23782. ** Many system calls are accessed through pointer-to-functions so that
  23783. ** they may be overridden at runtime to facilitate fault injection during
  23784. ** testing and sandboxing. The following array holds the names and pointers
  23785. ** to all overrideable system calls.
  23786. */
  23787. static struct unix_syscall {
  23788. const char *zName; /* Name of the sytem call */
  23789. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  23790. sqlite3_syscall_ptr pDefault; /* Default value */
  23791. } aSyscall[] = {
  23792. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  23793. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  23794. { "close", (sqlite3_syscall_ptr)close, 0 },
  23795. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  23796. { "access", (sqlite3_syscall_ptr)access, 0 },
  23797. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  23798. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  23799. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  23800. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  23801. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  23802. /*
  23803. ** The DJGPP compiler environment looks mostly like Unix, but it
  23804. ** lacks the fcntl() system call. So redefine fcntl() to be something
  23805. ** that always succeeds. This means that locking does not occur under
  23806. ** DJGPP. But it is DOS - what did you expect?
  23807. */
  23808. #ifdef __DJGPP__
  23809. { "fstat", 0, 0 },
  23810. #define osFstat(a,b,c) 0
  23811. #else
  23812. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  23813. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  23814. #endif
  23815. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  23816. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  23817. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  23818. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  23819. { "read", (sqlite3_syscall_ptr)read, 0 },
  23820. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  23821. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  23822. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  23823. #else
  23824. { "pread", (sqlite3_syscall_ptr)0, 0 },
  23825. #endif
  23826. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  23827. #if defined(USE_PREAD64)
  23828. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  23829. #else
  23830. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  23831. #endif
  23832. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  23833. { "write", (sqlite3_syscall_ptr)write, 0 },
  23834. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  23835. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  23836. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  23837. #else
  23838. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  23839. #endif
  23840. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  23841. aSyscall[12].pCurrent)
  23842. #if defined(USE_PREAD64)
  23843. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  23844. #else
  23845. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  23846. #endif
  23847. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  23848. aSyscall[13].pCurrent)
  23849. #if SQLITE_ENABLE_LOCKING_STYLE
  23850. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  23851. #else
  23852. { "fchmod", (sqlite3_syscall_ptr)0, 0 },
  23853. #endif
  23854. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  23855. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  23856. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  23857. #else
  23858. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  23859. #endif
  23860. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  23861. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  23862. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  23863. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  23864. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  23865. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  23866. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  23867. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  23868. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  23869. }; /* End of the overrideable system calls */
  23870. /*
  23871. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  23872. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  23873. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  23874. ** system call named zName.
  23875. */
  23876. static int unixSetSystemCall(
  23877. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  23878. const char *zName, /* Name of system call to override */
  23879. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  23880. ){
  23881. unsigned int i;
  23882. int rc = SQLITE_NOTFOUND;
  23883. UNUSED_PARAMETER(pNotUsed);
  23884. if( zName==0 ){
  23885. /* If no zName is given, restore all system calls to their default
  23886. ** settings and return NULL
  23887. */
  23888. rc = SQLITE_OK;
  23889. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23890. if( aSyscall[i].pDefault ){
  23891. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  23892. }
  23893. }
  23894. }else{
  23895. /* If zName is specified, operate on only the one system call
  23896. ** specified.
  23897. */
  23898. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23899. if( strcmp(zName, aSyscall[i].zName)==0 ){
  23900. if( aSyscall[i].pDefault==0 ){
  23901. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  23902. }
  23903. rc = SQLITE_OK;
  23904. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  23905. aSyscall[i].pCurrent = pNewFunc;
  23906. break;
  23907. }
  23908. }
  23909. }
  23910. return rc;
  23911. }
  23912. /*
  23913. ** Return the value of a system call. Return NULL if zName is not a
  23914. ** recognized system call name. NULL is also returned if the system call
  23915. ** is currently undefined.
  23916. */
  23917. static sqlite3_syscall_ptr unixGetSystemCall(
  23918. sqlite3_vfs *pNotUsed,
  23919. const char *zName
  23920. ){
  23921. unsigned int i;
  23922. UNUSED_PARAMETER(pNotUsed);
  23923. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23924. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  23925. }
  23926. return 0;
  23927. }
  23928. /*
  23929. ** Return the name of the first system call after zName. If zName==NULL
  23930. ** then return the name of the first system call. Return NULL if zName
  23931. ** is the last system call or if zName is not the name of a valid
  23932. ** system call.
  23933. */
  23934. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  23935. int i = -1;
  23936. UNUSED_PARAMETER(p);
  23937. if( zName ){
  23938. for(i=0; i<ArraySize(aSyscall)-1; i++){
  23939. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  23940. }
  23941. }
  23942. for(i++; i<ArraySize(aSyscall); i++){
  23943. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  23944. }
  23945. return 0;
  23946. }
  23947. /*
  23948. ** Retry open() calls that fail due to EINTR
  23949. */
  23950. static int robust_open(const char *z, int f, int m){
  23951. int rc;
  23952. do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
  23953. return rc;
  23954. }
  23955. /*
  23956. ** Helper functions to obtain and relinquish the global mutex. The
  23957. ** global mutex is used to protect the unixInodeInfo and
  23958. ** vxworksFileId objects used by this file, all of which may be
  23959. ** shared by multiple threads.
  23960. **
  23961. ** Function unixMutexHeld() is used to assert() that the global mutex
  23962. ** is held when required. This function is only used as part of assert()
  23963. ** statements. e.g.
  23964. **
  23965. ** unixEnterMutex()
  23966. ** assert( unixMutexHeld() );
  23967. ** unixEnterLeave()
  23968. */
  23969. static void unixEnterMutex(void){
  23970. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  23971. }
  23972. static void unixLeaveMutex(void){
  23973. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  23974. }
  23975. #ifdef SQLITE_DEBUG
  23976. static int unixMutexHeld(void) {
  23977. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  23978. }
  23979. #endif
  23980. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  23981. /*
  23982. ** Helper function for printing out trace information from debugging
  23983. ** binaries. This returns the string represetation of the supplied
  23984. ** integer lock-type.
  23985. */
  23986. static const char *azFileLock(int eFileLock){
  23987. switch( eFileLock ){
  23988. case NO_LOCK: return "NONE";
  23989. case SHARED_LOCK: return "SHARED";
  23990. case RESERVED_LOCK: return "RESERVED";
  23991. case PENDING_LOCK: return "PENDING";
  23992. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  23993. }
  23994. return "ERROR";
  23995. }
  23996. #endif
  23997. #ifdef SQLITE_LOCK_TRACE
  23998. /*
  23999. ** Print out information about all locking operations.
  24000. **
  24001. ** This routine is used for troubleshooting locks on multithreaded
  24002. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  24003. ** command-line option on the compiler. This code is normally
  24004. ** turned off.
  24005. */
  24006. static int lockTrace(int fd, int op, struct flock *p){
  24007. char *zOpName, *zType;
  24008. int s;
  24009. int savedErrno;
  24010. if( op==F_GETLK ){
  24011. zOpName = "GETLK";
  24012. }else if( op==F_SETLK ){
  24013. zOpName = "SETLK";
  24014. }else{
  24015. s = osFcntl(fd, op, p);
  24016. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  24017. return s;
  24018. }
  24019. if( p->l_type==F_RDLCK ){
  24020. zType = "RDLCK";
  24021. }else if( p->l_type==F_WRLCK ){
  24022. zType = "WRLCK";
  24023. }else if( p->l_type==F_UNLCK ){
  24024. zType = "UNLCK";
  24025. }else{
  24026. assert( 0 );
  24027. }
  24028. assert( p->l_whence==SEEK_SET );
  24029. s = osFcntl(fd, op, p);
  24030. savedErrno = errno;
  24031. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  24032. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  24033. (int)p->l_pid, s);
  24034. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  24035. struct flock l2;
  24036. l2 = *p;
  24037. osFcntl(fd, F_GETLK, &l2);
  24038. if( l2.l_type==F_RDLCK ){
  24039. zType = "RDLCK";
  24040. }else if( l2.l_type==F_WRLCK ){
  24041. zType = "WRLCK";
  24042. }else if( l2.l_type==F_UNLCK ){
  24043. zType = "UNLCK";
  24044. }else{
  24045. assert( 0 );
  24046. }
  24047. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  24048. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  24049. }
  24050. errno = savedErrno;
  24051. return s;
  24052. }
  24053. #undef osFcntl
  24054. #define osFcntl lockTrace
  24055. #endif /* SQLITE_LOCK_TRACE */
  24056. /*
  24057. ** Retry ftruncate() calls that fail due to EINTR
  24058. */
  24059. static int robust_ftruncate(int h, sqlite3_int64 sz){
  24060. int rc;
  24061. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  24062. return rc;
  24063. }
  24064. /*
  24065. ** This routine translates a standard POSIX errno code into something
  24066. ** useful to the clients of the sqlite3 functions. Specifically, it is
  24067. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  24068. ** and a variety of "please close the file descriptor NOW" errors into
  24069. ** SQLITE_IOERR
  24070. **
  24071. ** Errors during initialization of locks, or file system support for locks,
  24072. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  24073. */
  24074. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  24075. switch (posixError) {
  24076. #if 0
  24077. /* At one point this code was not commented out. In theory, this branch
  24078. ** should never be hit, as this function should only be called after
  24079. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  24080. ** the value of errno as the first argument. Since a system call has failed,
  24081. ** errno should be non-zero.
  24082. **
  24083. ** Despite this, if errno really is zero, we still don't want to return
  24084. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  24085. ** propagated back to the caller. Commenting this branch out means errno==0
  24086. ** will be handled by the "default:" case below.
  24087. */
  24088. case 0:
  24089. return SQLITE_OK;
  24090. #endif
  24091. case EAGAIN:
  24092. case ETIMEDOUT:
  24093. case EBUSY:
  24094. case EINTR:
  24095. case ENOLCK:
  24096. /* random NFS retry error, unless during file system support
  24097. * introspection, in which it actually means what it says */
  24098. return SQLITE_BUSY;
  24099. case EACCES:
  24100. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  24101. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  24102. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  24103. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  24104. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  24105. return SQLITE_BUSY;
  24106. }
  24107. /* else fall through */
  24108. case EPERM:
  24109. return SQLITE_PERM;
  24110. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  24111. ** this module never makes such a call. And the code in SQLite itself
  24112. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  24113. ** this case is also commented out. If the system does set errno to EDEADLK,
  24114. ** the default SQLITE_IOERR_XXX code will be returned. */
  24115. #if 0
  24116. case EDEADLK:
  24117. return SQLITE_IOERR_BLOCKED;
  24118. #endif
  24119. #if EOPNOTSUPP!=ENOTSUP
  24120. case EOPNOTSUPP:
  24121. /* something went terribly awry, unless during file system support
  24122. * introspection, in which it actually means what it says */
  24123. #endif
  24124. #ifdef ENOTSUP
  24125. case ENOTSUP:
  24126. /* invalid fd, unless during file system support introspection, in which
  24127. * it actually means what it says */
  24128. #endif
  24129. case EIO:
  24130. case EBADF:
  24131. case EINVAL:
  24132. case ENOTCONN:
  24133. case ENODEV:
  24134. case ENXIO:
  24135. case ENOENT:
  24136. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  24137. case ESTALE:
  24138. #endif
  24139. case ENOSYS:
  24140. /* these should force the client to close the file and reconnect */
  24141. default:
  24142. return sqliteIOErr;
  24143. }
  24144. }
  24145. /******************************************************************************
  24146. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  24147. **
  24148. ** On most versions of unix, we can get a unique ID for a file by concatenating
  24149. ** the device number and the inode number. But this does not work on VxWorks.
  24150. ** On VxWorks, a unique file id must be based on the canonical filename.
  24151. **
  24152. ** A pointer to an instance of the following structure can be used as a
  24153. ** unique file ID in VxWorks. Each instance of this structure contains
  24154. ** a copy of the canonical filename. There is also a reference count.
  24155. ** The structure is reclaimed when the number of pointers to it drops to
  24156. ** zero.
  24157. **
  24158. ** There are never very many files open at one time and lookups are not
  24159. ** a performance-critical path, so it is sufficient to put these
  24160. ** structures on a linked list.
  24161. */
  24162. struct vxworksFileId {
  24163. struct vxworksFileId *pNext; /* Next in a list of them all */
  24164. int nRef; /* Number of references to this one */
  24165. int nName; /* Length of the zCanonicalName[] string */
  24166. char *zCanonicalName; /* Canonical filename */
  24167. };
  24168. #if OS_VXWORKS
  24169. /*
  24170. ** All unique filenames are held on a linked list headed by this
  24171. ** variable:
  24172. */
  24173. static struct vxworksFileId *vxworksFileList = 0;
  24174. /*
  24175. ** Simplify a filename into its canonical form
  24176. ** by making the following changes:
  24177. **
  24178. ** * removing any trailing and duplicate /
  24179. ** * convert /./ into just /
  24180. ** * convert /A/../ where A is any simple name into just /
  24181. **
  24182. ** Changes are made in-place. Return the new name length.
  24183. **
  24184. ** The original filename is in z[0..n-1]. Return the number of
  24185. ** characters in the simplified name.
  24186. */
  24187. static int vxworksSimplifyName(char *z, int n){
  24188. int i, j;
  24189. while( n>1 && z[n-1]=='/' ){ n--; }
  24190. for(i=j=0; i<n; i++){
  24191. if( z[i]=='/' ){
  24192. if( z[i+1]=='/' ) continue;
  24193. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  24194. i += 1;
  24195. continue;
  24196. }
  24197. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  24198. while( j>0 && z[j-1]!='/' ){ j--; }
  24199. if( j>0 ){ j--; }
  24200. i += 2;
  24201. continue;
  24202. }
  24203. }
  24204. z[j++] = z[i];
  24205. }
  24206. z[j] = 0;
  24207. return j;
  24208. }
  24209. /*
  24210. ** Find a unique file ID for the given absolute pathname. Return
  24211. ** a pointer to the vxworksFileId object. This pointer is the unique
  24212. ** file ID.
  24213. **
  24214. ** The nRef field of the vxworksFileId object is incremented before
  24215. ** the object is returned. A new vxworksFileId object is created
  24216. ** and added to the global list if necessary.
  24217. **
  24218. ** If a memory allocation error occurs, return NULL.
  24219. */
  24220. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  24221. struct vxworksFileId *pNew; /* search key and new file ID */
  24222. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  24223. int n; /* Length of zAbsoluteName string */
  24224. assert( zAbsoluteName[0]=='/' );
  24225. n = (int)strlen(zAbsoluteName);
  24226. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  24227. if( pNew==0 ) return 0;
  24228. pNew->zCanonicalName = (char*)&pNew[1];
  24229. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  24230. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  24231. /* Search for an existing entry that matching the canonical name.
  24232. ** If found, increment the reference count and return a pointer to
  24233. ** the existing file ID.
  24234. */
  24235. unixEnterMutex();
  24236. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  24237. if( pCandidate->nName==n
  24238. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  24239. ){
  24240. sqlite3_free(pNew);
  24241. pCandidate->nRef++;
  24242. unixLeaveMutex();
  24243. return pCandidate;
  24244. }
  24245. }
  24246. /* No match was found. We will make a new file ID */
  24247. pNew->nRef = 1;
  24248. pNew->nName = n;
  24249. pNew->pNext = vxworksFileList;
  24250. vxworksFileList = pNew;
  24251. unixLeaveMutex();
  24252. return pNew;
  24253. }
  24254. /*
  24255. ** Decrement the reference count on a vxworksFileId object. Free
  24256. ** the object when the reference count reaches zero.
  24257. */
  24258. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  24259. unixEnterMutex();
  24260. assert( pId->nRef>0 );
  24261. pId->nRef--;
  24262. if( pId->nRef==0 ){
  24263. struct vxworksFileId **pp;
  24264. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  24265. assert( *pp==pId );
  24266. *pp = pId->pNext;
  24267. sqlite3_free(pId);
  24268. }
  24269. unixLeaveMutex();
  24270. }
  24271. #endif /* OS_VXWORKS */
  24272. /*************** End of Unique File ID Utility Used By VxWorks ****************
  24273. ******************************************************************************/
  24274. /******************************************************************************
  24275. *************************** Posix Advisory Locking ****************************
  24276. **
  24277. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  24278. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  24279. ** sets or clears a lock, that operation overrides any prior locks set
  24280. ** by the same process. It does not explicitly say so, but this implies
  24281. ** that it overrides locks set by the same process using a different
  24282. ** file descriptor. Consider this test case:
  24283. **
  24284. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  24285. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  24286. **
  24287. ** Suppose ./file1 and ./file2 are really the same file (because
  24288. ** one is a hard or symbolic link to the other) then if you set
  24289. ** an exclusive lock on fd1, then try to get an exclusive lock
  24290. ** on fd2, it works. I would have expected the second lock to
  24291. ** fail since there was already a lock on the file due to fd1.
  24292. ** But not so. Since both locks came from the same process, the
  24293. ** second overrides the first, even though they were on different
  24294. ** file descriptors opened on different file names.
  24295. **
  24296. ** This means that we cannot use POSIX locks to synchronize file access
  24297. ** among competing threads of the same process. POSIX locks will work fine
  24298. ** to synchronize access for threads in separate processes, but not
  24299. ** threads within the same process.
  24300. **
  24301. ** To work around the problem, SQLite has to manage file locks internally
  24302. ** on its own. Whenever a new database is opened, we have to find the
  24303. ** specific inode of the database file (the inode is determined by the
  24304. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  24305. ** and check for locks already existing on that inode. When locks are
  24306. ** created or removed, we have to look at our own internal record of the
  24307. ** locks to see if another thread has previously set a lock on that same
  24308. ** inode.
  24309. **
  24310. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  24311. ** For VxWorks, we have to use the alternative unique ID system based on
  24312. ** canonical filename and implemented in the previous division.)
  24313. **
  24314. ** The sqlite3_file structure for POSIX is no longer just an integer file
  24315. ** descriptor. It is now a structure that holds the integer file
  24316. ** descriptor and a pointer to a structure that describes the internal
  24317. ** locks on the corresponding inode. There is one locking structure
  24318. ** per inode, so if the same inode is opened twice, both unixFile structures
  24319. ** point to the same locking structure. The locking structure keeps
  24320. ** a reference count (so we will know when to delete it) and a "cnt"
  24321. ** field that tells us its internal lock status. cnt==0 means the
  24322. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  24323. ** cnt>0 means there are cnt shared locks on the file.
  24324. **
  24325. ** Any attempt to lock or unlock a file first checks the locking
  24326. ** structure. The fcntl() system call is only invoked to set a
  24327. ** POSIX lock if the internal lock structure transitions between
  24328. ** a locked and an unlocked state.
  24329. **
  24330. ** But wait: there are yet more problems with POSIX advisory locks.
  24331. **
  24332. ** If you close a file descriptor that points to a file that has locks,
  24333. ** all locks on that file that are owned by the current process are
  24334. ** released. To work around this problem, each unixInodeInfo object
  24335. ** maintains a count of the number of pending locks on tha inode.
  24336. ** When an attempt is made to close an unixFile, if there are
  24337. ** other unixFile open on the same inode that are holding locks, the call
  24338. ** to close() the file descriptor is deferred until all of the locks clear.
  24339. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  24340. ** be closed and that list is walked (and cleared) when the last lock
  24341. ** clears.
  24342. **
  24343. ** Yet another problem: LinuxThreads do not play well with posix locks.
  24344. **
  24345. ** Many older versions of linux use the LinuxThreads library which is
  24346. ** not posix compliant. Under LinuxThreads, a lock created by thread
  24347. ** A cannot be modified or overridden by a different thread B.
  24348. ** Only thread A can modify the lock. Locking behavior is correct
  24349. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  24350. ** on linux - with NPTL a lock created by thread A can override locks
  24351. ** in thread B. But there is no way to know at compile-time which
  24352. ** threading library is being used. So there is no way to know at
  24353. ** compile-time whether or not thread A can override locks on thread B.
  24354. ** One has to do a run-time check to discover the behavior of the
  24355. ** current process.
  24356. **
  24357. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  24358. ** was dropped beginning with version 3.7.0. SQLite will still work with
  24359. ** LinuxThreads provided that (1) there is no more than one connection
  24360. ** per database file in the same process and (2) database connections
  24361. ** do not move across threads.
  24362. */
  24363. /*
  24364. ** An instance of the following structure serves as the key used
  24365. ** to locate a particular unixInodeInfo object.
  24366. */
  24367. struct unixFileId {
  24368. dev_t dev; /* Device number */
  24369. #if OS_VXWORKS
  24370. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  24371. #else
  24372. ino_t ino; /* Inode number */
  24373. #endif
  24374. };
  24375. /*
  24376. ** An instance of the following structure is allocated for each open
  24377. ** inode. Or, on LinuxThreads, there is one of these structures for
  24378. ** each inode opened by each thread.
  24379. **
  24380. ** A single inode can have multiple file descriptors, so each unixFile
  24381. ** structure contains a pointer to an instance of this object and this
  24382. ** object keeps a count of the number of unixFile pointing to it.
  24383. */
  24384. struct unixInodeInfo {
  24385. struct unixFileId fileId; /* The lookup key */
  24386. int nShared; /* Number of SHARED locks held */
  24387. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  24388. unsigned char bProcessLock; /* An exclusive process lock is held */
  24389. int nRef; /* Number of pointers to this structure */
  24390. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  24391. int nLock; /* Number of outstanding file locks */
  24392. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  24393. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  24394. unixInodeInfo *pPrev; /* .... doubly linked */
  24395. #if SQLITE_ENABLE_LOCKING_STYLE
  24396. unsigned long long sharedByte; /* for AFP simulated shared lock */
  24397. #endif
  24398. #if OS_VXWORKS
  24399. sem_t *pSem; /* Named POSIX semaphore */
  24400. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  24401. #endif
  24402. };
  24403. /*
  24404. ** A lists of all unixInodeInfo objects.
  24405. */
  24406. static unixInodeInfo *inodeList = 0;
  24407. /*
  24408. **
  24409. ** This function - unixLogError_x(), is only ever called via the macro
  24410. ** unixLogError().
  24411. **
  24412. ** It is invoked after an error occurs in an OS function and errno has been
  24413. ** set. It logs a message using sqlite3_log() containing the current value of
  24414. ** errno and, if possible, the human-readable equivalent from strerror() or
  24415. ** strerror_r().
  24416. **
  24417. ** The first argument passed to the macro should be the error code that
  24418. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  24419. ** The two subsequent arguments should be the name of the OS function that
  24420. ** failed (e.g. "unlink", "open") and the the associated file-system path,
  24421. ** if any.
  24422. */
  24423. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  24424. static int unixLogErrorAtLine(
  24425. int errcode, /* SQLite error code */
  24426. const char *zFunc, /* Name of OS function that failed */
  24427. const char *zPath, /* File path associated with error */
  24428. int iLine /* Source line number where error occurred */
  24429. ){
  24430. char *zErr; /* Message from strerror() or equivalent */
  24431. int iErrno = errno; /* Saved syscall error number */
  24432. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  24433. ** the strerror() function to obtain the human-readable error message
  24434. ** equivalent to errno. Otherwise, use strerror_r().
  24435. */
  24436. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  24437. char aErr[80];
  24438. memset(aErr, 0, sizeof(aErr));
  24439. zErr = aErr;
  24440. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  24441. ** assume that the system provides the the GNU version of strerror_r() that
  24442. ** returns a pointer to a buffer containing the error message. That pointer
  24443. ** may point to aErr[], or it may point to some static storage somewhere.
  24444. ** Otherwise, assume that the system provides the POSIX version of
  24445. ** strerror_r(), which always writes an error message into aErr[].
  24446. **
  24447. ** If the code incorrectly assumes that it is the POSIX version that is
  24448. ** available, the error message will often be an empty string. Not a
  24449. ** huge problem. Incorrectly concluding that the GNU version is available
  24450. ** could lead to a segfault though.
  24451. */
  24452. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  24453. zErr =
  24454. # endif
  24455. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  24456. #elif SQLITE_THREADSAFE
  24457. /* This is a threadsafe build, but strerror_r() is not available. */
  24458. zErr = "";
  24459. #else
  24460. /* Non-threadsafe build, use strerror(). */
  24461. zErr = strerror(iErrno);
  24462. #endif
  24463. assert( errcode!=SQLITE_OK );
  24464. if( zPath==0 ) zPath = "";
  24465. sqlite3_log(errcode,
  24466. "os_unix.c:%d: (%d) %s(%s) - %s",
  24467. iLine, iErrno, zFunc, zPath, zErr
  24468. );
  24469. return errcode;
  24470. }
  24471. /*
  24472. ** Close a file descriptor.
  24473. **
  24474. ** We assume that close() almost always works, since it is only in a
  24475. ** very sick application or on a very sick platform that it might fail.
  24476. ** If it does fail, simply leak the file descriptor, but do log the
  24477. ** error.
  24478. **
  24479. ** Note that it is not safe to retry close() after EINTR since the
  24480. ** file descriptor might have already been reused by another thread.
  24481. ** So we don't even try to recover from an EINTR. Just log the error
  24482. ** and move on.
  24483. */
  24484. static void robust_close(unixFile *pFile, int h, int lineno){
  24485. if( osClose(h) ){
  24486. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  24487. pFile ? pFile->zPath : 0, lineno);
  24488. }
  24489. }
  24490. /*
  24491. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  24492. */
  24493. static void closePendingFds(unixFile *pFile){
  24494. unixInodeInfo *pInode = pFile->pInode;
  24495. UnixUnusedFd *p;
  24496. UnixUnusedFd *pNext;
  24497. for(p=pInode->pUnused; p; p=pNext){
  24498. pNext = p->pNext;
  24499. robust_close(pFile, p->fd, __LINE__);
  24500. sqlite3_free(p);
  24501. }
  24502. pInode->pUnused = 0;
  24503. }
  24504. /*
  24505. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  24506. **
  24507. ** The mutex entered using the unixEnterMutex() function must be held
  24508. ** when this function is called.
  24509. */
  24510. static void releaseInodeInfo(unixFile *pFile){
  24511. unixInodeInfo *pInode = pFile->pInode;
  24512. assert( unixMutexHeld() );
  24513. if( ALWAYS(pInode) ){
  24514. pInode->nRef--;
  24515. if( pInode->nRef==0 ){
  24516. assert( pInode->pShmNode==0 );
  24517. closePendingFds(pFile);
  24518. if( pInode->pPrev ){
  24519. assert( pInode->pPrev->pNext==pInode );
  24520. pInode->pPrev->pNext = pInode->pNext;
  24521. }else{
  24522. assert( inodeList==pInode );
  24523. inodeList = pInode->pNext;
  24524. }
  24525. if( pInode->pNext ){
  24526. assert( pInode->pNext->pPrev==pInode );
  24527. pInode->pNext->pPrev = pInode->pPrev;
  24528. }
  24529. sqlite3_free(pInode);
  24530. }
  24531. }
  24532. }
  24533. /*
  24534. ** Given a file descriptor, locate the unixInodeInfo object that
  24535. ** describes that file descriptor. Create a new one if necessary. The
  24536. ** return value might be uninitialized if an error occurs.
  24537. **
  24538. ** The mutex entered using the unixEnterMutex() function must be held
  24539. ** when this function is called.
  24540. **
  24541. ** Return an appropriate error code.
  24542. */
  24543. static int findInodeInfo(
  24544. unixFile *pFile, /* Unix file with file desc used in the key */
  24545. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  24546. ){
  24547. int rc; /* System call return code */
  24548. int fd; /* The file descriptor for pFile */
  24549. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  24550. struct stat statbuf; /* Low-level file information */
  24551. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  24552. assert( unixMutexHeld() );
  24553. /* Get low-level information about the file that we can used to
  24554. ** create a unique name for the file.
  24555. */
  24556. fd = pFile->h;
  24557. rc = osFstat(fd, &statbuf);
  24558. if( rc!=0 ){
  24559. pFile->lastErrno = errno;
  24560. #ifdef EOVERFLOW
  24561. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  24562. #endif
  24563. return SQLITE_IOERR;
  24564. }
  24565. #ifdef __APPLE__
  24566. /* On OS X on an msdos filesystem, the inode number is reported
  24567. ** incorrectly for zero-size files. See ticket #3260. To work
  24568. ** around this problem (we consider it a bug in OS X, not SQLite)
  24569. ** we always increase the file size to 1 by writing a single byte
  24570. ** prior to accessing the inode number. The one byte written is
  24571. ** an ASCII 'S' character which also happens to be the first byte
  24572. ** in the header of every SQLite database. In this way, if there
  24573. ** is a race condition such that another thread has already populated
  24574. ** the first page of the database, no damage is done.
  24575. */
  24576. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  24577. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  24578. if( rc!=1 ){
  24579. pFile->lastErrno = errno;
  24580. return SQLITE_IOERR;
  24581. }
  24582. rc = osFstat(fd, &statbuf);
  24583. if( rc!=0 ){
  24584. pFile->lastErrno = errno;
  24585. return SQLITE_IOERR;
  24586. }
  24587. }
  24588. #endif
  24589. memset(&fileId, 0, sizeof(fileId));
  24590. fileId.dev = statbuf.st_dev;
  24591. #if OS_VXWORKS
  24592. fileId.pId = pFile->pId;
  24593. #else
  24594. fileId.ino = statbuf.st_ino;
  24595. #endif
  24596. pInode = inodeList;
  24597. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  24598. pInode = pInode->pNext;
  24599. }
  24600. if( pInode==0 ){
  24601. pInode = sqlite3_malloc( sizeof(*pInode) );
  24602. if( pInode==0 ){
  24603. return SQLITE_NOMEM;
  24604. }
  24605. memset(pInode, 0, sizeof(*pInode));
  24606. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  24607. pInode->nRef = 1;
  24608. pInode->pNext = inodeList;
  24609. pInode->pPrev = 0;
  24610. if( inodeList ) inodeList->pPrev = pInode;
  24611. inodeList = pInode;
  24612. }else{
  24613. pInode->nRef++;
  24614. }
  24615. *ppInode = pInode;
  24616. return SQLITE_OK;
  24617. }
  24618. /*
  24619. ** This routine checks if there is a RESERVED lock held on the specified
  24620. ** file by this or any other process. If such a lock is held, set *pResOut
  24621. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24622. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24623. */
  24624. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  24625. int rc = SQLITE_OK;
  24626. int reserved = 0;
  24627. unixFile *pFile = (unixFile*)id;
  24628. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24629. assert( pFile );
  24630. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24631. /* Check if a thread in this process holds such a lock */
  24632. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24633. reserved = 1;
  24634. }
  24635. /* Otherwise see if some other process holds it.
  24636. */
  24637. #ifndef __DJGPP__
  24638. if( !reserved && !pFile->pInode->bProcessLock ){
  24639. struct flock lock;
  24640. lock.l_whence = SEEK_SET;
  24641. lock.l_start = RESERVED_BYTE;
  24642. lock.l_len = 1;
  24643. lock.l_type = F_WRLCK;
  24644. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  24645. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  24646. pFile->lastErrno = errno;
  24647. } else if( lock.l_type!=F_UNLCK ){
  24648. reserved = 1;
  24649. }
  24650. }
  24651. #endif
  24652. unixLeaveMutex();
  24653. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  24654. *pResOut = reserved;
  24655. return rc;
  24656. }
  24657. /*
  24658. ** Attempt to set a system-lock on the file pFile. The lock is
  24659. ** described by pLock.
  24660. **
  24661. ** If the pFile was opened read/write from unix-excl, then the only lock
  24662. ** ever obtained is an exclusive lock, and it is obtained exactly once
  24663. ** the first time any lock is attempted. All subsequent system locking
  24664. ** operations become no-ops. Locking operations still happen internally,
  24665. ** in order to coordinate access between separate database connections
  24666. ** within this process, but all of that is handled in memory and the
  24667. ** operating system does not participate.
  24668. **
  24669. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  24670. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  24671. ** and is read-only.
  24672. **
  24673. ** Zero is returned if the call completes successfully, or -1 if a call
  24674. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  24675. */
  24676. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  24677. int rc;
  24678. unixInodeInfo *pInode = pFile->pInode;
  24679. assert( unixMutexHeld() );
  24680. assert( pInode!=0 );
  24681. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  24682. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  24683. ){
  24684. if( pInode->bProcessLock==0 ){
  24685. struct flock lock;
  24686. assert( pInode->nLock==0 );
  24687. lock.l_whence = SEEK_SET;
  24688. lock.l_start = SHARED_FIRST;
  24689. lock.l_len = SHARED_SIZE;
  24690. lock.l_type = F_WRLCK;
  24691. rc = osFcntl(pFile->h, F_SETLK, &lock);
  24692. if( rc<0 ) return rc;
  24693. pInode->bProcessLock = 1;
  24694. pInode->nLock++;
  24695. }else{
  24696. rc = 0;
  24697. }
  24698. }else{
  24699. rc = osFcntl(pFile->h, F_SETLK, pLock);
  24700. }
  24701. return rc;
  24702. }
  24703. /*
  24704. ** Lock the file with the lock specified by parameter eFileLock - one
  24705. ** of the following:
  24706. **
  24707. ** (1) SHARED_LOCK
  24708. ** (2) RESERVED_LOCK
  24709. ** (3) PENDING_LOCK
  24710. ** (4) EXCLUSIVE_LOCK
  24711. **
  24712. ** Sometimes when requesting one lock state, additional lock states
  24713. ** are inserted in between. The locking might fail on one of the later
  24714. ** transitions leaving the lock state different from what it started but
  24715. ** still short of its goal. The following chart shows the allowed
  24716. ** transitions and the inserted intermediate states:
  24717. **
  24718. ** UNLOCKED -> SHARED
  24719. ** SHARED -> RESERVED
  24720. ** SHARED -> (PENDING) -> EXCLUSIVE
  24721. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24722. ** PENDING -> EXCLUSIVE
  24723. **
  24724. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24725. ** routine to lower a locking level.
  24726. */
  24727. static int unixLock(sqlite3_file *id, int eFileLock){
  24728. /* The following describes the implementation of the various locks and
  24729. ** lock transitions in terms of the POSIX advisory shared and exclusive
  24730. ** lock primitives (called read-locks and write-locks below, to avoid
  24731. ** confusion with SQLite lock names). The algorithms are complicated
  24732. ** slightly in order to be compatible with windows systems simultaneously
  24733. ** accessing the same database file, in case that is ever required.
  24734. **
  24735. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  24736. ** byte', each single bytes at well known offsets, and the 'shared byte
  24737. ** range', a range of 510 bytes at a well known offset.
  24738. **
  24739. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  24740. ** byte'. If this is successful, a random byte from the 'shared byte
  24741. ** range' is read-locked and the lock